Class: MR::ReadModel::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/mr/read_model/fields.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type) ⇒ Field

Returns a new instance of Field.



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/mr/read_model/fields.rb', line 124

def initialize(name, type)
  @name = name.to_s
  @type = type.to_sym
  unless MR::TypeConverter.valid?(@type)
    raise InvalidFieldTypeError, "`#{@type}` is not a valid field type"
  end

  @method_name    = @name
  @ivar_name      = "@#{@name}"
  @attribute_name = @name
  @converter      = nil
end

Instance Attribute Details

#ivar_nameObject (readonly)

Returns the value of attribute ivar_name.



122
123
124
# File 'lib/mr/read_model/fields.rb', line 122

def ivar_name
  @ivar_name
end

#method_nameObject (readonly)

Returns the value of attribute method_name.



122
123
124
# File 'lib/mr/read_model/fields.rb', line 122

def method_name
  @method_name
end

#nameObject (readonly)

Returns the value of attribute name.



121
122
123
# File 'lib/mr/read_model/fields.rb', line 121

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



121
122
123
# File 'lib/mr/read_model/fields.rb', line 121

def type
  @type
end

#valueObject (readonly)

Returns the value of attribute value.



121
122
123
# File 'lib/mr/read_model/fields.rb', line 121

def value
  @value
end

Instance Method Details

#define_on(model_class) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
# File 'lib/mr/read_model/fields.rb', line 142

def define_on(model_class)
  field = self
  model_class.class_eval do

    define_method(field.method_name) do
      instance_variable_get(field.ivar_name) ||
      instance_variable_set(field.ivar_name, field.read(self.read_model_data))
    end

  end
end

#read(data) ⇒ Object



137
138
139
140
# File 'lib/mr/read_model/fields.rb', line 137

def read(data)
  @converter ||= MR::TypeConverter.new(determine_ar_column_class(data))
  @converter.send(@type, data[@attribute_name])
end