Class: Modelish::Base

Inherits:
Hashie::Dash
  • Object
show all
Extended by:
Configuration
Includes:
PropertyTranslations, PropertyTypes, Validations
Defined in:
lib/modelish/base.rb

Instance Attribute Summary

Attributes included from Configuration

#ignore_unknown_properties

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Configuration

configure, extended, ignore_unknown_properties!, raise_errors_on_unknown_properties!, reset

Methods included from Validations

#valid?, #validate, #validate!

Constructor Details

#initialize(options = {}, &block) ⇒ Base

Returns a new instance of Base.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/modelish/base.rb', line 14

def initialize(options={}, &block)
  super(&block)

  attributes = options ? options.dup : {}

  attributes.delete_if do |k,v|
    if self.class.translations.keys.include?(k.to_sym)
      self[k]=v
      true
    end
  end

  attributes.each_pair do |att, value|
    self[att] = value
  end
end

Class Method Details

.property(name, options = {}) ⇒ Object

Creates a new attribute.

Parameters:

  • name (Symbol)

    the name of the property

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

    configuration for the property

  • opts (Hash)

    a customizable set of options



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/modelish/base.rb', line 54

def self.property(name, options={})

  #Hashie::Dash.property is going to delete :required from the options hash
  required = options[:required]

  super

  add_property_type(name, options[:type]) if options[:type]
  add_property_translation(options[:from], name) if options[:from]

  if options[:required] || (self.respond_to?(:required?) && required?(name))
    add_validator(name) { |val| validate_required(name => val).first }
  end

  add_validator(name) { |val| validate_length(name, val, options[:max_length]) } if options[:max_length]
  add_validator(name, &options[:validator]) if options[:validator]
  add_validator(name) { |val| validate_type(name, val, options[:type]) } if options[:validate_type]
end

Instance Method Details

#[]=(property, value) ⇒ Object



90
91
92
93
94
95
96
# File 'lib/modelish/base.rb', line 90

def []=(property, value)
  if self.class.translations.keys.include?(property.to_sym)
    send("#{property}=", value)
  elsif property_exists?(property)
    super
  end
end

#to_hashHash

Convert this Modelish object into a vanilla Hash with stringified keys.

Returns:

  • (Hash)

    the hash of properties



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/modelish/base.rb', line 76

def to_hash
  out = {}
  self.class.properties.each do |p|
    val = self.send(p)
    if val.is_a?(Array)
      out[p.to_s]||=[]
      out[p.to_s].concat(val.collect{|x|x.respond_to?(:to_hash) ? x.to_hash : x})
    else
      out[p.to_s] = val.respond_to?(:to_hash) ? val.to_hash : val
    end
  end
  out
end