diff options
author | Rafael França <rafaelmfranca@gmail.com> | 2019-04-23 10:53:31 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-04-23 10:53:31 -0400 |
commit | 3d0118f6d1ceaae48d1cdd70915b69da2871a735 (patch) | |
tree | 1dfbe711e087696074cf22e9609429cb99cd506c /activemodel/lib | |
parent | 3051007c6eb972566fde0df8b95a3dda10f33b25 (diff) | |
parent | e7a28c39908768acc1b8c836ab53af546c58c0c0 (diff) | |
download | rails-3d0118f6d1ceaae48d1cdd70915b69da2871a735.tar.gz rails-3d0118f6d1ceaae48d1cdd70915b69da2871a735.tar.bz2 rails-3d0118f6d1ceaae48d1cdd70915b69da2871a735.zip |
Merge pull request #36059 from composerinteralia/model-attribute-names
Add attribute_names to ActiveModel::Attributes
Diffstat (limited to 'activemodel/lib')
-rw-r--r-- | activemodel/lib/active_model/attributes.rb | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/activemodel/lib/active_model/attributes.rb b/activemodel/lib/active_model/attributes.rb index b7b2f35bcc..6048ff0113 100644 --- a/activemodel/lib/active_model/attributes.rb +++ b/activemodel/lib/active_model/attributes.rb @@ -26,6 +26,21 @@ module ActiveModel define_attribute_method(name) end + # Returns an array of attribute names as strings + # + # class Person + # include ActiveModel::Attributes + # + # attribute :name, :string + # attribute :age, :integer + # end + # + # Person.attribute_names + # # => ["name", "age"] + def attribute_names + attribute_types.keys + end + private def define_method_attribute=(name) @@ -65,10 +80,39 @@ module ActiveModel super end + # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. + # + # class Person + # include ActiveModel::Model + # include ActiveModel::Attributes + # + # attribute :name, :string + # attribute :age, :integer + # end + # + # person = Person.new(name: 'Francesco', age: 22) + # person.attributes + # # => {"name"=>"Francesco", "age"=>22} def attributes @attributes.to_hash end + # Returns an array of attribute names as strings + # + # class Person + # include ActiveModel::Attributes + # + # attribute :name, :string + # attribute :age, :integer + # end + # + # person = Person.new + # person.attribute_names + # # => ["name", "age"] + def attribute_names + @attributes.keys + end + private def write_attribute(attr_name, value) |