lib/dir_model/model/relations.rb in dir_model-0.5.2 vs lib/dir_model/model/relations.rb in dir_model-0.6.0
- old
+ new
@@ -19,13 +19,17 @@
# Appends model to the parent and returns it
#
# @return [Model] return the child if it is valid, otherwise returns nil
def append_dir_model(source_path, options={})
relation_name = self.class.has_one_relationship.keys.first
- related_class = self.class.has_one_relationship.values.first
+ _options = self.class.has_one_relationship.values.first
+ related_class = _options[:dir_model_class]
+ foreign_key = _options[:foreign_key]
+ foreign_value = self.send(foreign_key)
- related_dir_model = related_class.new(source_path, options.reverse_merge(parent: self))
+ related_dir_model = related_class.new(source_path,
+ options.reverse_merge(parent: self, foreign_value: foreign_value))
return unless related_dir_model
unless related_dir_model.skip?
if public_send(relation_name).present?
@@ -72,16 +76,16 @@
class_methods do
# Defines a relationship between a dir model
#
# @param [Symbol] relation_name the name of the relation
# @param [DirModel::Import] dir_model_class class of the relation
- def has_one(relation_name, dir_model_class)
+ def has_one(relation_name, dir_model_class, options)
raise "for now, DirModel's has_one may only be called once" if @_has_one_relationship.present?
relation_name = relation_name.to_sym
- merge_has_one_relationship(relation_name => dir_model_class)
+ merge_has_one_relationship(relation_name => { dir_model_class: dir_model_class }.merge(options))
define_method(:has_one?) do
true
end
@@ -92,10 +96,14 @@
define_method(relation_name) do
instance_variable_get("@#{relation_name}")
end
end
+ def has_one?
+ !!@_has_one_relationship
+ end
+
# Defines a relationship between a dir model
#
# @param [Symbol] relation_name the name of the relation
# @param [DirModel::Import] dir_model_class class of the relation
# @param [Hash] basically for set :foreign_key
@@ -115,9 +123,17 @@
# equal to: @relation_name ||= []
#
variable_name = "@#{relation_name}"
instance_variable_get(variable_name) || instance_variable_set(variable_name, [])
end
+ end
+
+ def has_many?
+ !!@_has_many_relationship
+ end
+
+ def has_relations?
+ has_one? || has_many?
end
end
end
end
end