Coder Social home page Coder Social logo

modularity's Introduction

Tests

Modularity - Traits and partial classes for Ruby

Modularity enhances Ruby's Module so it can be used traits and partial classes. This allows very simple definition of meta-programming macros like the has_many that you know from Rails.

Modularity also lets you organize large models into multiple source files in a way that is less awkward than using modules.

Installation

Add the following to your Gemfile:

gem 'modularity'

Now run bundle install.

Example 1: Easy meta-programming macros

Ruby allows you to construct classes using meta-programming macros like acts_as_tree or has_many :items. These macros will add methods, callbacks, etc. to the calling class. However, right now Ruby (and Rails) makes it awkward to define such macros in your project as part of your application domain.

Modularity allows you to extract common behaviour into reusable macros by defining traits with parameters. Your macros can live in your application, allowing you to express your application domain in both classes and macros.

Here is an example of a strip_field macro, which created setter methods that remove leading and trailing whitespace from newly assigned values:

# app/models/article.rb
class Article < ActiveRecord::Base
  include DoesStripFields[:name, :brand]
end

# app/models/shared/does_strip_fields.rb
module DoesStripFields
  as_trait do |*fields|
    fields.each do |field|
      define_method("#{field}=") do |value|
        self[field] = value.strip
      end
    end
  end
end

Notice the as_trait block.

We like to add app/models/shared and app/controllers/shared to the load paths of our Rails projects. These are great places to store macros that are re-used from multiple classes.

Example 2: Mixins with class methods

Using a module to add both instance methods and class methods is very awkward. Modularity does away with the clutter and lets you say this:

# app/models/model.rb
class Model
  include Mixin
end

# app/models/mixin.rb
module Mixin
  as_trait do
    def instance_method
      # ...
    end
    def self.class_method
      # ..
    end
  end
end

private and protected will also work as expected when defining a trait.

Example 3: Splitting a model into multiple source files

Models are often concerned with multiple themes like "authentication", "contact info" or "permissions", each requiring a couple of validations and callbacks here, and some method there. Modularity lets you organize your model into multiple partial classes, so each file can deal with a single aspect of your model:

# app/models/user.rb
class User < ActiveRecord::Base
  include DoesAuthentication
  include DoesPermissions
end

# app/models/user/does_authentication.rb
module User::DoesAuthentication
  as_trait do
    # methods, validations, etc. regarding usernames and passwords go here
  end
end

# app/models/user/does_permissions.rb
module User::DoesPermissions
  as_trait do
    # methods, validations, etc. regarding contact information go here
  end
end

Some criticism has been raised for splitting large models into files like this. Essentially, even though have an easier time navigating your code, you will still have one giant model with many side effects.

There are many better ways to decompose a huge Ruby class.

Development

  • Install Bundler 2 gem install bundler:2.2.22 and run bundle install to have a working development setup.
  • Running tests for the current Ruby version: bundle exec rake
  • Running tests for all supported Ruby version: Push the changes to Github in a feature branch, open a merge request and have a look at the test matrix in Github actions

Credits

Henning Koch from makandra.com

modularity's People

Contributors

5v3n avatar brunosedler avatar denzelem avatar kraatob avatar kratob avatar niklas-hasselmeyer avatar stemps avatar triskweline avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

modularity's Issues

Unexpected behavior with trait arguments

In a trait, I have a method that is using one of the trait arguments. In case the argument is not given, it falls back to a default value.

The unexpected: as soon as the default value is generated, it is stored at trait level and gets returned on each invocation. In other words, the default value is only evaluated once. In many cases, this will be no problem. However, the issue arises with a dynamic default value. See (and try) this Ruby script, where the default value is derived from the class name:

require 'modularity'

module DoesDemo
  as_trait do |name: nil|
  
    define_method :demo do
      name ||= self.class.name
      puts name
    end
    
  end
end

class Base
  include DoesDemo
end

class One < Base
end

class Two < Base
end

One.new.demo # => One
Two.new.demo # => One # wrong

As you can see, the return value of any subclass's demo method is the name of the first-defined class. (It would be the same with name ||= Time.now: the defaulted timestamp is instantiated once and returned on each invocation of demo.)

The distilled issue seems to be that assigning variables named like trait arguments will change state at trait level, i.e. modify the trait argument value.

Expected behavior

demo would always return the name of the current class (or the current time). Assigning a variable named like a trait argument should not change the value of the trait argument.

Workaround

Avoiding to assign variables named like any of the trait arguments.


I am not sure whether this behavior is a real bug, or if it might be a feature of define_method. Anyway, a solution that enables to ||=-assign variables named like trait arguments would be appreciated.

Does ActiveSupport::Concern solve the problem?

... so since Rails 3 ? you can do:

app/models/article.rb

# app/models/article.rb
class Article
  include Shared::StripFields

  strip_fields :name, :brand
end

app/models/shared/strip_fields.rb

module Shared::StripFields
  extend ActiveSupport::Concern

  module ClassMethods
    def strip_fields(fields)
      fields = fields.is_a?(Array) ? fields : [fields]

      fields.each do |field|
        define_method("#{field}=") do |value|
          self[field] = value.strip
        end
      end
    end
  end
end

Class methods can be called through an included block and instance methods can be declared inside the mixin directly without an InstanceMethods module like this:

module Shared::MyMixin
  extend ActiveSupport::Concern

  included do
    scope :by_type, lambda {|type| where(:type => type)}
    has_many ...
  end

  module ClassMethods
    ...
  end

  def my_instance_method
    ...
  end
end

ActiveSupport::Concern now also resolves mixin dependencies properly as described in its API doc.

P.S.: I also found no problems with the visibility of class and instance methods.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.