lib/chop/builder.rb in chop-0.8.0 vs lib/chop/builder.rb in chop-0.9.0

- old
+ new

@@ -1,30 +1,50 @@ +require "active_support/core_ext/string/inflections" +require "active_support/core_ext/object/blank" + module Chop class Builder < Struct.new(:table, :klass, :block) def self.build! table, klass, &block new(table, klass, block).build! end attr_accessor :transformations - def initialize(*) + def initialize(*, &other_block) super self.transformations = [] instance_eval &block if block.respond_to?(:call) + instance_eval &other_block if block_given? end - def build! - table.hashes.map do |attributes| + def build! cucumber_table = table + cucumber_table.hashes.map do |attributes| transformations.each { |transformation| transformation.call(attributes) } - klass.create! attributes + if klass.is_a?(Hash) + if factory = klass[:factory_girl] + FactoryGirl.create factory, attributes + else + raise "Unknown building strategy" + end + else + klass.create! attributes + end end end def transformation &block transformations << block end + def rename mappings + transformation do |attributes| + mappings.each do |old, new| + attributes[new.to_s] = attributes.delete(old.to_s) if attributes.key?(old.to_s) + end + end + end + def field attribute, default: "" transformation do |attributes| attributes[attribute.to_s] = yield(attributes.fetch(attribute.to_s, default)) end end @@ -64,10 +84,10 @@ end end def has_one key, klass=nil, name_field: :name field key do |name| - klass.find_by!(name_field => name) + klass.find_by!(name_field => name) if name.present? end end alias_method :belongs_to, :has_one end end