Sha256: 66403f8b4e87677814c1fd7f303a2f582a3f18f6ca9706385aec4ea20bda48ba

Contents?: true

Size: 1.4 KB

Versions: 5

Compression:

Stored size: 1.4 KB

Contents

# TODO allow a :type option and typecast the value

module HasOptions
  class << self
    def included(base)
      base.class_eval do
        extend ClassMethods
        class_attribute :option_definitions
        self.option_definitions = {}
        serialize :options
      end
    end

    module ClassMethods
      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
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
adva-0.1.4 lib/has_options.rb
adva-0.1.3 lib/has_options.rb
adva-0.1.2 lib/has_options.rb
adva-0.1.1 lib/has_options.rb
adva-0.1.0 lib/has_options.rb