repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/html_attributes.rb | lib/formtastic/html_attributes.rb | # frozen_string_literal: true
module Formtastic
# @private
module HtmlAttributes
# Returns a namespace passed by option or inherited from parent builders / class configuration
def dom_id_namespace
namespace = options[:custom_namespace]
parent = options[:parent_builder]
case
when namespace then namespace
when parent && parent != self then parent.dom_id_namespace
else custom_namespace
end
end
protected
def humanized_attribute_name(method)
if @object && @object.class.respond_to?(:human_attribute_name)
humanized_name = @object.class.human_attribute_name(method.to_s)
if humanized_name == method.to_s.send(:humanize)
method.to_s.send(label_str_method)
else
humanized_name
end
else
method.to_s.send(label_str_method)
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/actions.rb | lib/formtastic/actions.rb | # frozen_string_literal: true
module Formtastic
module Actions
extend ActiveSupport::Autoload
autoload :Base
autoload :Buttonish
eager_autoload do
autoload :InputAction
autoload :LinkAction
autoload :ButtonAction
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/deprecation.rb | lib/formtastic/deprecation.rb | # frozen_string_literal: true
require 'active_support/deprecation'
module Formtastic
Deprecation = ActiveSupport::Deprecation.new("5.0.0", "Formtastic")
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/version.rb | lib/formtastic/version.rb | # frozen_string_literal: true
module Formtastic
VERSION = "5.0.0"
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/localizer.rb | lib/formtastic/localizer.rb | # frozen_string_literal: true
module Formtastic
# Implementation for looking up localized values within Formtastic using I18n, if no
# explicit value (like the `:label` option) is set and I18n-lookups are enabled in the
# configuration.
#
# You can subclass this to implement your own Localizer, and configure Formtastic to use this
# localizer with:
#
# Formtastic::FormBuilder.i18n_localizer
#
# Enabled/disable i18n lookups completely with:
#
# Formtastic::FormBuilder.i18n_lookups_by_default = true/false
#
# Lookup priority:
#
# 'formtastic.%{type}.%{model}.%{action}.%{attribute}'
# 'formtastic.%{type}.%{model}.%{attribute}'
# 'formtastic.%{type}.%{attribute}'
#
# Example:
#
# 'formtastic.labels.post.edit.title'
# 'formtastic.labels.post.title'
# 'formtastic.labels.title'
class Localizer
class Cache
def get(key)
cache[key]
end
def has_key?(key)
cache.has_key?(key)
end
def set(key, result)
cache[key] = result
end
def cache
@cache ||= {}
end
def clear!
cache.clear
end
end
attr_accessor :builder
def self.cache
@cache ||= Cache.new
end
def initialize(current_builder)
self.builder = current_builder
end
def localize(key, value, type, options = {}) # @private
key = value if value.is_a?(::Symbol)
if value.is_a?(::String)
escape_html_entities(value)
else
use_i18n = value.nil? ? i18n_lookups_by_default : (value != false)
use_cache = i18n_cache_lookups
cache = self.class.cache
if use_i18n
model_name, nested_model_name = normalize_model_name(builder.model_name.underscore)
action_name = builder.template.params[:action].to_s rescue ''
attribute_name = key.to_s
# look in the cache first
if use_cache
cache_key = [::I18n.locale, action_name, model_name, nested_model_name, attribute_name, key, value, type, options]
return cache.get(cache_key) if cache.has_key?(cache_key)
end
defaults = Formtastic::I18n::SCOPES.reject do |i18n_scope|
nested_model_name.nil? && i18n_scope.match(/nested_model/)
end.collect do |i18n_scope|
i18n_path = i18n_scope.dup
i18n_path.gsub!('%{action}', action_name)
i18n_path.gsub!('%{model}', model_name)
i18n_path.gsub!('%{nested_model}', nested_model_name) unless nested_model_name.nil?
i18n_path.gsub!('%{attribute}', attribute_name)
i18n_path.tr!('..', '.')
i18n_path.to_sym
end
defaults << ''
defaults.uniq!
default_key = defaults.shift
i18n_value = Formtastic::I18n.t(default_key,
options.merge(:default => defaults, :scope => type.to_s.pluralize.to_sym))
i18n_value = i18n_value.is_a?(::String) ? i18n_value : nil
if i18n_value.blank? && type == :label
# This is effectively what Rails label helper does for i18n lookup
options[:scope] = [:helpers, type]
options[:default] = defaults
i18n_value = ::I18n.t(default_key, **options)
end
# save the result to the cache
result = (i18n_value.is_a?(::String) && i18n_value.present?) ? escape_html_entities(i18n_value) : nil
cache.set(cache_key, result) if use_cache
result
end
end
end
protected
def normalize_model_name(name)
if name =~ /(.+)\[(.+)\]/
# Nested builder case with :post rather than @post
# TODO: check if this is no longer required with a minimum of Rails 4.1
[$1, $2]
elsif builder.respond_to?(:options) && builder.options.key?(:as)
[builder.options[:as].to_s]
elsif builder.respond_to?(:options) && builder.options.key?(:parent_builder)
# Rails 3.0+ nested builder work-around case, where :parent_builder is provided by f.semantic_form_for
[builder.options[:parent_builder].object_name.to_s, name]
else
# Non-nested case
[name]
end
end
def escape_html_entities(string) # @private
if (builder.escape_html_entities_in_hints_and_labels) ||
(self.respond_to?(:escape_html_entities_in_hints_and_labels) && escape_html_entities_in_hints_and_labels)
string = builder.template.escape_once(string) unless string.respond_to?(:html_safe?) && string.html_safe? == true # Accept html_safe flag as indicator to skip escaping
end
string
end
def i18n_lookups_by_default
builder.i18n_lookups_by_default
end
def i18n_cache_lookups
builder.i18n_cache_lookups
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers.rb | lib/formtastic/helpers.rb | # frozen_string_literal: true
module Formtastic
module Helpers
autoload :ActionHelper, 'formtastic/helpers/action_helper'
autoload :ActionsHelper, 'formtastic/helpers/actions_helper'
autoload :ErrorsHelper, 'formtastic/helpers/errors_helper'
autoload :FieldsetWrapper, 'formtastic/helpers/fieldset_wrapper'
autoload :FileColumnDetection, 'formtastic/helpers/file_column_detection'
autoload :FormHelper, 'formtastic/helpers/form_helper'
autoload :InputHelper, 'formtastic/helpers/input_helper'
autoload :InputsHelper, 'formtastic/helpers/inputs_helper'
autoload :Reflection, 'formtastic/helpers/reflection'
autoload :Enum, 'formtastic/helpers/enum'
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/input_class_finder.rb | lib/formtastic/input_class_finder.rb | # frozen_string_literal: true
module Formtastic
# Uses the {Formtastic::NamespacedClassFinder} to look up input class names.
#
# See {Formtastic::FormBuilder#namespaced_input_class} for details.
#
class InputClassFinder < NamespacedClassFinder
# @param builder [FormBuilder]
def initialize(builder)
super builder.input_namespaces
end
def class_name(as)
"#{super}Input"
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/i18n.rb | lib/formtastic/i18n.rb | # encoding: utf-8
# frozen_string_literal: true
module Formtastic
# @private
module I18n
DEFAULT_SCOPE = [:formtastic].freeze
DEFAULT_VALUES = YAML.load_file(File.expand_path("../../locale/en.yml", __FILE__))["en"]["formtastic"].freeze
SCOPES = [
'%{model}.%{nested_model}.%{action}.%{attribute}',
'%{model}.%{nested_model}.%{attribute}',
'%{nested_model}.%{action}.%{attribute}',
'%{nested_model}.%{attribute}',
'%{model}.%{action}.%{attribute}',
'%{model}.%{attribute}',
'%{attribute}'
]
class << self
def translate(*args)
key = args.shift.to_sym
options = args.extract_options!
options.reverse_merge!(:default => DEFAULT_VALUES[key])
options[:scope] = [DEFAULT_SCOPE, options[:scope]].flatten.compact
::I18n.translate(key, *args, **options)
end
alias :t :translate
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/form_builder.rb | lib/formtastic/form_builder.rb | # frozen_string_literal: true
module Formtastic
class FormBuilder < ActionView::Helpers::FormBuilder
# Defines a new configurable option
# @param [Symbol] name the configuration name
# @param [Object] default the configuration default value
# @private
#
# @!macro [new] configure
# @!scope class
# @!attribute [rw] $1
# @api public
def self.configure(name, default = nil)
class_attribute(name)
self.send(:"#{name}=", default)
end
configure :custom_namespace
configure :default_text_field_size
configure :default_text_area_height, 20
configure :default_text_area_width
configure :all_fields_required_by_default, true
configure :include_blank_for_select_by_default, true
configure :required_string, proc { %{<abbr title="#{Formtastic::I18n.t(:required)}">*</abbr>}.html_safe }
configure :optional_string, ''
configure :inline_errors, :sentence
configure :label_str_method, :humanize
configure :collection_label_methods, %w[to_label display_name full_name name title username login value to_s]
configure :collection_value_methods, %w[id to_s]
configure :file_methods, [ :file?, :public_filename, :filename ]
configure :file_metadata_suffixes, ['content_type', 'file_name', 'file_size']
configure :priority_countries, ["Australia", "Canada", "United Kingdom", "United States"]
configure :i18n_lookups_by_default, true
configure :i18n_cache_lookups, true
configure :i18n_localizer, Formtastic::Localizer
configure :escape_html_entities_in_hints_and_labels, true
configure :default_commit_button_accesskey
configure :default_inline_error_class, 'inline-errors'
configure :default_error_list_class, 'errors'
configure :default_hint_class, 'inline-hints'
configure :semantic_errors_link_to_inputs, false
configure :use_required_attribute, false
configure :perform_browser_validations, false
# Check {Formtastic::InputClassFinder} to see how are inputs resolved.
configure :input_namespaces, [::Object, ::Formtastic::Inputs]
configure :input_class_finder, Formtastic::InputClassFinder
# Check {Formtastic::ActionClassFinder} to see how are inputs resolved.
configure :action_namespaces, [::Object, ::Formtastic::Actions]
configure :action_class_finder, Formtastic::ActionClassFinder
configure :skipped_columns, [:created_at, :updated_at, :created_on, :updated_on, :lock_version, :version]
configure :priority_time_zones, []
attr_reader :template
attr_reader :auto_index
include Formtastic::HtmlAttributes
include Formtastic::Helpers::InputHelper
include Formtastic::Helpers::InputsHelper
include Formtastic::Helpers::ActionHelper
include Formtastic::Helpers::ActionsHelper
include Formtastic::Helpers::ErrorsHelper
# This is a wrapper around Rails' `ActionView::Helpers::FormBuilder#fields_for`, originally
# provided to ensure that the `:builder` from `semantic_form_for` was passed down into
# the nested `fields_for`. Our supported versions of Rails no longer require us to do this,
# so this method is provided purely for backwards compatibility and DSL consistency.
#
# When constructing a `fields_for` form fragment *outside* of `semantic_form_for`, please use
# `Formtastic::Helpers::FormHelper#semantic_fields_for`.
#
# @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for ActionView::Helpers::FormBuilder#fields_for
# @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for ActionView::Helpers::FormHelper#fields_for
# @see Formtastic::Helpers::FormHelper#semantic_fields_for
#
# @example
# <% semantic_form_for @post do |post| %>
# <% post.semantic_fields_for :author do |author| %>
# <% author.inputs :name %>
# <% end %>
# <% end %>
#
# <form ...>
# <fieldset class="inputs">
# <ol>
# <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
# </ol>
# </fieldset>
# </form>
#
# @todo is there a way to test the params structure of the Rails helper we wrap to ensure forward compatibility?
def semantic_fields_for(record_or_name_or_array, *args, &block)
fields_for(record_or_name_or_array, *args, &block)
end
def initialize(object_name, object, template, options)
super
if respond_to?('multipart=') && options.is_a?(Hash) && options[:html]
self.multipart = options[:html][:multipart]
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/namespaced_class_finder.rb | lib/formtastic/namespaced_class_finder.rb | # frozen_string_literal: true
module Formtastic
# This class implements class resolution in a namespace chain. It
# is used both by Formtastic::Helpers::InputHelper and
# Formtastic::Helpers::ActionHelper to look up action and input classes.
#
# @example Implementing own class finder
# # You can implement own class finder that for example prefixes the class name or uses custom module.
# class MyInputClassFinder < Formtastic::NamespacedClassFinder
# def initialize(namespaces)
# super [MyNamespace] + namespaces # first lookup in MyNamespace then the defaults
# end
#
# private
#
# def class_name(as)
# "My#{super}Input" # for example MyStringInput
# end
# end
#
# # in config/initializers/formtastic.rb
# Formtastic::FormBuilder.input_class_finder = MyInputClassFinder
#
class NamespacedClassFinder
attr_reader :namespaces # @private
# @private
class NotFoundError < NameError
end
def self.use_const_defined?
defined?(Rails) && ::Rails.application && ::Rails.application.config.respond_to?(:eager_load) && ::Rails.application.config.eager_load
end
def self.finder_method
@finder_method ||= use_const_defined? ? :find_with_const_defined : :find_by_trying
end
# @param namespaces [Array<Module>]
def initialize(namespaces)
@namespaces = namespaces.flatten
@cache = {}
end
# Looks up the given reference in the configured namespaces.
#
# Two finder methods are provided, one for development tries to
# reference the constant directly, triggering Rails' autoloading
# const_missing machinery; the second one instead for production
# checks with .const_defined before referencing the constant.
#
def find(as)
@cache[as] ||= resolve(as)
end
def resolve(as)
class_name = class_name(as)
finder(class_name) or raise NotFoundError, "class #{class_name}"
end
# Converts symbol to class name
# Overridden in subclasses to create `StringInput` and `ButtonAction`
# @example
# class_name(:string) == "String"
def class_name(as)
as.to_s.camelize
end
private
def finder(class_name) # @private
send(self.class.finder_method, class_name)
end
# Looks up the given class name in the configured namespaces in order,
# returning the first one that has the class name constant defined.
def find_with_const_defined(class_name)
@namespaces.find do |namespace|
if namespace.const_defined?(class_name)
break namespace.const_get(class_name)
end
end
end
# Use auto-loading in development environment
def find_by_trying(class_name)
@namespaces.find do |namespace|
begin
break namespace.const_get(class_name)
rescue NameError
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/action_class_finder.rb | lib/formtastic/action_class_finder.rb | # frozen_string_literal: true
module Formtastic
# Uses the {NamespacedClassFinder} to look up action class names.
#
# See {Formtastic::Helpers::ActionHelper#namespaced_action_class} for details.
#
class ActionClassFinder < NamespacedClassFinder
# @param builder [FormBuilder]
def initialize(builder)
super builder.action_namespaces
end
def class_name(as)
"#{super}Action"
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/localized_string.rb | lib/formtastic/localized_string.rb | # frozen_string_literal: true
module Formtastic
module LocalizedString
def model_name
@object.present? ? @object.class.name : @object_name.to_s.classify
end
protected
def localized_string(key, value, type, options = {}) # @private
current_builder = respond_to?(:builder) ? builder : self
localizer = Formtastic::FormBuilder.i18n_localizer.new(current_builder)
localizer.localize(key, value, type, options)
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs.rb | lib/formtastic/inputs.rb | # frozen_string_literal: true
module Formtastic
module Inputs
extend ActiveSupport::Autoload
autoload :Base
autoload :Basic
autoload :Timeish
eager_autoload do
autoload :BooleanInput
autoload :CheckBoxesInput
autoload :ColorInput
autoload :CountryInput
autoload :DatalistInput
autoload :DateInput
autoload :DatePickerInput
autoload :DatetimePickerInput
autoload :DateSelectInput
autoload :DatetimeInput
autoload :DatetimeSelectInput
autoload :EmailInput
autoload :FileInput
autoload :HiddenInput
autoload :NumberInput
autoload :NumericInput
autoload :PasswordInput
autoload :PhoneInput
autoload :RadioInput
autoload :RangeInput
autoload :SearchInput
autoload :SelectInput
autoload :StringInput
autoload :TextInput
autoload :TimeInput
autoload :TimePickerInput
autoload :TimeSelectInput
autoload :TimeZoneInput
autoload :UrlInput
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/form_helper.rb | lib/formtastic/helpers/form_helper.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# FormHelper provides a handful of wrappers around Rails' built-in form helpers methods to set
# the `:builder` option to `Formtastic::FormBuilder` and apply some class names to the `<form>`
# tag.
#
# The following methods are wrapped:
#
# * `semantic_form_for` to `form_for`
# * `semantic_fields_for` to `fields_for`
# * `semantic_remote_form_for` and `semantic_form_remote_for` to `remote_form_for`
#
# The following two examples are effectively equivalent:
#
# <%= form_for(@post, :builder => Formtastic::FormBuilder, :class => 'formtastic post') do |f| %>
# #...
# <% end %>
#
# <%= semantic_form_for(@post) do |f| %>
# #...
# <% end %>
#
# This simple wrapping means that all arguments, options and variations supported by Rails' own
# helpers are also supported by Formtastic.
#
# Since `Formtastic::FormBuilder` subclasses Rails' own `FormBuilder`, you have access to all
# of Rails' built-in form helper methods such as `text_field`, `check_box`, `radio_button`,
# etc **in addition to** all of Formtastic's additional helpers like {InputsHelper#inputs inputs},
# {InputsHelper#input input}, {ButtonsHelper#buttons buttons}, etc:
#
# <%= semantic_form_for(@post) do |f| %>
#
# <!-- Formtastic -->
# <%= f.input :title %>
#
# <!-- Rails -->
# <li class='something-custom'>
# <%= f.label :title %>
# <%= f.text_field :title %>
# <p class='hints'>...</p>
# </li>
# <% end %>
#
# Formtastic is a superset of Rails' FormBuilder. It deliberately avoids overriding or modifying
# the behavior of Rails' own form helpers so that you can use Formtastic helpers when suited,
# and fall back to regular Rails helpers, ERB and HTML when needed. In other words, you're never
# fully committed to The Formtastic Way.
module FormHelper
# Allows the `:builder` option on `form_for` etc to be changed to your own which subclasses
# `Formtastic::FormBuilder`. Change this from `config/initializers/formtastic.rb`.
@@builder = Formtastic::FormBuilder
mattr_accessor :builder
# Allows the default class we add to all `<form>` tags to be changed from `formtastic` to
# `whatever`. Change this from `config/initializers/formtastic.rb`.
@@default_form_class = 'formtastic'
mattr_accessor :default_form_class
# Allows to set a custom proc to handle the class infered from the model's name. By default it
# will infer the name from the class name (eg. Post will be "post").
@@default_form_model_class_proc = proc { |model_class_name| model_class_name }
mattr_accessor :default_form_model_class_proc
# Allows to set a custom field_error_proc wrapper. By default this wrapper
# is disabled since `formtastic` already adds an error class to the LI tag
# containing the input. Change this from `config/initializers/formtastic.rb`.
@@formtastic_field_error_proc = proc { |html_tag, instance_tag| html_tag }
mattr_accessor :formtastic_field_error_proc
# Wrapper around Rails' own `form_for` helper to set the `:builder` option to
# `Formtastic::FormBuilder` and to set some class names on the `<form>` tag such as
# `formtastic` and the downcased and underscored model name (eg `post`).
#
# See Rails' `form_for` for full documentation of all supported arguments and options.
#
# Since `Formtastic::FormBuilder` subclasses Rails' own FormBuilder, you have access to all
# of Rails' built-in form helper methods such as `text_field`, `check_box`, `radio_button`,
# etc **in addition to** all of Formtastic's additional helpers like {InputsHelper#inputs inputs},
# {InputsHelper#input input}, {ButtonsHelper#buttons buttons}, etc.
#
# Most of the examples below have been adapted from the examples found in the Rails `form_for`
# documentation.
#
# @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html Rails' FormHelper documentation (`form_for`, etc)
# @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html Rails' FormBuilder documentaion (`text_field`, etc)
# @see FormHelper The overview of the FormBuilder module
#
# @example Resource-oriented form generation
# <%= semantic_form_for @user do |f| %>
# <%= f.input :name %>
# <%= f.input :email %>
# <%= f.input :password %>
# <% end %>
#
# @example Generic form generation
# <%= semantic_form_for :user do |f| %>
# <%= f.input :name %>
# <%= f.input :email %>
# <%= f.input :password %>
# <% end %>
#
# @example Resource-oriented with custom URL
# <%= semantic_form_for(@post, :url => super_post_path(@post)) do |f| %>
# ...
# <% end %>
#
# @example Resource-oriented with namespaced routes
# <%= semantic_form_for([:admin, @post]) do |f| %>
# ...
# <% end %>
#
# @example Resource-oriented with nested routes
# <%= semantic_form_for([@user, @post]) do |f| %>
# ...
# <% end %>
#
# @example Rename the resource
# <%= semantic_form_for(@post, :as => :article) do |f| %>
# ...
# <% end %>
#
# @example Remote forms (unobtrusive JavaScript)
# <%= semantic_form_for(@post, :remote => true) do |f| %>
# ...
# <% end %>
#
# @example Namespaced forms all multiple Formtastic forms to exist on the one page without DOM id clashes and invalid HTML documents.
# <%= semantic_form_for(@post, :namespace => 'first') do |f| %>
# ...
# <% end %>
#
# @example Accessing a mixture of Formtastic helpers and Rails FormBuilder helpers.
# <%= semantic_form_for(@post) do |f| %>
# <%= f.input :title %>
# <%= f.input :body %>
# <li class="something-custom">
# <label><%= f.check_box :published %></label>
# </li>
# <% end %>
#
# @param record_or_name_or_array
# Same behavior as Rails' `form_for`
#
# @option *args [Hash] :html
# Pass HTML attributes into the `<form>` tag. Same behavior as Rails' `form_for`, except we add in some of our own classes.
#
# @option *args [String, Hash] :url
# A hash of URL components just like you pass into `link_to` or `url_for`, or a named route (eg `posts_path`). Same behavior as Rails' `form_for`.
#
# @option *args [String] :namespace
def semantic_form_for(record_or_name_or_array, *args, &proc)
options = args.extract_options!
options[:builder] ||= @@builder
options[:html] ||= {}
options[:html][:novalidate] = !@@builder.perform_browser_validations unless options[:html].key?(:novalidate)
options[:custom_namespace] = options.delete(:namespace)
singularizer = defined?(ActiveModel::Naming.singular) ? ActiveModel::Naming.method(:singular) : ActionController::RecordIdentifier.method(:singular_class_name)
class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
class_names << @@default_form_class
model_class_name = case record_or_name_or_array
when String, Symbol then record_or_name_or_array.to_s # :post => "post"
when Array then options[:as] || singularizer.call(record_or_name_or_array[-1].class) # [@post, @comment] # => "comment"
else options[:as] || singularizer.call(record_or_name_or_array.class) # @post => "post"
end
class_names << @@default_form_model_class_proc.call(model_class_name)
options[:html][:class] = class_names.compact.join(" ")
with_custom_field_error_proc do
self.form_for(record_or_name_or_array, *(args << options), &proc)
end
end
# Wrapper around Rails' own `fields_for` helper to set the `:builder` option to
# `Formtastic::FormBuilder`.
#
# @see #semantic_form_for
def semantic_fields_for(record_name, record_object = nil, options = {}, &block)
options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
options[:builder] ||= @@builder
options[:custom_namespace] = options.delete(:namespace)
with_custom_field_error_proc do
self.fields_for(record_name, record_object, options, &block)
end
end
protected
def with_custom_field_error_proc(&block)
default_field_error_proc = ::ActionView::Base.field_error_proc
::ActionView::Base.field_error_proc = @@formtastic_field_error_proc
yield
ensure
::ActionView::Base.field_error_proc = default_field_error_proc
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/errors_helper.rb | lib/formtastic/helpers/errors_helper.rb | # frozen_string_literal: true
module Formtastic
module Helpers
module ErrorsHelper
include Formtastic::Helpers::FileColumnDetection
include Formtastic::Helpers::Reflection
include Formtastic::LocalizedString
INLINE_ERROR_TYPES = [:sentence, :list, :first]
# Generates an unordered list of error messages on the base object and optionally for a given
# set of named attribute. This is idea for rendering a block of error messages at the top of
# the form for hidden/special/virtual attributes (the Paperclip Rails plugin does this), or
# errors on the base model.
#
# A hash can be used as the last set of arguments to pass HTML attributes to the `<ul>`
# wrapper.
#
# # in config/initializers/formtastic.rb
# Setting `Formtastic::FormBuilder.semantic_errors_link_to_inputs = true`
# will render attribute errors as links to the corresponding errored inputs.
#
# @example A list of errors on the base model
# <%= semantic_form_for ... %>
# <%= f.semantic_errors %>
# ...
# <% end %>
#
# @example A list of errors on the base and named attributes
# <%= semantic_form_for ... %>
# <%= f.semantic_errors :something_special %>
# ...
# <% end %>
#
# @example A list of errors on the base model, with custom HTML attributes
# <%= semantic_form_for ... %>
# <%= f.semantic_errors :class => "awesome" %>
# ...
# <% end %>
#
# @example A list of errors on the base model and named attributes, with custom HTML attributes
# <%= semantic_form_for ... %>
# <%= f.semantic_errors :something_special, :something_else, :class => "awesome", :onclick => "Awesome();" %>
# ...
# <% end %>
def semantic_errors(*args)
html_options = args.extract_options!
html_options[:class] ||= "errors"
if Formtastic::FormBuilder.semantic_errors_link_to_inputs
attribute_error_hash = semantic_error_hash_from_attributes(args)
return nil if @object.errors[:base].blank? && attribute_error_hash.blank?
template.content_tag(:ul, html_options) do
(
@object.errors[:base].map { |base_error| template.content_tag(:li, base_error) } <<
attribute_error_hash.map { |attribute, error_message|
template.content_tag(:li) do
template.content_tag(:a, href: "##{object_name}_#{attribute}") do
error_message
end
end
}
).join.html_safe
end
else
full_errors = @object.errors[:base]
full_errors += semantic_error_list_from_attributes(args)
return nil if full_errors.blank?
template.content_tag(:ul, html_options) do
full_errors.map { |error| template.content_tag(:li, error) }.join.html_safe
end
end
end
protected
def error_keys(method, options)
@methods_for_error ||= {}
@methods_for_error[method] ||= begin
methods_for_error = [method.to_sym]
methods_for_error << file_metadata_suffixes.map{|suffix| "#{method}_#{suffix}".to_sym} if is_file?(method, options)
methods_for_error << [association_primary_key_for_method(method)] if [:belongs_to, :has_many].include? association_macro_for_method(method)
methods_for_error.flatten.compact.uniq
end
end
def has_errors?(method, options)
methods_for_error = error_keys(method,options)
@object && @object.respond_to?(:errors) && methods_for_error.any?{|error| !@object.errors[error].blank?}
end
def render_inline_errors?
@object && @object.respond_to?(:errors) && Formtastic::FormBuilder::INLINE_ERROR_TYPES.include?(inline_errors)
end
def semantic_error_list_from_attributes(*args)
attribute_errors = []
args = args.flatten
args.each do |attribute|
next if attribute == :base
full_message = error_message_for_attribute(attribute)
attribute_errors << full_message unless full_message.blank?
end
attribute_errors
end
# returns { 'attribute': 'error_message_for_attribute' }
def semantic_error_hash_from_attributes(*args)
attribute_error_hash = {}
args = args.flatten
args.each do |attribute|
next if attribute == :base
full_message = error_message_for_attribute(attribute)
attribute_error_hash[attribute] = full_message unless full_message.blank?
end
attribute_error_hash
end
# Returns "Attribute error_message_sentence" localized, humanized
def error_message_for_attribute(attribute)
attribute_string = localized_string(attribute, attribute.to_sym, :label) || humanized_attribute_name(attribute)
error_message = @object.errors[attribute.to_sym]&.to_sentence
return nil if error_message.blank?
full_message = [attribute_string, error_message].join(" ")
full_message
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/fieldset_wrapper.rb | lib/formtastic/helpers/fieldset_wrapper.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# @private
module FieldsetWrapper
protected
# Generates a fieldset and wraps the content in an ordered list. When working
# with nested attributes, it allows %i as interpolation option in :name. So you can do:
#
# f.inputs :name => 'Task #%i', :for => :tasks
#
# or the shorter equivalent:
#
# f.inputs 'Task #%i', :for => :tasks
#
# And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
# 'Task #3' and so on.
#
# Note: Special case for the inline inputs (non-block):
# f.inputs "My little legend", :title, :body, :author # Explicit legend string => "My little legend"
# f.inputs :my_little_legend, :title, :body, :author # Localized (118n) legend with I18n key => I18n.t(:my_little_legend, ...)
# f.inputs :title, :body, :author # First argument is a column => (no legend)
def field_set_and_list_wrapping(*args, &block) # @private
contents = args[-1].is_a?(::Hash) ? '' : args.pop.flatten
html_options = args.extract_options!
if block_given?
contents = if template.respond_to?(:is_haml?) && template.is_haml?
template.capture_haml(&block)
else
template.capture(&block)
end
end
# Work-around for empty contents block
contents ||= ""
# Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
contents = contents.join if contents.respond_to?(:join)
legend = field_set_legend(html_options)
fieldset = template.content_tag(:fieldset,
legend.html_safe << template.content_tag(:ol, contents.html_safe),
html_options.except(:builder, :parent, :name)
)
fieldset
end
def field_set_legend(html_options)
legend = (html_options[:name] || '').to_s
# only applying if String includes '%i' avoids argument error when $DEBUG is true
legend %= parent_child_index(html_options[:parent]) if html_options[:parent] && legend.include?('%i')
legend = template.content_tag(:legend, template.content_tag(:span, legend.html_safe)) unless legend.blank?
legend
end
# Gets the nested_child_index value from the parent builder. It returns a hash with each
# association that the parent builds.
def parent_child_index(parent) # @private
# Could be {"post[authors_attributes]"=>0} or { :authors => 0 }
duck = parent[:builder].instance_variable_get('@nested_child_index')
# Could be symbol for the association, or a model (or an array of either, I think? TODO)
child = parent[:for]
# Pull a sybol or model out of Array (TODO: check if there's an Array)
child = child.first if child.respond_to?(:first)
# If it's an object, get a symbol from the class name
child = child.class.name.underscore.to_sym unless child.is_a?(Symbol)
key = "#{parent[:builder].object_name}[#{child}_attributes]"
# TODO: One of the tests produces a scenario where duck is "0" and the test looks for a "1"
# in the legend, so if we have a number, return it with a +1 until we can verify this scenario.
return duck + 1 if duck.is_a?(Integer)
# First try to extract key from duck Hash, then try child
(duck[key] || duck[child]).to_i + 1
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/file_column_detection.rb | lib/formtastic/helpers/file_column_detection.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# @private
module FileColumnDetection
def is_file?(method, options = {})
@files ||= {}
@files[method] ||= (options[:as].present? && options[:as] == :file) || begin
file = @object.send(method) if @object && @object.respond_to?(method)
file && file_methods.any?{|m| file.respond_to?(m)}
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/inputs_helper.rb | lib/formtastic/helpers/inputs_helper.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# {#inputs} is used to wrap a series of form items in a `<fieldset>` and `<ol>`, with each item
# in the list containing the markup representing a single {#input}.
#
# {#inputs} is usually called with a block containing a series of {#input} methods:
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :title %>
# <%= f.input :body %>
# <% end %>
# <% end %>
#
# The HTML output will be something like:
#
# <form class="formtastic" method="post" action="...">
# <fieldset>
# <ol>
# <li class="string required" id="post_title_input">
# ...
# </li>
# <li class="text required" id="post_body_input">
# ...
# </li>
# </ol>
# </fieldset>
# </form>
#
# It's important to note that the `semantic_form_for` and {#inputs} blocks wrap the
# standard Rails `form_for` helper and FormBuilder, so you have full access to every standard
# Rails form helper, with any HTML markup and ERB syntax, allowing you to "break free" from
# Formtastic when it doesn't suit:
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :title %>
# <li>
# <%= f.text_area :body %>
# <li>
# <% end %>
# <% end %>
#
# @see Formtastic::Helpers::InputHelper#input
module InputsHelper
include Formtastic::Helpers::FieldsetWrapper
include Formtastic::LocalizedString
# {#inputs} creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be
# called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
# or with a list of fields (accepting all default arguments and options). These two examples
# are functionally equivalent:
#
# # With a block:
# <% semantic_form_for @post do |form| %>
# <% f.inputs do %>
# <%= f.input :title %>
# <%= f.input :body %>
# <% end %>
# <% end %>
#
# # With a list of fields (short hand syntax):
# <% semantic_form_for @post do |form| %>
# <%= f.inputs :title, :body %>
# <% end %>
#
# # Output:
# <form ...>
# <fieldset class="inputs">
# <ol>
# <li class="string">...</li>
# <li class="text">...</li>
# </ol>
# </fieldset>
# </form>
#
# **Quick Forms**
#
# Quick, scaffolding-style forms can be easily rendered for rapid early development if called
# without a block or a field list. In the case an input is rendered for **most** columns in
# the model's database table (like Rails' scaffolding) plus inputs for some model associations.
#
# In this case, all inputs are rendered with default options and arguments. You'll want more
# control than this in a production application, but it's a great way to get started, then
# come back later to customise the form with a field list or a block of inputs. Example:
#
# <% semantic_form_for @post do |form| %>
# <%= f.inputs %>
# <% end %>
#
# **Nested Attributes**
#
# One of the most complicated parts of Rails forms comes when nesting the inputs for
# attrinbutes on associated models. Formtastic can take the pain away for many (but not all)
# situations.
#
# Given the following models:
#
# # Models
# class User < ActiveRecord::Base
# has_one :profile
# accepts_nested_attributes_for :profile
# end
# class Profile < ActiveRecord::Base
# belongs_to :user
# end
#
# Formtastic provides a helper called `semantic_fields_for`, which wraps around Rails' built-in
# `fields_for` helper for backwards compatibility with previous versions of Formtastic, and for
# a consistent method naming API. The following examples are functionally equivalent:
#
# <% semantic_form_for @user do |form| %>
# <%= f.inputs :name, :email %>
#
# <% f.semantic_fields_for :profile do |profile| %>
# <% profile.inputs do %>
# <%= profile.input :biography %>
# <%= profile.input :twitter_name %>
# <% end %>
# <% end %>
# <% end %>
#
# <% semantic_form_for @user do |form| %>
# <%= f.inputs :name, :email %>
#
# <% f.fields_for :profile do |profile| %>
# <% profile.inputs do %>
# <%= profile.input :biography %>
# <%= profile.input :twitter_name %>
# <% end %>
# <% end %>
# <% end %>
#
# {#inputs} also provides a DSL similar to `fields_for` / `semantic_fields_for` to reduce the
# lines of code a little:
#
# <% semantic_form_for @user do |f| %>
# <%= f.inputs :name, :email %>
#
# <% f.inputs :for => :profile do %>
# <%= profile.input :biography %>
# <%= profile.input :twitter_name %>
# <%= profile.input :shoe_size %>
# <% end %>
# <% end %>
#
# The `:for` option also works with short hand syntax:
#
# <% semantic_form_for @post do |form| %>
# <%= f.inputs :name, :email %>
# <%= f.inputs :biography, :twitter_name, :shoe_size, :for => :profile %>
# <% end %>
#
# {#inputs} will always create a new `<fieldset>` wrapping, so only use it when it makes sense
# in the document structure and semantics (using `semantic_fields_for` otherwise).
#
# All options except `:name`, `:title` and `:for` will be passed down to the fieldset as HTML
# attributes (id, class, style, etc).
#
# When nesting `inputs()` inside another `inputs()` block, the nested content will
# automatically be wrapped in an `<li>` tag to preserve the HTML validity (a `<fieldset>`
# cannot be a direct descendant of an `<ol>`.
#
#
# @option *args :for [Symbol, ActiveModel, Array]
# The contents of this option is passed down to Rails' fields_for() helper, so it accepts the same values.
#
# @option *args :name [String]
# The optional name passed into the `<legend>` tag within the fieldset (alias of `:title`)
#
# @option *args :title [String]
# The optional name passed into the `<legend>` tag within the fieldset (alias of `:name`)
#
#
# @example Quick form: Render a scaffold-like set of inputs for automatically guessed attributes and simple associations on the model, with all default arguments and options
# <% semantic_form_for @post do |form| %>
# <%= f.inputs %>
# <% end %>
#
# @example Quick form: Skip one or more fields
# <%= f.inputs :except => [:featured, :something_for_admin_only] %>
# <%= f.inputs :except => :featured %>
#
# @example Short hand: Render inputs for a named set of attributes and simple associations on the model, with all default arguments and options
# <% semantic_form_for @post do |form| %>
# <%= f.inputs :title, :body, :user, :categories %>
# <% end %>
#
# @example Block: Render inputs for attributes and simple associations with full control over arguments and options
# <% semantic_form_for @post do |form| %>
# <%= f.inputs do %>
# <%= f.input :title ... %>
# <%= f.input :body ... %>
# <%= f.input :user ... %>
# <%= f.input :categories ... %>
# <% end %>
# <% end %>
#
# @example Multiple blocks: Render inputs in multiple fieldsets
# <% semantic_form_for @post do |form| %>
# <%= f.inputs do %>
# <%= f.input :title ... %>
# <%= f.input :body ... %>
# <% end %>
# <%= f.inputs do %>
# <%= f.input :user ... %>
# <%= f.input :categories ... %>
# <% end %>
# <% end %>
#
# @example Provide text for the `<legend>` to name a fieldset (with a block)
# <% semantic_form_for @post do |form| %>
# <%= f.inputs :name => 'Write something:' do %>
# <%= f.input :title ... %>
# <%= f.input :body ... %>
# <% end %>
# <%= f.inputs :name => 'Advanced options:' do %>
# <%= f.input :user ... %>
# <%= f.input :categories ... %>
# <% end %>
# <% end %>
#
# @example Provide text for the `<legend>` to name a fieldset (with short hand)
# <% semantic_form_for @post do |form| %>
# <%= f.inputs :title, :body, :name => 'Write something:'%>
# <%= f.inputs :user, :cateogies, :name => 'Advanced options:' %>
# <% end %>
#
# @example Inputs for nested attributes (don't forget `accepts_nested_attributes_for` in your model, see Rails' `fields_for` documentation)
# <% semantic_form_for @user do |form| %>
# <%= f.inputs do %>
# <%= f.input :name ... %>
# <%= f.input :email ... %>
# <% end %>
# <%= f.inputs :for => :profile do |profile| %>
# <%= profile.input :user ... %>
# <%= profile.input :categories ... %>
# <% end %>
# <% end %>
#
# @example Inputs for nested record (don't forget `accepts_nested_attributes_for` in your model, see Rails' `fields_for` documentation)
# <% semantic_form_for @user do |form| %>
# <%= f.inputs do %>
# <%= f.input :name ... %>
# <%= f.input :email ... %>
# <% end %>
# <%= f.inputs :for => @user.profile do |profile| %>
# <%= profile.input :user ... %>
# <%= profile.input :categories ... %>
# <% end %>
# <% end %>
#
# @example Inputs for nested record with a different name (don't forget `accepts_nested_attributes_for` in your model, see Rails' `fields_for` documentation)
# <% semantic_form_for @user do |form| %>
# <%= f.inputs do %>
# <%= f.input :name ... %>
# <%= f.input :email ... %>
# <% end %>
# <%= f.inputs :for => [:user_profile, @user.profile] do |profile| %>
# <%= profile.input :user ... %>
# <%= profile.input :categories ... %>
# <% end %>
# <% end %>
#
# @example Nesting {#inputs} blocks requires an extra `<li>` tag for valid markup
# <% semantic_form_for @user do |form| %>
# <%= f.inputs do %>
# <%= f.input :name ... %>
# <%= f.input :email ... %>
# <li>
# <%= f.inputs :for => [:user_profile, @user.profile] do |profile| %>
# <%= profile.input :user ... %>
# <%= profile.input :categories ... %>
# <% end %>
# </li>
# <% end %>
# <% end %>
def inputs(*args, &block)
wrap_it = @already_in_an_inputs_block ? true : false
@already_in_an_inputs_block = true
title = field_set_title_from_args(*args)
html_options = args.extract_options!
html_options[:class] ||= "inputs"
html_options[:name] = title
skipped_args = Array.wrap html_options.delete(:except)
out = begin
if html_options[:for] # Nested form
inputs_for_nested_attributes(*(args << html_options), &block)
elsif block_given?
field_set_and_list_wrapping(*(args << html_options), &block)
else
legend = args.shift if args.first.is_a?(::String)
args = default_columns_for_object - skipped_args if @object && args.empty?
contents = fieldset_contents_from_column_list(args)
args.unshift(legend) if legend.present?
field_set_and_list_wrapping(*((args << html_options) << contents))
end
end
out = template.content_tag(:li, out, :class => "input") if wrap_it
@already_in_an_inputs_block = wrap_it
out
end
protected
def default_columns_for_object
cols = association_columns(:belongs_to)
cols += content_columns
cols -= skipped_columns
cols.compact
end
def fieldset_contents_from_column_list(columns)
columns.collect do |method|
if @object
if @object.class.respond_to?(:reflect_on_association)
if (@object.class.reflect_on_association(method.to_sym) && @object.class.reflect_on_association(method.to_sym).options[:polymorphic] == true)
raise PolymorphicInputWithoutCollectionError.new("Please provide a collection for :#{method} input (you'll need to use block form syntax). Inputs for polymorphic associations can only be used when an explicit :collection is provided.")
end
elsif @object.class.respond_to?(:associations)
if (@object.class.associations[method.to_sym] && @object.class.associations[method.to_sym].options[:polymorphic] == true)
raise PolymorphicInputWithoutCollectionError.new("Please provide a collection for :#{method} input (you'll need to use block form syntax). Inputs for polymorphic associations can only be used when an explicit :collection is provided.")
end
end
end
input(method.to_sym)
end
end
# Collects association columns (relation columns) for the current form object class. Skips
# polymorphic associations because we can't guess which class to use for an automatically
# generated input.
def association_columns(*by_associations) # @private
if @object.present? && @object.class.respond_to?(:reflections)
@object.class.reflections.collect do |name, association_reflection|
if by_associations.present?
if by_associations.include?(association_reflection.macro) && association_reflection.options[:polymorphic] != true
name
end
else
name
end
end.compact
else
[]
end
end
# Collects all foreign key columns
def foreign_key_columns # @private
if @object.present? && @object.class.respond_to?(:reflect_on_all_associations)
@object.class.reflect_on_all_associations(:belongs_to).map{ |reflection| reflection.foreign_key.to_sym }
else
[]
end
end
# Collects content columns (non-relation columns) for the current form object class.
def content_columns # @private
# TODO: NameError is raised by Inflector.constantize. Consider checking if it exists instead.
begin klass = model_name.constantize; rescue NameError; return [] end
return [] unless klass.respond_to?(:content_columns)
klass.content_columns.collect { |c| c.name.to_sym }.compact - foreign_key_columns
end
# Deals with :for option when it's supplied to inputs methods. Additional
# options to be passed down to :for should be supplied using :for_options
# key.
#
# It should raise an error if a block with arity zero is given.
def inputs_for_nested_attributes(*args, &block) # @private
options = args.extract_options!
args << options.merge!(:parent => { :builder => self, :for => options[:for] })
fields_for_block = if block_given?
raise ArgumentError, 'You gave :for option with a block to inputs method, ' +
'but the block does not accept any argument.' if block.arity <= 0
lambda do |f|
contents = f.inputs(*args) do
if block.arity == 1 # for backwards compatibility with REE & Ruby 1.8.x
yield(f)
else
index = parent_child_index(options[:parent]) if options[:parent]
yield(f, index)
end
end
template.concat(contents)
end
else
lambda do |f|
contents = f.inputs(*args)
template.concat(contents)
end
end
fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten(1)
fields_for(*fields_for_args, &fields_for_block)
end
def field_set_title_from_args(*args) # @private
options = args.extract_options!
options[:name] ||= options.delete(:title)
title = options[:name]
if title.blank?
valid_name_classes = [::String, ::Symbol]
valid_name_classes.delete(::Symbol) if !block_given? && (args.first.is_a?(::Symbol) && content_columns.include?(args.first))
title = args.shift if valid_name_classes.any? { |valid_name_class| args.first.is_a?(valid_name_class) }
end
title = localized_string(title, title, :title) if title.is_a?(::Symbol)
title
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/action_helper.rb | lib/formtastic/helpers/action_helper.rb | # -*- coding: utf-8 -*-
# frozen_string_literal: true
module Formtastic
module Helpers
module ActionHelper
# Renders an action for the form (such as a subit/reset button, or a cancel link).
#
# Each action is wrapped in an `<li class="action">` tag with other classes added based on the
# type of action being rendered, and is intended to be rendered inside a {#buttons}
# block which wraps the button in a `fieldset` and `ol`.
#
# The textual value of the label can be changed from the default through the `:label`
# argument or through i18n.
#
# If using i18n, you'll need to provide the following translations:
#
# en:
# formtastic:
# actions:
# create: "Create new %{model}"
# update: "Save %{model}"
# cancel: "Cancel"
# reset: "Reset form"
# submit: "Submit"
#
# For forms with an object present, the `update` key will be used if calling `persisted?` on
# the object returns true (saving changes to a record), otherwise the `create` key will be
# used. The `submit` key is used as a fallback when there is no object or we cannot determine
# if `create` or `update` is appropriate.
#
# @example Basic usage
# # form
# <%= semantic_form_for @post do |f| %>
# ...
# <%= f.actions do %>
# <%= f.action :submit %>
# <%= f.action :reset %>
# <%= f.action :cancel %>
# <% end %>
# <% end %>
#
# # output
# <form ...>
# ...
# <fieldset class="buttons">
# <ol>
# <li class="action input_action">
# <input name="commit" type="submit" value="Create Post">
# </li>
# <li class="action input_action">
# <input name="commit" type="reset" value="Reset Post">
# </li>
# <li class="action link_action">
# <a href="/posts">Cancel Post</a>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Set the value through the `:label` option
# <%= f.action :submit, :label => "Go" %>
#
# @example Pass HTML attributes down to the tag inside the wrapper
# <%= f.action :submit, :button_html => { :class => 'pretty', :accesskey => 'g', :disable_with => "Wait..." } %>
#
# @example Pass HTML attributes down to the `<li>` wrapper
# <%= f.action :submit, :wrapper_html => { :class => 'special', :id => 'whatever' } %>
#
# @option *args :label [String, Symbol]
# Override the label text with a String or a symbold for an i18n translation key
#
# @option *args :button_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<input>` tag
#
# @option *args :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
#
# @todo document i18n keys
def action(method, options = {})
options = options.dup # Allow options to be shared without being tainted by Formtastic
options[:as] ||= default_action_type(method, options)
klass = namespaced_action_class(options[:as])
klass.new(self, template, @object, @object_name, method, options).to_html
end
protected
def default_action_type(method, options = {}) # @private
case method
when :submit then :input
when :reset then :input
when :cancel then :link
else method
end
end
# Takes the `:as` option and attempts to return the corresponding action
# class. In the case of `:as => :awesome` it will first attempt to find a
# top level `AwesomeAction` class (to allow the application to subclass
# and modify to suit), falling back to `Formtastic::Actions::AwesomeAction`.
#
# Custom action namespaces to look into can be configured via the
# {Formtastic::FormBuilder.action_namespaces} configuration setting.
# @see Helpers::InputHelper#namespaced_input_class
# @see Formtastic::ActionClassFinder
def namespaced_action_class(as)
@action_class_finder ||= action_class_finder.new(self)
@action_class_finder.find(as)
rescue Formtastic::ActionClassFinder::NotFoundError => e
raise Formtastic::UnknownActionError, "Unable to find action #{e.message}"
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/input_helper.rb | lib/formtastic/helpers/input_helper.rb | # -*- coding: utf-8 -*-
# frozen_string_literal: true
module Formtastic
module Helpers
# {#input} is used to render all content (labels, form widgets, error messages, hints, etc) for
# a single form input (or field), usually representing a single method or attribute on the
# form's object or model.
#
# The content is wrapped in an `<li>` tag, so it's usually called inside an {Formtastic::Helpers::InputsHelper#inputs inputs} block
# (which renders an `<ol>` inside a `<fieldset>`), which should be inside a {Formtastic::Helpers::FormHelper#semantic_form_for `semantic_form_for`}
# block:
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :title %>
# <%= f.input :body %>
# <% end %>
# <% end %>
#
# The HTML output will be something like:
#
# <form class="formtastic" method="post" action="...">
# <fieldset>
# <ol>
# <li class="string required" id="post_title_input">
# ...
# </li>
# <li class="text required" id="post_body_input">
# ...
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see #input
# @see Formtastic::Helpers::InputsHelper#inputs
# @see Formtastic::Helpers::FormHelper#semantic_form_for
module InputHelper
include Formtastic::Helpers::Reflection
include Formtastic::Helpers::Enum
include Formtastic::Helpers::FileColumnDetection
# Returns a chunk of HTML markup for a given `method` on the form object, wrapped in
# an `<li>` wrapper tag with appropriate `class` and `id` attribute hooks for CSS and JS.
# In many cases, the contents of the wrapper will be as simple as a `<label>` and an `<input>`:
#
# <%= f.input :title, :as => :string, :required => true %>
#
# <li class="string required" id="post_title_input">
# <label for="post_title">Title<abbr title="Required">*</abbr></label>
# <input type="text" name="post[title]" value="" id="post_title" required="required">
# </li>
#
# In other cases (like a series of checkboxes for a `has_many` relationship), the wrapper may
# include more complex markup, like a nested `<fieldset>` with a `<legend>` and an `<ol>` of
# checkbox/label pairs for each choice:
#
# <%= f.input :categories, :as => :check_boxes, :collection => Category.active.ordered %>
#
# <li class="check_boxes" id="post_categories_input">
# <fieldset>
# <legend>Categories</legend>
# <ol>
# <li>
# <label><input type="checkbox" name="post[categories][1]" value="1"> Ruby</label>
# </li>
# <li>
# <label><input type="checkbox" name="post[categories][2]" value="2"> Rails</label>
# </li>
# <li>
# <label><input type="checkbox" name="post[categories][2]" value="2"> Awesome</label>
# </li>
# </ol>
# </fieldset>
# </li>
#
# Sensible defaults for all options are guessed by looking at the method name, database column
# information, association information, validation information, etc. For example, a `:string`
# database column will map to a `:string` input, but if the method name contains 'email', will
# map to an `:email` input instead. `belongs_to` associations will have a `:select` input, etc.
#
# Formtastic supports many different styles of inputs, and you can/should override the default
# with the `:as` option. Internally, the symbol is used to map to a protected method
# responsible for the details. For example, `:as => :string` will map to `string_input`,
# defined in a module of the same name. Detailed documentation for each input style and it's
# supported options is available on the `*_input` method in each module (links provided below).
#
# Available input styles:
#
# * `:boolean` (see {Inputs::BooleanInput})
# * `:check_boxes` (see {Inputs::CheckBoxesInput})
# * `:color` (see {Inputs::ColorInput})
# * `:country` (see {Inputs::CountryInput})
# * `:datetime_select` (see {Inputs::DatetimeSelectInput})
# * `:date_select` (see {Inputs::DateSelectInput})
# * `:email` (see {Inputs::EmailInput})
# * `:file` (see {Inputs::FileInput})
# * `:hidden` (see {Inputs::HiddenInput})
# * `:number` (see {Inputs::NumberInput})
# * `:password` (see {Inputs::PasswordInput})
# * `:phone` (see {Inputs::PhoneInput})
# * `:radio` (see {Inputs::RadioInput})
# * `:search` (see {Inputs::SearchInput})
# * `:select` (see {Inputs::SelectInput})
# * `:string` (see {Inputs::StringInput})
# * `:text` (see {Inputs::TextInput})
# * `:time_zone` (see {Inputs::TimeZoneInput})
# * `:time_select` (see {Inputs::TimeSelectInput})
# * `:url` (see {Inputs::UrlInput})
#
# Calling `:as => :string` (for example) will call `#to_html` on a new instance of
# `Formtastic::Inputs::StringInput`. Before this, Formtastic will try to instantiate a top-level
# namespace StringInput, meaning you can subclass and modify `Formtastic::Inputs::StringInput`
# in `app/inputs/`. This also means you can create your own new input types in `app/inputs/`.
#
# @todo document the "guessing" of input style
#
# @param [Symbol] method
# The database column or method name on the form object that this input represents
#
# @option options :as [Symbol]
# Override the style of input should be rendered
#
# @option options :label [String, Symbol, false]
# Override the label text
#
# @option options :hint [String, Symbol, false]
# Override hint text
#
# @option options :required [Boolean]
# Override to mark the input as required (or not) — adds a required/optional class to the wrapper, and a HTML5 required attribute to the `<input>`
#
# @option options :input_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<input>` tag
# (If you use attr_readonly method in your model, formtastic will automatically set those attributes's input readonly)
#
# @option options :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
#
# @option options :collection [Array<ActiveModel, String, Symbol>, Hash{String => String, Boolean}, OrderedHash{String => String, Boolean}]
# Override collection of objects in the association (`:select`, `:radio` & `:check_boxes` inputs only)
#
# @option options :multiple [Boolean]
# Specify if the `:select` input should allow multiple selections or not (defaults to `belongs_to` associations, and `true` for `has_many` and `has_and_belongs_to_many` associations)
#
# @option options :include_blank [Boolean]
# Specify if a `:select` input should include a blank option or not (defaults to `include_blank_for_select_by_default` configuration)
#
# @option options :prompt [String]
# Specify the text in the first ('blank') `:select` input `<option>` to prompt a user to make a selection (implicitly sets `:include_blank` to `true`)
#
# @todo Can we deprecate & kill `:label`, `:hint` & `:prompt`? All strings could be shifted to i18n!
#
# @example Accept all default options
# <%= f.input :title %>
#
# @example Change the input type
# <%= f.input :title, :as => :string %>
#
# @example Changing the label with a String
# <%= f.input :title, :label => "Post title" %>
#
# @example Disabling the label with false, even if an i18n translation exists
# <%= f.input :title, :label => false %>
#
# @example Changing the hint with a String
# <%= f.input :title, :hint => "Every post needs a title!" %>
#
# @example Disabling the hint with false, even if an i18n translation exists
# <%= f.input :title, :hint => false %>
#
# @example Marking a field as required or not (even if validations do not enforce it)
# <%= f.input :title, :required => true %>
# <%= f.input :title, :required => false %>
#
# @example Changing or adding to HTML attributes in the main `<input>` or `<select>` tag
# <%= f.input :title, :input_html => { :onchange => "somethingAwesome();", :class => 'awesome' } %>
#
# @example Changing or adding to HTML attributes in the main `<label>` tag
# <%= f.input :title, :label_html => { :data => { :tooltip => 'Great Tooltip' } } %>
#
# @example Changing or adding to HTML attributes in the wrapper `<li>` tag
# <%= f.input :title, :wrapper_html => { :class => "important-input" } %>
#
# @example Changing the association choices with `:collection`
# <%= f.input :author, :collection => User.active %>
# <%= f.input :categories, :collection => Category.where(...).order(...) %>
# <%= f.input :status, :collection => ["Draft", "Published"] %>
# <%= f.input :status, :collection => [:draft, :published] %>
# <%= f.input :status, :collection => {"Draft" => 0, "Published" => 1} %>
# <%= f.input :status, :collection => OrderedHash.new("Draft" => 0, "Published" => 1) %>
# <%= f.input :status, :collection => [["Draft", 0], ["Published", 1]] %>
# <%= f.input :status, :collection => grouped_options_for_select(...) %>
# <%= f.input :status, :collection => options_for_select(...) %>
#
# @example Specifying if a `:select` should allow multiple selections:
# <%= f.input :cateogies, :as => :select, :multiple => true %>
# <%= f.input :cateogies, :as => :select, :multiple => false %>
#
# @example Specifying if a `:select` should have a 'blank' first option to prompt selection:
# <%= f.input :author, :as => :select, :include_blank => true %>
# <%= f.input :author, :as => :select, :include_blank => false %>
#
# @example Specifying the text for a `:select` input's 'blank' first option to prompt selection:
# <%= f.input :author, :as => :select, :prompt => "Select an Author" %>
#
# @example Modifying an input to suit your needs in `app/inputs`:
# class StringInput < Formtastic::Inputs::StringInput
# def to_html
# puts "this is my custom version of StringInput"
# super
# end
# end
#
# @example Creating your own input to suit your needs in `app/inputs`:
# class DatePickerInput
# include Formtastic::Inputs::Base
# def to_html
# # ...
# end
# end
#
# @example Providing HTML5 placeholder text through i18n:
# en:
# formtastic:
# placeholders:
# user:
# email: "you@yours.com"
# first_name: "Joe"
# last_name: "Smith"
#
# @see #namespaced_input_class
# @todo Many many more examples. Some of the detail probably needs to be pushed out to the relevant methods too.
# @todo More i18n examples.
def input(method, options = {})
method = method.to_sym
options = options.dup # Allow options to be shared without being tainted by Formtastic
options[:as] ||= default_input_type(method, options)
klass = namespaced_input_class(options[:as])
klass.new(self, template, @object, @object_name, method, options).to_html
end
protected
# First try if we can detect special things like :file. With CarrierWave the method does have
# an underlying column so we don't want :string to get selected.
#
# For methods that have a database column, take a best guess as to what the input method
# should be. In most cases, it will just return the column type (eg :string), but for special
# cases it will simplify (like the case of :integer, :float & :decimal to :number), or do
# something different (like :password and :select).
#
# If there is no column for the method (eg "virtual columns" with an attr_accessor), the
# default is a :string, a similar behaviour to Rails' scaffolding.
def default_input_type(method, options = {}) # @private
if @object
return :select if reflection_for(method)
return :file if is_file?(method, options)
end
column = column_for(method)
if column && column.type
# Special cases where the column type doesn't map to an input method.
case column.type
when :string
return :password if method.to_s =~ /password/
return :country if method.to_s =~ /country$/
return :time_zone if method.to_s =~ /time_zone/
return :email if method.to_s =~ /email/
return :url if method.to_s =~ /^url$|^website$|_url$/
return :phone if method.to_s =~ /(phone|fax)/
return :search if method.to_s =~ /^search$/
return :color if method.to_s =~ /color/
when :integer
return :select if reflection_for(method)
return :select if enum_for(method)
return :number
when :float, :decimal
return :number
when :datetime, :timestamp
return :datetime_select
when :time
return :time_select
when :date
return :date_select
when :hstore, :json, :jsonb
return :text
when :citext, :inet
return :string
end
# Try look for hints in options hash. Quite common senario: Enum keys stored as string in the database.
return :select if column.type == :string && options.key?(:collection)
# Try 3: Assume the input name will be the same as the column type (e.g. string_input).
return column.type
else
return :select if options.key?(:collection)
return :password if method.to_s =~ /password/
return :string
end
end
# Get a column object for a specified attribute method - if possible.
# @return [ActiveModel::Type::Value, #type] in case of rails 5 attributes api
# @return [ActiveRecord::ConnectionAdapters::Column] in case of rails 4
def column_for(method) # @private
case
when @object.class.respond_to?(:type_for_attribute)
@object.class.type_for_attribute(method.to_s)
when @object.class.respond_to?(:column_for_attribute)
@object.class.column_for_attribute(method)
when @object.respond_to?(:column_for_attribute)
@object.column_for_attribute(method)
else nil
end
end
# Takes the `:as` option and attempts to return the corresponding input
# class. In the case of `:as => :awesome` it will first attempt to find a
# top level `AwesomeInput` class (to allow the application to subclass
# and modify to suit), falling back to `Formtastic::Inputs::AwesomeInput`.
#
# Custom input namespaces to look into can be configured via the
# {Formtastic::FormBuilder.input_namespaces} configuration setting.
#
# @param [Symbol] as A symbol representing the type of input to render
# @raise [Formtastic::UnknownInputError] An appropriate input class could not be found
# @return [Class] An input class constant
#
# @example Normal use
# input_class(:string) #=> Formtastic::Inputs::StringInput
# input_class(:date) #=> Formtastic::Inputs::DateInput
#
# @example When a top-level class is found
# input_class(:string) #=> StringInput
# input_class(:awesome) #=> AwesomeInput
# @see NamespacedClassFinder#find
def namespaced_input_class(as)
@input_class_finder ||= input_class_finder.new(self)
@input_class_finder.find(as)
rescue Formtastic::InputClassFinder::NotFoundError
raise Formtastic::UnknownInputError, "Unable to find input #{$!.message}"
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/reflection.rb | lib/formtastic/helpers/reflection.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# @private
module Reflection
# If an association method is passed in (f.input :author) try to find the
# reflection object.
def reflection_for(method) # @private
if @object.class.respond_to?(:reflect_on_association)
@object.class.reflect_on_association(method)
elsif @object.class.respond_to?(:associations) # MongoMapper uses the 'associations(method)' instead
@object.class.associations[method]
end
end
def association_macro_for_method(method) # @private
reflection = reflection_for(method)
reflection.macro if reflection
end
def association_primary_key_for_method(method) # @private
reflection = reflection_for(method)
if reflection
case association_macro_for_method(method)
when :has_and_belongs_to_many, :has_many, :references_and_referenced_in_many, :references_many
:"#{method.to_s.singularize}_ids"
else
return reflection.foreign_key.to_sym if reflection.respond_to?(:foreign_key)
return reflection.options[:foreign_key].to_sym unless reflection.options[:foreign_key].blank?
:"#{method}_id"
end
else
method.to_sym
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/enum.rb | lib/formtastic/helpers/enum.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# @private
module Enum
# Returns the enum (if defined) for the given method
def enum_for(method) # @private
if @object.respond_to?(:defined_enums)
@object.defined_enums[method.to_s]
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/helpers/actions_helper.rb | lib/formtastic/helpers/actions_helper.rb | # frozen_string_literal: true
module Formtastic
module Helpers
# ActionsHelper encapsulates the responsibilties of the {#actions} DSL for acting on
# (submitting, cancelling, resetting) forms.
#
# {#actions} is a block helper used to wrap the form's actions (buttons, links) in a
# `<fieldset>` and `<ol>`, with each item in the list containing the markup representing a
# single action.
#
# <%= semantic_form_for @post do |f| %>
# ...
# <%= f.actions do %>
# <%= f.action :submit
# <%= f.action :cancel
# <% end %>
# <% end %>
#
# The HTML output will be something like:
#
# <form class="formtastic" method="post" action="...">
# ...
# <fieldset class="actions">
# <ol>
# <li class="action input_action">
# <input type="submit" name="commit" value="Create Post">
# </li>
# <li class="action input_action">
# <a href="/posts">Cancel Post</a>
# </li>
# </ol>
# </fieldset>
# </form>
#
# It's important to note that the `semantic_form_for` and {#actions} blocks wrap the
# standard Rails `form_for` helper and form builder, so you have full access to every standard
# Rails form helper, with any HTML markup and ERB syntax, allowing you to "break free" from
# Formtastic when it doesn't suit to create your own buttons, links and actions:
#
# <%= semantic_form_for @post do |f| %>
# ...
# <%= f.actions do %>
# <li class="save">
# <%= f.submit "Save" %>
# <li>
# <li class="cancel-link">
# Or <%= link_to "Cancel", posts_url %>
# <li>
# <% end %>
# <% end %>
#
# There are many other syntax variations and arguments to customize your form. See the
# full documentation of {#actions} and {#action} for details.
module ActionsHelper
include Formtastic::Helpers::FieldsetWrapper
# Creates a fieldset and ol tag wrapping for use around a set of buttons. It can be
# called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
# or with a list of named actions. These two examples are functionally equivalent:
#
# # With a block:
# <% semantic_form_for @post do |f| %>
# ...
# <% f.actions do %>
# <%= f.action :submit %>
# <%= f.action :cancel %>
# <% end %>
# <% end %>
#
# # With a list of fields:
# <% semantic_form_for @post do |f| %>
# <%= f.actions :submit, :cancel %>
# <% end %>
#
# # Output:
# <form ...>
# <fieldset class="buttons">
# <ol>
# <li class="action input_action">
# <input type="submit" ...>
# </li>
# <li class="action link_action">
# <a href="...">...</a>
# </li>
# </ol>
# </fieldset>
# </form>
#
# All options except `:name` and `:title` are passed down to the fieldset as HTML
# attributes (`id`, `class`, `style`...). If provided, the `:name` or `:title` option is
# passed into a `<legend>` inside the `<fieldset>` to name the set of buttons.
#
# @example Quickly add button(s) to the form, accepting all default values, options and behaviors
# <% semantic_form_for @post do |f| %>
# ...
# <%= f.actions %>
# <% end %>
#
# @example Specify which named buttons you want, accepting all default values, options and behaviors
# <% semantic_form_for @post do |f| %>
# ...
# <%= f.actions :commit %>
# <% end %>
#
# @example Specify which named buttons you want, and name the fieldset
# <% semantic_form_for @post do |f| %>
# ...
# <%= f.actions :commit, :name => "Actions" %>
# or
# <%= f.actions :commit, :label => "Actions" %>
# <% end %>
#
# @example Get full control over the action options
# <% semantic_form_for @post do |f| %>
# ...
# <%= f.actions do %>
# <%= f.action :label => "Go", :button_html => { :class => "pretty" :disable_with => "Wait..." }, :wrapper_html => { ... }
# <% end %>
# <% end %>
#
# @example Make your own actions with standard Rails helpers or HTML
# <% semantic_form_for @post do |f| %>
# <%= f.actions do %>
# <li>
# ...
# </li>
# <% end %>
# <% end %>
#
# @example Add HTML attributes to the fieldset
# <% semantic_form_for @post do |f| %>
# ...
# <%= f.actions :commit, :style => "border:1px;" %>
# or
# <%= f.actions :style => "border:1px;" do %>
# ...
# <% end %>
# <% end %>
#
# @option *args :label [String, Symbol]
# Optionally specify text for the legend of the fieldset
#
# @option *args :name [String, Symbol]
# Optionally specify text for the legend of the fieldset (alias for `:label`)
#
# @todo document i18n keys
def actions(*args, &block)
html_options = args.extract_options!
html_options[:class] ||= "actions"
if block_given?
field_set_and_list_wrapping(html_options, &block)
else
args = default_actions if args.empty?
contents = args.map { |action_name| action(action_name) }
field_set_and_list_wrapping(html_options, contents)
end
end
protected
def default_actions
[:submit]
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/actions/input_action.rb | lib/formtastic/actions/input_action.rb | # frozen_string_literal: true
module Formtastic
module Actions
# Outputs an `<input type="submit">` or `<input type="reset">` wrapped in the standard `<li>`
# wrapper. This the default for `:submit` and `:reset` actions, but `:as => :button` is also
# available as an alternative.
#
# @example The `:as` can be ommitted, these are functionally equivalent
# <%= f.action :submit, :as => :input %>
# <%= f.action :submit %>
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.actions do %>
# <%= f.action :reset, :as => :input %>
# <%= f.action :submit, :as => :input %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset class="actions">
# <ol>
# <li class="action input_action" id="post_reset_action">
# <input type="reset" value="Reset">
# </li>
# <li class="action input_action" id="post_submit_action">
# <input type="submit" value="Create Post">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Specifying a label with a String
# <%= f.action :submit, :as => :input, :label => "Go" %>
#
# @example Pass HTML attributes down to the `<input>`
# <%= f.action :submit, :as => :input, :button_html => { :class => 'pretty', :accesskey => 'g', :disable_with => "Wait..." } %>
#
# @example Access key can also be set as a top-level option
# <%= f.action :submit, :as => :input, :accesskey => 'g' %>
#
# @example Pass HTML attributes down to the `<li>` wrapper (classes are appended to the existing classes)
# <%= f.action :submit, :as => :input, :wrapper_html => { :class => 'special', :id => 'whatever' } %>
# <%= f.action :submit, :as => :input, :wrapper_html => { :class => ['extra', 'special'], :id => 'whatever' } %>
# @todo document i18n keys
# @todo document i18n translation with :label (?)
class InputAction
include Base
include Buttonish
# @see Formtastic::Helpers::ActionHelper#action
# @option *args :label [String, Symbol]
# Override the label text with a String or a symbol for an i18n translation key
#
# @option *args :button_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<input>` tag
#
# @option *args :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
#
def to_html
wrapper do
builder.submit(text, button_html)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/actions/buttonish.rb | lib/formtastic/actions/buttonish.rb | # frozen_string_literal: true
module Formtastic
module Actions
module Buttonish
def supported_methods
[:submit, :reset]
end
def extra_button_html_options
{
:type => method
}
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/actions/button_action.rb | lib/formtastic/actions/button_action.rb | # frozen_string_literal: true
module Formtastic
module Actions
# Outputs a `<button type="submit">` or `<button type="reset">` wrapped in the standard `<li>`
# wrapper. This is an alternative choice for `:submit` and `:reset` actions, which render with
# `<input type="submit">` and `<input type="reset">` by default.
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.actions do %>
# <%= f.action :reset, :as => :button %>
# <%= f.action :submit, :as => :button %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset class="actions">
# <ol>
# <li class="action button_action" id="post_reset_action">
# <button type="reset" value="Reset">
# </li>
# <li class="action button_action" id="post_submit_action">
# <button type="submit" value="Create Post">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Specifying a label with a String
# <%= f.action :submit, :as => :button, :label => "Go" %>
#
# @example Pass HTML attributes down to the `<button>`
# <%= f.action :submit, :as => :button, :button_html => { :class => 'pretty', :accesskey => 'g', :disable_with => "Wait..." } %>
#
# @example Access key can also be set as a top-level option
# <%= f.action :submit, :as => :button, :accesskey => 'g' %>
#
# @example Pass HTML attributes down to the `<li>` wrapper (classes are appended to the existing classes)
# <%= f.action :submit, :as => :button, :wrapper_html => { :class => 'special', :id => 'whatever' } %>
# <%= f.action :submit, :as => :button, :wrapper_html => { :class => ['extra', 'special'], :id => 'whatever' } %>
#
# @todo document i18n keys
# @todo document i18n translation with :label (?)
class ButtonAction
include Base
include Buttonish
# @see Formtastic::Helpers::ActionHelper#action
# @option *args :label [String, Symbol]
# Override the label text with a String or a symbol for an i18n translation key
#
# @option *args :button_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<input>` tag
#
# @option *args :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
# TODO reset_action class?
def to_html
wrapper do
template.button_tag(text, button_html)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/actions/link_action.rb | lib/formtastic/actions/link_action.rb | # frozen_string_literal: true
module Formtastic
module Actions
# Outputs a link wrapped in the standard `<li>` wrapper. This the default for `:cancel` actions.
# The link's URL defaults to Rails' built-in `:back` macro (the HTTP referrer, or Javascript for the
# browser's history), but can be altered with the `:url` option.
#
# @example The `:as` can be ommitted, these are functionally equivalent
# <%= f.action :cancel, :as => :link %>
# <%= f.action :cancel %>
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.actions do %>
# <%= f.action :submit, :as => :input %>
# <%= f.action :cancel, :as => :link %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset class="actions">
# <ol>
# <li class="action input_action" id="post_submit_action">
# <input type="submit" value="Create Post">
# </li>
# <li class="action link_action" id="post_cancel_action">
# <a href="javascript:history.back()">Cancel</a>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Modifying the URL for the link
# <%= f.action :cancel, :as => :link, :url => "http://example.com/path" %>
# <%= f.action :cancel, :as => :link, :url => "/path" %>
# <%= f.action :cancel, :as => :link, :url => posts_path %>
# <%= f.action :cancel, :as => :link, :url => url_for(...) %>
# <%= f.action :cancel, :as => :link, :url => { :controller => "posts", :action => "index" } %>
#
# @example Specifying a label with a String
# <%= f.action :cancel, :as => :link, :label => "Stop" %>
#
# @example Pass HTML attributes down to the `<a>`
# <%= f.action :cancel, :as => :link, :button_html => { :class => 'pretty', :accesskey => 'x' } %>
#
# @example Access key can also be set as a top-level option
# <%= f.action :cancel, :as => :link, :accesskey => 'x' %>
#
# @example Pass HTML attributes down to the `<li>` wrapper (classes are appended to the existing classes)
# <%= f.action :cancel, :as => :link, :wrapper_html => { :class => 'special', :id => 'whatever' } %>
# <%= f.action :cancel, :as => :link, :wrapper_html => { :class => ['extra', 'special'], :id => 'whatever' } %>
#
# @todo document i18n keys
# @todo document i18n translation with :label (?)
# @todo :prefix and :suffix options? (can also be done with CSS or subclassing for custom Actions)
class LinkAction
include Base
# @see Formtastic::Helpers::ActionHelper#action
# @option *args :label [String, Symbol]
# Override the label text with a String or a symbol for an i18n translation key
#
# @option *args :button_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<a>` tag
#
# @option *args :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
#
def supported_methods
[:cancel]
end
# TODO reset_action class?
def to_html
wrapper do
template.link_to(text, url, button_html)
end
end
def url
return options[:url] if options.key?(:url)
:back
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/actions/base.rb | lib/formtastic/actions/base.rb | # frozen_string_literal: true
module Formtastic
module Actions
module Base
include Formtastic::LocalizedString
attr_accessor :builder, :template, :object, :object_name, :method, :options
def initialize(builder, template, object, object_name, method, options)
@builder = builder
@template = template
@object = object
@object_name = object_name
@method = method
@options = options.dup
check_supported_methods!
end
def to_html
raise NotImplementedError
end
def wrapper(&block)
template.content_tag(:li,
template.capture(&block),
wrapper_html_options
)
end
def wrapper_html_options
wrapper_html_options_from_options.merge(default_wrapper_html_options)
end
def wrapper_html_options_from_options
options[:wrapper_html] || {}
end
def default_wrapper_html_options
{
:class => wrapper_class,
:id => wrapper_id
}
end
def wrapper_class
(default_wrapper_classes << wrapper_classes_from_options).join(" ")
end
def default_wrapper_classes
["action", "#{options[:as]}_action"]
end
def wrapper_classes_from_options
classes = wrapper_html_options_from_options[:class] || []
classes = classes.split(" ") if classes.is_a? String
classes
end
def wrapper_html_options_from_options
options[:wrapper_html] || {}
end
def wrapper_id
wrapper_id_from_options || default_wrapper_id
end
def wrapper_id_from_options
wrapper_html_options_from_options[:id]
end
def default_wrapper_id
"#{object_name}_#{method}_action"
end
def supported_methods
raise NotImplementedError
end
def text
text = options[:label]
text = (localized_string(i18n_key, text, :action, :model => sanitized_object_name) ||
Formtastic::I18n.t(i18n_key, :model => sanitized_object_name)) unless text.is_a?(::String)
text
end
def button_html
default_button_html.merge(button_html_from_options || {}).merge(extra_button_html_options)
end
def button_html_from_options
options[:button_html]
end
def extra_button_html_options
{}
end
def default_button_html
{ :accesskey => accesskey }
end
def accesskey
# TODO could be cleaner and separated, remember that nil is an allowed value for all of these
return options[:accesskey] if options.key?(:accesskey)
return options[:button_html][:accesskey] if options.key?(:button_html) && options[:button_html].key?(:accesskey)
# TODO might be different for cancel, etc?
return builder.default_commit_button_accesskey
end
protected
def check_supported_methods!
raise Formtastic::UnsupportedMethodForAction unless supported_methods.include?(method)
end
def i18n_key
return submit_i18n_key if method == :submit
method
end
def submit_i18n_key
if new_or_persisted_object?
key = @object.persisted? ? :update : :create
else
key = :submit
end
end
def new_or_persisted_object?
object && (object.respond_to?(:persisted?) || object.respond_to?(:new_record?))
end
def sanitized_object_name
if new_or_persisted_object?
# Deal with some complications with ActiveRecord::Base.human_name and two name models (eg UserPost)
# ActiveRecord::Base.human_name falls back to ActiveRecord::Base.name.humanize ("Userpost")
# if there's no i18n, which is pretty crappy. In this circumstance we want to detect this
# fall back (human_name == name.humanize) and do our own thing name.underscore.humanize ("User Post")
if object.class.model_name.respond_to?(:human)
sanitized_object_name = object.class.model_name.human
else
object_human_name = @object.class.human_name # default is UserPost => "Userpost", but i18n may do better ("User post")
crappy_human_name = @object.class.name.humanize # UserPost => "Userpost"
decent_human_name = @object.class.name.underscore.humanize # UserPost => "User post"
sanitized_object_name = (object_human_name == crappy_human_name) ? decent_human_name : object_human_name
end
else
sanitized_object_name = object_name.to_s.send(builder.label_str_method)
end
sanitized_object_name
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/date_select_input.rb | lib/formtastic/inputs/date_select_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a series of select boxes for the fragments that make up a date (year, month, day).
#
# @see Formtastic::Inputs::Base::Timeish Timeish module for documentation of date, time and datetime input options.
class DateSelectInput
include Base
include Base::Timeish
# We don't want hour and minute fragments on a date input
def time_fragments
[]
end
def hidden_date_fragments
default_date_fragments - date_fragments
end
def hidden_fragments
hidden_date_fragments.map do |fragment|
template.hidden_field_tag(hidden_field_name(fragment), fragment_value(fragment), :id => fragment_id(fragment), :disabled => input_html_options[:disabled] )
end.join.html_safe
end
def fragment_value(fragment)
if fragment == :year
Time.now.year
else
'1'
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/check_boxes_input.rb | lib/formtastic/inputs/check_boxes_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# A CheckBoxes input is used to render a series of checkboxes. This is an alternative input choice
# for `has_many` or `has_and_belongs_to_many` associations like a `Post` belonging to many
# `categories` (by default, a {SelectInput `:select`} input is used, allowing multiple selections).
#
# Within the standard `<li>` wrapper, the output is a `<fieldset>` with a `<legend>` to
# represent the "label" for the input, and an `<ol>` containing `<li>`s for each choice in
# the association. Each `<li>` choice contains a hidden `<input>` tag for the "unchecked"
# value (like Rails), and a `<label>` containing the checkbox `<input>` and the label text
# for each choice.
#
# @example Basic example with full form context
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :categories, :as => :check_boxes %>
# <% end %>
# <% end %>
#
# <li class='check_boxes'>
# <fieldset>
# <legend class="label"><label>Categories</label></legend>
# <ol>
# <li>
# <input type="hidden" name="post[category_ids][1]" value="">
# <label for="post_category_ids_1"><input id="post_category_ids_1" name="post[category_ids][1]" type="checkbox" value="1" /> Ruby</label>
# </li>
# <li>
# <input type="hidden" name="post[category_ids][2]" value="">
# <label for="post_category_ids_2"><input id="post_category_ids_2" name="post[category_ids][2]" type="checkbox" value="2" /> Rails</label>
# </li>
# </ol>
# </fieldset>
# </li>
#
# @example `:collection` can be used to customize the choices
# <%= f.input :categories, :as => :check_boxes, :collection => @categories %>
# <%= f.input :categories, :as => :check_boxes, :collection => Category.all %>
# <%= f.input :categories, :as => :check_boxes, :collection => Category.some_named_scope %>
# <%= f.input :categories, :as => :check_boxes, :collection => Category.pluck(:label, :id) %>
# <%= f.input :categories, :as => :check_boxes, :collection => [Category.find_by_name("Ruby"), Category.find_by_name("Rails")] %>
# <%= f.input :categories, :as => :check_boxes, :collection => ["Ruby", "Rails"] %>
# <%= f.input :categories, :as => :check_boxes, :collection => [["Ruby", "ruby"], ["Rails", "rails"]] %>
# <%= f.input :categories, :as => :check_boxes, :collection => [["Ruby", "1"], ["Rails", "2"]] %>
# <%= f.input :categories, :as => :check_boxes, :collection => [["Ruby", 1], ["Rails", 2]] %>
# <%= f.input :categories, :as => :check_boxes, :collection => [["Ruby", 1, {'data-attr' => 'attr-value'}]] %>
# <%= f.input :categories, :as => :check_boxes, :collection => 1..5 %>
# <%= f.input :categories, :as => :check_boxes, :collection => [:ruby, :rails] %>
# <%= f.input :categories, :as => :check_boxes, :collection => [["Ruby", :ruby], ["Rails", :rails]] %>
# <%= f.input :categories, :as => :check_boxes, :collection => Set.new([:ruby, :rails]) %>
#
# @example `:hidden_fields` can be used to skip Rails' rendering of a hidden field before every checkbox
# <%= f.input :categories, :as => :check_boxes, :hidden_fields => false %>
#
# @example `:disabled` can be used to disable any checkboxes with a value found in the given Array
# <%= f.input :categories, :as => :check_boxes, :collection => ["a", "b"], :disabled => ["a"] %>
#
# @example `:value_as_class` can be used to add a class to the `<li>` wrapped around each choice using the checkbox value for custom styling of each choice
# <%= f.input :categories, :as => :check_boxes, :value_as_class => true %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
# @see Formtastic::Inputs::BooleanInput BooleanInput for a single checkbox for boolean (checked = true) inputs
#
# @todo Do/can we support the per-item HTML options like RadioInput?
class CheckBoxesInput
include Base
include Base::Collections
include Base::Choices
def initialize(*args)
super
raise Formtastic::UnsupportedEnumCollection if collection_from_enum?
end
def to_html
input_wrapping do
choices_wrapping do
legend_html <<
hidden_field_for_all <<
choices_group_wrapping do
collection.map { |choice|
choice_wrapping(choice_wrapping_html_options(choice)) do
choice_html(choice)
end
}.join("\n").html_safe
end
end
end
end
def choice_html(choice)
template.content_tag(
:label,
checkbox_input(choice) + choice_label(choice),
label_html_options.merge(:for => choice_input_dom_id(choice), :class => nil)
)
end
def hidden_field_for_all
if hidden_fields_for_every?
+''
else
options = {}
options[:class] = [method.to_s.singularize, 'default'].join('_') if value_as_class?
options[:id] = [object_name, method, 'none'].join('_')
template.hidden_field_tag(input_name, '', options)
end
end
def hidden_fields_for_every?
options[:hidden_fields]
end
def check_box_with_hidden_input(choice)
value = choice_value(choice)
builder.check_box(
association_primary_key || method,
extra_html_options(choice).merge(:id => choice_input_dom_id(choice), :name => input_name, :disabled => disabled?(value), :required => false),
value,
unchecked_value
)
end
def check_box_without_hidden_input(choice)
value = choice_value(choice)
template.check_box_tag(
input_name,
value,
checked?(value),
extra_html_options(choice).merge(:id => choice_input_dom_id(choice), :disabled => disabled?(value), :required => false)
)
end
def extra_html_options(choice)
input_html_options.merge(custom_choice_html_options(choice))
end
def checked?(value)
selected_values.include?(value)
end
def disabled?(value)
disabled_values.include?(value)
end
def selected_values
@selected_values ||= make_selected_values
end
def disabled_values
vals = options[:disabled] || []
vals = [vals] unless vals.is_a?(Array)
vals
end
def unchecked_value
options[:unchecked_value] || ''
end
def input_name
if builder.options.key?(:index)
"#{object_name}[#{builder.options[:index]}][#{association_primary_key || method}][]"
else
"#{object_name}[#{association_primary_key || method}][]"
end
end
protected
def checkbox_input(choice)
if hidden_fields_for_every?
check_box_with_hidden_input(choice)
else
check_box_without_hidden_input(choice)
end
end
def make_selected_values
if object.respond_to?(method)
selected_items = object.send(method)
# Construct an array from the return value, regardless of the return type
selected_items = [*selected_items].compact.flatten
selected = []
selected_items.map do |selected_item|
selected_item_id = selected_item.id if selected_item.respond_to? :id
item = send_or_call_or_object(value_method, selected_item) || selected_item_id
end.compact
else
[]
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/number_input.rb | lib/formtastic/inputs/number_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="number">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for all database columns of the type `:float`
# and `:decimal`, as well as `:integer` columns that aren't used for `belongs_to` associations,
# but can be applied to any text-like input with `:as => :number`.
#
# Sensible default values for the `min`, `max` and `step` attributes are found by reflecting on
# the model's validations (when provided). An `IndeterminableMinimumAttributeError` exception
# will be raised when the following conditions are all true:
#
# * you haven't specified a `:min` or `:max` for the input
# * the model's database column type is a `:float` or `:decimal`
# * the validation uses `:less_than` or `:greater_than`
#
# The solution is to either:
#
# * manually specify the `:min` or `:max` for the input
# * change the database column type to an `:integer` (if appropriate)
# * change the validations to use `:less_than_or_equal_to` or `:greater_than_or_equal_to`
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :shoe_size, :as => :number %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="numeric">
# <label for="user_shoe_size">Shoe size</label>
# <input type="number" id="user_shoe_size" name="user[shoe_size]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Default HTML5 min/max/step attributes are detected from the numericality validations
#
# class Person < ActiveRecord::Base
# validates_numericality_of :age,
# :less_than_or_equal_to => 100,
# :greater_than_or_equal_to => 18,
# :only_integer => true
# end
#
# <%= f.input :age, :as => :number %>
#
# <li class="numeric">
# <label for="persom_age">Age</label>
# <input type="number" id="person_age" name="person[age]" min="18" max="100" step="1">
# </li>
#
# @example Pass attributes down to the `<input>` tag with :input_html
# <%= f.input :shoe_size, :as => :number, :input_html => { :min => 3, :max => 15, :step => 1, :class => "special" } %>
#
# @example Min/max/step also work as options
# <%= f.input :shoe_size, :as => :number, :min => 3, :max => 15, :step => 1, :input_html => { :class => "special" } %>
#
# @example Use :in with a Range as a shortcut for :min/:max
# <%= f.input :shoe_size, :as => :number, :in => 3..15, :step => 1 %>
# <%= f.input :shoe_size, :as => :number, :input_html => { :in => 3..15, :step => 1 } %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
# @see http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_numericality_of Rails' Numericality validation documentation
class NumberInput
include Base
include Base::Numeric
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.number_field(method, input_html_options)
end
end
def step_option
super || "any"
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/url_input.rb | lib/formtastic/inputs/url_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="url">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for all attributes matching
# `/^url$|^website$|_url$/`, but can be applied to any text-like input with `:as => :url`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :home_page, :as => :url %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="url">
# <label for="user_home_page">Home page</label>
# <input type="number" id="user_home_page" name="user[home_page]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class UrlInput
include Base
include Base::Stringish
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.url_field(method, input_html_options)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/radio_input.rb | lib/formtastic/inputs/radio_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# A radio input is used to render a series of radio inputs. This is an alternative input choice
# for `belongs_to` associations like a `Post` belonging to a `Section` or an `Author`, or any
# case where the user needs to make a single selection from a pre-defined collectioon of choices.
#
# Within the standard `<li>` wrapper, the output is a `<fieldset>` with a `<legend>` to
# represent the "label" for the input, and an `<ol>` containing `<li>`s for each choice in
# the association. Each `<li>` choice has a `<label>` containing an `<input type="radio">` and
# the label text to describe each choice.
#
# Radio inputs can be considered as an alternative where a (non-multi) select input is used,
# especially in cases where there are only a few choices, however they are not used by default
# for any type of association or model attribute. You can choose to use a radio input instead of
# a select with `:as => :radio`.
#
# Like a select input, the flexibility of the `:collection` option (see examples) makes the
# :radio input viable as an alternative for many other input types. For example, instead of...
#
# * a `:string` input (where you want to force the user to choose from a few specific strings rather than entering anything)
# * a `:boolean` checkbox input (where the user could choose yes or no, rather than checking a box)
# * a `:date_select`, `:time_select` or `:datetime_select` input (where the user could choose from a small set of pre-determined dates)
# * a `:number` input (where the user could choose from a small set of pre-defined numbers)
# * a `:time_zone` input (where you want to provide your own small set of choices instead of relying on Rails)
# * a `:country` input (where you want to provide a small set of choices, no need for a plugin really)
#
# For radio inputs that map to associations on the object model, Formtastic will automatically
# load in a collection of objects on the association as options to choose from. This might be an
# `Author.all` on a `Post` form with an input for a `belongs_to :user` association, or a
# `Section.all` for a `Post` form with an input for a `belongs_to :section` association.
# You can override or customise this collection through the `:collection` option (see examples).
#
# For radio inputs that map to ActiveRecord `enum` attributes, Formtastic will automatically
# load in your enum options to be used as the radio button choices. This can be overridden with
# the `:collection` option, or augmented with I18n translations. See examples below.
#
# The way on which Formtastic renders the `value` attribute and label for each choice in the `:collection` is
# customisable (see examples below). When not provided, we fall back to a list of methods to try on each
# object such as `:to_label`, `:name` and `:to_s`, which are defined in the configurations
# `collection_label_methods` and `collection_value_methods`.
#
# @example Basic `belongs_to` example with full form context
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :author, :as => :radio %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class='radio'>
# <fieldset>
# <legend class="label"><label>Categories</label></legend>
# <ol>
# <li>
# <label for="post_author_id_1">
# <input type="radio" id="post_author_id_1" value="1"> Justin
# </label>
# </li>
# <li>
# <label for="post_author_id_3">
# <input type="radio" id="post_author_id_3" value="3"> Kate
# </label>
# </li>
# <li>
# <label for="post_author_id_2">
# <input type="radio" id="post_author_id_2" value="2"> Amelia
# </label>
# </li>
# </ol>
# </fieldset>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example The `:collection` option can be used to customize the choices
# <%= f.input :author, :as => :radio, :collection => @authors %>
# <%= f.input :author, :as => :radio, :collection => Author.all %>
# <%= f.input :author, :as => :radio, :collection => Author.some_named_scope %>
# <%= f.input :author, :as => :radio, :collection => Author.pluck(:full_name, :id) %>
# <%= f.input :author, :as => :radio, :collection => Author.pluck(Arel.sql("CONCAT(`first_name`, ' ', `last_name`)"), :id)) %>
# <%= f.input :author, :as => :radio, :collection => [Author.find_by_login("justin"), Category.find_by_name("kate")] %>
# <%= f.input :author, :as => :radio, :collection => ["Justin", "Kate"] %>
# <%= f.input :author, :as => :radio, :collection => [["Justin", "justin"], ["Kate", "kate"]] %>
# <%= f.input :author, :as => :radio, :collection => [["Justin", "1"], ["Kate", "3"]] %>
# <%= f.input :author, :as => :radio, :collection => [["Justin", 1], ["Kate", 3]] %>
# <%= f.input :author, :as => :radio, :collection => [["Justin", :justin], ["Kate", :kate]] %>
# <%= f.input :author, :as => :radio, :collection => [:justin, :kate] %>
# <%= f.input :author, :as => :radio, :collection => 1..5 %>
#
# @example Set HTML attributes on each `<input type="radio">` tag with `:input_html`
# <%= f.input :author, :as => :radio, :input_html => { :size => 20, :multiple => true, :class => "special" } %>
#
# @example Set HTML attributes on the `<li>` wrapper with `:wrapper_html`
# <%= f.input :author, :as => :radio, :wrapper_html => { :class => "special" } %>
#
# @example `:value_as_class` can be used to add a class to the `<li>` wrapped around each choice using the radio value for custom styling of each choice
# <%= f.input :author, :as => :radio, :value_as_class => true %>
#
# @example Set HTML options on a specific radio input option with a 3rd element in the array for a collection member
# <%= f.input :author, :as => :radio, :collection => [["Test", 'test'], ["Try", "try", {:disabled => true}]]
#
# @example Using ActiveRecord enum attribute with i18n translation:
# # post.rb
# class Post < ActiveRecord::Base
# enum :status => [ :active, :archived ]
# end
# # en.yml
# en:
# activerecord:
# attributes:
# post:
# statuses:
# active: I am active!
# archived: I am archived!
# # form
# <%= f.input :status, :as => :radio %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
# @see Formtastic::Inputs::RadioInput as an alternative for `belongs_to` associations
#
# @todo :disabled like CheckBoxes?
class RadioInput
include Base
include Base::Collections
include Base::Choices
def to_html
input_wrapping do
choices_wrapping do
legend_html <<
choices_group_wrapping do
collection.map { |choice|
choice_wrapping(choice_wrapping_html_options(choice)) do
choice_html(choice)
end
}.join("\n").html_safe
end
end
end
end
def choice_html(choice)
template.content_tag(:label,
builder.radio_button(input_name, choice_value(choice), input_html_options.merge(choice_html_options(choice)).merge(:required => false)) <<
choice_label(choice),
label_html_options.merge(:for => choice_input_dom_id(choice), :class => nil)
)
end
# Override to remove the for attribute since this isn't associated with any element, as it's
# nested inside the legend.
def label_html_options
super.merge(:for => nil)
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/country_input.rb | lib/formtastic/inputs/country_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a country select input, wrapping around a regular country_select helper.
# Rails doesn't come with a `country_select` helper by default any more, so you'll need to do
# one of the following:
#
# * install the [country_select](https://github.com/countries/country_select) gem
# * install any other country_select plugin that behaves in a similar way
# * roll your own `country_select` helper with the same args and options as the Rails one
#
# By default, Formtastic includes a handful of English-speaking countries as "priority
# countries", which can be set in the `priority_countries` configuration array in the
# formtastic.rb initializer to suit your market and user base (see README for more info on
# configuration). Additionally, it is possible to set the :priority_countries on a per-input
# basis through the `:priority_countries` option. These priority countries will be passed down
# to the `country_select` helper of your choice, and may or may not be used by the helper.
#
# @example Basic example with full form context using `priority_countries` from config
#
# <%= semantic_form_for @user do |f| %>
# <%= f.inputs do %>
# <%= f.input :nationality, :as => :country %>
# <% end %>
# <% end %>
#
# <li class='country'>
# <label for="user_nationality">Country</label>
# <select id="user_nationality" name="user[nationality]">
# <option value="...">...</option>
# # ...
# </li>
#
# @example `:priority_countries` set on a specific input (country_select 1.x)
#
# <%= semantic_form_for @user do |f| %>
# <%= f.inputs do %>
# <%= f.input :nationality, :as => :country, :priority_countries => ["Australia", "New Zealand"] %>
# <% end %>
# <% end %>
#
# <li class='country'>
# <label for="user_nationality">Country</label>
# <select id="user_nationality" name="user[nationality]">
# <option value="...">...</option>
# # ...
# </li>
#
# @example `:priority_countries` set on a specific input (country_select 2.x)
#
# <%= semantic_form_for @user do |f| %>
# <%= f.inputs do %>
# <%= f.input :nationality, :as => :country, :priority_countries => ["AU", "NZ"] %>
# <% end %>
# <% end %>
#
# <li class='country'>
# <label for="user_nationality">Country</label>
# <select id="user_nationality" name="user[nationality]">
# <option value="...">...</option>
# # ...
# </li>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class CountryInput
include Base
CountrySelectPluginMissing = Class.new(StandardError)
def to_html
raise CountrySelectPluginMissing, "To use the :country input, please install a country_select plugin, like this one: https://github.com/countries/country_select" unless builder.respond_to?(:country_select)
input_wrapping do
label_html <<
builder.country_select(method, input_options_including_priorities, input_html_options)
end
end
def input_options_including_priorities
return input_options unless priority_countries
input_options.merge(:priority_countries => priority_countries)
end
def priority_countries
options[:priority_countries] || builder.priority_countries
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/datetime_picker_input.rb | lib/formtastic/inputs/datetime_picker_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="datetime-local">` (or
# `<input type="datetime">`) wrapped in the standard `<li>` wrapper. This is an alternative to
# `:date_select` for `:date`, `:time`, `:datetime` database columns. You can use this input with
# `:as => :datetime_picker`.
#
# *Please note:* Formtastic only provides suitable markup for a date picker, but does not supply
# any additional CSS or Javascript to render calendar-style date pickers. Browsers that support
# this input type (such as Mobile Webkit and Opera on the desktop) will render a native widget.
# Browsers that don't will default to a plain text field`<input type="text">` and can be
# poly-filled with some Javascript and a UI library of your choice.
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.inputs do %>
# <%= f.input :publish_at, :as => :datetime_picker %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="string">
# <label for="post_publish_at">First name</label>
# <input type="date" id="post_publish_at" name="post[publish_at]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Setting the size (defaults to 16 for YYYY-MM-DD HH:MM)
# <%= f.input :publish_at, :as => :datetime_picker, :size => 20 %>
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :size => 20 } %>
#
# @example Setting the maxlength (defaults to 16 for YYYY-MM-DD HH:MM)
# <%= f.input :publish_at, :as => :datetime_picker, :maxlength => 20 %>
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :maxlength => 20 } %>
#
# @example Setting the value (defaults to YYYY-MM-DD HH:MM for Date and Time objects, otherwise renders string)
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :value => "1970-01-01 00:00" } %>
#
# @example Setting the step attribute (defaults to 1)
# <%= f.input :publish_at, :as => :datetime_picker, :step => 60 %>
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :step => 60 } %>
#
# @example Setting the step attribute with a macro
# <%= f.input :publish_at, :as => :datetime_picker, :step => :second %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :minute %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :quarter_hour %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :fifteen_minutes %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :half_hour %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :thirty_minutes %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :hour %>
# <%= f.input :publish_at, :as => :datetime_picker, :step => :sixty_minutes %>
#
# @example Setting the min attribute
# <%= f.input :publish_at, :as => :datetime_picker, :min => "2012-01-01 09:00" %>
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :min => "2012-01-01 09:00" } %>
#
# @example Setting the max attribute
# <%= f.input :publish_at, :as => :datetime_picker, :max => "2012-12-31 16:00" %>
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :max => "2012-12-31 16:00" } %>
#
# @example Setting the placeholder attribute
# <%= f.input :publish_at, :as => :datetime_picker, :placeholder => "YYYY-MM-DD HH:MM" %>
# <%= f.input :publish_at, :as => :datetime_picker, :input_html => { :placeholder => "YYYY-MM-DD HH:MM" } %>
#
# @example Using `type=datetime-local` with `:local` option (this is the default, and recommended for browser support on iOS7 and Chrome)
# <%= f.input :publish_at, :as => :datetime_picker, :local => true %>
#
# @example Using `type=datetime` with `:local` option (not recommended)
# <%= f.input :publish_at, :as => :datetime_picker, :local => false %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class DatetimePickerInput
include Base
include Base::Stringish
include Base::DatetimePickerish
def html_input_type
options[:local] = true unless options.key?(:local)
options[:local] ? "datetime-local" : "datetime"
end
def default_size
16
end
def value
return options[:input_html][:value] if options[:input_html] && options[:input_html].key?(:value)
val = object.send(method)
return val.strftime("%Y-%m-%dT%H:%M:%S") if val.is_a?(Time)
return "#{val.year}-#{val.month}-#{val.day}T00:00:00" if val.is_a?(Date)
return val if val.nil?
val.to_s
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/string_input.rb | lib/formtastic/inputs/string_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a `<input type="text">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for database columns of the `:string` type,
# and is the default choice for all inputs when no other logical input type can be inferred.
# You can force any input to be a string input with `:as => :string`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :first_name, :as => :string %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="string">
# <label for="user_first_name">First name</label>
# <input type="text" id="user_first_name" name="user[first_name]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class StringInput
include Base
include Base::Stringish
include Base::Placeholder
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/datetime_select_input.rb | lib/formtastic/inputs/datetime_select_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a series of select boxes for the fragments that make up a date and time (year, month, day, hour, minute, second).
#
# @see Formtastic::Inputs::Base::Timeish Timeish module for documentation of date, time and datetime input options.
class DatetimeSelectInput
include Base
include Base::Timeish
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/time_zone_input.rb | lib/formtastic/inputs/time_zone_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a `<label>` with a `<select>` containing a series of time zones (using Rails' own
# `time_zone_select` helper), wrapped in the standard `<li>` wrapper.
# This is the default input choice for attributes matching /time_zone/, but can be applied to
# any text-like input with `:as => :time_zone`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :time_zone, :as => :time_zone %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="time_zone">
# <label for="user_time_zone">Time zone</label>
# <input type="text" id="user_time_zone" name="user[time_zone]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
#
# The priority_zones option:
# Since this input actually uses Rails' `time_zone_select` helper, the :priority_zones
# option needs to be an array of ActiveSupport::TimeZone objects.
#
# And you can configure default value using
#
# ```
# Formtastic::FormBuilder.priority_time_zones = [timezone1, timezone2]
# ```
#
# See http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/time_zone_select for more information.
#
class TimeZoneInput
include Base
def to_html
input_wrapping do
label_html <<
builder.time_zone_select(method, priority_zones, input_options, input_html_options)
end
end
def priority_zones
options[:priority_zones] || Formtastic::FormBuilder.priority_time_zones
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/range_input.rb | lib/formtastic/inputs/range_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="range">` wrapped in the standard
# `<li>` wrapper. This is an alternative input choice to a number input.
#
# Sensible default for the `min`, `max` and `step` attributes are found by reflecting on
# the model's validations. When validations are not provided, the `min` and `step` default to
# `1` and the `max` default to `100`. An `IndeterminableMinimumAttributeError` exception
# will be raised when the following conditions are all true:
#
# * you haven't specified a `:min` or `:max` for the input
# * the model's database column type is a `:float` or `:decimal`
# * the validation uses `:less_than` or `:greater_than`
#
# The solution is to either:
#
# * manually specify the `:min` or `:max` for the input
# * change the database column type to an `:integer` (if appropriate)
# * change the validations to use `:less_than_or_equal_to` or `:greater_than_or_equal_to`
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :shoe_size, :as => :range %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="numeric">
# <label for="user_shoe_size">Shoe size</label>
# <input type="range" id="user_shoe_size" name="user[shoe_size]" min="1" max="100" step="1">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Default HTML5 min/max/step attributes are detected from the numericality validations
#
# class Person < ActiveRecord::Base
# validates_numericality_of :age,
# :less_than_or_equal_to => 100,
# :greater_than_or_equal_to => 18,
# :only_integer => true
# end
#
# <%= f.input :age, :as => :number %>
#
# <li class="numeric">
# <label for="persom_age">Age</label>
# <input type="range" id="person_age" name="person[age]" min="18" max="100" step="1">
# </li>
#
# @example Pass attributes down to the `<input>` tag with :input_html
# <%= f.input :shoe_size, :as => :range, :input_html => { :min => 3, :max => 15, :step => 1, :class => "special" } %>
#
# @example Min/max/step also work as options
# <%= f.input :shoe_size, :as => :range, :min => 3, :max => 15, :step => 1, :input_html => { :class => "special" } %>
#
# @example Use :in with a Range as a shortcut for :min/:max
# <%= f.input :shoe_size, :as => :range, :in => 3..15, :step => 1 %>
# <%= f.input :shoe_size, :as => :range, :input_html => { :in => 3..15, :step => 1 } %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
# @see http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_numericality_of Rails' Numericality validation documentation
#
class RangeInput
include Base
include Base::Numeric
def to_html
input_wrapping do
label_html <<
builder.range_field(method, input_html_options)
end
end
def min_option
super || 1
end
def max_option
super || 100
end
def step_option
super || 1
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/color_input.rb | lib/formtastic/inputs/color_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="color">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for attributes with a name matching
# `/color/`, but can be applied to any text-like input with `:as => :color`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :color, :as => :color %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="color">
# <label for="user_color">Color</label>
# <input type="color" id="user_color" name="user[color]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class ColorInput
include Base
include Base::Stringish
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.color_field(method, input_html_options)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/datalist_input.rb | lib/formtastic/inputs/datalist_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a label and a text field, along with a datalist tag
# datalist tag provides a list of options which drives a simple autocomplete
# on the text field. This is a HTML5 feature, more info can be found at
# {https://developer.mozilla.org/en/docs/Web/HTML/Element/datalist <datalist> at MDN}
# This input accepts a :collection option which takes data in all the usual formats accepted by
# {http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select options_for_select}
#
# @example Input is used as follows
# f.input :fav_book, :as => :datalist, :collection => Book.pluck(:name)
#
class DatalistInput
include Base
include Base::Stringish
include Base::Collections
def to_html
@name = input_html_options[:id].gsub(/_id$/, "")
input_wrapping do
label_html <<
builder.text_field(method, input_html_options) << # standard input
data_list_html # append new datalist element
end
end
def input_html_options
super.merge(:list => html_id_of_datalist)
end
def html_id_of_datalist
"#{@name}_datalist"
end
def data_list_html
html = builder.template.options_for_select(collection)
builder.template.content_tag(:datalist,html, { :id => html_id_of_datalist }, false)
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base.rb | lib/formtastic/inputs/base.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
attr_accessor :builder, :template, :object, :object_name, :method, :options
def initialize(builder, template, object, object_name, method, options)
@builder = builder
@template = template
@object = object
@object_name = object_name
@method = method
@options = options.dup
# Deprecate :member_label and :member_value, remove v4.0
member_deprecation_message = "passing an Array of label/value pairs like [['Justin', 2], ['Kate', 3]] into :collection directly (consider building the array in your model using Model.pluck)"
warn_deprecated_option!(:member_label, member_deprecation_message)
warn_deprecated_option!(:member_value, member_deprecation_message)
end
# Usefull for deprecating options.
def warn_and_correct_option!(old_option_name, new_option_name)
if options.key?(old_option_name)
Deprecation.warn("The :#{old_option_name} option is deprecated in favour of :#{new_option_name} and will be removed from Formtastic in the next version", caller_locations(6))
options[new_option_name] = options.delete(old_option_name)
end
end
# Usefull for deprecating options.
def warn_deprecated_option!(old_option_name, instructions)
if options.key?(old_option_name)
Deprecation.warn("The :#{old_option_name} option is deprecated in favour of `#{instructions}`. :#{old_option_name} will be removed in the next version", caller_locations(6))
end
end
# Usefull for raising an error on previously supported option.
def removed_option!(old_option_name)
raise ArgumentError, ":#{old_option_name} is no longer available" if options.key?(old_option_name)
end
extend ActiveSupport::Autoload
autoload :DatetimePickerish
autoload :Associations
autoload :Collections
autoload :Choices
autoload :Database
autoload :Errors
autoload :Fileish
autoload :Hints
autoload :Html
autoload :Labelling
autoload :Naming
autoload :Numeric
autoload :Options
autoload :Placeholder
autoload :Stringish
autoload :Timeish
autoload :Validations
autoload :Wrapping
autoload :Aria
include Html
include Options
include Database
include Errors
include Hints
include Naming
include Validations
include Fileish
include Associations
include Labelling
include Wrapping
include Aria
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/search_input.rb | lib/formtastic/inputs/search_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="search">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for attributes with a name matching
# `/^search$/`, but can be applied to any text-like input with `:as => :search`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@search, :html => { :method => :get }) do |f| %>
# <%= f.inputs do %>
# <%= f.input :q, :as => :search, :label => false, :input_html => { :name => "q" } %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="search">
# <input type="search" id="search_q" name="q">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class SearchInput
include Base
include Base::Stringish
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.search_field(method, input_html_options)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/boolean_input.rb | lib/formtastic/inputs/boolean_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Boolean inputs are used to render an input for a single checkbox, typically for attributes
# with a simple yes/no or true/false value. Boolean inputs are used by default for boolean
# database columns.
#
# @example Full form context and markup
# <%= semantic_form_for @post %>
# <%= f.inputs do %>
# <%= f.input :published, :as => :boolean %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="boolean" id="post_published_input">
# <input type="hidden" name="post[published]" id="post_published" value="0">
# <label for="post_published">
# <input type="checkbox" name="post[published]" id="post_published" value="1">
# Published?
# </label>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Set the values for the checked and unchecked states
# <%= f.input :published, :checked_value => "yes", :unchecked_value => "no" %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class BooleanInput
include Base
def to_html
input_wrapping do
hidden_field_html <<
label_with_nested_checkbox
end
end
def hidden_field_html
template.hidden_field_tag(input_html_options[:name], unchecked_value, :id => nil, :disabled => input_html_options[:disabled] )
end
def label_with_nested_checkbox
builder.label(
method,
label_text_with_embedded_checkbox,
label_html_options
)
end
def label_html_options
{
:for => input_html_options[:id],
:class => super[:class] - ['label'] # remove 'label' class
}
end
def label_text_with_embedded_checkbox
check_box_html << +"" << label_text
end
def check_box_html
template.check_box_tag("#{object_name}[#{method}]", checked_value, checked?, input_html_options)
end
def unchecked_value
options[:unchecked_value] || '0'
end
def checked_value
options[:checked_value] || '1'
end
def responds_to_global_required?
false
end
def input_html_options
{:name => input_html_options_name}.merge(super)
end
def input_html_options_name
if builder.options.key?(:index)
"#{object_name}[#{builder.options[:index]}][#{method}]"
else
"#{object_name}[#{method}]"
end
end
def checked?
object && boolean_checked?(object.send(method), checked_value)
end
private
def boolean_checked?(value, checked_value)
case value
when TrueClass, FalseClass
value
when NilClass
false
when Integer
value == checked_value.to_i
when String
value == checked_value
when Array
value.include?(checked_value)
else
value.to_i != 0
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/file_input.rb | lib/formtastic/inputs/file_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a `<input type="file">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for objects with attributes that appear
# to be for file uploads, by detecting some common method names used by popular file upload
# libraries such as Paperclip and CarrierWave. You can add to or alter these method names
# through the `file_methods` config, but can be applied to any input with `:as => :file`.
#
# Don't forget to set the multipart attribute in your `<form>` tag!
#
# @example Full form context and output
#
# <%= semantic_form_for(@user, :html => { :multipart => true }) do |f| %>
# <%= f.inputs do %>
# <%= f.input :avatar, :as => :file %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="file">
# <label for="user_avatar">Avatar</label>
# <input type="file" id="user_avatar" name="user[avatar]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class FileInput
include Base
def to_html
input_wrapping do
label_html <<
builder.file_field(method, input_html_options)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/time_picker_input.rb | lib/formtastic/inputs/time_picker_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="time">` wrapped in the standard
# `<li>` wrapper. This is an alternative to `:time_select` for `:date`, `:time`, `:datetime`
# database columns. You can use this input with `:as => :time_picker`.
#
# *Please note:* Formtastic only provides suitable markup for a date picker, but does not supply
# any additional CSS or Javascript to render calendar-style date pickers. Browsers that support
# this input type (such as Mobile Webkit and Opera on the desktop) will render a native widget.
# Browsers that don't will default to a plain text field`<input type="text">` and can be
# poly-filled with some Javascript and a UI library of your choice.
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.inputs do %>
# <%= f.input :publish_at, :as => :time_picker %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="string">
# <label for="post_publish_at">First name</label>
# <input type="date" id="post_publish_at" name="post[publish_at]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Setting the size (defaults to 5 for HH:MM)
# <%= f.input :publish_at, :as => :time_picker, :size => 20 %>
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :size => 20 } %>
#
# @example Setting the maxlength (defaults to 5 for HH:MM)
# <%= f.input :publish_at, :as => :time_picker, :maxlength => 20 %>
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :maxlength => 20 } %>
#
# @example Setting the value (defaults to HH:MM for Date and Time objects, otherwise renders string)
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :value => "14:14" } %>
#
# @example Setting the step attribute (defaults to 60)
# <%= f.input :publish_at, :as => :time_picker, :step => 120 %>
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :step => 120 } %>
#
# @example Setting the step attribute with a macro
# <%= f.input :publish_at, :as => :time_picker, :step => :second %>
# <%= f.input :publish_at, :as => :time_picker, :step => :minute %>
# <%= f.input :publish_at, :as => :time_picker, :step => :quarter_hour %>
# <%= f.input :publish_at, :as => :time_picker, :step => :fifteen_minutes %>
# <%= f.input :publish_at, :as => :time_picker, :step => :half_hour %>
# <%= f.input :publish_at, :as => :time_picker, :step => :thirty_minutes %>
# <%= f.input :publish_at, :as => :time_picker, :step => :hour %>
# <%= f.input :publish_at, :as => :time_picker, :step => :sixty_minutes %>
#
# @example Setting the min attribute
# <%= f.input :publish_at, :as => :time_picker, :min => "09:00" %>
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :min => "01:00" } %>
#
# @example Setting the max attribute
# <%= f.input :publish_at, :as => :time_picker, :max => "18:00" %>
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :max => "18:00" } %>
#
# @example Setting the placeholder attribute
# <%= f.input :publish_at, :as => :time_picker, :placeholder => "HH:MM" %>
# <%= f.input :publish_at, :as => :time_picker, :input_html => { :placeholder => "HH:MM" } %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class TimePickerInput
include Base
include Base::Stringish
include Base::DatetimePickerish
def html_input_type
"time"
end
def default_size
5
end
def value
return options[:input_html][:value] if options[:input_html] && options[:input_html].key?(:value)
val = object.send(method)
return "00:00" if val.is_a?(Date)
return val.strftime("%H:%M") if val.is_a?(Time)
return val if val.nil?
val.to_s
end
def default_step
60
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/date_picker_input.rb | lib/formtastic/inputs/date_picker_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="date">` wrapped in the standard
# `<li>` wrapper. This is an alternative to `:date_select` for `:date`, `:time`, `:datetime`
# database columns. You can use this input with `:as => :date_picker`.
#
# *Please note:* Formtastic only provides suitable markup for a date picker, but does not supply
# any additional CSS or Javascript to render calendar-style date pickers. Browsers that support
# this input type (such as Mobile Webkit and Opera on the desktop) will render a native widget.
# Browsers that don't will default to a plain text field`<input type="text">` and can be
# poly-filled with some Javascript and a UI library of your choice.
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.inputs do %>
# <%= f.input :publish_at, :as => :date_picker %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="string">
# <label for="post_publish_at">First name</label>
# <input type="date" id="post_publish_at" name="post[publish_at]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Setting the size (defaults to 10 for YYYY-MM-DD)
# <%= f.input :publish_at, :as => :date_picker, :size => 20 %>
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :size => 20 } %>
#
# @example Setting the maxlength (defaults to 10 for YYYY-MM-DD)
# <%= f.input :publish_at, :as => :date_picker, :maxlength => 20 %>
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :maxlength => 20 } %>
#
# @example Setting the value (defaults to YYYY-MM-DD for Date and Time objects, otherwise renders string)
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :value => "1970-01-01" } %>
#
# @example Setting the step attribute (defaults to 1)
# <%= f.input :publish_at, :as => :date_picker, :step => 7 %>
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :step => 7 } %>
#
# @example Setting the step attribute with a macro
# <%= f.input :publish_at, :as => :date_picker, :step => :day %>
# <%= f.input :publish_at, :as => :date_picker, :step => :week %>
# <%= f.input :publish_at, :as => :date_picker, :step => :seven_days %>
# <%= f.input :publish_at, :as => :date_picker, :step => :fortnight %>
# <%= f.input :publish_at, :as => :date_picker, :step => :two_weeks %>
# <%= f.input :publish_at, :as => :date_picker, :step => :four_weeks %>
# <%= f.input :publish_at, :as => :date_picker, :step => :thirty_days %>
#
# @example Setting the min attribute
# <%= f.input :publish_at, :as => :date_picker, :min => "2012-01-01" %>
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :min => "2012-01-01" } %>
#
# @example Setting the max attribute
# <%= f.input :publish_at, :as => :date_picker, :max => "2012-12-31" %>
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :max => "2012-12-31" } %>
#
# @example Setting the placeholder attribute
# <%= f.input :publish_at, :as => :date_picker, :placeholder => 20 %>
# <%= f.input :publish_at, :as => :date_picker, :input_html => { :placeholder => "YYYY-MM-DD" } %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class DatePickerInput
include Base
include Base::Stringish
include Base::DatetimePickerish
def html_input_type
"date"
end
def default_size
10
end
def value
return options[:input_html][:value] if options[:input_html] && options[:input_html].key?(:value)
val = object.send(method)
return Date.new(val.year, val.month, val.day).to_s if val.is_a?(Time)
return val if val.nil?
val.to_s
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/email_input.rb | lib/formtastic/inputs/email_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="email">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for attributes with a name matching
# `/email/`, but can be applied to any text-like input with `:as => :email`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :email_address, :as => :email %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="email">
# <label for="user_email_address">Email address</label>
# <input type="email" id="user_email_address" name="user[email_address]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class EmailInput
include Base
include Base::Stringish
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.email_field(method, input_html_options)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/password_input.rb | lib/formtastic/inputs/password_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a `<input type="password">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for all attributes matching `/password/`, but
# can be applied to any text-like input with `:as => :password`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :password, :as => :password %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="password">
# <label for="user_password">Password</label>
# <input type="password" id="user_password" name="user[password]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class PasswordInput
include Base
include Base::Stringish
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.password_field(method, input_html_options)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/hidden_input.rb | lib/formtastic/inputs/hidden_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<input type="hidden">` wrapped in the standard `<li>` wrapper. This is
# provided for situations where a hidden field needs to be rendered in the flow of a form with
# many inputs that form an `<ol>`. Wrapping the hidden input inside the `<li>` maintains the
# HTML validity. The `<li>` is marked with a `class` of `hidden` so that stylesheet authors can
# hide these list items with CSS (formtastic.css does this out of the box).
#
# @example Full form context, output and CSS
#
# <%= semantic_form_for(@something) do |f| %>
# <%= f.inputs do %>
# <%= f.input :secret, :as => :hidden %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="hidden">
# <input type="hidden" id="something_secret" name="something[secret]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# form.formtastic li.hidden { display:none; }
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class HiddenInput
include Base
def input_html_options
super.merge(:required => nil).merge(:autofocus => nil)
end
def to_html
input_wrapping do
builder.hidden_field(method, input_html_options)
end
end
def error_html
+""
end
def errors?
false
end
def hint_html
+""
end
def hint?
false
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/time_select_input.rb | lib/formtastic/inputs/time_select_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a series of select boxes for the fragments that make up a time (hour, minute, second).
# Unless `:ignore_date` is true, it will render hidden inputs for the year, month and day as
# well, defaulting to `Time.current` if the form object doesn't have a value, much like Rails'
# own `time_select`.
#
# @see Formtastic::Inputs::Base::Timeish Timeish module for documentation of date, time and datetime input options.
class TimeSelectInput
include Base
include Base::Timeish
# we don't want year / month / day fragments if :ignore_date => true
def fragments
time_fragments
end
def value_or_default_value
value ? value : Time.current
end
def fragment_value(fragment)
value_or_default_value.send(fragment)
end
def hidden_fragments
if !options[:ignore_date]
date_fragments.map do |fragment|
template.hidden_field_tag(hidden_field_name(fragment), fragment_value(fragment), :id => fragment_id(fragment), :disabled => input_html_options[:disabled] )
end.join.html_safe
else
super
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/text_input.rb | lib/formtastic/inputs/text_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a `<textarea>` wrapped in the standard
# `<li>` wrapper. This is the default input choice for database columns of the `:text` type,
# but can forced on any text-like input with `:as => :text`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :first_name, :as => :text %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="text">
# <label for="user_first_name">First name</label>
# <textarea cols="30" id="user_first_name" name="user[first_name]" rows="20"></textarea>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class TextInput
include Base
include Base::Placeholder
def input_html_options
{
:cols => builder.default_text_area_width,
:rows => builder.default_text_area_height
}.merge(super)
end
def to_html
input_wrapping do
label_html <<
builder.text_area(method, input_html_options)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/select_input.rb | lib/formtastic/inputs/select_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# A select input is used to render a `<select>` tag with a series of options to choose from.
# It works for both single selections (like a `belongs_to` relationship, or "yes/no" boolean),
# as well as multiple selections (like a `has_and_belongs_to_many`/`has_many` relationship,
# for assigning many genres to a song, for example).
#
# This is the default input choice when:
#
# * the database column type is an `:integer` and there is an association (`belongs_to`)
# * the database column type is an `:integer` and there is an enum defined (`enum`)
# * the database column type is a `:string` and the `:collection` option is used
# * there an object with an association, but no database column on the object (`has_many`, etc)
# * there is no object and the `:collection` option is used
#
# The flexibility of the `:collection` option (see examples) makes the :select input viable as
# an alternative for many other input types. For example, instead of...
#
# * a `:string` input (where you want to force the user to choose from a few specific strings rather than entering anything)
# * a `:boolean` checkbox input (where the user could choose yes or no, rather than checking a box)
# * a `:date_select`, `:time_select` or `:datetime_select` input (where the user could choose from pre-selected dates)
# * a `:number` input (where the user could choose from a set of pre-defined numbers)
# * a `:time_zone` input (where you want to provide your own set of choices instead of relying on Rails)
# * a `:country` input (no need for a plugin really)
#
# Within the standard `<li>` wrapper, the output is a `<label>` tag followed by a `<select>`
# tag containing `<option>` tags.
#
# For inputs that map to associations on the object model, Formtastic will automatically load
# in a collection of objects on the association as options to choose from. This might be an
# `Author.all` on a `Post` form with an input for a `belongs_to :user` association, or a
# `Tag.all` for a `Post` form with an input for a `has_and_belongs_to_many :tags` association.
# You can override or customise this collection and the `<option>` tags it will render through
# the `:collection` option (see examples).
#
# The way on which Formtastic renders the `value` attribute and content of each `<option>` tag
# is customisable through the `:member_label` and `:member_value` options. When not provided,
# we fall back to a list of methods to try on each object such as `:to_label`, `:name` and
# `:to_s`, which are defined in the configurations `collection_label_methods` and
# `collection_value_methods` (see examples below).
#
# For select inputs that map to ActiveRecord `enum` attributes, Formtastic will automatically
# load in your enum options to be used as the select's options. This can be overridden with
# the `:collection` option, or augmented with I18n translations. See examples below.
# An error is raised if you try to render a multi-select with an enum, as ActiveRecord can
# only store one choice in the database.
#
#
# @example Basic `belongs_to` example with full form context
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :author, :as => :select %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class='select'>
# <label for="post_author_id">Author</label>
# <select id="post_author_id" name="post[post_author_id]">
# <option value=""></option>
# <option value="1">Justin</option>
# <option value="3">Kate</option>
# <option value="2">Amelia</option>
# </select>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Basic `has_many` or `has_and_belongs_to_many` example with full form context
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :tags, :as => :select %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class='select'>
# <label for="post_tag_ids">Author</label>
# <select id="post_tag_ids" name="post[tag_ids]" multiple="true">
# <option value="1">Ruby</option>
# <option value="6">Rails</option>
# <option value="3">Forms</option>
# <option value="4">Awesome</option>
# </select>
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Override Formtastic's assumption on when you need a multi select
# <%= f.input :authors, :as => :select, :input_html => { :multiple => true } %>
# <%= f.input :authors, :as => :select, :input_html => { :multiple => false } %>
#
# @example The `:collection` option can be used to customize the choices
# <%= f.input :author, :as => :select, :collection => @authors %>
# <%= f.input :author, :as => :select, :collection => Author.all %>
# <%= f.input :author, :as => :select, :collection => Author.some_named_scope %>
# <%= f.input :author, :as => :select, :collection => Author.pluck(:full_name, :id) %>
# <%= f.input :author, :as => :select, :collection => Author.pluck(Arel.sql("CONCAT(`first_name`, ' ', `last_name`)"), :id)) %>
# <%= f.input :author, :as => :select, :collection => [Author.find_by_login("justin"), Category.find_by_name("kate")] %>
# <%= f.input :author, :as => :select, :collection => ["Justin", "Kate"] %>
# <%= f.input :author, :as => :select, :collection => [["Justin", "justin"], ["Kate", "kate"]] %>
# <%= f.input :author, :as => :select, :collection => [["Justin", "1"], ["Kate", "3"]] %>
# <%= f.input :author, :as => :select, :collection => [["Justin", 1], ["Kate", 3]] %>
# <%= f.input :author, :as => :select, :collection => 1..5 %>
# <%= f.input :author, :as => :select, :collection => "<option>your own options HTML string</option>" %>
# <%= f.input :author, :as => :select, :collection => options_for_select(...) %>
# <%= f.input :author, :as => :select, :collection => options_from_collection_for_select(...) %>
# <%= f.input :author, :as => :select, :collection => grouped_options_for_select(...) %>
# <%= f.input :author, :as => :select, :collection => time_zone_options_for_select(...) %>
#
# @example Set HTML attributes on the `<select>` tag with `:input_html`
# <%= f.input :authors, :as => :select, :input_html => { :size => 20, :multiple => true, :class => "special" } %>
#
# @example Set HTML attributes on the `<li>` wrapper with `:wrapper_html`
# <%= f.input :authors, :as => :select, :wrapper_html => { :class => "special" } %>
#
# @example Exclude, include, or customize the blank option at the top of the select. Always shown, even if the field already has a value. Suitable for optional inputs.
# <%= f.input :author, :as => :select, :include_blank => false %>
# <%= f.input :author, :as => :select, :include_blank => true %> => <option value=""></option>
# <%= f.input :author, :as => :select, :include_blank => "No author" %>
#
# @example Exclude, include, or customize the prompt at the top of the select. Only shown if the field does not have a value. Suitable for required inputs.
# <%= f.input :author, :as => :select, :prompt => false %>
# <%= f.input :author, :as => :select, :prompt => true %> => <option value="">Please select</option>
# <%= f.input :author, :as => :select, :prompt => "Please select an author" %>
#
# @example Using ActiveRecord enum attribute with i18n translation:
# # post.rb
# class Post < ActiveRecord::Base
# enum :status => [ :active, :archived ]
# end
# # en.yml
# en:
# activerecord:
# attributes:
# post:
# statuses:
# active: I am active!
# archived: I am archived!
# # form
# <%= f.input :status, :as => :select %>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
# @see Formtastic::Inputs::CheckBoxesInput CheckBoxesInput as an alternative for `has_many` and `has_and_belongs_to_many` associations
# @see Formtastic::Inputs::RadioInput RadioInput as an alternative for `belongs_to` associations
#
# @todo Do/can we support the per-item HTML options like RadioInput?
class SelectInput
include Base
include Base::Collections
def initialize(*args)
super
raise Formtastic::UnsupportedEnumCollection if collection_from_enum? && multiple?
end
def to_html
input_wrapping do
label_html <<
select_html
end
end
def select_html
builder.select(input_name, collection, input_options, input_html_options)
end
def include_blank
options.key?(:include_blank) ? options[:include_blank] : (single? && builder.include_blank_for_select_by_default)
end
def prompt?
!!options[:prompt]
end
def label_html_options
super.merge(:for => input_html_options[:id])
end
def input_options
super.merge :include_blank => (include_blank unless prompt?)
end
def input_html_options
extra_input_html_options.merge(super.reject {|k,v| k==:name && v.nil?} )
end
def extra_input_html_options
{
:multiple => multiple?,
:name => multiple? ? input_html_options_name_multiple : input_html_options_name
}
end
def input_html_options_name
if builder.options.key?(:index)
"#{object_name}[#{builder.options[:index]}][#{association_primary_key}]"
else
"#{object_name}[#{association_primary_key}]"
end
end
def input_html_options_name_multiple
input_html_options_name + "[]"
end
def multiple_by_association?
reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro)
end
def multiple_by_options?
options[:multiple] || (options[:input_html] && options[:input_html][:multiple])
end
def multiple?
multiple_by_options? || multiple_by_association?
end
def single?
!multiple?
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/phone_input.rb | lib/formtastic/inputs/phone_input.rb | # frozen_string_literal: true
module Formtastic
module Inputs
# Outputs a simple `<label>` with a HTML5 `<input type="phone">` wrapped in the standard
# `<li>` wrapper. This is the default input choice for attributes with a name matching
# `/(phone|fax)/`, but can be applied to any text-like input with `:as => :phone`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :mobile, :as => :phone %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="phone">
# <label for="user_mobile">Mobile</label>
# <input type="tel" id="user_mobile" name="user[mobile]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class PhoneInput
include Base
include Base::Stringish
include Base::Placeholder
def to_html
input_wrapping do
label_html <<
builder.phone_field(method, input_html_options)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/fileish.rb | lib/formtastic/inputs/base/fileish.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Fileish
def file?
@file ||= begin
# TODO return true if self.is_a?(Formtastic::Inputs::FileInput::Woo)
object && object.respond_to?(method) && builder.file_methods.any? { |m| object.send(method).respond_to?(m) }
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/labelling.rb | lib/formtastic/inputs/base/labelling.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Labelling
include Formtastic::LocalizedString
def label_html
render_label? ? builder.label(input_name, label_text, label_html_options) : +"".html_safe
end
def label_html_options
{
:for => input_html_options[:id],
:class => ['label'],
}.merge(options[:label_html] || {})
end
def label_text
((localized_label || humanized_method_name) + requirement_text).html_safe
end
# TODO: why does this need to be memoized in order to make the inputs_spec tests pass?
def requirement_text_or_proc
@requirement_text_or_proc ||= required? ? builder.required_string : builder.optional_string
end
def requirement_text
if requirement_text_or_proc.respond_to?(:call)
requirement_text_or_proc.call
else
requirement_text_or_proc
end
end
def label_from_options
options[:label]
end
def localized_label
localized_string(method, label_from_options || method, :label)
end
def render_label?
return false if options[:label] == false
true
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/aria.rb | lib/formtastic/inputs/base/aria.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Aria
def error_aria_attributes
return {} unless builder.semantic_errors_link_to_inputs
return {} unless errors?
{
'aria-describedby': describedby,
'aria-invalid': options.dig(:input_html, :'aria-invalid') || 'true'
}
end
def describedby
describedby = options.dig(:input_html, :'aria-describedby') || ''
describedby += ' ' unless describedby.empty?
describedby += "#{method}_error"
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/errors.rb | lib/formtastic/inputs/base/errors.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Errors
def error_html
errors? ? send(:"error_#{builder.inline_errors}_html") : +""
end
def error_sentence_html
error_class = builder.default_inline_error_class
template.content_tag(:p, errors.to_sentence, id: "#{method}_error", :class => error_class)
end
def error_list_html
error_class = builder.default_error_list_class
list_elements = []
errors.each do |error|
list_elements << template.content_tag(:li, error.html_safe)
end
template.content_tag(:ul, list_elements.join("\n").html_safe, :class => error_class)
end
def error_first_html
error_class = builder.default_inline_error_class
template.content_tag(:p, errors.first.untaint.html_safe, :class => error_class)
end
def error_none_html
+""
end
def errors?
!errors.blank?
end
def errors
errors = []
if object && object.respond_to?(:errors)
error_keys.each do |key|
errors << object.errors[key] unless object.errors[key].blank?
end
end
errors.flatten.compact.uniq
end
def error_keys
keys = [method.to_sym]
keys << builder.file_metadata_suffixes.map{|suffix| "#{method}_#{suffix}".to_sym} if file?
keys << association_primary_key if belongs_to? || has_many?
keys.flatten.compact.uniq
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/wrapping.rb | lib/formtastic/inputs/base/wrapping.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
# @todo relies on `dom_id`, `required?`, `optional`, `errors?`, `association_primary_key` & `sanitized_method_name` methods from another module
module Wrapping
# Override this method if you want to change the display order (for example, rendering the
# errors before the body of the input).
def input_wrapping(&block)
template.content_tag(:li,
[template.capture(&block), error_html, hint_html].join("\n").html_safe,
wrapper_html_options
)
end
def wrapper_html_options
opts = wrapper_html_options_raw
opts[:class] = wrapper_classes
opts[:id] = wrapper_dom_id unless opts.has_key? :id
opts
end
def wrapper_html_options_raw
(options[:wrapper_html] || {}).dup
end
def wrapper_classes_raw
[*wrapper_html_options_raw[:class]]
end
def wrapper_classes
classes = wrapper_classes_raw
classes << as
classes << "input"
classes << "error" if errors?
classes << "optional" if optional?
classes << "required" if required?
classes << "autofocus" if autofocus?
classes.join(' ')
end
def wrapper_dom_id
@wrapper_dom_id ||= "#{dom_id.to_s.gsub((association_primary_key || method).to_s, sanitized_method_name.to_s)}_input"
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/options.rb | lib/formtastic/inputs/base/options.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Options
def input_options
options.except(*formtastic_options)
end
def formtastic_options
[:priority_countries, :priority_zones, :member_label, :member_value, :collection, :required, :label, :as, :hint, :input_html, :value_as_class, :class]
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/stringish.rb | lib/formtastic/inputs/base/stringish.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Stringish
# @abstract Override this method in your input class to describe how the input should render itself.
def to_html
input_wrapping do
label_html <<
builder.text_field(method, input_html_options)
end
end
# Overrides standard `input_html_options` to provide a `maxlength` and `size` attribute.
def input_html_options
{
:maxlength => maxlength,
:size => size
}.merge(super)
end
def size
builder.default_text_field_size
end
def maxlength
options[:input_html].try(:[], :maxlength) || limit
end
def wrapper_html_options
new_class = [super[:class], "stringish"].compact.join(" ")
super.merge(:class => new_class)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/datetime_pickerish.rb | lib/formtastic/inputs/base/datetime_pickerish.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module DatetimePickerish
include Base::Placeholder
def html_input_type
raise NotImplementedError
end
def default_size
raise NotImplementedError
end
def value
raise NotImplementedError
end
def input_html_options
super.merge(extra_input_html_options)
end
def extra_input_html_options
{
:type => html_input_type,
:size => size,
:maxlength => maxlength,
:step => step,
:value => value
}
end
def size
return options[:size] if options.key?(:size)
return options[:input_html][:size] if options[:input_html] && options[:input_html].key?(:size)
default_size
end
def step
return step_from_macro(options[:input_html][:step]) if options[:input_html] && options[:input_html][:step] && options[:input_html][:step].is_a?(Symbol)
return options[:input_html][:step] if options[:input_html] && options[:input_html].key?(:step)
default_step
end
def maxlength
return options[:maxlength] if options.key?(:maxlength)
return options[:input_html][:maxlength] if options[:input_html] && options[:input_html].key?(:maxlength)
default_size
end
def default_maxlength
default_size
end
def default_step
1
end
protected
def step_from_macro(sym)
case sym
# date
when :day then "1"
when :seven_days, :week then "7"
when :two_weeks, :fortnight then "14"
when :four_weeks then "28"
when :thirty_days then "30"
# time
when :second then "1"
when :minute then "60"
when :fifteen_minutes, :quarter_hour then "900"
when :thirty_minutes, :half_hour then "1800"
when :sixty_minutes, :hour then "3600"
else sym
end
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/choices.rb | lib/formtastic/inputs/base/choices.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Choices
def choices_wrapping(&block)
template.content_tag(:fieldset,
template.capture(&block),
choices_wrapping_html_options
)
end
def choices_wrapping_html_options
{ :class => "choices" }
end
def choices_group_wrapping(&block)
template.content_tag(:ol,
template.capture(&block),
choices_group_wrapping_html_options
)
end
def choices_group_wrapping_html_options
{ :class => "choices-group" }
end
def choice_wrapping(html_options, &block)
template.content_tag(:li,
template.capture(&block),
html_options
)
end
def choice_wrapping_html_options(choice)
classes = ['choice']
classes << "#{sanitized_method_name.singularize}_#{choice_html_safe_value(choice)}" if value_as_class?
{ :class => classes.join(" ") }
end
def choice_html(choice)
raise "choice_html() needs to be implemented when including Formtastic::Inputs::Base::Choices"
end
def choice_label(choice)
if choice.is_a?(Array)
choice.first
else
choice
end.to_s
end
def choice_value(choice)
choice.is_a?(Array) ? choice[1] : choice
end
def choice_html_options(choice)
custom_choice_html_options(choice).merge(default_choice_html_options(choice))
end
def default_choice_html_options(choice)
{ :id => choice_input_dom_id(choice) }
end
def custom_choice_html_options(choice)
(choice.is_a?(Array) && choice.size > 2) ? choice[-1] : {}
end
def choice_html_safe_value(choice)
choice_value(choice).to_s.gsub(/\s/, '_').gsub(/[^\w-]/, '').downcase
end
def choice_input_dom_id(choice)
[
builder.dom_id_namespace,
sanitized_object_name,
builder.options[:index],
association_primary_key || method,
choice_html_safe_value(choice)
].compact.reject { |i| i.blank? }.join("_")
end
def value_as_class?
options[:value_as_class]
end
def legend_html
if render_label?
template.content_tag(:legend,
template.content_tag(:label, label_text),
label_html_options.merge(:class => "label")
)
else
+"".html_safe
end
end
# Override to remove the for attribute since this isn't associated with any element, as it's
# nested inside the legend.
def label_html_options
super.merge(:for => nil)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/validations.rb | lib/formtastic/inputs/base/validations.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Validations
class IndeterminableMinimumAttributeError < ArgumentError
def message
[
"A minimum value can not be determined when the validation uses :greater_than on a :decimal or :float column type.",
"Please alter the validation to use :greater_than_or_equal_to, or provide a value for this attribute explicitly with the :min option on input()."
].join("\n")
end
end
class IndeterminableMaximumAttributeError < ArgumentError
def message
[
"A maximum value can not be determined when the validation uses :less_than on a :decimal or :float column type.",
"Please alter the validation to use :less_than_or_equal_to, or provide a value for this attribute explicitly with the :max option on input()."
].join("\n")
end
end
def validations
@validations ||= if object && object.class.respond_to?(:validators_on)
object.class.validators_on(attributized_method_name).select do |validator|
validator_relevant?(validator)
end
else
nil
end
end
def validator_relevant?(validator)
return true unless validator.options.key?(:if) || validator.options.key?(:unless)
conditional = validator.options.key?(:if) ? validator.options[:if] : validator.options[:unless]
result = if conditional.respond_to?(:call) && conditional.arity > 0
conditional.call(object)
elsif conditional.respond_to?(:call) && conditional.arity == 0
object.instance_exec(&conditional)
elsif conditional.is_a?(::Symbol) && object.respond_to?(conditional)
object.send(conditional)
else
conditional
end
result = validator.options.key?(:unless) ? !result : !!result
not_required_through_negated_validation! if !result && [:presence, :inclusion, :length].include?(validator.kind)
result
end
def validation_limit
validation = validations? && validations.find do |validation|
validation.kind == :length
end
if validation
validation.options[:maximum] || (validation.options[:within].present? ? validation.options[:within].max : nil)
else
nil
end
end
# Prefer :greater_than_or_equal_to over :greater_than, for no particular reason.
def validation_min
validation = validations? && validations.find do |validation|
validation.kind == :numericality
end
if validation
# We can't determine an appropriate value for :greater_than with a float/decimal column
raise IndeterminableMinimumAttributeError if validation.options[:greater_than] && column? && [:float, :decimal].include?(column.type)
if validation.options[:greater_than_or_equal_to]
return option_value(validation.options[:greater_than_or_equal_to], object)
end
if validation.options[:greater_than]
return option_value(validation.options[:greater_than], object) + 1
end
end
end
# Prefer :less_than_or_equal_to over :less_than, for no particular reason.
def validation_max
validation = validations? && validations.find do |validation|
validation.kind == :numericality
end
if validation
# We can't determine an appropriate value for :greater_than with a float/decimal column
raise IndeterminableMaximumAttributeError if validation.options[:less_than] && column? && [:float, :decimal].include?(column.type)
if validation.options[:less_than_or_equal_to]
return option_value(validation.options[:less_than_or_equal_to], object)
end
if validation.options[:less_than]
return option_value(validation.options[:less_than], object) - 1
end
end
end
def validation_step
validation = validations? && validations.find do |validation|
validation.kind == :numericality
end
if validation
validation.options[:step] || (1 if validation_integer_only?)
else
nil
end
end
def validation_integer_only?
validation = validations? && validations.find do |validation|
validation.kind == :numericality
end
if validation
validation.options[:only_integer]
else
false
end
end
def validations?
validations != nil
end
def required?
return false if options[:required] == false
return true if options[:required] == true
return false if not_required_through_negated_validation?
if validations?
validations.any? { |validator|
if validator.options.key?(:on)
validator_on = Array(validator.options[:on])
next false if (validator_on.exclude?(:save)) && ((object.new_record? && validator_on.exclude?(:create)) || (!object.new_record? && validator_on.exclude?(:update)))
end
case validator.kind
when :presence
true
when :inclusion
validator.options[:allow_blank] != true
when :length
validator.options[:allow_blank] != true &&
validator.options[:minimum].to_i > 0 ||
validator.options[:within].try(:first).to_i > 0
else
false
end
}
else
return responds_to_global_required? && !!builder.all_fields_required_by_default
end
end
def required_attribute?
required? && builder.use_required_attribute
end
def not_required_through_negated_validation?
@not_required_through_negated_validation
end
def not_required_through_negated_validation!
@not_required_through_negated_validation = true
end
def responds_to_global_required?
true
end
def optional?
!required?
end
def autofocus?
opt_autofocus = options[:input_html] && options[:input_html][:autofocus]
!!opt_autofocus
end
def column_limit
return unless column?
return unless column.respond_to?(:limit)
limit = column.limit # already in characters for string, text, etc
if column.type == :integer && column.limit.is_a?(Integer)
return {
1 => 3, # 8 bit
2 => 5, # 16 bit
3 => 7, # 24 bit
4 => 10, # 32 bit
8 => 19, # 64 bit
}[limit] || nil
end
return limit
end
def limit
validation_limit || column_limit
end
def readonly?
readonly_from_options? || readonly_attribute?
end
def readonly_attribute?
object_class = self.object.class
object_class.respond_to?(:readonly_attributes) &&
self.object.persisted? &&
column.respond_to?(:name) &&
object_class.readonly_attributes.include?(column.name.to_s)
end
def readonly_from_options?
options[:input_html] && options[:input_html][:readonly]
end
private
# Loosely based on
# https://github.com/rails/rails/blob/459e7cf62252558bbf65f582a230562ab1a76c5e/activemodel/lib/active_model/validations/numericality.rb#L65-L70
def option_value(option, object)
case option
when Symbol
object.send(option)
when Proc
option.call(object)
else
option
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/placeholder.rb | lib/formtastic/inputs/base/placeholder.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Placeholder
def input_html_options
{:placeholder => placeholder_text}.merge(super)
end
def placeholder_text
localized_string(method, options[:placeholder], :placeholder)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/hints.rb | lib/formtastic/inputs/base/hints.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Hints
def hint_html
if hint?
template.content_tag(
:p,
hint_text.html_safe,
:class => builder.default_hint_class
)
end
end
def hint?
!hint_text.blank? && !hint_text.kind_of?(Hash)
end
def hint_text
localized_string(method, options[:hint], :hint)
end
def hint_text_from_options
options[:hint]
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/associations.rb | lib/formtastic/inputs/base/associations.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Associations
include Formtastic::Helpers::Reflection
# :belongs_to, etc
def association
@association ||= association_macro_for_method(method)
end
def reflection
@reflection ||= reflection_for(method)
end
def belongs_to?
association == :belongs_to
end
def has_many?
association == :has_many
end
def association_primary_key
association_primary_key_for_method(method)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/collections.rb | lib/formtastic/inputs/base/collections.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Collections
def label_method
@label_method ||= (label_method_from_options || label_and_value_method.first)
end
def label_method_from_options
options[:member_label]
end
def value_method
@value_method ||= (value_method_from_options || label_and_value_method[-1])
end
def value_method_from_options
options[:member_value]
end
def label_and_value_method
@label_and_value_method ||= label_and_value_method_from_collection(raw_collection)
end
def label_and_value_method_from_collection(_collection)
sample = _collection.first || _collection[-1]
case sample
when Array
label, value = :first, :last
when Integer
label, value = :to_s, :to_i
when Symbol, String, NilClass
label, value = :to_s, :to_s
end
# Order of preference: user supplied method, class defaults, auto-detect
label ||= builder.collection_label_methods.find { |m| sample.respond_to?(m) }
value ||= builder.collection_value_methods.find { |m| sample.respond_to?(m) }
[label, value]
end
def raw_collection
@raw_collection ||= (collection_from_options || collection_from_enum || collection_from_association || collection_for_boolean)
end
def collection
# Return if we have a plain string
return raw_collection if raw_collection.is_a?(String)
# Return if we have an Array of strings, integers or arrays
return raw_collection if (raw_collection.instance_of?(Array) || raw_collection.instance_of?(Range)) &&
([Array, String, Symbol].include?(raw_collection.first.class) || raw_collection.first.is_a?(Integer)) &&
!(options.include?(:member_label) || options.include?(:member_value))
raw_collection.map { |o| [send_or_call(label_method, o), send_or_call(value_method, o)] }
end
def collection_from_options
items = options[:collection]
case items
when Hash
items.to_a
when Range
items.to_a.collect{ |c| [c.to_s, c] }
else
items
end
end
def collection_from_association
if reflection
if reflection.respond_to?(:options)
raise PolymorphicInputWithoutCollectionError.new(
"A collection must be supplied for #{method} input. Collections cannot be guessed for polymorphic associations."
) if reflection.options[:polymorphic] == true
end
return reflection.klass.merge(reflection.scope) if reflection.scope
conditions_from_reflection = (reflection.respond_to?(:options) && reflection.options[:conditions]) || {}
conditions_from_reflection = conditions_from_reflection.call if conditions_from_reflection.is_a?(Proc)
scope_conditions = conditions_from_reflection.empty? ? nil : {:conditions => conditions_from_reflection}
where_conditions = (scope_conditions && scope_conditions[:conditions]) || {}
reflection.klass.where(where_conditions)
end
end
# Assuming the following model:
#
# class Post < ActiveRecord::Base
# enum :status => [ :active, :archived ]
# end
#
# We would end up with a collection like this:
#
# [["Active", "active"], ["Archived", "archived"]
#
# The first element in each array uses String#humanize, but I18n
# translations are available too. Set them with the following structure.
#
# en:
# activerecord:
# attributes:
# post:
# statuses:
# active: Custom Active Label Here
# archived: Custom Archived Label Here
def collection_from_enum
if collection_from_enum?
method_name = method.to_s
enum_options_hash = object.defined_enums[method_name]
enum_options_hash.map do |name, value|
key = "activerecord.attributes.#{object.model_name.i18n_key}.#{method_name.pluralize}.#{name}"
label = ::I18n.translate(key, :default => name.humanize)
[label, name]
end
end
end
def collection_from_enum?
object.respond_to?(:defined_enums) && object.defined_enums.has_key?(method.to_s)
end
def collection_for_boolean
true_text = options[:true] || Formtastic::I18n.t(:yes)
false_text = options[:false] || Formtastic::I18n.t(:no)
# TODO options[:value_as_class] = true unless options.key?(:value_as_class)
[ [true_text, true], [false_text, false] ]
end
def send_or_call(duck, object)
if duck.respond_to?(:call)
duck.call(object)
elsif object.respond_to? duck.to_sym
object.send(duck)
end
end
# Avoids an issue where `send_or_call` can be a String and duck can be something simple like
# `:first`, which obviously String responds to.
def send_or_call_or_object(duck, object)
return object if object.is_a?(String) || object.is_a?(Integer) || object.is_a?(Symbol) # TODO what about other classes etc?
send_or_call(duck, object)
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/timeish.rb | lib/formtastic/inputs/base/timeish.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
# Timeish inputs (`:date_select`, `:datetime_select`, `:time_select`) are similar to the Rails date and time
# helpers (`date_select`, `datetime_select`, `time_select`), rendering a series of `<select>`
# tags for each fragment (year, month, day, hour, minute, seconds). The fragments are then
# re-combined to a date by ActiveRecord through multi-parameter assignment.
#
# The mark-up produced by Rails is simple but far from ideal, with no way to label the
# individual fragments for accessibility, no fieldset to group the related fields, and no
# legend describing the group. Formtastic addresses this within the standard `<li>` wrapper
# with a `<fieldset>` with a `<legend>` as a label, followed by an ordered list (`<ol>`) of
# list items (`<li>`), one for each fragment (year, month, ...). Each `<li>` fragment contains
# a `<label>` (eg "Year") for the fragment, and a `<select>` containing `<option>`s (eg a
# range of years).
#
# In the supplied formtastic.css file, the resulting mark-up is styled to appear a lot like a
# standard Rails date time select by:
#
# * styling the legend to look like the other labels (to the left hand side of the selects)
# * floating the `<li>` fragments against each other as a single line
# * hiding the `<label>` of each fragment with `display:none`
#
# @example `:date_select` input with full form context and sample HTMl output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.inputs do %>
# ...
# <%= f.input :publish_at, :as => :date_select %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset class="inputs">
# <ol>
# <li class="date">
# <fieldset class="fragments">
# <ol class="fragments-group">
# <li class="fragment">
# <label for="post_publish_at_1i">Year</label>
# <select id="post_publish_at_1i" name="post[publish_at_1i]">...</select>
# </li>
# <li class="fragment">
# <label for="post_publish_at_2i">Month</label>
# <select id="post_publish_at_2i" name="post[publish_at_2i]">...</select>
# </li>
# <li class="fragment">
# <label for="post_publish_at_3i">Day</label>
# <select id="post_publish_at_3i" name="post[publish_at_3i]">...</select>
# </li>
# </ol>
# </fieldset>
# </li>
# </ol>
# </fieldset>
# </form>
#
#
# @example `:time_select` input
# <%= f.input :publish_at, :as => :time_select %>
#
# @example `:datetime_select` input
# <%= f.input :publish_at, :as => :datetime_select %>
#
# @example Change the labels for each fragment
# <%= f.input :publish_at, :as => :date_select, :labels => { :year => "Y", :month => "M", :day => "D" } %>
#
# @example Suppress the labels for all fragments
# <%= f.input :publish_at, :as => :date_select, :labels => false %>
#
# @example Skip a fragment (defaults to 1, skips all following fragments)
# <%= f.input :publish_at, :as => :datetime_select, :discard_minute => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_hour => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_day => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_month => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_year => true %>
#
# @example Change the order
# <%= f.input :publish_at, :as => :date_select, :order => [:month, :day, :year] %>
#
# @example Include seconds with times (excluded by default)
# <%= f.input :publish_at, :as => :time_select, :include_seconds => true %>
#
# @example Specify if there should be a blank option at the start of each select or not. Note that, unlike select inputs, :include_blank does not accept a string value.
# <%= f.input :publish_at, :as => :time_select, :include_blank => true %>
# <%= f.input :publish_at, :as => :time_select, :include_blank => false %>
#
# @example Provide a value for the field via selected
# <%= f.input :publish_at, :as => :datetime_select, :selected => DateTime.new(2018, 10, 4, 12, 00)
#
# @todo Document i18n
# @todo Check what other Rails options are supported (`start_year`, `end_year`, `use_month_numbers`, `use_short_month`, `add_month_numbers`, `prompt`), write tests for them, and otherwise support them
# @todo Could we take the rendering from Rails' helpers and inject better HTML in and around it rather than re-inventing the whee?
module Timeish
def to_html
input_wrapping do
fragments_wrapping do
hidden_fragments <<
fragments_label <<
template.content_tag(:ol,
fragments.map do |fragment|
fragment_wrapping do
fragment_label_html(fragment) <<
fragment_input_html(fragment)
end
end.join.html_safe, # TODO is this safe?
{ :class => 'fragments-group' } # TODO refactor to fragments_group_wrapping
)
end
end
end
def fragments
date_fragments + time_fragments
end
def time_fragments
options[:include_seconds] ? [:hour, :minute, :second] : [:hour, :minute]
end
def date_fragments
options[:order] || i18n_date_fragments || default_date_fragments
end
def default_date_fragments
[:year, :month, :day]
end
def fragment_wrapping(&block)
template.content_tag(:li, template.capture(&block), fragment_wrapping_html_options)
end
def fragment_wrapping_html_options
{ :class => 'fragment' }
end
def fragment_label(fragment)
labels_from_options = options.key?(:labels) ? options[:labels] : {}
if !labels_from_options
''
elsif labels_from_options.key?(fragment)
labels_from_options[fragment]
else
::I18n.t(fragment.to_s, :default => fragment.to_s.humanize, :scope => [:datetime, :prompts])
end
end
def fragment_id(fragment)
"#{input_html_options[:id]}_#{position(fragment)}i"
end
def fragment_name(fragment)
"#{method}(#{position(fragment)}i)"
end
def fragment_label_html(fragment)
text = fragment_label(fragment)
text.blank? ? +"".html_safe : template.content_tag(:label, text, :for => fragment_id(fragment))
end
def value
return input_options[:selected] if options.key?(:selected)
object.send(method) if object && object.respond_to?(method)
end
def fragment_input_html(fragment)
opts = input_options.merge(:prefix => fragment_prefix, :field_name => fragment_name(fragment), :default => value, :include_blank => include_blank?)
template.send(:"select_#{fragment}", value, opts, input_html_options.merge(:id => fragment_id(fragment)))
end
def fragment_prefix
if builder.options.key?(:index)
object_name + "[#{builder.options[:index]}]"
else
object_name
end
end
# TODO extract to BlankOptions or similar -- Select uses similar code
def include_blank?
options.key?(:include_blank) ? options[:include_blank] : builder.include_blank_for_select_by_default
end
def positions
{ :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
end
def position(fragment)
positions[fragment]
end
def i18n_date_fragments
order = ::I18n.t(:order, :scope => [:date])
if order.is_a?(Array)
order.map &:to_sym
else
nil
end
end
def fragments_wrapping(&block)
template.content_tag(:fieldset,
template.capture(&block).html_safe,
fragments_wrapping_html_options
)
end
def fragments_wrapping_html_options
{ :class => "fragments" }
end
def fragments_label
if render_label?
template.content_tag(:legend,
builder.label(method, label_text, :for => fragment_id(fragments.first)),
:class => "label"
)
else
+"".html_safe
end
end
def fragments_inner_wrapping(&block)
template.content_tag(:ol,
template.capture(&block)
)
end
def hidden_fragments
+"".html_safe
end
def hidden_field_name(fragment)
if builder.options.key?(:index)
"#{object_name}[#{builder.options[:index]}][#{fragment_name(fragment)}]"
else
"#{object_name}[#{fragment_name(fragment)}]"
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/naming.rb | lib/formtastic/inputs/base/naming.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Naming
def as
self.class.name.split("::")[-1].underscore.gsub(/_input$/, '')
end
def sanitized_object_name
object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
end
def sanitized_method_name
@sanitized_method_name ||= method.to_s.gsub(/[\?\/\-]$/, '')
end
def attributized_method_name
method.to_s.gsub(/_id$/, '').to_sym
end
def humanized_method_name
if builder.label_str_method != :humanize
# Special case where label_str_method should trump the human_attribute_name
# TODO: is this actually a desired bheavior, or should we ditch label_str_method and
# rely purely on :human_attribute_name.
method.to_s.send(builder.label_str_method)
elsif object && object.class.respond_to?(:human_attribute_name)
object.class.human_attribute_name(method.to_s)
else
method.to_s.send(builder.label_str_method)
end
end
def input_name
association_primary_key
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/numeric.rb | lib/formtastic/inputs/base/numeric.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Numeric
def input_html_options
defaults = super
# override rails default size - does not apply to numeric inputs
#@todo document/spec
defaults[:size] = nil
if in_option
defaults[:min] = in_option.to_a.min
defaults[:max] = in_option.to_a.max
else
defaults[:min] ||= min_option
defaults[:max] ||= max_option
end
defaults[:step] ||= step_option
defaults
end
def step_option
return options[:step] if options.key?(:step)
validation_step
end
def min_option
return options[:min] if options.key?(:min)
validation_min
end
def max_option
return options[:max] if options.key?(:max)
validation_max
end
def in_option
options[:in]
end
def wrapper_html_options
new_class = [super[:class], "numeric", "stringish"].compact.join(" ")
super.merge(:class => new_class)
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/database.rb | lib/formtastic/inputs/base/database.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Database
def column
if object.respond_to?(:column_for_attribute)
object.column_for_attribute(method)
end
end
def column?
!column.nil?
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic/inputs/base/html.rb | lib/formtastic/inputs/base/html.rb | # frozen_string_literal: true
module Formtastic
module Inputs
module Base
module Html
# Defines how the instance of an input should be rendered to a HTML string.
#
# @abstract Implement this method in your input class to describe how the input should render itself.
#
# @example A basic label and text field input inside a standard wrapping might look like this:
# def to_html
# input_wrapping do
# label_html <<
# builder.text_field(method, input_html_options)
# end
# end
def to_html
raise NotImplementedError
end
def input_html_options
{
:id => dom_id,
:required => required_attribute?,
:autofocus => autofocus?,
:readonly => readonly?
}.merge(options[:input_html] || {}).merge(error_aria_attributes)
end
def dom_id
[
builder.dom_id_namespace,
sanitized_object_name,
dom_index,
association_primary_key || sanitized_method_name
].reject { |x| x.blank? }.join('_')
end
def dom_index
if builder.options.has_key?(:index)
builder.options[:index]
elsif !builder.auto_index.blank?
# TODO there's no coverage for this case, not sure how to create a scenario for it
builder.auto_index
else
+""
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/install.rb | install.rb | #! /usr/bin/env ruby
#--
# Copyright 2004 Austin Ziegler <ruby-install@halostatue.ca>
# Install utility. Based on the original installation script for rdoc by the
# Pragmatic Programmers.
#
# This program is free software. It may be redistributed and/or modified under
# the terms of the GPL version 2 (or later) or the Ruby licence.
#
# Usage
# -----
# In most cases, if you have a typical project layout, you will need to do
# absolutely nothing to make this work for you. This layout is:
#
# bin/ # executable files -- "commands"
# lib/ # the source of the library
#
# The default behaviour:
# 1) Build Rdoc documentation from all files in bin/ (excluding .bat and .cmd),
# all .rb files in lib/, ./README, ./ChangeLog, and ./Install.
# 2) Build ri documentation from all files in bin/ (excluding .bat and .cmd),
# and all .rb files in lib/. This is disabled by default on Microsoft Windows.
# 3) Install commands from bin/ into the Ruby bin directory. On Windows, if a
# if a corresponding batch file (.bat or .cmd) exists in the bin directory,
# it will be copied over as well. Otherwise, a batch file (always .bat) will
# be created to run the specified command.
# 4) Install all library files ending in .rb from lib/ into Ruby's
# site_lib/version directory.
#
#++
require 'rbconfig'
require 'find'
require 'fileutils'
require 'tempfile'
require 'optparse'
require 'ostruct'
PREREQS = %w{openssl facter cgi}
MIN_FACTER_VERSION = 1.5
InstallOptions = OpenStruct.new
def glob(list)
g = list.map { |i| Dir.glob(i) }
g.flatten!
g.compact!
g
end
def do_configs(configs, target, strip = 'conf/')
Dir.mkdir(target) unless File.directory? target
configs.each do |cf|
ocf = File.join(InstallOptions.config_dir, cf.gsub(/#{strip}/, ''))
FileUtils.install(cf, ocf, mode: 0644, preserve: true, verbose: true)
end
end
def do_bins(bins, target, strip = 's?bin/')
Dir.mkdir(target) unless File.directory? target
bins.each do |bf|
obf = bf.gsub(/#{strip}/, '')
install_binfile(bf, obf, target)
end
end
def do_libs(libs, strip = 'lib/')
libs.each do |lf|
next if File.directory? lf
olf = File.join(InstallOptions.site_dir, lf.sub(/^#{strip}/, ''))
op = File.dirname(olf)
FileUtils.makedirs(op, mode: 0755, verbose: true)
FileUtils.chmod(0755, op)
FileUtils.install(lf, olf, mode: 0644, preserve: true, verbose: true)
end
end
def do_man(man, strip = 'man/')
man.each do |mf|
omf = File.join(InstallOptions.man_dir, mf.gsub(/#{strip}/, ''))
om = File.dirname(omf)
FileUtils.makedirs(om, mode: 0755, verbose: true)
FileUtils.chmod(0755, om)
FileUtils.install(mf, omf, mode: 0644, preserve: true, verbose: true)
# Solaris does not support gzipped man pages. When called with
# --no-check-prereqs/without facter the default gzip behavior still applies
unless $osname == "Solaris"
gzip = %x{which gzip}
gzip.chomp!
%x{#{gzip} -f #{omf}}
end
end
end
def do_locales(locale, strip = 'locales/')
locale.each do |lf|
next if File.directory? lf
olf = File.join(InstallOptions.locale_dir, lf.sub(/^#{strip}/, ''))
op = File.dirname(olf)
FileUtils.makedirs(op, mode: 0755, verbose: true)
FileUtils.chmod(0755, op)
FileUtils.install(lf, olf, mode: 0644, preserve: true, verbose: true)
end
end
# Verify that all of the prereqs are installed
def check_prereqs
PREREQS.each { |pre|
begin
require pre
if pre == "facter"
# to_f isn't quite exact for strings like "1.5.1" but is good
# enough for this purpose.
facter_version = Facter.version.to_f
if facter_version < MIN_FACTER_VERSION
puts "Facter version: #{facter_version}; minimum required: #{MIN_FACTER_VERSION}; cannot install"
exit(-1)
end
end
rescue LoadError
puts "Could not load #{pre}; cannot install"
exit(-1)
end
}
end
##
# Prepare the file installation.
#
def prepare_installation
InstallOptions.configs = true
InstallOptions.check_prereqs = true
InstallOptions.batch_files = true
ARGV.options do |opts|
opts.banner = "Usage: #{File.basename($0)} [options]"
opts.separator ""
opts.on('--[no-]configs', 'Prevents the installation of config files', 'Default off.') do |ontest|
InstallOptions.configs = ontest
end
opts.on('--destdir[=OPTIONAL]', 'Installation prefix for all targets', 'Default essentially /') do |destdir|
InstallOptions.destdir = destdir
end
opts.on('--configdir[=OPTIONAL]', 'Installation directory for config files', 'Default /etc/puppetlabs/puppet') do |configdir|
InstallOptions.configdir = configdir
end
opts.on('--codedir[=OPTIONAL]', 'Installation directory for code files', 'Default /etc/puppetlabs/code') do |codedir|
InstallOptions.codedir = codedir
end
opts.on('--vardir[=OPTIONAL]', 'Installation directory for var files', 'Default /opt/puppetlabs/puppet/cache') do |vardir|
InstallOptions.vardir = vardir
end
opts.on('--publicdir[=OPTIONAL]', 'Installation directory for public files such as the `last_run_summary.yaml` report', 'Default /opt/puppetlabs/puppet/public') do |publicdir|
InstallOptions.publicdir = publicdir
end
opts.on('--rundir[=OPTIONAL]', 'Installation directory for state files', 'Default /var/run/puppetlabs') do |rundir|
InstallOptions.rundir = rundir
end
opts.on('--logdir[=OPTIONAL]', 'Installation directory for log files', 'Default /var/log/puppetlabs/puppet') do |logdir|
InstallOptions.logdir = logdir
end
opts.on('--bindir[=OPTIONAL]', 'Installation directory for binaries', 'overrides RbConfig::CONFIG["bindir"]') do |bindir|
InstallOptions.bindir = bindir
end
opts.on('--localedir[=OPTIONAL]', 'Installation directory for locale information', 'Default /opt/puppetlabs/puppet/share/locale') do |localedir|
InstallOptions.localedir = localedir
end
opts.on('--ruby[=OPTIONAL]', 'Ruby interpreter to use with installation', 'overrides ruby used to call install.rb') do |ruby|
InstallOptions.ruby = ruby
end
opts.on('--sitelibdir[=OPTIONAL]', 'Installation directory for libraries', 'overrides RbConfig::CONFIG["sitelibdir"]') do |sitelibdir|
InstallOptions.sitelibdir = sitelibdir
end
opts.on('--mandir[=OPTIONAL]', 'Installation directory for man pages', 'overrides RbConfig::CONFIG["mandir"]') do |mandir|
InstallOptions.mandir = mandir
end
opts.on('--[no-]check-prereqs', 'Prevents validation of prerequisite libraries', 'Default on') do |prereq|
InstallOptions.check_prereqs = prereq
end
opts.on('--no-batch-files', 'Prevents installation of batch files for windows', 'Default off') do |batch_files|
InstallOptions.batch_files = false
end
opts.on('--quick', 'Performs a quick installation. Only the', 'installation is done.') do |quick|
InstallOptions.configs = true
warn "--quick is deprecated. Use --configs"
end
opts.separator("")
opts.on_tail('--help', "Shows this help text.") do
$stderr.puts opts
exit
end
opts.parse!
end
# Mac OS X 10.5 and higher declare bindir
# /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin
# which is not generally where people expect executables to be installed
# These settings are appropriate defaults for all OS X versions.
if RUBY_PLATFORM =~ /^universal-darwin[\d\.]+$/
RbConfig::CONFIG['bindir'] = "/usr/bin"
end
# Here we only set $osname if we have opted to check for prereqs.
# Otherwise facter won't be guaranteed to be present.
if InstallOptions.check_prereqs
check_prereqs
$osname = Facter.value('os.name')
end
if not InstallOptions.configdir.nil?
configdir = InstallOptions.configdir
elsif $osname == "windows"
configdir = File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "etc")
else
configdir = "/etc/puppetlabs/puppet"
end
if not InstallOptions.codedir.nil?
codedir = InstallOptions.codedir
elsif $osname == "windows"
codedir = File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "code")
else
codedir = "/etc/puppetlabs/code"
end
if not InstallOptions.vardir.nil?
vardir = InstallOptions.vardir
elsif $osname == "windows"
vardir = File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "cache")
else
vardir = "/opt/puppetlabs/puppet/cache"
end
if not InstallOptions.publicdir.nil?
publicdir = InstallOptions.publicdir
elsif $osname == "windows"
publicdir = File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "public")
else
publicdir = "/opt/puppetlabs/puppet/public"
end
if not InstallOptions.rundir.nil?
rundir = InstallOptions.rundir
elsif $osname == "windows"
rundir = File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "var", "run")
else
rundir = "/var/run/puppetlabs"
end
if not InstallOptions.logdir.nil?
logdir = InstallOptions.logdir
elsif $osname == "windows"
logdir = File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "var", "log")
else
logdir = "/var/log/puppetlabs/puppet"
end
if not InstallOptions.bindir.nil?
bindir = InstallOptions.bindir
else
bindir = RbConfig::CONFIG['bindir']
end
if not InstallOptions.localedir.nil?
localedir = InstallOptions.localedir
else
if $osname == "windows"
localedir = File.join(ENV['PROGRAMFILES'], "Puppet Labs", "Puppet", "puppet", "share", "locale")
else
localedir = "/opt/puppetlabs/puppet/share/locale"
end
end
if not InstallOptions.sitelibdir.nil?
sitelibdir = InstallOptions.sitelibdir
else
sitelibdir = RbConfig::CONFIG["sitelibdir"]
if sitelibdir.nil?
sitelibdir = $LOAD_PATH.find { |x| x =~ /site_ruby/ }
if sitelibdir.nil?
version = [RbConfig::CONFIG["MAJOR"], RbConfig::CONFIG["MINOR"]].join(".")
sitelibdir = File.join(RbConfig::CONFIG["libdir"], "ruby", version, "site_ruby")
elsif sitelibdir !~ Regexp.quote(version)
sitelibdir = File.join(sitelibdir, version)
end
end
end
if not InstallOptions.mandir.nil?
mandir = InstallOptions.mandir
else
mandir = RbConfig::CONFIG['mandir']
end
# This is the new way forward
if not InstallOptions.destdir.nil?
destdir = InstallOptions.destdir
else
destdir = ''
end
configdir = join(destdir, configdir)
codedir = join(destdir, codedir)
vardir = join(destdir, vardir)
publicdir = join(destdir, publicdir)
rundir = join(destdir, rundir)
logdir = join(destdir, logdir)
bindir = join(destdir, bindir)
localedir = join(destdir, localedir)
mandir = join(destdir, mandir)
sitelibdir = join(destdir, sitelibdir)
FileUtils.makedirs(configdir) if InstallOptions.configs
FileUtils.makedirs(codedir)
FileUtils.makedirs(bindir)
FileUtils.makedirs(mandir)
FileUtils.makedirs(sitelibdir)
FileUtils.makedirs(vardir)
FileUtils.makedirs(publicdir)
FileUtils.makedirs(rundir)
FileUtils.makedirs(logdir)
FileUtils.makedirs(localedir)
InstallOptions.site_dir = sitelibdir
InstallOptions.codedir = codedir
InstallOptions.config_dir = configdir
InstallOptions.bin_dir = bindir
InstallOptions.man_dir = mandir
InstallOptions.var_dir = vardir
InstallOptions.public_dir = publicdir
InstallOptions.run_dir = rundir
InstallOptions.log_dir = logdir
InstallOptions.locale_dir = localedir
end
##
# Join two paths. On Windows, dir must be converted to a relative path,
# by stripping the drive letter, but only if the basedir is not empty.
#
def join(basedir, dir)
return "#{basedir}#{dir[2..-1]}" if $osname == "windows" and basedir.length > 0 and dir.length > 2
"#{basedir}#{dir}"
end
##
# Install file(s) from ./bin to RbConfig::CONFIG['bindir']. Patch it on the way
# to insert a #! line; on a Unix install, the command is named as expected
# (e.g., bin/rdoc becomes rdoc); the shebang line handles running it. Under
# windows, we add an '.rb' extension and let file associations do their stuff.
def install_binfile(from, op_file, target)
tmp_file = Tempfile.new('puppet-binfile')
if not InstallOptions.ruby.nil?
ruby = InstallOptions.ruby
else
ruby = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'])
end
File.open(from) do |ip|
File.open(tmp_file.path, "w") do |op|
op.puts "#!#{ruby}" unless $osname == "windows"
contents = ip.readlines
contents.shift if contents[0] =~ /^#!/
op.write contents.join
end
end
if $osname == "windows" && InstallOptions.batch_files
installed_wrapper = false
unless File.extname(from) =~ /\.(cmd|bat)/
if File.exist?("#{from}.bat")
FileUtils.install("#{from}.bat", File.join(target, "#{op_file}.bat"), mode: 0755, preserve: true, verbose: true)
installed_wrapper = true
end
if File.exist?("#{from}.cmd")
FileUtils.install("#{from}.cmd", File.join(target, "#{op_file}.cmd"), mode: 0755, preserve: true, verbose: true)
installed_wrapper = true
end
if not installed_wrapper
tmp_file2 = Tempfile.new('puppet-wrapper')
cwv = <<-EOS
@echo off
SETLOCAL
if exist "%~dp0environment.bat" (
call "%~dp0environment.bat" %0 %*
) else (
SET "PATH=%~dp0;%PATH%"
)
ruby.exe -S -- puppet %*
EOS
File.open(tmp_file2.path, "w") { |cw| cw.puts cwv }
FileUtils.install(tmp_file2.path, File.join(target, "#{op_file}.bat"), mode: 0755, preserve: true, verbose: true)
tmp_file2.unlink
end
end
end
FileUtils.install(tmp_file.path, File.join(target, op_file), mode: 0755, preserve: true, verbose: true)
tmp_file.unlink
end
# Change directory into the puppet root so we don't get the wrong files for install.
FileUtils.cd File.dirname(__FILE__) do
# Set these values to what you want installed.
configs = glob(%w{conf/puppet.conf conf/hiera.yaml})
bins = glob(%w{bin/*})
man = glob(%w{man/man[0-9]/*})
libs = glob(%w{lib/**/*})
locales = glob(%w{locales/**/*})
prepare_installation
if $osname == "windows"
windows_bins = glob(%w{ext/windows/*bat})
end
do_configs(configs, InstallOptions.config_dir) if InstallOptions.configs
do_bins(bins, InstallOptions.bin_dir)
do_bins(windows_bins, InstallOptions.bin_dir, 'ext/windows/') if $osname == "windows" && InstallOptions.batch_files
do_libs(libs)
do_locales(locales)
do_man(man) unless $osname == "windows"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/rakelib/references/get_typedocs.rb | rakelib/references/get_typedocs.rb | # This script will print the Puppet type docs to stdout in JSON format.
# There are some subtleties that make this a pain to run. Basically: Even if you
# 'require' a specific copy of the Puppet code, the autoloader will grab bits
# and pieces of Puppet code from other copies of Puppet scattered about the Ruby
# load path. This causes a mixture of docs from different versions: although I
# think the version you require will usually win for things that exist in both
# versions, providers or attributes that only exist in one version will leak
# through and you'll get an amalgamation.
# So the only safe thing to do is run this in a completely separate process, and
# ruthlessly control the Ruby load path. We expect that when you're executing
# this code, your $RUBYLIB contains the version of Puppet you want to load, and
# there are no other versions of Puppet available as gems, installed via system
# packages, etc. etc. etc.
require 'json'
require 'puppet'
require 'puppet/util/docs'
extend Puppet::Util::Docs
# We use scrub().
# The schema of the typedocs object:
# { :name_of_type => {
# :description => 'Markdown fragment: description of type',
# :features => { :feature_name => 'feature description', ... }
# # If there are no features, the value of :features will be an empty hash.
# :providers => { # If there are no providers, the value of :providers will be an empty hash.
# :name_of_provider => {
# :description => 'Markdown fragment: docs for this provider',
# :features => [:feature_name, :other_feature, ...]
# # If provider has no features, the value of :features will be an empty array.
# },
# ...etc...
# }
# :attributes => { # Puppet dictates that there will ALWAYS be at least one attribute.
# :name_of_attribute => {
# :description => 'Markdown fragment: docs for this attribute',
# :kind => (:property || :parameter),
# :namevar => (true || false), # always false if :kind => :property
# },
# ...etc...
# },
# },
# ...etc...
# }
typedocs = {}
Puppet::Type.loadall
Puppet::Type.eachtype { |type|
# List of types to ignore:
next if type.name == :puppet
next if type.name == :component
next if type.name == :whit
# Initialize the documentation object for this type
docobject = {
:description => scrub(type.doc),
:attributes => {}
}
# Handle features:
# inject will return empty hash if type.features is empty.
docobject[:features] = type.features.inject( {} ) { |allfeatures, name|
allfeatures[name] = scrub( type.provider_feature(name).docs )
allfeatures
}
# Handle providers:
# inject will return empty hash if type.providers is empty.
docobject[:providers] = type.providers.inject( {} ) { |allproviders, name|
allproviders[name] = {
:description => scrub( type.provider(name).doc ),
:features => type.provider(name).features
}
allproviders
}
# Override several features missing due to bug #18426:
if type.name == :user
docobject[:providers][:useradd][:features] << :manages_passwords << :manages_password_age << :libuser
if docobject[:providers][:openbsd]
docobject[:providers][:openbsd][:features] << :manages_passwords << :manages_loginclass
end
end
if type.name == :group
docobject[:providers][:groupadd][:features] << :libuser
end
# Handle properties:
docobject[:attributes].merge!(
type.validproperties.inject( {} ) { |allproperties, name|
property = type.propertybyname(name)
raise "Could not retrieve property #{propertyname} on type #{type.name}" unless property
description = property.doc
$stderr.puts "No docs for property #{name} of #{type.name}" unless description and !description.empty?
allproperties[name] = {
:description => scrub(description),
:kind => :property,
:namevar => false # Properties can't be namevars.
}
allproperties
}
)
# Handle parameters:
docobject[:attributes].merge!(
type.parameters.inject( {} ) { |allparameters, name|
description = type.paramdoc(name)
$stderr.puts "No docs for parameter #{name} of #{type.name}" unless description and !description.empty?
# Strip off the too-huge provider list. The question of what to do about
# providers is a decision for the formatter, not the fragment collector.
description = description.split('Available providers are')[0] if name == :provider
allparameters[name] = {
:description => scrub(description),
:kind => :parameter,
:namevar => type.key_attributes.include?(name) # returns a boolean
}
allparameters
}
)
# Finally:
typedocs[type.name] = docobject
}
print JSON.dump(typedocs)
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/util/binary_search_specs.rb | util/binary_search_specs.rb | #!/usr/bin/env ruby
# Author: Nick Lewis
specs_in_order = File.read('spec_order.txt').split
failing_spec = ARGV.first
specs = specs_in_order[0...specs_in_order.index(failing_spec)]
suspects = specs
while suspects.length > 1 do
count = suspects.length
specs_to_run = suspects[0...(count/2)]
puts "Trying #{specs_to_run.join(' ')}"
start = Time.now
system("bundle exec rspec #{specs_to_run.join(' ')} #{failing_spec}")
puts "Finished in #{Time.now - start} seconds"
if $? == 0
puts "This group is innocent. The culprit is in the other half."
suspects = suspects[(count/2)..-1]
else
puts "One of these is guilty."
suspects = specs_to_run
end
end
puts "The culprit is #{suspects.first}"
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/system_startup/benchmarker.rb | benchmarks/system_startup/benchmarker.rb | class Benchmarker
def initialize(target, size)
end
def setup
end
def generate
end
def run(args=nil)
# Just running help is probably a good proxy of a full startup.
# Simply asking for the version might also be good, but it would miss all
# of the app searching and loading parts
`puppet help`
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/function_loading/benchmarker.rb | benchmarks/function_loading/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
@@benchmark_count ||= 0
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
end
def run(args=nil)
envs = Puppet.lookup(:environments)
envs.clear('benchmarking')
# # Uncomment to get some basic memory statistics
# ObjectSpace.garbage_collect
# result = {}
# ObjectSpace.count_objects(result)
# puts "C(#{result[:T_CLASS]}) O(#{result[:T_OBJECT]}) F(#{result[:FREE]}) #{result[:T_CLASS] + result[:T_OBJECT]}"
node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
Puppet::Resource::Catalog.indirection.find('testing', :use_node => node)
end
def benchmark_count
bc = @@benchmark_count
@@benchmark_count += 1
bc
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
modules = File.join(environment, 'modules')
env_functions = File.join(environment, 'lib', 'puppet', 'functions', 'environment')
templates = File.join('benchmarks', 'function_loading')
mkdir_p(modules)
mkdir_p(env_functions)
mkdir_p(File.join(environment, 'manifests'))
module_count = @size / 5
function_count = @size * 3
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => module_count,
:function_count => function_count)
env_function_template = File.join(templates, 'env_function.erb')
function_count.times { |n| render(env_function_template, File.join(env_functions, "f#{n}.rb"), :n => n) }
module_count.times do |i|
module_name = "module#{i}"
module_base = File.join(modules, module_name)
manifests = File.join(module_base, 'manifests')
module_functions = File.join(module_base, 'lib', 'puppet', 'functions', module_name)
mkdir_p(manifests)
mkdir_p(module_functions)
File.open(File.join(module_base, 'metadata.json'), 'w') do |f|
JSON.dump({
'name' => "tester-#{module_name}",
'author' => 'Puppet Labs tester',
'license' => 'Apache 2.0',
'version' => '1.0.0',
'summary' => 'Benchmark module',
'dependencies' => dependencies_for(i),
'source' => ''
}, f)
end
render(File.join(templates, 'module', 'init.pp.erb'),
File.join(manifests, 'init.pp'),
:name => module_name, :mc => i, :function_count => function_count)
function_template = File.join(templates, 'module', 'function.erb')
function_count.times do |n|
render(function_template,
File.join(module_functions, "f#{n}.rb"),
:name => module_name, :n => n)
end
end
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def dependencies_for(n)
return [] if n == 0
Array.new(n) do |m|
{'name' => "tester-module#{m}", 'version_requirement' => '1.0.0'}
end
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
site.filename = erb_file
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/many_environments/benchmarker.rb | benchmarks/many_environments/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 1000 ? size : 1000
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
end
def run(args=nil)
Puppet.settings.clear
environment_loaders = Puppet.lookup(:environments)
environment_loaders.clear_all
environment_loaders.get!("anenv#{@size/2}")
end
def generate
environments = File.join(@target, 'environments')
puppet_conf = File.join(@target, 'puppet.conf')
File.open(puppet_conf, 'w') do |f|
f.puts(<<-EOF)
environmentpath=#{environments}
EOF
end
@size.times do |i|
mkdir_p(File.join(environments, "anenv#{i}"))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/type_inference/benchmarker.rb | benchmarks/type_inference/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
end
def setup
end
def run(args=nil)
unless @initialized
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
@initialized = true
end
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
# Mimic what apply does (or the benchmark will in part run for the *root* environment)
Puppet.push_context({:current_environment => env},'current env for benchmark')
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'type_inference')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(
File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/defined_types/benchmarker.rb | benchmarks/defined_types/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
end
def run(args=nil)
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'defined_types')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
@size.times do |i|
module_name = "module#{i}"
module_base = File.join(environment, 'modules', module_name)
manifests = File.join(module_base, 'manifests')
mkdir_p(manifests)
File.open(File.join(module_base, 'metadata.json'), 'w') do |f|
JSON.dump({
"types" => [],
"source" => "",
"author" => "Defined Types Benchmark",
"license" => "Apache 2.0",
"version" => "1.0.0",
"description" => "Defined Types benchmark module #{i}",
"summary" => "Just this benchmark module, you know?",
"dependencies" => [],
}, f)
end
render(File.join(templates, 'module', 'testing.pp.erb'),
File.join(manifests, 'testing.pp'),
:name => module_name)
end
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/empty_catalog/benchmarker.rb | benchmarks/empty_catalog/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
end
def setup
end
def run(args=nil)
unless @initialized
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
@initialized = true
end
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
# Mimic what apply does (or the benchmark will in part run for the *root* environment)
Puppet.push_context({:current_environment => env},'current env for benchmark')
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'empty_catalog')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),{})
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/many_modules/benchmarker.rb | benchmarks/many_modules/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
end
def run(args=nil)
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'many_modules')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
@size.times do |i|
module_name = "module#{i}"
module_base = File.join(environment, 'modules', module_name)
manifests = File.join(module_base, 'manifests')
locales = File.join(module_base, 'locales')
mkdir_p(manifests)
mkdir_p(locales)
File.open(File.join(module_base, 'metadata.json'), 'w') do |f|
JSON.dump({
"name" => "module#{i}",
"types" => [],
"source" => "",
"author" => "ManyModules Benchmark",
"license" => "Apache 2.0",
"version" => "1.0.0",
"description" => "Many Modules benchmark module #{i}",
"summary" => "Just this benchmark module, you know?",
"dependencies" => [],
}, f)
end
File.open(File.join(locales, 'config.yaml'), 'w') do |f|
f.puts(
{"gettext"=>
{"project_name"=>"module#{i}",
"package_name"=>"module#{i}",
"default_locale"=>"en",
"bugs_address"=>"docs@puppet.com",
"copyright_holder"=>"Puppet, Inc.",
"comments_tag"=>"TRANSLATOR",
"source_files"=>["./lib/**/*.rb"]}}.to_yaml
)
end
roles = 0.upto(10).to_a
render(File.join(templates, 'module', 'init.pp.erb'),
File.join(manifests, 'init.pp'),
:name => module_name,
:roles => roles
)
render(File.join(templates, 'module', 'internal.pp.erb'),
File.join(manifests, 'internal.pp'),
:name => module_name)
roles.each do |j|
render(File.join(templates, 'module', 'role.pp.erb'),
File.join(manifests, "role#{j}.pp"),
:name => module_name,
:index => j)
end
end
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/hiera_include/benchmarker.rb | benchmarks/hiera_include/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 100 ? size : 100
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
envs = Puppet.lookup(:environments)
@node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
end
def run(args=nil)
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.compile do |catalog|
scope = @compiler.topscope
scope['confdir'] = 'test'
@size.times do
100.times do |index|
hiera_func = @compiler.loaders.puppet_system_loader.load(:function, 'hiera_include')
hiera_func.call(scope, 'common_entry')
end
end
catalog
end
end
def generate
env_dir = File.join(@target, 'environments', 'benchmarking')
manifests_dir = File.join(env_dir, 'manifests')
dummy_class_manifest = File.join(manifests_dir, 'foo.pp')
hiera_yaml = File.join(@target, 'hiera.yaml')
datadir = File.join(@target, 'data')
common_yaml = File.join(datadir, 'common.yaml')
groups_yaml = File.join(datadir, 'groups.yaml')
mkdir_p(env_dir)
mkdir_p(manifests_dir)
mkdir_p(datadir)
File.open(hiera_yaml, 'w') do |f|
f.puts(<<-YAML)
---
:backends: yaml
:yaml:
:datadir: #{datadir}
:hierarchy:
- common
- groups
:logger: noop
YAML
end
File.open(groups_yaml, 'w') do |f|
f.puts(<<-YAML)
---
puppet:
staff:
groups:
YAML
0.upto(50).each do |i|
f.puts(" group#{i}:")
0.upto(125).each do |j|
f.puts(" - user#{j}")
end
end
end
File.open(dummy_class_manifest, 'w') do |f|
f.puts("class dummy_class { }")
end
File.open(common_yaml, 'w') do |f|
f.puts(<<-YAML)
common_entry:
- dummy_class
YAML
end
templates = File.dirname(File.realpath(__FILE__))
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/hiera_conf_interpol/benchmarker.rb | benchmarks/hiera_conf_interpol/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 100 ? size : 100
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
envs = Puppet.lookup(:environments)
@node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
end
def run(args=nil)
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.compile do |catalog|
scope = @compiler.topscope
50.times { |index| scope["d#{index}"] = "dir_#{index}" }
@size.times do
100.times do |index|
invocation = Puppet::Pops::Lookup::Invocation.new(scope)
Puppet::Pops::Lookup.lookup('a', nil, nil, true, nil, invocation)
end
end
catalog
end
end
def generate
env_dir = File.join(@target, 'environments', 'benchmarking')
hiera_yaml = File.join(@target, 'hiera.yaml')
datadir = File.join(@target, 'data')
mkdir_p(env_dir)
File.open(hiera_yaml, 'w') do |f|
f.puts('version: 5')
f.puts('hierarchy:')
50.times do |index|
5.times do |repeat|
f.puts(" - name: Entry_#{index}_#{repeat}")
f.puts(" path: \"%{::d#{index}}/data_#{repeat}\"")
end
end
end
dir_0_dir = File.join(datadir, 'dir_0')
mkdir_p(dir_0_dir)
data_0_yaml = File.join(dir_0_dir, 'data_0.yaml')
File.open(data_0_yaml, 'w') do |f|
f.puts('a: value a')
end
templates = File.join('benchmarks', 'hiera_conf_interpol')
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/virtual_collection/benchmarker.rb | benchmarks/virtual_collection/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = 200
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
end
def run(args=nil)
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'virtual_collection')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/catalog_memory/benchmarker.rb | benchmarks/catalog_memory/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
# For memory debugging - if the core_ext is not loaded, things break inside mass
# require 'mass'
require 'objspace'
# Only runs for Ruby > 2.1.0, and must do this early since ObjectSpace.trace_object_allocations_start must be called
# as early as possible.
#
RUBYVER_ARRAY = RUBY_VERSION.split(".").collect {|s| s.to_i }
RUBYVER = (RUBYVER_ARRAY[0] << 16 | RUBYVER_ARRAY[1] << 8 | RUBYVER_ARRAY[2])
if RUBYVER < (2 << 16 | 1 << 8 | 0)
puts "catalog_memory requires Ruby version >= 2.1.0 to run. Skipping"
exit(0)
end
ObjectSpace.trace_object_allocations_start
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
@@first_counts = nil
@@first_refs = nil
@@count = 0
end
def setup
end
def run(args=nil)
unless @initialized
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
@initialized = true
end
@@count += 1
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
# Mimic what apply does (or the benchmark will in part run for the *root* environment)
Puppet.push_context({:current_environment => env},'current env for benchmark')
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
Puppet.pop_context
GC.start
sleep(2)
counted = ObjectSpace.count_objects({})
if @@first_counts && @@count == 10
diff = @@first_counts.merge(counted) {|k, base_v, new_v| new_v - base_v }
puts "Count of objects TOTAL = #{diff[:TOTAL]}, FREE = #{diff[:FREE]}, T_OBJECT = #{diff[:T_OBJECT]}, T_CLASS = #{diff[:T_CLASS]}"
changed = diff.reject {|k,v| v == 0}
puts "Number of changed classes = #{changed}"
GC.start
# Find references to leaked Objects
leaked_instances = ObjectSpace.each_object.reduce([]) {|x, o| x << o.object_id; x } - @@first_refs
File.open("diff.json", "w") do |f|
leaked_instances.each do |id|
o = ObjectSpace._id2ref(id)
f.write(ObjectSpace.dump(o)) if !o.nil?
end
end
# Output information where bound objects where instantiated
map_of_allocations = leaked_instances.reduce(Hash.new(0)) do |memo, x|
o = ObjectSpace._id2ref(x)
class_path = ObjectSpace.allocation_class_path(o)
class_path = class_path.nil? ? ObjectSpace.allocation_sourcefile(o) : class_path
if !class_path.nil?
method = ObjectSpace.allocation_method_id(o)
source_line = ObjectSpace.allocation_sourceline(o)
memo["#{class_path}##{method}-#{source_line}"] += 1
end
memo
end
map_of_allocations.sort_by {|k, v| v}.reverse_each {|k,v| puts "#{v} #{k}" }
# Dump the heap for further analysis
GC.start
ObjectSpace.dump_all(output: File.open('heap.json','w'))
elsif @@count == 1
# Set up baseline and output info for first run
@@first_counts = counted
@@first_refs = ObjectSpace.each_object.reduce([]) {|x, o| x << o.object_id; x }
diff = @@first_counts
puts "Count of objects TOTAL = #{diff[:TOTAL]}, FREE = #{diff[:FREE]}, T_OBJECT = #{diff[:T_OBJECT]}, T_CLASS = #{diff[:T_CLASS]}"
end
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'empty_catalog')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),{})
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/hiera_include_one/benchmarker.rb | benchmarks/hiera_include_one/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 1000 ? size : 1000
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
envs = Puppet.lookup(:environments)
@node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
end
def run(args=nil)
@size.times do
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.compile do |catalog|
scope = @compiler.topscope
scope['confdir'] = 'test'
hiera_func = @compiler.loaders.puppet_system_loader.load(:function, 'hiera_include')
hiera_func.call(scope, 'common_entry')
catalog
end
end
end
def generate
env_dir = File.join(@target, 'environments', 'benchmarking')
manifests_dir = File.join(env_dir, 'manifests')
dummy_class_manifest = File.join(manifests_dir, 'foo.pp')
hiera_yaml = File.join(@target, 'hiera.yaml')
datadir = File.join(@target, 'data')
common_yaml = File.join(datadir, 'common.yaml')
groups_yaml = File.join(datadir, 'groups.yaml')
mkdir_p(env_dir)
mkdir_p(manifests_dir)
mkdir_p(datadir)
File.open(hiera_yaml, 'w') do |f|
f.puts(<<-YAML)
---
:backends: yaml
:yaml:
:datadir: #{datadir}
:hierarchy:
- common
- groups
:logger: noop
YAML
end
File.open(groups_yaml, 'w') do |f|
f.puts(<<-YAML)
---
puppet:
staff:
groups:
YAML
0.upto(50).each do |i|
f.puts(" group#{i}:")
0.upto(125).each do |j|
f.puts(" - user#{j}")
end
end
end
File.open(dummy_class_manifest, 'w') do |f|
f.puts("class dummy_class { }")
end
File.open(common_yaml, 'w') do |f|
f.puts(<<-YAML)
common_entry:
- dummy_class
YAML
end
templates = File.dirname(File.realpath(__FILE__))
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/evaluations/benchmarker_task.rb | benchmarks/evaluations/benchmarker_task.rb | # Helper class that is used by the Rake task generator.
# Currently only supports defining arguments that are passed to run
# (The rake task generator always passes :warm_up_runs as an Integer when profiling).
# Other benchmarks, and for regular runs that wants arguments must specified them
# as an Array of symbols.
#
class BenchmarkerTask
def self.run_args
[:detail]
end
end | ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/evaluations/benchmarker.rb | benchmarks/evaluations/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
@micro_benchmarks = {}
@parsecount = 100
@evalcount = 100
end
def setup
require 'puppet'
require 'puppet/pops'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
manifests = File.join('benchmarks', 'evaluations', 'manifests')
Dir.foreach(manifests) do |f|
if f =~ /^(.*)\.pp$/
@micro_benchmarks[$1] = File.read(File.join(manifests, f))
end
end
# Run / Evaluate the common puppet logic
@env = Puppet.lookup(:environments).get('benchmarking')
@node = Puppet::Node.new("testing", :environment => @env)
@parser = Puppet::Pops::Parser::EvaluatingParser.new
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = @compiler.topscope
# Perform a portion of what a compile does (just enough to evaluate the site.pp logic)
@compiler.catalog.environment_instance = @compiler.environment
@compiler.send(:evaluate_main)
# Then pretend we are running as part of a compilation
Puppet.push_context(@compiler.context_overrides, "Benchmark masquerading as compiler configured context")
end
def run(args = {})
details = args[:detail] || 'all'
measurements = []
@micro_benchmarks.each do |name, source|
# skip if all but the wanted if a single benchmark is wanted
match = details.match(/#{name}(?:[\._\s](parse|eval))?$/)
next unless details == 'all' || match
# if name ends with .parse or .eval only do that part, else do both parts
ending = match ? match[1] : nil # parse, eval or nil ending
unless ending == 'eval'
measurements << Benchmark.measure("#{name} parse") do
1..@parsecount.times { @parser.parse_string(source, name) }
end
end
unless ending == 'parse'
model = @parser.parse_string(source, name)
measurements << Benchmark.measure("#{name} eval") do
1..@evalcount.times do
begin
# Run each in a local scope
scope_memo = @scope.ephemeral_level
@scope.new_ephemeral(true)
@parser.evaluate(@scope, model)
ensure
# Toss the created local scope
@scope.pop_ephemerals(scope_memo)
end
end
end
end
end
measurements
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'evaluations')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),{})
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
# Generate one module with a 3x function and a 4x function (namespaces)
module_name = "module1"
module_base = File.join(environment, 'modules', module_name)
manifests = File.join(module_base, 'manifests')
mkdir_p(manifests)
functions_3x = File.join(module_base, 'lib', 'puppet', 'parser', 'functions')
functions_4x = File.join(module_base, 'lib', 'puppet', 'functions')
mkdir_p(functions_3x)
mkdir_p(functions_4x)
File.open(File.join(module_base, 'metadata.json'), 'w') do |f|
JSON.dump({
"types" => [],
"source" => "",
"author" => "Evaluations Benchmark",
"license" => "Apache 2.0",
"version" => "1.0.0",
"description" => "Evaluations Benchmark module 1",
"summary" => "Module with supporting logic for evaluations benchmark",
"dependencies" => [],
}, f)
end
render(File.join(templates, 'module', 'init.pp.erb'),
File.join(manifests, 'init.pp'),
:name => module_name)
render(File.join(templates, 'module', 'func3.rb.erb'),
File.join(functions_3x, 'func3.rb'),
:name => module_name)
# namespaced function
mkdir_p(File.join(functions_4x, module_name))
render(File.join(templates, 'module', 'module1_func4.rb.erb'),
File.join(functions_4x, module_name, 'func4.rb'),
:name => module_name)
# non namespaced
render(File.join(templates, 'module', 'func4.rb.erb'),
File.join(functions_4x, 'func4.rb'),
:name => module_name)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/missing_type_caching/benchmarker.rb | benchmarks/missing_type_caching/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
Puppet[:always_retry_plugins] = false
end
def run(args=nil)
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'missing_type_caching')
test_module_dir = File.join(environment, 'modules', 'testmodule',
'manifests')
mkdir_p(File.join(environment, 'modules'))
@size.times.each do |i|
mkdir_p(File.join(environment, 'modules', "mymodule_#{i}", 'lib',
'puppet', 'type'))
mkdir_p(File.join(environment, 'modules', "mymodule_#{i}", 'manifests'))
end
mkdir_p(File.join(environment, 'manifests'))
mkdir_p(test_module_dir)
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
render(File.join(templates, 'module', 'testmodule.pp.erb'),
File.join(test_module_dir, 'init.pp'),
:name => "foo")
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/hiera_global_lookup/benchmarker.rb | benchmarks/hiera_global_lookup/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 100 ? size : 100
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
envs = Puppet.lookup(:environments)
@node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
end
def run(args=nil)
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.compile do |catalog|
scope = @compiler.topscope
scope['confdir'] = 'test'
@size.times do
100.times do |index|
invocation = Puppet::Pops::Lookup::Invocation.new(scope)
Puppet::Pops::Lookup.lookup("x#{index}", nil, nil, true, nil, invocation)
end
100.times do
invocation = Puppet::Pops::Lookup::Invocation.new(scope)
Puppet::Pops::Lookup.lookup("h1.h2.h3.k0", nil, nil, true, nil, invocation)
end
end
catalog
end
end
def generate
# $codedir/
# environments/benchmarking/
# hiera.yaml
# data/
# test/data.yaml
# common.yaml
#
env_dir = File.join(@target, 'environments', 'benchmarking')
hiera_yaml = File.join(@target, 'hiera.yaml')
datadir = File.join(@target, 'data')
datadir_test = File.join(datadir, 'test')
test_data_yaml = File.join(datadir_test, 'data.yaml')
common_yaml = File.join(datadir, 'common.yaml')
mkdir_p(env_dir)
mkdir_p(datadir_test)
File.open(hiera_yaml, 'w') do |f|
f.puts(<<-YAML)
---
version: 5
defaults:
datadir: data
data_hash: yaml_data
hierarchy:
- name: Configured
path: test/data.yaml
- name: Common
path: common.yaml
YAML
end
File.open(common_yaml, 'w') do |f|
100.times do |index|
f.puts("a#{index}: value a#{index}")
f.puts("b#{index}: value b#{index}")
f.puts("c#{index}: value c#{index}")
f.puts("cbm#{index}: \"%{hiera('a#{index}')}, %{hiera('b#{index}')}, %{hiera('c#{index}')}\"")
end
end
File.open(test_data_yaml, 'w') do |f|
100.times { |index| f.puts("x#{index}: \"%{hiera('cbm#{index}')}\"")}
f.puts(<<-YAML)
h1:
h2:
h3:
YAML
100.times { |index| f.puts(<<-YAML) }
k#{index}: v#{index}
YAML
end
templates = File.join('benchmarks', 'hiera_global_lookup')
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/legacy_hiera_lookup/benchmarker.rb | benchmarks/legacy_hiera_lookup/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@hiera_yaml = File.join(target, 'hiera.yaml')
@size = size > 100 ? size : 100
end
def setup
require 'puppet'
require 'hiera'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
Hiera.logger = 'noop'
@hiera = ::Hiera.new(:config => @hiera_yaml)
end
def run(args=nil)
@size.times do
100.times do |index|
@hiera.lookup("x#{index}", nil, { 'confdir' => 'test' })
end
end
end
def generate
datadir = File.join(@target, 'data')
datadir_test = File.join(datadir, 'test')
test_data_yaml = File.join(datadir_test, 'data.yaml')
common_yaml = File.join(datadir, 'common.yaml')
mkdir_p(datadir)
mkdir_p(datadir_test)
File.open(@hiera_yaml, 'w') do |f|
f.puts(<<-YAML)
---
:backends: yaml
:yaml:
:datadir: #{datadir}
:hierarchy:
- "%{confdir}/data"
- common
:logger: noop
YAML
end
File.open(common_yaml, 'w') do |f|
100.times do |index|
f.puts("a#{index}: value a#{index}")
f.puts("b#{index}: value b#{index}")
f.puts("c#{index}: value c#{index}")
f.puts("cbm#{index}: \"%{hiera('a#{index}')}, %{hiera('b#{index}')}, %{hiera('c#{index}')}\"")
end
end
File.open(test_data_yaml, 'w') do |f|
100.times { |index| f.puts("x#{index}: \"%{hiera('cbm#{index}')}\"")}
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/hiera_env_lookup/benchmarker.rb | benchmarks/hiera_env_lookup/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 100 ? size : 100
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
envs = Puppet.lookup(:environments)
@node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
end
def run(args=nil)
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.compile do |catalog|
scope = @compiler.topscope
scope['confdir'] = 'test'
@size.times do
100.times do |index|
invocation = Puppet::Pops::Lookup::Invocation.new(scope)
Puppet::Pops::Lookup.lookup("x#{index}", nil, nil, true, nil, invocation)
end
100.times do
invocation = Puppet::Pops::Lookup::Invocation.new(scope)
Puppet::Pops::Lookup.lookup("h1.h2.h3.k0", nil, nil, true, nil, invocation)
end
end
catalog
end
end
def generate
# $codedir/
# environments/benchmarking/
# hiera.yaml
# data/
# test/data.yaml
# common.yaml
#
env_dir = File.join(@target, 'environments', 'benchmarking')
hiera_yaml = File.join(env_dir, 'hiera.yaml')
datadir = File.join(env_dir, 'data')
datadir_test = File.join(datadir, 'test')
test_data_yaml = File.join(datadir_test, 'data.yaml')
common_yaml = File.join(datadir, 'common.yaml')
mkdir_p(datadir_test)
File.open(hiera_yaml, 'w') do |f|
f.puts(<<-YAML)
version: 5
defaults:
datadir: data
data_hash: yaml_data
hierarchy:
- name: Common
path: common.yaml
- name: Configured
path: test/data.yaml
YAML
end
File.open(common_yaml, 'w') do |f|
100.times do |index|
f.puts("a#{index}: value a#{index}")
f.puts("b#{index}: value b#{index}")
f.puts("c#{index}: value c#{index}")
f.puts("cbm#{index}: \"%{hiera('a#{index}')}, %{hiera('b#{index}')}, %{hiera('c#{index}')}\"")
end
end
File.open(test_data_yaml, 'w') do |f|
100.times { |index| f.puts("x#{index}: \"%{hiera('cbm#{index}')}\"")}
f.puts(<<-YAML)
h1:
h2:
h3:
YAML
100.times { |index| f.puts(<<-YAML) }
k#{index}: v#{index}
YAML
end
templates = File.join('benchmarks', 'hiera_env_lookup')
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/fq_var_lookup/benchmarker.rb | benchmarks/fq_var_lookup/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
end
def run(args=nil)
env = Puppet.lookup(:environments).get('benchmarking')
node = Puppet::Node.new("testing", :environment => env)
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
templates = File.join('benchmarks', 'fq_var_lookup')
mkdir_p(File.join(environment, 'modules'))
mkdir_p(File.join(environment, 'manifests'))
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
module_name = "tst_generate"
module_base = File.join(environment, 'modules', module_name)
manifests = File.join(module_base, 'manifests')
mkdir_p(manifests)
File.open(File.join(module_base, 'metadata.json'), 'w') do |f|
JSON.dump({
"types" => [],
"source" => "",
"author" => "tst_generate Benchmark",
"license" => "Apache 2.0",
"version" => "1.0.0",
"description" => "Qualified variable lookup benchmark module 1",
"summary" => "Just this benchmark module, you know?",
"dependencies" => [],
}, f)
render(File.join(templates, 'module', 'params.pp.erb'),
File.join(manifests, 'params.pp'),
:name => module_name)
render(File.join(templates, 'module', 'badclass.pp.erb'),
File.join(manifests, 'badclass.pp'),
:size => @size)
end
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/full_catalog/benchmarker.rb | benchmarks/full_catalog/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
require 'bundler'
class Benchmarker
include FileUtils
def initialize(target, size='medium')
@target = target
@size = 'large'
end
def check_submodule
submodule = File.join('benchmarks', 'full_catalog', 'puppetlabs-puppetserver_perf_control')
unless File.exist?(File.join(submodule, 'Puppetfile'))
raise RuntimeError, 'The perf control repo is not readable. Make sure to initialize submodules by running: git submodule update --init --recursive'
end
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
environment = File.join(@target, 'environments', 'perf_control')
Puppet.initialize_settings(['--config', config])
FileUtils.cd(@target) do
Bundler::with_clean_env do
system("bundle install")
system("bundle exec r10k puppetfile install --puppetfile #{File.join(environment, 'Puppetfile')} --moduledir #{File.join(environment, 'modules')} --config r10k.yaml")
end
end
# Loading the base system affects the first run a lot so burn one run here
run
end
def run(args=nil)
# Probably could pare down these facts a lot
facts = Puppet::Node::Facts.new("testing", {
'pe_concat_basedir' => '/tmp/file',
'platform_symlink_writable' => true,
'pe_build' => '2016.4.4',
'identity' => {
'privileged' => true,
},
'mountpoints' => {
'/tmp' => {
'options' => ['rw'],
}
},
'puppet_files_dir_present' => true,
'puppetversion' => '4.10.4',
'aio_agent_version' => '1.10.4',
'aio_agent_build' => '1.10.4',
'memory' => {
'system' => {
'total_bytes' => 8589934592,
}
},
'memorysize' => '8 GiB',
'osfamily' => 'RedHat',
'selinux' => false,
'operatingsystem' => 'CentOS',
'operatingsystemrelease' => '6.8',
'path' => '/tmp/staging/',
'processorcount' => '2',
'fake_domain' => 'pgtomcat.mycompany.org',
'function' => 'app',
'group' => 'pgtomcat',
'stage' => 'prod',
'staging_http_get' => 'curl',
'whereami' => 'portland',
'hostname' => 'pgtomcat',
'fqdn' => 'pgtomcat.mycompany.org',
'lsbdistcodename' => 'n/a',
'processor0' => 'AMD Ryzen 7 1700 Eight-Core Processor',
})
env = Puppet.lookup(:environments).get('perf_control')
node = Puppet::Node.indirection.find("testing", :environment => env, :facts => facts)
Puppet.push_context({:current_environment => env}, 'current env for benchmark')
Puppet::Resource::Catalog.indirection.find("testing", :use_node => node)
Puppet.pop_context
Puppet.lookup(:environments).clear('perf_control')
end
def generate
check_submodule
templates = File.join('benchmarks', 'full_catalog')
source = File.join(templates, "puppetlabs-puppetserver_perf_control")
environment = File.join(@target, 'environments', 'perf_control')
mkdir_p(File.join(@target, 'environments'))
FileUtils.cp_r(source, environment)
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:codedir => File.join(@target, 'environments'),
:target => @target)
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => @size)
render(File.join(templates, 'hiera.yaml.erb'),
File.join(@target, 'hiera.yaml'),
:datadir => File.join(environment, 'hieradata'))
FileUtils.cp(File.join(templates, 'Gemfile'), @target)
FileUtils.cp(File.join(templates, 'r10k.yaml'), @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/hiera_function/benchmarker.rb | benchmarks/hiera_function/benchmarker.rb | require 'fileutils'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size > 100 ? size : 100
end
def setup
require 'puppet'
@config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', @config])
envs = Puppet.lookup(:environments)
@node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
end
def run(args=nil)
@compiler = Puppet::Parser::Compiler.new(@node)
@compiler.compile do |catalog|
scope = @compiler.topscope
scope['confdir'] = 'test'
@size.times do
100.times do |index|
hiera_func = @compiler.loaders.puppet_system_loader.load(:function, 'hiera')
hiera_func.call(scope, "x#{index}")
end
end
catalog
end
end
def generate
env_dir = File.join(@target, 'environments', 'benchmarking')
hiera_yaml = File.join(@target, 'hiera.yaml')
datadir = File.join(@target, 'data')
datadir_test = File.join(datadir, 'test')
test_data_yaml = File.join(datadir_test, 'data.yaml')
common_yaml = File.join(datadir, 'common.yaml')
mkdir_p(env_dir)
mkdir_p(datadir)
mkdir_p(datadir_test)
File.open(hiera_yaml, 'w') do |f|
f.puts(<<-YAML)
---
:backends: yaml
:yaml:
:datadir: #{datadir}
:hierarchy:
- "%{confdir}/data"
- common
:logger: noop
YAML
end
File.open(common_yaml, 'w') do |f|
100.times do |index|
f.puts("a#{index}: value a#{index}")
f.puts("b#{index}: value b#{index}")
f.puts("c#{index}: value c#{index}")
f.puts("cbm#{index}: \"%{hiera('a#{index}')}, %{hiera('b#{index}')}, %{hiera('c#{index}')}\"")
end
end
File.open(test_data_yaml, 'w') do |f|
100.times { |index| f.puts("x#{index}: \"%{hiera('cbm#{index}')}\"")}
end
templates = File.join('benchmarks', 'hiera_function')
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/dependency_loading/benchmarker.rb | benchmarks/dependency_loading/benchmarker.rb | require 'erb'
require 'ostruct'
require 'fileutils'
require 'json'
class Benchmarker
include FileUtils
def initialize(target, size)
@target = target
@size = size
@@benchmark_count ||= 0
end
def setup
require 'puppet'
config = File.join(@target, 'puppet.conf')
Puppet.initialize_settings(['--config', config])
end
def run(args=nil)
envs = Puppet.lookup(:environments)
50.times do
envs.clear('benchmarking')
node = Puppet::Node.new('testing', :environment => envs.get('benchmarking'))
Puppet::Resource::Catalog.indirection.find('testing', :use_node => node)
end
end
def benchmark_count
bc = @@benchmark_count
@@benchmark_count += 1
bc
end
def generate
environment = File.join(@target, 'environments', 'benchmarking')
modules = File.join(environment, 'modules')
templates = File.join('benchmarks', 'dependency_loading')
mkdir_p(modules)
mkdir_p(File.join(environment, 'manifests'))
module_count = @size * 2
modula = 10
render(File.join(templates, 'site.pp.erb'),
File.join(environment, 'manifests', 'site.pp'),
:size => module_count, :modula => modula)
module_count.times do |i|
module_name = "module#{i}"
module_base = File.join(modules, module_name)
manifests = File.join(module_base, 'manifests')
global_module_functions = File.join(module_base, 'lib', 'puppet', 'functions')
module_functions = File.join(global_module_functions, module_name)
mkdir_p(manifests)
mkdir_p(module_functions)
File.open(File.join(module_base, 'metadata.json'), 'w') do |f|
JSON.dump({
'name' => "tester-#{module_name}",
'author' => 'Puppet Labs tester',
'license' => 'Apache 2.0',
'version' => '1.0.0',
'summary' => 'Benchmark module',
'dependencies' => i > 0 ? dependency_to(i - 1) : [],
'source' => ''
}, f)
end
if (i + 1) % modula == 0
render(File.join(templates, 'module', 'init.pp.erb'),
File.join(manifests, 'init.pp'),
:name => module_name, :other => "module#{i - 1}")
else
render(File.join(templates, 'module', 'init.pp_no_call.erb'),
File.join(manifests, 'init.pp'),
:name => module_name)
end
function_template = File.join(templates, 'module', 'function.erb')
render(function_template, File.join(module_functions, "f#{module_name}.rb"), :name => module_name)
global_function_template = File.join(templates, 'module', 'global_function.erb')
render(global_function_template, File.join(global_module_functions, "f#{module_name}.rb"), :name => module_name)
end
render(File.join(templates, 'puppet.conf.erb'),
File.join(@target, 'puppet.conf'),
:location => @target)
end
def dependency_to(n)
[ {'name' => "tester-module#{n}", 'version_requirement' => '1.0.0'} ]
end
def render(erb_file, output_file, bindings)
site = ERB.new(File.read(erb_file))
site.filename = erb_file
File.open(output_file, 'w') do |fh|
fh.write(site.result(OpenStruct.new(bindings).instance_eval { binding }))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/benchmarks/serialization/benchmarker.rb | benchmarks/serialization/benchmarker.rb | require 'puppet'
class Benchmarker
def initialize(target, size)
@size = size
@direction = ENV['SER_DIRECTION'] == 'generate' ? :generate : :parse
@format = ENV['SER_FORMAT'] == 'pson' ? :pson : :json
puts "Benchmarker #{@direction} #{@format}"
end
def setup
end
def generate
path = File.expand_path(File.join(__FILE__, '../catalog.json'))
puts "Using catalog #{path}"
@data = File.read(path)
@catalog = JSON.parse(@data)
end
def run(args=nil)
0.upto(@size) do |i|
# This parses a catalog from JSON data, which is a combination of parsing
# the data into a JSON hash, and the parsing the hash into a Catalog. It's
# interesting to see just how slow that latter process is:
#
# Puppet::Resource::Catalog.convert_from(:json, @data)
#
# However, for this benchmark, we're just testing how long JSON vs PSON
# parsing and generation are, where we default to parsing JSON.
#
if @direction == :generate
if @format == :pson
PSON.dump(@catalog)
else
JSON.dump(@catalog)
end
else
if @format == :pson
PSON.parse(@data)
else
JSON.parse(@data)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/yardoc/templates/default/method_details/html/setup.rb | yardoc/templates/default/method_details/html/setup.rb | def init
super
end
def format_method_detail_extras(object)
result = ""
if object
if object.respond_to?(:visibility)
if object.visibility != :public
result << "<span class=\"note title #{object.visibility}\">#{object.visibility}</span>"
end
end
if object.has_tag?(:abstract)
result << '<span class="abstract note title">abstract</span>'
end
if object.has_tag?(:deprecated)
result << '<span class="deprecated note title">deprecated</span>'
end
if object.respond_to?(:visibility)
if object.has_tag?(:api) && object.tag(:api).text == 'private' && object.visibility != :private
result << '<span class="private note title">private</span>'
end
else
if object.has_tag?(:api) && object.tag(:api).text == 'private'
result << '<span class="private note title">private</span>'
end
end
if object.has_tag?(:dsl)
result << '<span class="note title readonly">DSL</span>'
end
end
# separate the extras with one space
if result != ""
result = " " + result
end
result
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.