Module: ActiveStoreAccessor

Defined in:
lib/active_store_accessor.rb

Instance Method Summary collapse

Instance Method Details

#active_store_accessor(column_name, attrs) ⇒ Object



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
47
48
49
50
# File 'lib/active_store_accessor.rb', line 8

def active_store_accessor(column_name, attrs)
  column = columns.detect { |column| column.name == column_name.to_s }
  if !column
    raise "[active_store_accessor] The column '#{column_name}' does not exist in the model #{name}."
  elsif column.type == :text
    serialize(column_name) unless serialized_attributes.include?(column_name.to_s)
  end

  store_accessor column_name, *attrs.keys

  attrs.each do |attr_name, options|
    options = { type: options.to_s } unless options.is_a?(Hash)
    type = options.fetch(:type) { raise ArgumentError, "please specify type of `#{ attr_name }` attribute" }.to_s

    config = if connection.respond_to?(:lookup_cast_type)
      column = connection.lookup_cast_type(type)
      [column.method(:type_cast_from_database), column.method(:type_cast_for_database)]
    else
      # time for activerecord is only a hours and minutes without date part
      # but for most rubist and rails developer it should contains a date too
      type = 'datetime' if type == 'time'
      args = [attr_name.to_s, options[:default], type]
      column = ActiveRecord::ConnectionAdapters::Column.new(*args)
      [column.method(:type_cast), column.method(:type_cast_for_write)]
    end

    config << options[:default]
    active_store_attributes[attr_name] = config

    _active_store_accessor_module.module_eval "      def \#{ attr_name }\n        getter, _, default = self.class.active_store_attributes[:\#{ attr_name }]\n        value = getter.call(super)\n        value.nil? ? default : value\n      end\n\n      def \#{ attr_name }=(value)\n        _, setter, _ = self.class.active_store_attributes[:\#{ attr_name }]\n        super setter.call(value)\n      end\n    RUBY\n  end\nend\n"

#active_store_attributesObject



2
3
4
5
6
# File 'lib/active_store_accessor.rb', line 2

def active_store_attributes
  return @active_store_attributes if @active_store_attributes

  @active_store_attributes = superclass.respond_to?(:active_store_attributes) ? superclass.active_store_attributes : {}
end