Class: MagicModels::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/magic_models/model.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, name) ⇒ Model

Returns a new instance of Model.



11
12
13
14
# File 'lib/magic_models/model.rb', line 11

def initialize(schema, name)
  @schema = schema
  @name   = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/magic_models/model.rb', line 6

def name
  @name
end

#schemaObject (readonly)

Returns the value of attribute schema.



6
7
8
# File 'lib/magic_models/model.rb', line 6

def schema
  @schema
end

Instance Method Details

#belongs_toObject Also known as: associations



38
39
40
41
42
# File 'lib/magic_models/model.rb', line 38

def belongs_to
  schema.foreign_keys(name).map do |fk|
    Associations::BelongsTo.new(fk)
  end
end

#defineObject



29
30
31
32
# File 'lib/magic_models/model.rb', line 29

def define
  schema.evaluate(render)
  constantize
end

#filenameObject



16
17
18
# File 'lib/magic_models/model.rb', line 16

def filename
  File.join(schema.destination, "#{model_name.underscore}.rb")
end

#model_nameObject



48
49
50
# File 'lib/magic_models/model.rb', line 48

def model_name
  name.singularize.camelize
end

#primary_keyObject



34
35
36
# File 'lib/magic_models/model.rb', line 34

def primary_key
  @primary_key ||= schema.primary_key(name)
end

#renderObject



20
21
22
# File 'lib/magic_models/model.rb', line 20

def render
  ERB.new(File.read(template)).result(binding)
end

#writeObject



24
25
26
27
# File 'lib/magic_models/model.rb', line 24

def write
  File.open(filename, 'w') { |f| f.write render }
  filename
end