Class: Factory
- Inherits:
-
Object
- Object
- Factory
- Defined in:
- lib/rails_factory/factory.rb
Class Method Summary collapse
- .attributes(*args, &block) ⇒ Object
- .before_create(*args, &block) ⇒ Object
- .create_record(model, attrs = {}) ⇒ Object
- .define(&block) ⇒ Object
- .method_missing(name, *args, &block) ⇒ Object
- .new_record(model, attrs = {}) ⇒ Object
- .record_hash(model, attrs = {}) ⇒ Object
Class Method Details
.attributes(*args, &block) ⇒ Object
8 9 10 11 |
# File 'lib/rails_factory/factory.rb', line 8 def attributes(*args, &block) model = check_model(args[0]) model[:attributes] = block end |
.before_create(*args, &block) ⇒ Object
13 14 15 16 |
# File 'lib/rails_factory/factory.rb', line 13 def before_create(*args, &block) model = check_model(args[0]) model[:before_create] = block end |
.create_record(model, attrs = {}) ⇒ Object
22 23 24 25 26 27 |
# File 'lib/rails_factory/factory.rb', line 22 def create_record(model, attrs={}) record = new_record(model, attrs) @@models[model][:before_create].call(record) if @@models[model].has_key? :before_create record.save record end |
.define(&block) ⇒ Object
4 5 6 |
# File 'lib/rails_factory/factory.rb', line 4 def define(&block) class_eval &block end |
.method_missing(name, *args, &block) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/rails_factory/factory.rb', line 33 def method_missing(name, *args, &block) if name.to_s.start_with?('new_') call = :new_record regex = /new_(.+)/ elsif name.to_s.start_with?('create_') call = :create_record regex = /create_(.+)/ elsif name.to_s.end_with?('_hash') call = :record_hash regex = /(.+)_hash/ end model = name.to_s.match(regex)[1].to_sym send(call, *([model] | args), &block) end |
.new_record(model, attrs = {}) ⇒ Object
18 19 20 |
# File 'lib/rails_factory/factory.rb', line 18 def new_record(model, attrs={}) model.to_s.camelize.constantize.new record_hash(model, attrs) end |
.record_hash(model, attrs = {}) ⇒ Object
29 30 31 |
# File 'lib/rails_factory/factory.rb', line 29 def record_hash(model, attrs={}) @@models[model][:attributes].call.merge(attrs) end |