Module: MundoPepino::Base
- Included in:
- MundoPepino
- Defined in:
- lib/mundo_pepino/base.rb
Instance Method Summary collapse
- #conditions_from_attributes(attributes) ⇒ Object
- #create(model, raw_attributes = {}) ⇒ Object
- #find_or_create(model_or_modelo, attributes = {}, options = {}) ⇒ Object
- #parsed_attributes(raw_attributes) ⇒ Object
Instance Method Details
#conditions_from_attributes(attributes) ⇒ Object
123 124 125 126 |
# File 'lib/mundo_pepino/base.rb', line 123 def conditions_from_attributes(attributes) attribs = attributes.reject {|k,v| k == :through} [attribs.keys.map{|s| "#{s}=?"}.join(' AND ')] + attribs.values end |
#create(model, raw_attributes = {}) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/mundo_pepino/base.rb', line 74 def create(model, raw_attributes = {}) through = raw_attributes.delete(:through) attributes = parsed_attributes(raw_attributes) obj = if defined?(FixtureReplacement) self.send "create_#{model.name.underscore}", attributes elsif defined?(Machinist) model.make attributes elsif defined?(Factory) Factory(model.name.underscore.to_sym, attributes) else model.create! attributes end if(through) create through['model'], through['attributes'].merge(model.name.underscore.to_sym => obj) end obj end |
#find_or_create(model_or_modelo, attributes = {}, options = {}) ⇒ Object
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/mundo_pepino/base.rb', line 92 def find_or_create(model_or_modelo, attributes = {}, = {}) model = if model_or_modelo.is_a?(String) model_or_modelo.to_model else model_or_modelo end if attributes.any? attribs = Hash.new attributes.each do |key, value| if child_model = (key.to_s.to_model || key.to_s.to_relation_model) child = add_resource(child_model, field_for(child_model) => value) field_name = key.to_s.to_relation_model ? key : child_model.name.underscore attribs["#{field_name}_id"] = child.id else attribs[key] = value end end if (([:force_creation].nil? || ![:force_creation]) && obj = model.find(:first, :conditions => conditions_from_attributes(attribs))) if(through = attribs[:through]) create through['model'], through['attributes'].merge(model.name.underscore.to_sym => obj) end obj else create model, attribs end else create model end end |
#parsed_attributes(raw_attributes) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/mundo_pepino/base.rb', line 58 def parsed_attributes(raw_attributes) attributes = {} raw_attributes.each do |k, v| if k =~ /^(.+)_id$/ if polymorph = raw_attributes.delete($1 + '_type') attributes[$1.to_sym] = polymorph.constantize.find(v.to_i) else attributes[$1.to_sym] = ($1.to_relation_model || $1.camelize.constantize).find(v.to_i) end else attributes[k] = real_value_for(v) end end attributes end |