Module: SQLRecord::Attributes::Mapper

Included in:
Base
Defined in:
lib/sql_record/attributes/mapper.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#sql_select_columnsObject (readonly)

Returns the value of attribute sql_select_columns.



6
7
8
# File 'lib/sql_record/attributes/mapper.rb', line 6

def sql_select_columns
  @sql_select_columns
end

Instance Method Details

#column(attribute_name, opts = {}) ⇒ Object

Specifies the mapping from an ActiveRecord#column_definition to an SQLRecord instance attribute.

Examples:

Simple mapping

# Account#name column maps to the "name" attribute
column :name, :class => Account

Mapping a different column name

# Account#name column maps to the "account name" attribute
column :account_name, :class => Account, :from => :name

Parameters:

  • attribute_name (Symbol)

    the attribute you are defining for this model

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :class (Class)

    the active record this attribute will use to type_cast from

  • :from (Symbol, String)

    if it differs from the attribute_name, the schema column of the active record to use for type_cast

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sql_record/attributes/mapper.rb', line 52

def column attribute_name, opts = {}
  klass = opts[:class] || @default_opts[:class] || nil
  raise ArgumentError, 'You must specify a :class option, either explicitly, or using with_opts' if klass.nil?

  source_attribute = (opts[:from] || attribute_name).to_s

  define_method attribute_name do
    klass.columns_hash[source_attribute].type_cast(@raw_attributes[attribute_name.to_s])
  end

  # bit mucky, a lot here that feels like it should be a little method of its own
  select_column = "#{klass.table_name}.#{source_attribute}"
  select_column += " as #{attribute_name}" if opts[:from]
  (@sql_select_columns ||= []) << select_column
end

#with_class(klass, opts = {}, &block) ⇒ Object

Sugar for with



33
34
35
36
# File 'lib/sql_record/attributes/mapper.rb', line 33

def with_class klass, opts = {}, &block
  opts[:class] = klass
  with_opts opts, &block
end

#with_opts(opts, &block) ⇒ Object

with_opts blocks specify default options for calls to #column

Examples:

Longhand (not using with_opts)

column :name, :class => Account
column :id, :class => Account
...snip...
column :created_at, :class => Account

Shorthand (using with_opts)

with_opts :class => Account
  column :name
  column :id
  ...snip...
  column :created_at
end

Parameters:

  • opts (Hash)

    anything that #column supports. Currently this should only be :class



26
27
28
29
30
# File 'lib/sql_record/attributes/mapper.rb', line 26

def with_opts opts, &block
  @default_opts = opts
  block.arity == 2 ? yield(self) : self.instance_eval(&block)
  @default_opts = nil
end