Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

rails include module

module Features
  FEATURES = [Running, Walking]

  # include Features::Running
  FEATURES.each do |feature|
    include feature
  end

  module ClassMethods
    # include Features::Running::ClassMethods
    FEATURES.each do |feature|
      include feature::ClassMethods
    end
  end

  module InstanceMethods
    def method_missing(meth)
      # Catch feature checks that are not included in models to return false
      if meth[-1] == '?' && meth.to_s =~ /can_(w+)z?/
        false
      else
        # You *must* call super if you don't handle the method,
        # otherwise you'll mess up Ruby's method lookup
        super
      end
    end
  end

  def self.included(base)
    base.send :extend, ClassMethods
    base.send :include, InstanceMethods
  end
end

# lib/features/running.rb
module Features::Running
  module ClassMethods
    def can_run
      ...

      # Define a method to have model know a way they have that feature
      define_method(:can_run?) { true }
    end
  end
end

# lib/features/walking.rb
module Features::Walking
  module ClassMethods
    def can_walk
      ...

      # Define a method to have model know a way they have that feature
      define_method(:can_walk?) { true }
    end
  end
end
Comment

PREVIOUS NEXT
Code Example
Ruby :: rails form validation custom message 
Ruby :: ruby sort method 
Ruby :: ruby map 
Ruby :: linker command failed with exit code 1 ruby 
Ruby :: check if the substring is present in the column of the record rails console 
Ruby :: rails many to many relationship same model 
Ruby :: setp in ruby loop 
Ruby :: ruby array of symbols 
Ruby :: In Jekyll - get the parent url path of a collection with concatenation 
Ruby :: deliver_later not sending mail in sidekiq in rails 
Ruby :: how to require all .rb files in rails 
Ruby :: ruby on rails multiple models pagination 
Ruby :: ruby ** 
Ruby :: rails convert euro to dollar 
Ruby :: ruby get classname 
Ruby :: array sort_by nil ruby 
Ruby :: paranoia gem 
Ruby :: class ruby 
R :: outlier tagging boxplot r 
R :: delete first three lines dataframe R 
R :: Error in value[[3L]](cond) : Package ‘lavaan’ version 0.6.8 cannot be unloaded: 
R :: how to use recursion in r 
R :: r - change column name 
R :: how to change the index of a dataframe in r 
R :: create a table from dataframe in r 
R :: lubridate sequence of dates 
R :: covert -Inf to 0 r 
R :: r count list 
R :: find nas in a vector r 
R :: not displaying prints and on.exit in r 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =