Lots of fields in a model, but want to have a public / private attribute for all of them
I have a model where almost every field needs to have a public / private flag (boolean) for each item. At first I thought I'd make a boolean for each 开发者_开发百科field, however, I am not sure if thats the best way of handeling this. Is there a better way? I'm up for all suggestions.
I suppose it would depend on several things, among which would be who would change it and how often it would need to be changed. If this is just configuration that would change rarely, if at all - then I would put it in a configuration file or initializer of some kind:
PUBLIC_FIELDS = %w(field_one, field_two, field_three)
PRIVATE_FIELDS = %w(field_four, field_five, field_six)
If this is something that was going to be dynamic and static to the application with users being able to modify the information regularly, I would opt for a separate model, called field_visibility
, with the following fields field_name
, visibility
. I would load the fields in initially as seed data and then give the user a UI to modify. I would give the model two named scopes:
named_scope :public_fields, :conditions => {:visiblity => 'public'}
named_scope :private_fields, :conditions => {:visiblity => 'private'}
You could of course use a bit field in place of a string. You can also add a table name to the model if this were to stretch to additional models.
Then in the model that this pertains to, you could do a few things to reference back. including named scopes:
named_scope :public_fields, :select => FieldVisiblity.public_fields
individual functions, metaprogramming... This also lends itself to possible enhancements down the road.
I hope this helps!
I would better encapsulate your class by making all your variables private and providing get methods for each variable. This also makes it easier to add variables later on.
You could also use a flagmap (see dm-types how it would work) and an Array in each class which defines the position of the columns in the flagmap. Then overwrite the attribute readers to return nil unless @visible
is set to true if the field is marked private via the flag map. Happy bitshifting ;-)
精彩评论