charlypoly / attr_bitwise

Bitwise attribute for ruby class and Rails model
MIT License
68 stars 9 forks source link

User Defined Mappings #8

Closed scottwater closed 8 years ago

scottwater commented 8 years ago

I wanted to ensure we could explicitly manage our mapping values.

Example:

attr_bitwise :fruits, mapping: {banana: 2, kiwi: 4, apple: 1}

I forked the project and created a branch with this work.

See: https://github.com/scottwater/attr_bitwise/tree/define_values

Would you be interested in a pull request? If so, any suggestion for how you would want to see the specs? Currently I simply copied the existing specs and updated them for the more defined mapping.

charlypoly commented 8 years ago

Hi @scottwater,

Thanks for your fork !

Your feature looks great but how do you ensure that "user defined values" are power of 2 ? (if it's not the case, the lib may have strange behaviour because of the dependency on bitwise operations)

scottwater commented 8 years ago

@wittydeveloper I guess I could add a check to ensure they are properly set.

Here is quick validation method:

    def validate_user_defined_values(hash, name)
      hash.select{|key,value| (Math.log2(value) % 1.0)!=0}.tap do |invalid_options|
        if invalid_options.count > 1
          raise(ArgumentError, "#{invalid_options.to_s} are not valid log2 options for #{name}")
        end
      end
    end

Although, I suspect you would see a failure pretty quickly yourself even without the validation.

I updated my fork with the above code and a test to verify it is working.

charlypoly commented 8 years ago

@scottwater great !

Just a quick "wording issue", I will make the error message more clear like :

raise(ArgumentError, "#{name} value should be a power of two number")

scottwater commented 8 years ago

@wittydeveloper I made the error message change. I left the list of invalid values as well since I figured this would make it much easier to spot the issue in a long list.

Here is the pull request. #9

Thanks, Scott

P.S. I made no changes to version numbers.