setting.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # frozen_string_literal: true
  2. class UserSettings::Setting
  3. attr_reader :name, :namespace, :in
  4. def initialize(name, options = {})
  5. @name = name.to_sym
  6. @default_value = options[:default]
  7. @namespace = options[:namespace]
  8. @in = options[:in]
  9. end
  10. def inverse_of(name)
  11. @inverse_of = name.to_sym
  12. self
  13. end
  14. def value_for(name, original_value)
  15. value = begin
  16. if original_value.nil?
  17. default_value
  18. else
  19. original_value
  20. end
  21. end
  22. if !@inverse_of.nil? && @inverse_of == name.to_sym
  23. !value
  24. else
  25. value
  26. end
  27. end
  28. def default_value
  29. if @default_value.respond_to?(:call)
  30. @default_value.call
  31. else
  32. @default_value
  33. end
  34. end
  35. def type
  36. case default_value
  37. when TrueClass, FalseClass
  38. ActiveModel::Type::Boolean.new
  39. else
  40. ActiveModel::Type::String.new
  41. end
  42. end
  43. def type_cast(value)
  44. if type.respond_to?(:cast)
  45. type.cast(value)
  46. else
  47. value
  48. end
  49. end
  50. def to_a
  51. [key, default_value]
  52. end
  53. def key
  54. if namespace
  55. :"#{namespace}.#{name}"
  56. else
  57. name
  58. end
  59. end
  60. end