Module: Features::ActiveRecordExtension::ClassMethods

Defined in:
lib/features/active_record_extension.rb

Instance Method Summary collapse

Instance Method Details

#has_features(&block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/features/active_record_extension.rb', line 4

def has_features(&block)
  builder = FeatureTreeBuilder.new(self)
  builder.instance_eval(&block)
  builder.build

  has_many :features, :class_name => 'Features::Feature', :dependent => :destroy do
    def available?(feature_name)
      @owner.features?(*Feature.sym_to_class(feature_name).required_features.map(&:to_sym))
    end
    
    # Define the feature query methods, given that the feature +wiffle+ is defined,
    # then the methods +account.features.wiffle?+ and +account.features.wiffle!+ will
    # be available
    Feature::LIST.each do |f|

      # The query method, does this account have a given feature? account.features.wiffle?
      define_method "#{f}?" do
        any? { |feature| feature.matches?(f) }
      end

      # The finder method which returns the feature if present, otherwise a new instance, allows
      # non-destructive create and delete operations:
      #
      #   account.features.wiffle.destroy
      #   account.features.wiffle.create
      #
      # In the latter case, a the +wiffle+ feature will only be enabled if it's not already. Be careful
      # not to confuse this method with the "feature enabled" method above, ie. avoid
      #
      #   format_c if account.feature.wiffle
      #
      define_method "#{f}" do
        instance = detect { |feature| feature.matches?(f) }
        instance ||= Feature.sym_to_class(f).new(@owner.class.name.underscore.to_sym => @owner)
      end
    end
  end
  
  include Features::ActiveRecordExtension::InstanceMethods
  alias_method_chain :update_attributes, :features
  alias_method_chain :update_attributes!, :features
  
end