form_configurable.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. module FormConfigurable
  2. extend ActiveSupport::Concern
  3. included do
  4. class_attribute :_form_configurable_fields
  5. self._form_configurable_fields = HashWithIndifferentAccess.new { |h,k| h[k] = [] }
  6. end
  7. delegate :form_configurable_attributes, to: :class
  8. delegate :form_configurable_fields, to: :class
  9. def is_form_configurable?
  10. true
  11. end
  12. def validate_option(method)
  13. if self.respond_to? "validate_#{method}".to_sym
  14. self.send("validate_#{method}".to_sym)
  15. else
  16. false
  17. end
  18. end
  19. def complete_option(method)
  20. if self.respond_to? "complete_#{method}".to_sym
  21. self.send("complete_#{method}".to_sym)
  22. end
  23. end
  24. module ClassMethods
  25. def form_configurable(name, *args)
  26. options = args.extract_options!.reverse_merge(roles: [], type: :string)
  27. if args.all? { |arg| arg.is_a?(Symbol) }
  28. options.assert_valid_keys([:type, :roles, :values])
  29. end
  30. if options[:type] == :array && (options[:values].blank? || !options[:values].is_a?(Array))
  31. raise ArgumentError.new('When using :array as :type you need to provide the :values as an Array')
  32. end
  33. if options[:roles].is_a?(Symbol)
  34. options[:roles] = [options[:roles]]
  35. end
  36. _form_configurable_fields[name] = options
  37. end
  38. def form_configurable_fields
  39. self._form_configurable_fields
  40. end
  41. def form_configurable_attributes
  42. form_configurable_fields.keys
  43. end
  44. end
  45. end