Class: Resto::Attributes

Inherits:
Object
  • Object
show all
Defined in:
lib/resto/attributes.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes, resource, property_handler = nil) ⇒ Attributes

Returns a new instance of Attributes.



5
6
7
8
9
10
11
12
13
# File 'lib/resto/attributes.rb', line 5

def initialize(attributes, resource, property_handler = nil)
  @resource = resource
  @property_handler = property_handler || resource.class.property_handler
  @attributes = {} # TODO must handle indifferent access :name and 'name'
  @attributes_before_cast = {}
  @errors = {}

  update_attributes(attributes)
end

Instance Method Details

#add_error(key, value) ⇒ Object



44
45
46
# File 'lib/resto/attributes.rb', line 44

def add_error(key, value)
  @errors.store(key, value)
end

#errorsObject



48
49
50
# File 'lib/resto/attributes.rb', line 48

def errors
  @errors.map {|key, value| value }.compact
end

#get(key) ⇒ Object



27
28
29
# File 'lib/resto/attributes.rb', line 27

def get(key)
  @attributes.fetch(key, nil)
end

#get_without_cast(key) ⇒ Object



31
32
33
# File 'lib/resto/attributes.rb', line 31

def get_without_cast(key)
   @attributes_before_cast.fetch(key, nil)
end

#present?(key) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/resto/attributes.rb', line 35

def present?(key)
  @attributes.fetch(key, false) ? true : false
end

#set(key, value) ⇒ Object



22
23
24
25
# File 'lib/resto/attributes.rb', line 22

def set(key, value)
  @attributes_before_cast.store(key, value)
  @attributes.store(key, @property_handler.cast(key, value, @errors))
end

#to_hashObject



52
53
54
# File 'lib/resto/attributes.rb', line 52

def to_hash
  @attributes.merge({})
end

#update_attributes(attributes) ⇒ Object



15
16
17
18
19
20
# File 'lib/resto/attributes.rb', line 15

def update_attributes(attributes)
  attributes.each do |key, value|
    key = @property_handler.attribute_key(key)
    set(key, value) if key
  end
end

#valid?Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/resto/attributes.rb', line 39

def valid?
  @property_handler.validate(@resource)
  errors.empty?
end