Module: Reamaze::Opinionated::ClassMethods

Defined in:
lib/opinionated.rb

Overview

Make methods available to ActiveRecord in the class context

Instance Method Summary collapse

Instance Method Details

#preferences(preferential = :preferences, options = {}) {|configuration| ... } ⇒ Object

Yields:

  • (configuration)

Raises:

  • (ArgumentError)


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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/opinionated.rb', line 14

def preferences(preferential = :preferences, options = {})
  send :include, InstanceMethods

  preferential = Helpers.normalize(preferential)

  # Create accessor methods to our configuration info
  class << self
    attr_accessor :preferential_configuration unless method_defined?(:preferential_configuration)
  end

  # Initialize the configuration to an empty hash
  self.preferential_configuration = {} if self.preferential_configuration.nil?

  # Redefining a preference configuration once defined should not be allowed
  raise ArgumentError, "#{self} class already preferences :#{preferential} defined" if self.preferential_configuration.has_key?(preferential)

  configuration = Configuration.new(self, preferential, options)
  yield configuration if block_given?
  preferential_configuration[preferential] = configuration

  # override hstore Hash with a custom Hash
  class_eval do 
    eval(
      <<-EOS
        def #{preferential}
          h = Reamaze::Opinionated::PrefHash.new self, "#{preferential}"
          h.replace self["#{preferential}"] if self["#{preferential}"]
          h
        end
      EOS
    )
  end
  
  # add form accessible attributes
  configuration.definitions.values.each do |definition|
    class_eval do 
      eval(
        <<-EOS
          def #{preferential}_#{definition.name}=(value)
            set_preferential('#{preferential}', '#{definition.name}', value, true)
          end
          def #{preferential}_#{definition.name}
            get_preferential('#{preferential}', '#{definition.name}', true)
          end
          def #{preferential}_#{definition.name}?
            !!get_preferential('#{preferential}', '#{definition.name}', true)
          end
        EOS
      )
    end
  end
end