Class: FormInput
- Inherits:
-
Object
- Object
- FormInput
- Includes:
- R18n::Helpers
- Defined in:
- lib/form_input/core.rb,
lib/form_input/r18n.rb,
lib/form_input/steps.rb,
lib/form_input/types.rb,
lib/form_input/version.rb,
lib/form_input/localize.rb
Overview
Version number.
Defined Under Namespace
Modules: StepMethods, Version Classes: Parameter
Constant Summary collapse
- DEFAULT_SIZE_LIMIT =
Default size limit applied to all input.
255- DEFAULT_FILTER =
Default input filter applied to all input.
->{ gsub( /\s+/, ' ' ).strip }
- DEFAULT_MIN_KEY =
Minimum hash key value we allow by default.
0- DEFAULT_MAX_KEY =
Maximum hash key value we allow by default.
( 1 << 64 ) - 1
- DEFAULT_ENCODING =
Encoding we convert all input request parameters into.
Encoding::UTF_8
- DEFAULT_ERROR_MESSAGES =
Hash mapping error codes to default error messages.
{ required_scalar: "%p is required", required_array: "%p are required", not_array: "%p are not an array", not_hash: "%p are not a hash", not_string: "%p is not a string", match_key: "%p contain invalid key", invalid_key: "%p contain invalid key", min_key: "%p contain too small key", max_key: "%p contain too large key", min_count: "%p must have at least", max_count: "%p may have at most", value_type: "%p like this is not valid", element_type: "%p contain invalid value", min_limit: "%p must be at least", max_limit: "%p may be at most", inf_limit: "%p must be greater than", sup_limit: "%p must be less than", invalid_encoding: "%p must use valid encoding", invalid_characters: "%p may not contain invalid characters", min_size: "%p must have at least", max_size: "%p may have at most", min_bytesize: "%p must have at least", max_bytesize: "%p may have at most", reject_msg: "%p like this is not allowed", match_msg: "%p like this is not valid", }
- MERGEABLE_OPTIONS =
Parameter options which can be merged together into an array when multiple option hashes are merged.
[ :check, :test ]
- LATIN_NAMES_RE =
Matches names using latin alphabet.
/\A[\p{Latin}\-\. ]+\z/u
- SIMPLE_EMAIL_RE =
Matches common email addresses. Note that it doesn't match all addresses allowed by RFC, though.
/\A[-_.=+%a-z0-9]+@(?:[-_a-z0-9]+\.)+[a-z]{2,4}\z/i- ZIP_CODE_RE =
Matches generic ZIP code. Note that the real format changes for each country.
/\A[A-Z\d]++(?:[- ]?[A-Z\d]+)*+\z/i- PHONE_NUMBER_FILTER =
Filter for phone numbers.
->{ gsub( /\s*[-\/\.]\s*/, '-' ).gsub( /\s+/, ' ' ).strip }
- PHONE_NUMBER_RE =
Matches generic phone number.
/\A\+?\d++(?:[- ]?(?:\d+|\(\d+\)))*+(?:[- ]?[A-Z\d]+)*+\z/i- INTEGER_ARGS =
Integer number.
{ filter: ->{ ( Integer( self, 10 ) rescue self ) unless empty? }, class: Integer, }
- FLOAT_ARGS =
Float number.
{ filter: ->{ ( Float( self ) rescue self ) unless empty? }, class: Float, }
- BOOL_ARGS =
Boolean value, displayed as a select menu.
{ type: :select, data: [ [ true, 'Yes' ], [ false, 'No' ] ], filter: ->{ self == 'true' unless empty? }, class: [ TrueClass, FalseClass ], }
- CHECKBOX_ARGS =
Boolean value, displayed as a checkbox.
{ type: :checkbox, filter: ->{ not empty? }, format: ->{ self if self }, class: [ TrueClass, FalseClass ], }
- EMAIL_ARGS =
Email.
{ match: SIMPLE_EMAIL_RE, }
- ZIP_ARGS =
Zip code.
{ match: ZIP_CODE_RE, }
- PHONE_ARGS =
Phone number.
{ filter: PHONE_NUMBER_FILTER, match: PHONE_NUMBER_RE, }
- TIME_FORMAT =
Full time format.
"%Y-%m-%d %H:%M:%S".freeze
- TIME_FORMAT_EXAMPLE =
Full time format example.
"YYYY-MM-DD HH:MM:SS".freeze
- TIME_ARGS =
Full time.
{ placeholder: TIME_FORMAT_EXAMPLE, filter: ->{ ( FormInput.parse_time!( self, TIME_FORMAT ) rescue self ) unless empty? }, format: ->{ utc.strftime( TIME_FORMAT ) rescue self }, class: Time, }
- US_DATE_FORMAT =
US date format.
"%m/%d/%Y".freeze
- US_DATE_FORMAT_EXAMPLE =
US date format example.
"MM/DD/YYYY".freeze
- US_DATE_ARGS =
Time in US date format.
{ placeholder: US_DATE_FORMAT_EXAMPLE, filter: ->{ ( FormInput.parse_time!( self, US_DATE_FORMAT ) rescue self ) unless empty? }, format: ->{ utc.strftime( US_DATE_FORMAT ) rescue self }, class: Time, }
- UK_DATE_FORMAT =
UK date format.
"%d/%m/%Y".freeze
- UK_DATE_FORMAT_EXAMPLE =
UK date format example.
"DD/MM/YYYY".freeze
- UK_DATE_ARGS =
Time in UK date format.
{ placeholder: UK_DATE_FORMAT_EXAMPLE, filter: ->{ ( FormInput.parse_time!( self, UK_DATE_FORMAT ) rescue self ) unless empty? }, format: ->{ utc.strftime( UK_DATE_FORMAT ) rescue self }, class: Time, }
- EU_DATE_FORMAT =
EU date format.
"%-d.%-m.%Y".freeze
- EU_DATE_FORMAT_EXAMPLE =
EU date format example.
"D.M.YYYY".freeze
- EU_DATE_ARGS =
Time in EU date format.
{ placeholder: EU_DATE_FORMAT_EXAMPLE, filter: ->{ ( FormInput.parse_time!( self, EU_DATE_FORMAT ) rescue self ) unless empty? }, format: ->{ utc.strftime( EU_DATE_FORMAT ) rescue self }, class: Time, }
- HOURS_FORMAT =
Hours format.
"%H:%M".freeze
- HOURS_FORMAT_EXAMPLE =
Hours format example.
"HH:MM".freeze
- HOURS_ARGS =
Seconds since midnight in hours:minutes format.
{ placeholder: HOURS_FORMAT_EXAMPLE, filter: ->{ ( FormInput.parse_time( self, HOURS_FORMAT ).to_i % 86400 rescue self ) unless empty? }, format: ->{ Time.at( self ).utc.strftime( HOURS_FORMAT ) rescue self }, class: Integer, }
- PRUNED_ARGS =
Transformation which drops empty values from hashes and arrays and turns empty string into nil.
{ transform: ->{ case self when Array reject{ |v| v.nil? or ( v.respond_to?( :empty? ) && v.empty? ) } when Hash reject{ |k,v| v.nil? or ( v.respond_to?( :empty? ) && v.empty? ) } when String self unless empty? else self end } }
Class Method Summary collapse
-
.[](*names) ⇒ Object
Get given parameter(s), hash style.
-
.add(param) ⇒ Object
Add given parameter to the form, after performing basic validity checks.
-
.array(name, *args, &block) ⇒ Object
Like param, except that it defines array parameter.
-
.array!(name, *args, &block) ⇒ Object
Like param!, except that it defines required array parameter.
-
.copy(source, opts = {}) ⇒ Object
Copy given/all form parameters.
-
.default_translation(forms = self.forms) ⇒ Object
Get string containing YAML representation of the default R18n translation for all/given FormInput classes.
-
.define_steps(steps) ⇒ Object
Turn this form into multi-step form using given steps.
-
.find_inflection(string) ⇒ Object
Iterate over each possible inflection for given inflection string and return first non-nil result.
-
.form_params ⇒ Object
Get hash mapping parameter names to parameters themselves.
-
.form_steps ⇒ Object
Get hash mapping defined steps to their names, or nil if there are none.
-
.forms ⇒ Object
Get list of all classes inherited from FormInput.
-
.from_hash(hash) ⇒ Object
Create new form from hash with internal values.
-
.from_params(params) ⇒ Object
(also: from_data)
Create new form from hash with external values.
-
.from_request(request) ⇒ Object
Create new form from request with external values.
-
.hash(name, *args, &block) ⇒ Object
Like param, except that it defines hash parameter.
-
.hash!(name, *args, &block) ⇒ Object
Like param!, except that it defines required hash parameter.
-
.inherited(into) ⇒ Object
Create standalone copy of form parameters in case someone inherits an existing form.
-
.param(name, *args, &block) ⇒ Object
Define form parameter with given name, code, title, maximum size, options, and filter block.
-
.param!(name, *args, &block) ⇒ Object
Like param, except this defines required parameter.
-
.parse_time(string, format) ⇒ Object
Parse time like Time#strptime but raise on trailing garbage.
-
.parse_time!(string, format) ⇒ Object
Like parse_time, but falls back to DateTime.parse heuristics when the date/time can't be parsed.
-
.translation_hash ⇒ Object
Get hash of all form values which may need to be localized.
-
.translation_name ⇒ Object
Get name of the form used as translation scope for text translations.
-
.translations_path ⇒ Object
Get path to R18n translations provided by this gem.
Instance Method Summary collapse
-
#[](*names) ⇒ Object
Get given parameter(s) value(s), hash style.
-
#[]=(name, value) ⇒ Object
Set given parameter value, hash style.
-
#array_params ⇒ Object
(also: #array_parameters)
Get list of array parameters.
-
#blank_params ⇒ Object
(also: #blank_parameters)
Get list of parameters with blank values.
-
#build_url(url, args = {}) ⇒ Object
Build URL from given URL and combination of current paramaters and provided parameters.
-
#chunked_params(params = self.params) ⇒ Object
Get all/given parameters chunked into individual rows for nicer form display.
-
#clear(*names) ⇒ Object
Clear all/given parameter values.
-
#correct_params ⇒ Object
(also: #correct_parameters)
Get list of parameters with correct value types.
-
#disabled_params ⇒ Object
(also: #disabled_parameters)
Get list of disabled parameters.
-
#empty? ⇒ Boolean
Return true if all parameters are empty.
-
#empty_params ⇒ Object
(also: #empty_parameters)
Get list of parameters with empty values.
-
#enabled_params ⇒ Object
(also: #enabled_parameters)
Get list of enabled parameters.
-
#error_for(name) ⇒ Object
Get first error for given parameter.
-
#error_messages ⇒ Object
Get list of error messages, but including only the first one reported for each parameter.
-
#errors ⇒ Object
Get hash of all errors detected for each parameter.
-
#errors_for(name) ⇒ Object
Get list of errors for given parameter.
-
#except(*names) ⇒ Object
Create copy of itself, with given parameters unset.
-
#extend_url(url) ⇒ Object
Extend given URL with query created from all current non-empty parameters.
-
#filled_params ⇒ Object
(also: #filled_parameters)
Get list of parameters with non-empty values.
-
#freeze ⇒ Object
Freeze the form.
-
#ft(*args) ⇒ Object
Like t helper, except that the translation is looked up in the forms.
scope. -
#hash_params ⇒ Object
(also: #hash_parameters)
Get list of hash parameters.
-
#hidden_params ⇒ Object
(also: #hidden_parameters)
Get list of hidden parameters.
-
#ignored_params ⇒ Object
(also: #ignored_parameters)
Get list of ignored parameters.
-
#import(request) ⇒ Object
Import parameter values from given request or hash.
-
#incorrect_params ⇒ Object
(also: #incorrect_parameters)
Get list of parameters with incorrect value types.
-
#initialize(*args) ⇒ FormInput
constructor
Create new form info, initializing it from given hash or request, if anything.
-
#initialize_clone(other) ⇒ Object
Initialize form clone.
-
#initialize_dup(other) ⇒ Object
Initialize form copy.
-
#invalid?(*names) ⇒ Boolean
Test if there were some errors (overall or for given parameters) reported.
-
#invalid_params ⇒ Object
(also: #invalid_parameters)
Get list of parameters with some errors reported.
-
#named_params(*names) ⇒ Object
(also: #named_parameters)
Get list of given named parameters.
-
#only(*names) ⇒ Object
Create copy of itself, with only given parameters set.
-
#optional_params ⇒ Object
(also: #optional_parameters)
Get list of optional parameters.
-
#param(name) ⇒ Object
(also: #parameter)
Get given named parameter.
-
#params ⇒ Object
(also: #parameters)
Get list of all parameters.
-
#params_names ⇒ Object
(also: #parameters_names)
Get list of all parameter names.
-
#report(name, msg) ⇒ Object
Remember error concerning given parameter.
-
#report!(name, msg) ⇒ Object
Remember error concerning given parameter.
-
#required_params ⇒ Object
(also: #required_parameters)
Get list of required parameters.
-
#scalar_params ⇒ Object
(also: #scalar_parameters)
Get list of scalar parameters.
-
#set(hash) ⇒ Object
Set parameter values from given hash.
-
#tagged_params(*tags) ⇒ Object
(also: #tagged_parameters)
Get list of parameters tagged with given/any tags.
-
#to_data ⇒ Object
Return all non-nil parameters as a hash.
-
#to_hash ⇒ Object
(also: #to_h)
Return all non-empty parameters as a hash.
-
#untagged_params(*tags) ⇒ Object
(also: #untagged_parameters)
Get list of parameters not tagged with given/any tags.
-
#url_params ⇒ Object
(also: #url_parameters, #to_params)
Get hash of all non-empty parameters for use in URL.
-
#url_query ⇒ Object
Create string containing URL query from all current non-empty parameters.
-
#valid(name, *names) ⇒ Object
Return parameter(s) value(s) as long as they are all valid, nil otherwise.
-
#valid?(*names) ⇒ Boolean
Test if there were no errors (overall or for given parameters) reported.
-
#valid_params ⇒ Object
(also: #valid_parameters)
Get list of parameters with no errors reported.
-
#validate ⇒ Object
Validate parameter values and remember any errors detected.
-
#validate! ⇒ Object
Like validate, except that it forces revalidation of all parameters.
-
#validate? ⇒ Boolean
Like validate, except that it does nothing if validation was already done.
-
#visible_params ⇒ Object
(also: #visible_parameters)
Get list of visible parameters.
Constructor Details
#initialize(*args) ⇒ FormInput
Create new form info, initializing it from given hash or request, if anything.
765 766 767 768 769 770 771 772 773 774 775 |
# File 'lib/form_input/core.rb', line 765 def initialize( *args ) @params = bound_params @errors = nil for arg in args if arg.is_a? Hash set( arg ) else import( arg ) end end end |
Class Method Details
.[](*names) ⇒ Object
Get given parameter(s), hash style.
619 620 621 622 623 624 625 |
# File 'lib/form_input/core.rb', line 619 def []( *names ) if names.count == 1 form_params[ names.first ] else form_params.values_at( *names ) end end |
.add(param) ⇒ Object
Add given parameter to the form, after performing basic validity checks.
628 629 630 631 632 633 634 635 636 637 |
# File 'lib/form_input/core.rb', line 628 def add( param ) name = param.name fail ArgumentError, "duplicate parameter #{name}" if form_params[ name ] fail ArgumentError, "invalid parameter name #{name}" if method_defined?( name ) self.send( :attr_accessor, name ) form_params[ name ] = param end |
.array(name, *args, &block) ⇒ Object
Like param, except that it defines array parameter.
717 718 719 |
# File 'lib/form_input/core.rb', line 717 def array( name, *args, &block ) param( name, *args, array: true, &block ) end |
.array!(name, *args, &block) ⇒ Object
Like param!, except that it defines required array parameter.
722 723 724 |
# File 'lib/form_input/core.rb', line 722 def array!( name, *args, &block ) param!( name, *args, array: true, &block ) end |
.copy(source, opts = {}) ⇒ Object
Copy given/all form parameters. Returns self for chaining.
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
# File 'lib/form_input/core.rb', line 642 def copy( source, opts = {} ) case source when Parameter add( Parameter.new( opts[ :name ] || source.name, opts[ :code ] || opts[ :name ] || source.code, source.opts.merge( opts ) ) ) when Array source.each{ |x| copy( x, opts ) } when Class fail ArgumentError, "invalid source form #{source.inspect}" unless source < FormInput copy( source.form_params.values, opts ) else fail ArgumentError, "invalid source parameter #{source.inspect}" end self end |
.default_translation(forms = self.forms) ⇒ Object
Get string containing YAML representation of the default R18n translation for all/given FormInput classes.
43 44 45 46 |
# File 'lib/form_input/localize.rb', line 43 def self.default_translation( forms = self.forms ) hash = Hash[ forms.map{ |x| [ x.translation_name, x.translation_hash ] }.reject{ |k, v| v.empty? } ] YAML::dump( { forms: hash }.stringify_keys ) end |
.define_steps(steps) ⇒ Object
Turn this form into multi-step form using given steps. Returns self for chaining.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/form_input/steps.rb', line 7 def self.define_steps( steps ) @steps = steps = steps.to_hash.dup.freeze self.send( :include, StepMethods ) opts = { filter: ->{ steps.keys.find{ |x| x.to_s == self } }, class: Symbol } param :step, opts, type: :hidden param :next, opts, type: :ignore param :last, opts, type: :hidden param :seen, opts, type: :hidden self end |
.find_inflection(string) ⇒ Object
Iterate over each possible inflection for given inflection string and return first non-nil result. You may override this if you need more complex inflection fallbacks for some locale.
129 130 131 132 133 134 135 |
# File 'lib/form_input/r18n.rb', line 129 def self.find_inflection( string ) until string.empty? break if result = yield( string ) string = string[0..-2] end result end |
.form_params ⇒ Object
Get hash mapping parameter names to parameters themselves.
614 615 616 |
# File 'lib/form_input/core.rb', line 614 def form_params @params ||= {} end |
.form_steps ⇒ Object
Get hash mapping defined steps to their names, or nil if there are none.
23 24 25 |
# File 'lib/form_input/steps.rb', line 23 def self.form_steps @steps end |
.forms ⇒ Object
Get list of all classes inherited from FormInput.
38 39 40 |
# File 'lib/form_input/localize.rb', line 38 def self.forms ObjectSpace.each_object( Class ).select{ |x| x < FormInput and x.name }.sort_by{ |x| x.name } end |
.from_hash(hash) ⇒ Object
Create new form from hash with internal values.
748 749 750 |
# File 'lib/form_input/core.rb', line 748 def from_hash( hash ) new.set( hash ) end |
.from_params(params) ⇒ Object Also known as: from_data
Create new form from hash with external values.
742 743 744 |
# File 'lib/form_input/core.rb', line 742 def from_params( params ) new.import( params ) end |
.from_request(request) ⇒ Object
Create new form from request with external values.
737 738 739 |
# File 'lib/form_input/core.rb', line 737 def from_request( request ) new.import( request ) end |
.hash(name, *args, &block) ⇒ Object
Like param, except that it defines hash parameter.
727 728 729 |
# File 'lib/form_input/core.rb', line 727 def hash( name, *args, &block ) param( name, *args, hash: true, &block ) end |
.hash!(name, *args, &block) ⇒ Object
Like param!, except that it defines required hash parameter.
732 733 734 |
# File 'lib/form_input/core.rb', line 732 def hash!( name, *args, &block ) param!( name, *args, hash: true, &block ) end |
.inherited(into) ⇒ Object
Create standalone copy of form parameters in case someone inherits an existing form.
609 610 611 |
# File 'lib/form_input/core.rb', line 609 def inherited( into ) into.instance_variable_set( '@params', form_params.dup ) end |
.param(name, *args, &block) ⇒ Object
Define form parameter with given name, code, title, maximum size, options, and filter block. All fields except name are optional. In case the code is missing, name is used instead. If no size limits are specified, 255 characters and bytes limits are applied by default. If no filter is explicitly defined, default filter squeezing and stripping whitespace is applied. Returns self for chaining.
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 |
# File 'lib/form_input/core.rb', line 666 def param( name, *args, &block ) # Fetch arguments. code = name code = args.shift if args.first.is_a? Symbol title = args.shift if args.first.is_a? String size = args.shift if args.first.is_a? Numeric opts = {} opts.merge!( args.shift ){ |k, o, n| ( n && MERGEABLE_OPTIONS.include?( k ) ) ? [ *o, *n ] : n } while args.first.is_a? Hash fail ArgumentError, "invalid arguments #{args}" unless args.empty? # Set the title. opts[ :title ] = title.freeze if title # Set input filter. opts[ :filter ] = block if block opts[ :filter ] = DEFAULT_FILTER unless opts.key?( :filter ) # Enforce default size limits for any input processed. limit = DEFAULT_SIZE_LIMIT size = ( opts[ :max_size ] ||= size || limit ) opts[ :max_bytesize ] ||= limit if size.is_a?( Proc ) or size <= limit # Set default key limits for hash parameters. if opts[ :hash ] opts[ :min_key ] ||= DEFAULT_MIN_KEY opts[ :max_key ] ||= DEFAULT_MAX_KEY end # Define parameter. add( Parameter.new( name, code, opts ) ) self end |
.param!(name, *args, &block) ⇒ Object
Like param, except this defines required parameter.
712 713 714 |
# File 'lib/form_input/core.rb', line 712 def param!( name, *args, &block ) param( name, *args, required: true, &block ) end |
.parse_time(string, format) ⇒ Object
Parse time like Time#strptime but raise on trailing garbage. Also ignores -, _ and ^ % modifiers, so the same format can be used for both parsing and formatting.
143 144 145 146 147 148 149 |
# File 'lib/form_input/types.rb', line 143 def self.parse_time( string, format ) format = format.gsub( /%[-_^]?(.)/, '%\1' ) # Rather than using _strptime and checking the leftover field, # add required trailing character to both the string and format parameters. suffix = ( string[ -1 ] == "\1" ? "\2" : "\1" ) Time.strptime( "+0000 #{string}#{suffix}", "%z #{format}#{suffix}" ).utc end |
.parse_time!(string, format) ⇒ Object
Like parse_time, but falls back to DateTime.parse heuristics when the date/time can't be parsed.
152 153 154 155 156 |
# File 'lib/form_input/types.rb', line 152 def self.parse_time!( string, format ) parse_time( string, format ) rescue DateTime.parse( string ).to_time.utc end |
.translation_hash ⇒ Object
Get hash of all form values which may need to be localized.
31 32 33 34 35 |
# File 'lib/form_input/localize.rb', line 31 def self.translation_hash hash = Hash[ form_params.map{ |k, v| [ k, v.translation_hash ] }.reject{ |k, v| v.empty? } ] hash[ :steps ] = form_steps.reject{ |k, v| v.nil? } if form_steps hash end |
.translation_name ⇒ Object
Get name of the form used as translation scope for text translations.
112 113 114 115 116 117 |
# File 'lib/form_input/r18n.rb', line 112 def self.translation_name @translation_name ||= name.split( '::' ).last .gsub( /([A-Z]+)([A-Z][a-z])/, '\1_\2' ) .gsub( /([a-z\d])([A-Z])/, '\1_\2' ) .downcase end |
.translations_path ⇒ Object
Get path to R18n translations provided by this gem.
107 108 109 |
# File 'lib/form_input/r18n.rb', line 107 def self.translations_path File.( "#{__FILE__}/../r18n" ) end |
Instance Method Details
#[](*names) ⇒ Object
Get given parameter(s) value(s), hash style.
870 871 872 873 874 875 876 |
# File 'lib/form_input/core.rb', line 870 def []( *names ) if names.count == 1 send( names.first ) else names.map{ |x| send( x ) } end end |
#[]=(name, value) ⇒ Object
Set given parameter value, hash style. Unlike setting the attribute directly, this triggers a revalidation in the future.
880 881 882 883 |
# File 'lib/form_input/core.rb', line 880 def []=( name, value ) @errors = nil send( "#{name}=", value ) end |
#array_params ⇒ Object Also known as: array_parameters
Get list of array parameters.
1036 1037 1038 |
# File 'lib/form_input/core.rb', line 1036 def array_params params.select{ |x| x.array? } end |
#blank_params ⇒ Object Also known as: blank_parameters
Get list of parameters with blank values.
976 977 978 |
# File 'lib/form_input/core.rb', line 976 def blank_params params.select{ |x| x.blank? } end |
#build_url(url, args = {}) ⇒ Object
Build URL from given URL and combination of current paramaters and provided parameters.
1114 1115 1116 |
# File 'lib/form_input/core.rb', line 1114 def build_url( url, args = {} ) dup.set( args ).extend_url( url ) end |
#chunked_params(params = self.params) ⇒ Object
Get all/given parameters chunked into individual rows for nicer form display.
1078 1079 1080 |
# File 'lib/form_input/core.rb', line 1078 def chunked_params( params = self.params ) params.chunk{ |p| p[ :row ] || :_alone }.map{ |x,a| a.count > 1 ? a : a.first } end |
#clear(*names) ⇒ Object
Clear all/given parameter values. Both names and parameters are accepted. Returns self for chaining.
861 862 863 864 865 866 867 |
# File 'lib/form_input/core.rb', line 861 def clear( *names ) names = names.empty? ? params_names : validate_names( names ) for name in names self[ name ] = nil end self end |
#correct_params ⇒ Object Also known as: correct_parameters
Get list of parameters with correct value types.
964 965 966 |
# File 'lib/form_input/core.rb', line 964 def correct_params params.select{ |x| x.correct? } end |
#disabled_params ⇒ Object Also known as: disabled_parameters
Get list of disabled parameters.
1006 1007 1008 |
# File 'lib/form_input/core.rb', line 1006 def disabled_params params.select{ |x| x.disabled? } end |
#empty? ⇒ Boolean
Return true if all parameters are empty.
1085 1086 1087 |
# File 'lib/form_input/core.rb', line 1085 def empty? filled_params.empty? end |
#empty_params ⇒ Object Also known as: empty_parameters
Get list of parameters with empty values.
982 983 984 |
# File 'lib/form_input/core.rb', line 982 def empty_params params.select{ |x| x.empty? } end |
#enabled_params ⇒ Object Also known as: enabled_parameters
Get list of enabled parameters.
1012 1013 1014 |
# File 'lib/form_input/core.rb', line 1012 def enabled_params params.select{ |x| x.enabled? } end |
#error_for(name) ⇒ Object
Get first error for given parameter. Returns nil if there were no errors.
1155 1156 1157 |
# File 'lib/form_input/core.rb', line 1155 def error_for( name ) errors_for( name ).first end |
#error_messages ⇒ Object
Get list of error messages, but including only the first one reported for each parameter.
1127 1128 1129 |
# File 'lib/form_input/core.rb', line 1127 def errors.values.map{ |x| x.first } end |
#errors ⇒ Object
Get hash of all errors detected for each parameter.
1121 1122 1123 1124 |
# File 'lib/form_input/core.rb', line 1121 def errors validate? @errors.dup end |
#errors_for(name) ⇒ Object
Get list of errors for given parameter. Returns empty list if there were no errors.
1150 1151 1152 |
# File 'lib/form_input/core.rb', line 1150 def errors_for( name ) errors[ name ] || [] end |
#except(*names) ⇒ Object
Create copy of itself, with given parameters unset. Both names and parameters are accepted.
916 917 918 919 920 921 922 |
# File 'lib/form_input/core.rb', line 916 def except( *names ) result = dup for name in validate_names( names ) result[ name ] = nil end result end |
#extend_url(url) ⇒ Object
Extend given URL with query created from all current non-empty parameters.
1104 1105 1106 1107 1108 1109 1110 1111 |
# File 'lib/form_input/core.rb', line 1104 def extend_url( url ) url = url.to_s.dup query = url_query unless query.empty? url << ( url['?'] ? '&' : '?' ) << query end url end |
#filled_params ⇒ Object Also known as: filled_parameters
Get list of parameters with non-empty values.
988 989 990 |
# File 'lib/form_input/core.rb', line 988 def filled_params params.select{ |x| x.filled? } end |
#freeze ⇒ Object
Freeze the form.
792 793 794 795 796 797 798 |
# File 'lib/form_input/core.rb', line 792 def freeze unless frozen? validate? @errors.freeze.each{ |k,v| v.freeze } end super end |
#ft(*args) ⇒ Object
Like t helper, except that the translation is looked up in the forms.
121 122 123 124 125 |
# File 'lib/form_input/r18n.rb', line 121 def ft( *args ) fail "You need to set the locale with R18n.set('en') or similar. No locale, no helper. Sorry." unless r18n translation = t.forms[ self.class.translation_name ] args.empty? ? translation : translation[ *args ] end |
#hash_params ⇒ Object Also known as: hash_parameters
Get list of hash parameters.
1042 1043 1044 |
# File 'lib/form_input/core.rb', line 1042 def hash_params params.select{ |x| x.hash? } end |
#hidden_params ⇒ Object Also known as:
Get list of hidden parameters.
1018 1019 1020 |
# File 'lib/form_input/core.rb', line 1018 def hidden_params params.select{ |x| x.hidden? } end |
#ignored_params ⇒ Object Also known as: ignored_parameters
Get list of ignored parameters.
1024 1025 1026 |
# File 'lib/form_input/core.rb', line 1024 def ignored_params params.select{ |x| x.ignored? } end |
#import(request) ⇒ Object
Import parameter values from given request or hash. Applies parameter input filters and transforms as well. Returns self for chaining.
837 838 839 840 841 842 843 844 845 846 847 848 |
# File 'lib/form_input/core.rb', line 837 def import( request ) for name, param in @params if value = request[ param.code ] value = sanitize_value( value, param.filter ) if transform = param.transform value = value.instance_exec( &transform ) end self[ name ] = value end end self end |
#incorrect_params ⇒ Object Also known as: incorrect_parameters
Get list of parameters with incorrect value types.
970 971 972 |
# File 'lib/form_input/core.rb', line 970 def incorrect_params params.select{ |x| x.incorrect? } end |
#initialize_clone(other) ⇒ Object
Initialize form clone.
778 779 780 781 782 |
# File 'lib/form_input/core.rb', line 778 def initialize_clone( other ) super @params = bound_params @errors &&= Hash[ @errors.map{ |k,v| [ k, v.clone ] } ] end |
#initialize_dup(other) ⇒ Object
Initialize form copy.
785 786 787 788 789 |
# File 'lib/form_input/core.rb', line 785 def initialize_dup( other ) super @params = bound_params @errors = nil end |
#invalid?(*names) ⇒ Boolean
Test if there were some errors (overall or for given parameters) reported.
1169 1170 1171 |
# File 'lib/form_input/core.rb', line 1169 def invalid?( *names ) not valid?( *names ) end |
#invalid_params ⇒ Object Also known as: invalid_parameters
Get list of parameters with some errors reported.
1072 1073 1074 |
# File 'lib/form_input/core.rb', line 1072 def invalid_params params.select{ |x| x.invalid? } end |
#named_params(*names) ⇒ Object Also known as: named_parameters
Get list of given named parameters. Note that nil is returned for unknown names, and duplicate parameters for duplicate names.
958 959 960 |
# File 'lib/form_input/core.rb', line 958 def named_params( *names ) @params.values_at( *names ) end |
#only(*names) ⇒ Object
Create copy of itself, with only given parameters set. Both names and parameters are accepted.
925 926 927 928 929 930 931 932 933 934 |
# File 'lib/form_input/core.rb', line 925 def only( *names ) # It would be easier to create new instance here and only copy selected values, # but we want to use dup instead of new here, as the derived form can use # different parameters in its construction. result = dup for name in params_names - validate_names( names ) result[ name ] = nil end result end |
#optional_params ⇒ Object Also known as: optional_parameters
Get list of optional parameters.
1000 1001 1002 |
# File 'lib/form_input/core.rb', line 1000 def optional_params params.select{ |x| x.optional? } end |
#param(name) ⇒ Object Also known as: parameter
Get given named parameter.
939 940 941 |
# File 'lib/form_input/core.rb', line 939 def param( name ) @params[ name ] end |
#params ⇒ Object Also known as: parameters
Get list of all parameters.
945 946 947 |
# File 'lib/form_input/core.rb', line 945 def params @params.values end |
#params_names ⇒ Object Also known as: parameters_names
Get list of all parameter names.
951 952 953 |
# File 'lib/form_input/core.rb', line 951 def params_names @params.keys end |
#report(name, msg) ⇒ Object
Remember error concerning given parameter. In case of multiple errors, the message is added to the end of the list, making it less important than the other errors. Returns self for chaining.
1134 1135 1136 1137 1138 |
# File 'lib/form_input/core.rb', line 1134 def report( name, msg ) validate? ( @errors[ name ] ||= [] ) << msg.to_s.dup.freeze self end |
#report!(name, msg) ⇒ Object
Remember error concerning given parameter. In case of multiple errors, the message is added to the beginning of the list, making it more important than the other errors. Returns self for chaining.
1143 1144 1145 1146 1147 |
# File 'lib/form_input/core.rb', line 1143 def report!( name, msg ) validate? ( @errors[ name ] ||= [] ).unshift( msg.to_s.dup.freeze ) self end |
#required_params ⇒ Object Also known as: required_parameters
Get list of required parameters.
994 995 996 |
# File 'lib/form_input/core.rb', line 994 def required_params params.select{ |x| x.required? } end |
#scalar_params ⇒ Object Also known as: scalar_parameters
Get list of scalar parameters.
1048 1049 1050 |
# File 'lib/form_input/core.rb', line 1048 def scalar_params params.select{ |x| x.scalar? } end |
#set(hash) ⇒ Object
Set parameter values from given hash. Returns self for chaining.
852 853 854 855 856 857 |
# File 'lib/form_input/core.rb', line 852 def set( hash ) for name, value in hash self[ name ] = value end self end |
#tagged_params(*tags) ⇒ Object Also known as: tagged_parameters
Get list of parameters tagged with given/any tags.
1054 1055 1056 |
# File 'lib/form_input/core.rb', line 1054 def tagged_params( * ) params.select{ |x| x.tagged?( * ) } end |
#to_data ⇒ Object
Return all non-nil parameters as a hash.
Note that the keys are external names of the parameters (should they differ),
so the keys created by from_data(data).to_data remain consistent.
See also #to_hash, which creates a hash of non-empty parameters.
899 900 901 902 903 |
# File 'lib/form_input/core.rb', line 899 def to_data result = {} params.each{ |x| result[ x.code ] = x.value unless x.value.nil? } result end |
#to_hash ⇒ Object Also known as: to_h
Return all non-empty parameters as a hash. See also #to_data, which creates a hash of non-nil parameters, and #url_params, which creates a hash suitable for url output.
888 889 890 891 892 |
# File 'lib/form_input/core.rb', line 888 def to_hash result = {} filled_params.each{ |x| result[ x.name ] = x.value } result end |
#untagged_params(*tags) ⇒ Object Also known as: untagged_parameters
Get list of parameters not tagged with given/any tags.
1060 1061 1062 |
# File 'lib/form_input/core.rb', line 1060 def untagged_params( * ) params.select{ |x| x.untagged?( * ) } end |
#url_params ⇒ Object Also known as: url_parameters, to_params
Get hash of all non-empty parameters for use in URL.
1090 1091 1092 1093 1094 |
# File 'lib/form_input/core.rb', line 1090 def url_params result = {} filled_params.each{ |x| result[ x.code ] = x.form_value } result end |
#url_query ⇒ Object
Create string containing URL query from all current non-empty parameters.
1099 1100 1101 |
# File 'lib/form_input/core.rb', line 1099 def url_query Rack::Utils.build_nested_query( url_params ) end |
#valid(name, *names) ⇒ Object
Return parameter(s) value(s) as long as they are all valid, nil otherwise.
1174 1175 1176 |
# File 'lib/form_input/core.rb', line 1174 def valid( name, *names ) self[ name, *names ] if valid?( name, *names ) end |
#valid?(*names) ⇒ Boolean
Test if there were no errors (overall or for given parameters) reported.
1160 1161 1162 1163 1164 1165 1166 |
# File 'lib/form_input/core.rb', line 1160 def valid?( *names ) if names.empty? errors.empty? else validate_names( names ).all?{ |x| errors_for( x ).empty? } end end |
#valid_params ⇒ Object Also known as: valid_parameters
Get list of parameters with no errors reported.
1066 1067 1068 |
# File 'lib/form_input/core.rb', line 1066 def valid_params params.select{ |x| x.valid? } end |
#validate ⇒ Object
Validate parameter values and remember any errors detected. You can override this in your class if you need more specific validation and :check callback is not good enough. Just make sure to call super first. Returns self for chaining.
1182 1183 1184 1185 1186 |
# File 'lib/form_input/core.rb', line 1182 def validate @errors ||= {} params.each{ |x| x.validate } self end |
#validate! ⇒ Object
Like validate, except that it forces revalidation of all parameters. Returns self for chaining.
1190 1191 1192 1193 1194 |
# File 'lib/form_input/core.rb', line 1190 def validate! @errors = {} validate self end |
#validate? ⇒ Boolean
Like validate, except that it does nothing if validation was already done. Returns self for chaining.
1198 1199 1200 1201 |
# File 'lib/form_input/core.rb', line 1198 def validate? validate unless @errors self end |
#visible_params ⇒ Object Also known as: visible_parameters
Get list of visible parameters.
1030 1031 1032 |
# File 'lib/form_input/core.rb', line 1030 def visible_params params.select{ |x| x.visible? } end |