Module: Adva::HasOptions::ClassMethods

Defined in:
lib/adva/has_options.rb

Instance Method Summary collapse

Instance Method Details

#has_option(*names) ⇒ Object



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
# File 'lib/adva/has_options.rb', line 12

def has_option(*names)
  definition = names.extract_options!
  names.each do |name|
    self.option_definitions[name] = definition.reverse_update(:default => nil, :type => :text_field)
    class_eval <<-src, __FILE__, __LINE__
      def #{name}
        #{name}_before_type_cast
      end

      def #{name}_before_type_cast
        self.options ||= {}
        options.key?(:#{name}) ? options[:#{name}] : self.class.option_definition(:#{name}, :default)
      end

      def #{name}=(value)
        options_will_change!
        if self.class.option_definition(:#{name}, :type) == :boolean
          value = ActiveRecord::Type::Boolean.new.cast(value)
        end
        self.options ||= {}
        options[:#{name}] = value
      end
    src
  end

  def option_definition(name, key)
    option_definitions[name][key]
  rescue
    superclass.option_definition(name, key) unless self.class.superclass == ActiveRecord::Base
  end
end

#option_definition(name, key) ⇒ Object



37
38
39
40
41
# File 'lib/adva/has_options.rb', line 37

def option_definition(name, key)
  option_definitions[name][key]
rescue
  superclass.option_definition(name, key) unless self.class.superclass == ActiveRecord::Base
end