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

.attr_accessor(*args) ⇒ Object



39
40
41
42
# File 'lib/yukata/base.rb', line 39

def self.attr_accessor(*args)
  args.each { |name| self.attributes[name] = Attribute.new(Object) }
  super
end

.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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/yukata/base.rb', line 49

def self.attribute(name, type=String, options={})
  config = { writer: true, reader: true, coerce: true }.merge(options)

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

  # -------------
  # Define Writer
  # -------------
  if config[:writer]
    define_method("#{name}=") do |object|
      if config[:coerce]
        val = Yukata.coercer.coerce(object, attr.type)
        instance_variable_set(variable, val)
      else
        instance_variable_set(variable, object)
      end
    end
  end

  # -------------
  # Define reader
  # -------------
  if config[:reader]
    define_method(name) do
      val = instance_variable_get(variable)
      unless val
        val = attr.default
        instance_variable_set(variable, val)
      end
      val
    end
  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] = send(k) if respond_to?(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