I am creating a module with one method, that when included in a class, the class will obtain a new field defined by the method.
i.e.
module HasColors
extend ActiveSupport::Concern
included do
def self.has_colors(
colors_array,
is_required: false,
default: [],
allow_empty: true,
)
field :colors, type: Array, default: default
validate :colors_are_valid, if: :colors_changed?
def colors_are_valid
return if colors.length == 0 && allow_empty
return unless colors.all?{|color| colors_array.includes?(color) }
errors.add(
:colors,
"Please include valid colors: #{colors_array.join(", ")}"
)
end
end
end
When called in a class:
class ColorPallete
include HasColors
has_colors(["green", "orange", "red"])
...
end
the problem I'm running into, is regarding the validation method inside the module.
The colors_are_valid method is not able to read any of the arguments defined in the has_colors method, i.e. allow_empty, colors_array, etc.
Is there a way I can access these arguments?