Class: Heresy::Schema::Fields

Inherits:
Object
  • Object
show all
Defined in:
lib/heresy/schema/fields.rb

Overview

This class is a helper for setting up fields in the model. This is likely called from the model class and never used directly:

class Entry < Heresy::Model
  fields do |f|
    f.field :title, :string
    f.string :body # Uses #string convenience method
  end
end

Defined Under Namespace

Modules: DateTime, Float, Integer

Constant Summary collapse

@@types =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Fields

Returns a new instance of Fields.



50
51
52
# File 'lib/heresy/schema/fields.rb', line 50

def initialize(model)
  @model = model
end

Class Method Details

.type(key, type = nil) ⇒ Object



40
41
42
43
# File 'lib/heresy/schema/fields.rb', line 40

def self.type(key, type = nil)
  class_eval "def #{key}(name) field(name, :#{key}) end"
  @@types[key] = type
end

.typesObject



39
# File 'lib/heresy/schema/fields.rb', line 39

def self.types() @@types end

Instance Method Details

#field(name, type_name) ⇒ Object

Adds a field of the given type to the model by creating an attribute reader and writer.



55
56
57
58
59
60
61
62
63
# File 'lib/heresy/schema/fields.rb', line 55

def field(name, type_name)
  if type = self.class.types[type_name]
    @model.send(:attr_reader, name)
    @model.class_eval "def #{name}=(v) @#{name} = self.class.body_fields[:#{name}].parse(v) end"
  else
    @model.send(:attr_accessor, name)
  end
  @model.body_fields[name] = type
end