Skip to content

Commit

Permalink
map_belongs_to now maps the association to (and from) the model objec…
Browse files Browse the repository at this point in the history
…t, not its id
  • Loading branch information
malakai97 committed Nov 14, 2016
1 parent cacba4e commit a1bf1e4
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 9 deletions.
7 changes: 3 additions & 4 deletions lib/rails_view_adapters/definition_proxy.rb
Expand Up @@ -94,18 +94,17 @@ def map_bool(model_field, public_field)
def map_belongs_to(model_field, public_field, options = {})
model_class = options[:model_class] || model_field.to_s.classify.constantize
sub_method = options[:sub_method] || :id
model_field_id = :"#{model_field.to_s.sub(/(_id|)\Z/, "_id")}"

unless options[:only] == :to
map_from_public public_field do |value|
record = model_class.send(:"find_by_#{sub_method}", value)
{ model_field_id => record ? record.id : nil }
{ model_field => record ? record : model_class.new(sub_method => value) }
end
end

unless options[:only] == :from
map_to_public model_field_id do |id|
{ public_field => model_class.find_by(id: id).send(sub_method) }
map_to_public model_field do |record|
{ public_field => record.send(sub_method) }
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/rails_view_adapters/version.rb
@@ -1,4 +1,4 @@
# frozen_string_literal: true
module RailsViewAdapters
VERSION = "0.2.4"
VERSION = "0.3.0"
end
2 changes: 1 addition & 1 deletion spec/integration/an_adapter_spec.rb
Expand Up @@ -40,7 +40,7 @@ module RailsViewAdapters
join_date: @model.join_date,
admin: @model.admin,
secret: @model.secret,
team_id: @model.team_id,
team: @model.team,
posts: @model.posts,
created_at: @model.created_at,
updated_at: @model.updated_at
Expand Down
6 changes: 3 additions & 3 deletions spec/lib/definition_proxy_spec.rb
Expand Up @@ -190,13 +190,13 @@ def to_hash
end
it "defines a to_map that converts the model's parent to the public's field:value string" do
proxy.map_belongs_to(model_field, public_field, options)
expect(proxy.map.to_maps[0][1].call(post.user.id))
expect(proxy.map.to_maps[0][1].call(post.user))
.to eql(public_field => post.user.name)
end
it "defines a from_map that converts the public's string to the model's owning model id" do
it "defines a from_map that converts the public's string to the model's owning model object" do
proxy.map_belongs_to(model_field, public_field, options)
expect(proxy.map.from_maps[0][1].call(post.user.name))
.to eql(model_field => post.user.id)
.to eql(model_field => post.user)
end
end

Expand Down

0 comments on commit a1bf1e4

Please sign in to comment.