Created
November 18, 2015 02:49
-
-
Save grimmwerks/8ea0985817fb90bf4388 to your computer and use it in GitHub Desktop.
A base product where I'm allowing x amounts of location and feedback as enums and saved via bitmasking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseProduct < ActiveRecord::Base | |
enum location: { unknown: 0, upper: 1, middle: 2, lower: 3} | |
enum feedback: { light: 1, vibration: 2} | |
# has_many :sensor_locations | |
has_many :products | |
def sensor_locations=(sensor_locations) | |
self.locations_mask = (sensor_locations & BaseProduct.locations.keys).map { |r| 2**BaseProduct.locations.keys.index(r) }.sum | |
end | |
def sensor_locations | |
BaseProduct.locations.reject { |r| ((locations_mask.to_i || 0) & 2**BaseProduct.locations.keys.index(r)).zero? } | |
end | |
def product_feedbacks=(product_feedbacks) | |
self.feedbacks_mask = (product_feedbacks & BaseProduct.feedbacks.keys).map { |r| 2**BaseProduct.feedbacks.keys.index(r) }.sum | |
end | |
def product_feedbacks | |
BaseProduct.feedbacks.reject { |r| ((feedbacks_mask.to_i || 0) & 2**BaseProduct.feedbacks.keys.index(r)).zero? } | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# also use things like the following in product which is based off of a base_product (base_product is sort of a prototype / template) | |
def active_feedback=(active_feedback) | |
self.feedback = (active_feedback & BaseProduct.feedbacks.keys).map { |r| 2**BaseProduct.feedbacks.keys.index(r) }.sum | |
end | |
def active_feedback | |
BaseProduct.feedbacks.reject { |r| ((feedback.to_i || 0) & 2**BaseProduct.feedbacks.keys.index(r)).zero? } | |
end | |
def feedback_states | |
# need to return base_product product_feedbacks.keys as true / false | |
ret = Array.new | |
self.base_product.product_feedbacks.map{|key,enum| ret<<{'name'=>key, 'value'=>enum, | |
'active'=> self.active_feedback.keys.include?(key)} } | |
return ret | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment