solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 228 forks source link

Add method AttributeSet#names to return array of all attribute names #379

Open tracyloisel opened 7 years ago

tracyloisel commented 7 years ago

Returns all the attributes name defined on a Class

#
# @example
#   class User
#     include Virtus
#
#     attribute :name, String
#     attribute :age,  Integer
#   end
#
# @return [:name, :age]
#
# @api public
Roman2K commented 7 years ago

I think it's bloat as AttributeSet is already an enumerable of attributes that have a #name method. So AttributeSet#names doesn't bring anything not already easily accessible. You can already do:

User.attribute_set.map(&:name)  # => [:name, :age]
tracyloisel commented 7 years ago

I think a lot of people may find this feature useful so it should be part of the gem. Once it will a public method in AttributeSet class, it will be great to add the feature on the README.

In our case, we use Virtus in a ruby (ruby only) project. In some factory classes we want to permit the params with the strict list of attributes as described in our virtus classes. The 30 minutes we took to read the source code and write the method could benefit to all the community around Virtus.

Roman2K commented 7 years ago

Params whitelisting is your specific use case. If you find that you repeat SomeClass.attribute_set.map(&:name) in your code, then add a helper method to factor it out, in your code.

Otherwise, what stops you from adding more methods at the Virtus::AttributeSet-level (i.e. #names) for each Attribute-level method (i.e. #name). Why stop at #names when there are many more attribute methods?

That's why IMO, you're bloating a generic library for your specific needs.