Class: Modelish::Base

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

Overview

Base class for all modelish objects

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.



17
18
19
20
21
22
# File 'lib/modelish/base.rb', line 17

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

  attributes = options ? options.dup : {}
  init_attributes(attributes)
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



121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/modelish/base.rb', line 121

def property(name, options = {})
  # Hashie::Dash.property deletes the :required key from the options
  required = options[:required]
  super

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

  process_required(name) if required
  process_max_length(name, options)
  process_validate_type(name, options)

  add_validator(name, &options[:validator]) if options[:validator]
end

Instance Method Details

#[]=(property, value) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/modelish/base.rb', line 33

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



27
28
29
30
31
# File 'lib/modelish/base.rb', line 27

def to_hash
  out = {}
  self.class.properties.each { |p| out[hash_key(p)] = hash_value(p) }
  out
end