Instantly share code, notes, and snippets.

View set_associations.rb
def set_associations(inst)
@associations.each do |assoc|
relation_plural = assoc.supposed_table_name.to_s.pluralize
relation_singular = assoc.supposed_table_name.to_s
if inst.respond_to? relation_plural
inst.send(relation_plural).create(**assoc.attributes_to_columns)
elsif inst.respond_to? relation_singular
inst.send("#{relation_singular}=", assoc.create)
else
raise "#{model} doesnt have the relation #{relation}!"
View set_attributes.rb
def set_attributes(inst)
@attributes.each do |attr|
column = attr[:name]
raise unless inst.attributes.keys.include? column.to_s
value = attr[:value]
if value.respond_to? :call
inst[column] = value.call
else
inst[column] = value
end
View create_v2.rb
class Construction
# ...
def create
model = supposed_table_name.to_s.classify.constantize
inst = model.new
set_attributes(inst)
inst.save
set_associations(inst)
View create_1.rb
class ConstructionGirl
# ...
def self.create(name)
construction = @@constructions.find { |c| c.supposed_table_name == name }
raise "No structure found with name #{name}" unless construction
construction.create
end
end
View implicit.rb
class Construction
# ...
def add_attribute(name, value = nil, &block)
raise "Can not given value and block" if value && block_given?
to_pass = value || block
if to_pass.nil? && ConstructionGirl.registered?(name)
@associations << ConstructionGirl.structure_by_name(name)
else
add_attribute_value(name, to_pass)
end
View v8.rb
class Construction
attr_reader :supposed_table_name, :attributes, :associations
def initialize(supposed_table_name)
# ...
@associations = []
end
# ...
def with(assoc_name, &block)
View create_2.rb
structure :product do
product_type "Package"
name "Product 2"
price 11.20
owner
end
View create_1.rb
structure :owner do
# ...
with :product do
product_type "Type 2"
name "Product 3"
price 0
end
end
View v7.rb
class ConstructionGirl
@@constructions = []
def self.registered_structures
@@constructions
end
def self.registered?(name)
registered_structures.any? { |c| c.supposed_table_name === name }
end
View v6.rb
class DSL
# ...
def structure(name, &block)
raise "Structure #{name} already registered" if ConstructionGirl.registered? name
@local_construction = Construction.new(name)
@local_construction.instance_eval(&block) if block_given?
ConstructionGirl.register_structure(@local_construction)
end
end