Skip to content

Commit

Permalink
Deprecate extract! calling private methods
Browse files Browse the repository at this point in the history
Fix #140
  • Loading branch information
rwz committed Jul 27, 2013
1 parent ebf5460 commit b9e1953
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,9 @@ def array!(collection, *attributes, &block)
# json.(@person, :name, :age)
def extract!(object, *attributes)
if ::Hash === object
attributes.each { |attribute| _set_value attribute, object.fetch(attribute) }
_extract_hash_values(object, *attributes)
else
attributes.each { |attribute| _set_value attribute, object.send(attribute) }
_extract_method_values(object, *attributes)
end
end

Expand Down Expand Up @@ -285,6 +285,26 @@ def target!

private

def _extract_hash_values(object, *attributes)
attributes.each{ |key| _set_value key, object.fetch(key) }
end

def _extract_method_values(object, *attributes)
attributes.each do |method_name|
value = if object.respond_to?(method_name)
object.public_send(method_name)
else
message = "Private method #{method_name.inspect} was used to " +
'extract value. This will be an error in future versions of Jbuilder'

::ActiveSupport::Deprecation.warn message
object.send(method_name)
end

_set_value method_name, value
end
end

def _set_value(key, value)
raise NullError, key if @attributes.nil?
unless @ignore_nil && value.nil?
Expand Down
17 changes: 17 additions & 0 deletions test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ class JbuilderTest < ActiveSupport::TestCase
assert_equal 32, parsed['age']
end

test 'extracting from object using private method' do
person = Struct.new(:name) do
private
def age
32
end
end.new('David')

message = 'Private method :age was used to extract value. This will be' +
' an error in future versions of Jbuilder'

::ActiveSupport::Deprecation.expects(:warn).with(message)
json = Jbuilder.encode do |json|
json.extract! person, :name, :age
end
end

test 'extracting from object using call style for 1.9' do
person = Struct.new(:name, :age).new('David', 32)

Expand Down

0 comments on commit b9e1953

Please sign in to comment.