1
0

form_configurable.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, :ace, :cache_response])
  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. if options[:type] == :array
  37. options[:roles] << :completable
  38. class_eval <<-EOF
  39. def complete_#{name}
  40. #{options[:values]}.map { |v| {text: v, id: v} }
  41. end
  42. EOF
  43. end
  44. _form_configurable_fields[name] = options
  45. end
  46. def form_configurable_fields
  47. self._form_configurable_fields
  48. end
  49. def form_configurable_attributes
  50. form_configurable_fields.keys
  51. end
  52. end
  53. end