Class: Yukata::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/yukata/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Base

Returns a new instance of Base.

Parameters:

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

    the parameters you wish to initialize the model with. If the model does not have an accessor set, it will ignore the attribute passed.



6
7
8
# File 'lib/yukata/base.rb', line 6

def initialize(params={})
  self.attributes = params
end

Class Method Details

.attribute(name, type = String, options = {}) ⇒ Object

Declares an attribute on the model

Parameters:

  • name (String)
  • type (Class) (defaults to: String)

    a class that represents the type

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

    extra options to apply to the attribute



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/yukata/base.rb', line 43

def self.attribute(name, type=String, options={})
  attr = Attribute.new(type, options)
  self.attributes[name] = attr
  variable = "@#{name}"

  define_method("#{name}=") do |object|
    val = Yukata.coercer.coerce(object, attr.type)
    instance_variable_set(variable, val)
  end

  define_method(name) do
    val = instance_variable_get(variable)
    unless val
      val = attr.default
      instance_variable_set(variable, val)
    end
    val
  end

end

.attributesObject



34
35
36
# File 'lib/yukata/base.rb', line 34

def self.attributes
  @attributes ||= {}
end

Instance Method Details

#attributesHash

Get the attributes on the model. If the attribute was not

Returns:

  • (Hash)


22
23
24
25
26
27
28
# File 'lib/yukata/base.rb', line 22

def attributes
  hash = {}
  self.class.attributes.keys.each do |k|
    hash[k] = self.send(k)
  end
  hash
end

#attributes=(hash) ⇒ Object

Sets the attributes on the model

Parameters:

  • hash (Hash)


12
13
14
15
16
17
# File 'lib/yukata/base.rb', line 12

def attributes=(hash)
  hash.each do |k, v|
    setter = "#{k}="
    self.send(setter, v) if self.respond_to?(setter)
  end
end

#to_hObject



30
31
32
# File 'lib/yukata/base.rb', line 30

def to_h
  self.attributes
end