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
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb
provider/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb
module ActionController # In <b>routes.rb</b> one defines URL-to-controller mappings, but the reverse # is also possible: an URL can be generated from one of your routing definitions. # URL generation functionality is centralized in this module. # # See ActionController::Routing and ActionController::Resources for general # information about routing and routes.rb. # # <b>Tip:</b> If you need to generate URLs from your models or some other place, # then ActionController::UrlWriter is what you're looking for. Read on for # an introduction. # # == URL generation from parameters # # As you may know, some functions - such as ActionController::Base#url_for # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set # of parameters. For example, you've probably had the chance to write code # like this in one of your views: # # <%= link_to('Click here', :controller => 'users', # :action => 'new', :message => 'Welcome!') %> # # #=> Generates a link to: /users/new?message=Welcome%21 # # link_to, and all other functions that require URL generation functionality, # actually use ActionController::UrlWriter under the hood. And in particular, # they use the ActionController::UrlWriter#url_for method. One can generate # the same path as the above example by using the following code: # # include UrlWriter # url_for(:controller => 'users', # :action => 'new', # :message => 'Welcome!', # :only_path => true) # # => "/users/new?message=Welcome%21" # # Notice the <tt>:only_path => true</tt> part. This is because UrlWriter has no # information about the website hostname that your Rails app is serving. So if you # want to include the hostname as well, then you must also pass the <tt>:host</tt> # argument: # # include UrlWriter # url_for(:controller => 'users', # :action => 'new', # :message => 'Welcome!', # :host => 'www.example.com') # Changed this. # # => "http://www.example.com/users/new?message=Welcome%21" # # By default, all controllers and views have access to a special version of url_for, # that already knows what the current hostname is. So if you use url_for in your # controllers or your views, then you don't need to explicitly pass the <tt>:host</tt> # argument. # # For convenience reasons, mailers provide a shortcut for ActionController::UrlWriter#url_for. # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlWriter#url_for' # in full. However, mailers don't have hostname information, and what's why you'll still # have to specify the <tt>:host</tt> argument when generating URLs in mailers. # # # == URL generation for named routes # # UrlWriter also allows one to access methods that have been auto-generated from # named routes. For example, suppose that you have a 'users' resource in your # <b>routes.rb</b>: # # map.resources :users # # This generates, among other things, the method <tt>users_path</tt>. By default, # this method is accessible from your controllers, views and mailers. If you need # to access this auto-generated method from other places (such as a model), then # you can do that in two ways. # # The first way is to include ActionController::UrlWriter in your class: # # class User < ActiveRecord::Base # include ActionController::UrlWriter # !!! # # def name=(value) # write_attribute('name', value) # write_attribute('base_uri', users_path) # !!! # end # end # # The second way is to access them through ActionController::UrlWriter. # The autogenerated named routes methods are available as class methods: # # class User < ActiveRecord::Base # def name=(value) # write_attribute('name', value) # path = ActionController::UrlWriter.users_path # !!! # write_attribute('base_uri', path) # !!! # end # end module UrlWriter def self.included(base) #:nodoc: ActionController::Routing::Routes.install_helpers(base) base.mattr_accessor :default_url_options # The default options for urls written by this writer. Typically a <tt>:host</tt> pair is provided. base.default_url_options ||= {} end # Generate a url based on the options provided, default_url_options and the # routes defined in routes.rb. The following options are supported: # # * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+. # * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'. # * <tt>:host</tt> - Specifies the host the link should be targetted at. # If <tt>:only_path</tt> is false, this option must be # provided either explicitly, or via +default_url_options+. # * <tt>:port</tt> - Optionally specify the port to connect to. # * <tt>:anchor</tt> - An anchor name to be appended to the path. # * <tt>:skip_relative_url_root</tt> - If true, the url is not constructed using the # +relative_url_root+ set in ActionController::Base.relative_url_root. # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/" # # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to # +url_for+ is forwarded to the Routes module. # # Examples: # # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing' # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' def url_for(options) options = self.class.default_url_options.merge(options) url = '' unless options.delete(:only_path) url << (options.delete(:protocol) || 'http') url << '://' unless url.match("://") raise "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" unless options[:host] url << options.delete(:host) url << ":#{options.delete(:port)}" if options.key?(:port) else # Delete the unused options to prevent their appearance in the query string. [:protocol, :host, :port, :skip_relative_url_root].each { |k| options.delete(k) } end trailing_slash = options.delete(:trailing_slash) if options.key?(:trailing_slash) url << ActionController::Base.relative_url_root.to_s unless options[:skip_relative_url_root] anchor = "##{CGI.escape options.delete(:anchor).to_param.to_s}" if options[:anchor] generated = Routing::Routes.generate(options, {}) url << (trailing_slash ? generated.sub(/\?|\z/) { "/" + $& } : generated) url << anchor if anchor url end end # Rewrites URLs for Base.redirect_to and Base.url_for in the controller. class UrlRewriter #:nodoc: RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :skip_relative_url_root] def initialize(request, parameters) @request, @parameters = request, parameters end def rewrite(options = {}) rewrite_url(options) end def to_str "#{@request.protocol}, #{@request.host_with_port}, #{@request.path}, #{@parameters[:controller]}, #{@parameters[:action]}, #{@request.parameters.inspect}" end alias_method :to_s, :to_str private # Given a path and options, returns a rewritten URL string def rewrite_url(options) rewritten_url = "" unless options[:only_path] rewritten_url << (options[:protocol] || @request.protocol) rewritten_url << "://" unless rewritten_url.match("://") rewritten_url << rewrite_authentication(options) rewritten_url << (options[:host] || @request.host_with_port) rewritten_url << ":#{options.delete(:port)}" if options.key?(:port) end path = rewrite_path(options) rewritten_url << ActionController::Base.relative_url_root.to_s unless options[:skip_relative_url_root] rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) rewritten_url << "##{CGI.escape(options[:anchor].to_param.to_s)}" if options[:anchor] rewritten_url end # Given a Hash of options, generates a route def rewrite_path(options) options = options.symbolize_keys options.update(options[:params].symbolize_keys) if options[:params] if (overwrite = options.delete(:overwrite_params)) options.update(@parameters.symbolize_keys) options.update(overwrite.symbolize_keys) end RESERVED_OPTIONS.each { |k| options.delete(k) } # Generates the query string, too Routing::Routes.generate(options, @request.symbolized_path_parameters) end def rewrite_authentication(options) if options[:user] && options[:password] "#{CGI.escape(options.delete(:user))}:#{CGI.escape(options.delete(:password))}@" else "" end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/routing_ext.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/routing_ext.rb
class Object def to_param to_s end end class TrueClass def to_param self end end class FalseClass def to_param self end end class NilClass def to_param self end end class Regexp #:nodoc: def number_of_captures Regexp.new("|#{source}").match('').captures.length end def multiline? options & MULTILINE == MULTILINE end class << self def optionalize(pattern) case unoptionalize(pattern) when /\A(.|\(.*\))\Z/ then "#{pattern}?" else "(?:#{pattern})?" end end def unoptionalize(pattern) [/\A\(\?:(.*)\)\?\Z/, /\A(.|\(.*\))\?\Z/].each do |regexp| return $1 if regexp =~ pattern end return pattern end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/route.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/route.rb
module ActionController module Routing class Route #:nodoc: attr_accessor :segments, :requirements, :conditions, :optimise def initialize(segments = [], requirements = {}, conditions = {}) @segments = segments @requirements = requirements @conditions = conditions if !significant_keys.include?(:action) && !requirements[:action] @requirements[:action] = "index" @significant_keys << :action end # Routes cannot use the current string interpolation method # if there are user-supplied <tt>:requirements</tt> as the interpolation # code won't raise RoutingErrors when generating has_requirements = @segments.detect { |segment| segment.respond_to?(:regexp) && segment.regexp } if has_requirements || @requirements.keys.to_set != Routing::ALLOWED_REQUIREMENTS_FOR_OPTIMISATION @optimise = false else @optimise = true end end # Indicates whether the routes should be optimised with the string interpolation # version of the named routes methods. def optimise? @optimise && ActionController::Base::optimise_named_routes end def segment_keys segments.collect do |segment| segment.key if segment.respond_to? :key end.compact end def required_segment_keys required_segments = segments.select {|seg| (!seg.optional? && !seg.is_a?(DividerSegment)) || seg.is_a?(PathSegment) } required_segments.collect { |seg| seg.key if seg.respond_to?(:key)}.compact end # Build a query string from the keys of the given hash. If +only_keys+ # is given (as an array), only the keys indicated will be used to build # the query string. The query string will correctly build array parameter # values. def build_query_string(hash, only_keys = nil) elements = [] (only_keys || hash.keys).each do |key| if value = hash[key] elements << value.to_query(key) end end elements.empty? ? '' : "?#{elements.sort * '&'}" end # A route's parameter shell contains parameter values that are not in the # route's path, but should be placed in the recognized hash. # # For example, +{:controller => 'pages', :action => 'show'} is the shell for the route: # # map.connect '/page/:id', :controller => 'pages', :action => 'show', :id => /\d+/ # def parameter_shell @parameter_shell ||= returning({}) do |shell| requirements.each do |key, requirement| shell[key] = requirement unless requirement.is_a? Regexp end end end # Return an array containing all the keys that are used in this route. This # includes keys that appear inside the path, and keys that have requirements # placed upon them. def significant_keys @significant_keys ||= returning([]) do |sk| segments.each { |segment| sk << segment.key if segment.respond_to? :key } sk.concat requirements.keys sk.uniq! end end # Return a hash of key/value pairs representing the keys in the route that # have defaults, or which are specified by non-regexp requirements. def defaults @defaults ||= returning({}) do |hash| segments.each do |segment| next unless segment.respond_to? :default hash[segment.key] = segment.default unless segment.default.nil? end requirements.each do |key,req| next if Regexp === req || req.nil? hash[key] = req end end end def matches_controller_and_action?(controller, action) prepare_matching! (@controller_requirement.nil? || @controller_requirement === controller) && (@action_requirement.nil? || @action_requirement === action) end def to_s @to_s ||= begin segs = segments.inject("") { |str,s| str << s.to_s } "%-6s %-40s %s" % [(conditions[:method] || :any).to_s.upcase, segs, requirements.inspect] end end # TODO: Route should be prepared and frozen on initialize def freeze unless frozen? write_generation! write_recognition! prepare_matching! parameter_shell significant_keys defaults to_s end super end def generate(options, hash, expire_on = {}) path, hash = generate_raw(options, hash, expire_on) append_query_string(path, hash, extra_keys(options)) end def generate_extras(options, hash, expire_on = {}) path, hash = generate_raw(options, hash, expire_on) [path, extra_keys(options)] end private def requirement_for(key) return requirements[key] if requirements.key? key segments.each do |segment| return segment.regexp if segment.respond_to?(:key) && segment.key == key end nil end # Write and compile a +generate+ method for this Route. def write_generation! # Build the main body of the generation body = "expired = false\n#{generation_extraction}\n#{generation_structure}" # If we have conditions that must be tested first, nest the body inside an if body = "if #{generation_requirements}\n#{body}\nend" if generation_requirements args = "options, hash, expire_on = {}" # Nest the body inside of a def block, and then compile it. raw_method = method_decl = "def generate_raw(#{args})\npath = begin\n#{body}\nend\n[path, hash]\nend" instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})" # expire_on.keys == recall.keys; in other words, the keys in the expire_on hash # are the same as the keys that were recalled from the previous request. Thus, # we can use the expire_on.keys to determine which keys ought to be used to build # the query string. (Never use keys from the recalled request when building the # query string.) raw_method end # Build several lines of code that extract values from the options hash. If any # of the values are missing or rejected then a return will be executed. def generation_extraction segments.collect do |segment| segment.extraction_code end.compact * "\n" end # Produce a condition expression that will check the requirements of this route # upon generation. def generation_requirements requirement_conditions = requirements.collect do |key, req| if req.is_a? Regexp value_regexp = Regexp.new "\\A#{req.to_s}\\Z" "hash[:#{key}] && #{value_regexp.inspect} =~ options[:#{key}]" else "hash[:#{key}] == #{req.inspect}" end end requirement_conditions * ' && ' unless requirement_conditions.empty? end def generation_structure segments.last.string_structure segments[0..-2] end # Write and compile a +recognize+ method for this Route. def write_recognition! # Create an if structure to extract the params from a match if it occurs. body = "params = parameter_shell.dup\n#{recognition_extraction * "\n"}\nparams" body = "if #{recognition_conditions.join(" && ")}\n#{body}\nend" # Build the method declaration and compile it method_decl = "def recognize(path, env = {})\n#{body}\nend" instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})" method_decl end # Plugins may override this method to add other conditions, like checks on # host, subdomain, and so forth. Note that changes here only affect route # recognition, not generation. def recognition_conditions result = ["(match = #{Regexp.new(recognition_pattern).inspect}.match(path))"] result << "[conditions[:method]].flatten.include?(env[:method])" if conditions[:method] result end # Build the regular expression pattern that will match this route. def recognition_pattern(wrap = true) pattern = '' segments.reverse_each do |segment| pattern = segment.build_pattern pattern end wrap ? ("\\A" + pattern + "\\Z") : pattern end # Write the code to extract the parameters from a matched route. def recognition_extraction next_capture = 1 extraction = segments.collect do |segment| x = segment.match_extraction(next_capture) next_capture += segment.number_of_captures x end extraction.compact end # Generate the query string with any extra keys in the hash and append # it to the given path, returning the new path. def append_query_string(path, hash, query_keys = nil) return nil unless path query_keys ||= extra_keys(hash) "#{path}#{build_query_string(hash, query_keys)}" end # Determine which keys in the given hash are "extra". Extra keys are # those that were not used to generate a particular route. The extra # keys also do not include those recalled from the prior request, nor # do they include any keys that were implied in the route (like a # <tt>:controller</tt> that is required, but not explicitly used in the # text of the route.) def extra_keys(hash, recall = {}) (hash || {}).keys.map { |k| k.to_sym } - (recall || {}).keys - significant_keys end def prepare_matching! unless defined? @matching_prepared @controller_requirement = requirement_for(:controller) @action_requirement = requirement_for(:action) @matching_prepared = true end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/optimisations.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/optimisations.rb
module ActionController module Routing # Much of the slow performance from routes comes from the # complexity of expiry, <tt>:requirements</tt> matching, defaults providing # and figuring out which url pattern to use. With named routes # we can avoid the expense of finding the right route. So if # they've provided the right number of arguments, and have no # <tt>:requirements</tt>, we can just build up a string and return it. # # To support building optimisations for other common cases, the # generation code is separated into several classes module Optimisation def generate_optimisation_block(route, kind) return "" unless route.optimise? OPTIMISERS.inject("") do |memo, klazz| memo << klazz.new(route, kind).source_code memo end end class Optimiser attr_reader :route, :kind GLOBAL_GUARD_CONDITIONS = [ "(!defined?(default_url_options) || default_url_options.blank?)", "(!defined?(controller.default_url_options) || controller.default_url_options.blank?)", "defined?(request)", "request" ] def initialize(route, kind) @route = route @kind = kind end def guard_conditions ["false"] end def generation_code 'nil' end def source_code if applicable? guard_condition = (GLOBAL_GUARD_CONDITIONS + guard_conditions).join(" && ") "return #{generation_code} if #{guard_condition}\n" else "\n" end end # Temporarily disabled <tt>:url</tt> optimisation pending proper solution to # Issues around request.host etc. def applicable? true end end # Given a route # # map.person '/people/:id' # # If the user calls <tt>person_url(@person)</tt>, we can simply # return a string like "/people/#{@person.to_param}" # rather than triggering the expensive logic in +url_for+. class PositionalArguments < Optimiser def guard_conditions number_of_arguments = route.required_segment_keys.size # if they're using foo_url(:id=>2) it's one # argument, but we don't want to generate /foos/id2 if number_of_arguments == 1 ["args.size == 1", "!args.first.is_a?(Hash)"] else ["args.size == #{number_of_arguments}"] end end def generation_code elements = [] idx = 0 if kind == :url elements << '#{request.protocol}' elements << '#{request.host_with_port}' end elements << '#{ActionController::Base.relative_url_root if ActionController::Base.relative_url_root}' # The last entry in <tt>route.segments</tt> appears to *always* be a # 'divider segment' for '/' but we have assertions to ensure that # we don't include the trailing slashes, so skip them. (route.segments.size == 1 ? route.segments : route.segments[0..-2]).each do |segment| if segment.is_a?(DynamicSegment) elements << segment.interpolation_chunk("args[#{idx}].to_param") idx += 1 else elements << segment.interpolation_chunk end end %("#{elements * ''}") end end # This case is mostly the same as the positional arguments case # above, but it supports additional query parameters as the last # argument class PositionalArgumentsWithAdditionalParams < PositionalArguments def guard_conditions ["args.size == #{route.segment_keys.size + 1}"] + UrlRewriter::RESERVED_OPTIONS.collect{ |key| "!args.last.has_key?(:#{key})" } end # This case uses almost the same code as positional arguments, # but add a question mark and args.last.to_query on the end, # unless the last arg is empty def generation_code super.insert(-2, '#{\'?\' + args.last.to_query unless args.last.empty?}') end # To avoid generating "http://localhost/?host=foo.example.com" we # can't use this optimisation on routes without any segments def applicable? super && route.segment_keys.size > 0 end end OPTIMISERS = [PositionalArguments, PositionalArgumentsWithAdditionalParams] end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/route_set.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/route_set.rb
module ActionController module Routing class RouteSet #:nodoc: # Mapper instances are used to build routes. The object passed to the draw # block in config/routes.rb is a Mapper instance. # # Mapper instances have relatively few instance methods, in order to avoid # clashes with named routes. class Mapper #:doc: include ActionController::Resources def initialize(set) #:nodoc: @set = set end # Create an unnamed route with the provided +path+ and +options+. See # ActionController::Routing for an introduction to routes. def connect(path, options = {}) @set.add_route(path, options) end # Creates a named route called "root" for matching the root level request. def root(options = {}) if options.is_a?(Symbol) if source_route = @set.named_routes.routes[options] options = source_route.defaults.merge({ :conditions => source_route.conditions }) end end named_route("root", '', options) end def named_route(name, path, options = {}) #:nodoc: @set.add_named_route(name, path, options) end # Enables the use of resources in a module by setting the name_prefix, path_prefix, and namespace for the model. # Example: # # map.namespace(:admin) do |admin| # admin.resources :products, # :has_many => [ :tags, :images, :variants ] # end # # This will create +admin_products_url+ pointing to "admin/products", which will look for an Admin::ProductsController. # It'll also create +admin_product_tags_url+ pointing to "admin/products/#{product_id}/tags", which will look for # Admin::TagsController. def namespace(name, options = {}, &block) if options[:namespace] with_options({:path_prefix => "#{options.delete(:path_prefix)}/#{name}", :name_prefix => "#{options.delete(:name_prefix)}#{name}_", :namespace => "#{options.delete(:namespace)}#{name}/" }.merge(options), &block) else with_options({:path_prefix => name, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block) end end def method_missing(route_name, *args, &proc) #:nodoc: super unless args.length >= 1 && proc.nil? @set.add_named_route(route_name, *args) end end # A NamedRouteCollection instance is a collection of named routes, and also # maintains an anonymous module that can be used to install helpers for the # named routes. class NamedRouteCollection #:nodoc: include Enumerable include ActionController::Routing::Optimisation attr_reader :routes, :helpers def initialize clear! end def clear! @routes = {} @helpers = [] @module ||= Module.new @module.instance_methods.each do |selector| @module.class_eval { remove_method selector } end end def add(name, route) routes[name.to_sym] = route define_named_route_methods(name, route) end def get(name) routes[name.to_sym] end alias []= add alias [] get alias clear clear! def each routes.each { |name, route| yield name, route } self end def names routes.keys end def length routes.length end def reset! old_routes = routes.dup clear! old_routes.each do |name, route| add(name, route) end end def install(destinations = [ActionController::Base, ActionView::Base], regenerate = false) reset! if regenerate Array(destinations).each do |dest| dest.__send__(:include, @module) end end private def url_helper_name(name, kind = :url) :"#{name}_#{kind}" end def hash_access_name(name, kind = :url) :"hash_for_#{name}_#{kind}" end def define_named_route_methods(name, route) {:url => {:only_path => false}, :path => {:only_path => true}}.each do |kind, opts| hash = route.defaults.merge(:use_route => name).merge(opts) define_hash_access route, name, kind, hash define_url_helper route, name, kind, hash end end def named_helper_module_eval(code, *args) @module.module_eval(code, *args) end def define_hash_access(route, name, kind, options) selector = hash_access_name(name, kind) named_helper_module_eval <<-end_eval # We use module_eval to avoid leaks def #{selector}(options = nil) # def hash_for_users_url(options = nil) options ? #{options.inspect}.merge(options) : #{options.inspect} # options ? {:only_path=>false}.merge(options) : {:only_path=>false} end # end protected :#{selector} # protected :hash_for_users_url end_eval helpers << selector end def define_url_helper(route, name, kind, options) selector = url_helper_name(name, kind) # The segment keys used for positional paramters hash_access_method = hash_access_name(name, kind) # allow ordered parameters to be associated with corresponding # dynamic segments, so you can do # # foo_url(bar, baz, bang) # # instead of # # foo_url(:bar => bar, :baz => baz, :bang => bang) # # Also allow options hash, so you can do # # foo_url(bar, baz, bang, :sort_by => 'baz') # named_helper_module_eval <<-end_eval # We use module_eval to avoid leaks def #{selector}(*args) # def users_url(*args) # #{generate_optimisation_block(route, kind)} # #{generate_optimisation_block(route, kind)} # opts = if args.empty? || Hash === args.first # opts = if args.empty? || Hash === args.first args.first || {} # args.first || {} else # else options = args.extract_options! # options = args.extract_options! args = args.zip(#{route.segment_keys.inspect}).inject({}) do |h, (v, k)| # args = args.zip([]).inject({}) do |h, (v, k)| h[k] = v # h[k] = v h # h end # end options.merge(args) # options.merge(args) end # end # url_for(#{hash_access_method}(opts)) # url_for(hash_for_users_url(opts)) # end # end #Add an alias to support the now deprecated formatted_* URL. # #Add an alias to support the now deprecated formatted_* URL. def formatted_#{selector}(*args) # def formatted_users_url(*args) ActiveSupport::Deprecation.warn( # ActiveSupport::Deprecation.warn( "formatted_#{selector}() has been deprecated. " + # "formatted_users_url() has been deprecated. " + "Please pass format to the standard " + # "Please pass format to the standard " + "#{selector} method instead.", caller) # "users_url method instead.", caller) #{selector}(*args) # users_url(*args) end # end protected :#{selector} # protected :users_url end_eval helpers << selector end end attr_accessor :routes, :named_routes, :configuration_files def initialize self.configuration_files = [] self.routes = [] self.named_routes = NamedRouteCollection.new clear_recognize_optimized! end # Subclasses and plugins may override this method to specify a different # RouteBuilder instance, so that other route DSL's can be created. def builder @builder ||= RouteBuilder.new end def draw yield Mapper.new(self) install_helpers end def clear! routes.clear named_routes.clear @combined_regexp = nil @routes_by_controller = nil # This will force routing/recognition_optimization.rb # to refresh optimisations. clear_recognize_optimized! end def install_helpers(destinations = [ActionController::Base, ActionView::Base], regenerate_code = false) Array(destinations).each { |d| d.module_eval { include Helpers } } named_routes.install(destinations, regenerate_code) end def empty? routes.empty? end def add_configuration_file(path) self.configuration_files << path end # Deprecated accessor def configuration_file=(path) add_configuration_file(path) end # Deprecated accessor def configuration_file configuration_files end def load! Routing.use_controllers!(nil) # Clear the controller cache so we may discover new ones clear! load_routes! end # reload! will always force a reload whereas load checks the timestamp first alias reload! load! def reload if configuration_files.any? && @routes_last_modified if routes_changed_at == @routes_last_modified return # routes didn't change, don't reload else @routes_last_modified = routes_changed_at end end load! end def load_routes! if configuration_files.any? configuration_files.each { |config| load(config) } @routes_last_modified = routes_changed_at else add_route ":controller/:action/:id" end end def routes_changed_at routes_changed_at = nil configuration_files.each do |config| config_changed_at = File.stat(config).mtime if routes_changed_at.nil? || config_changed_at > routes_changed_at routes_changed_at = config_changed_at end end routes_changed_at end def add_route(path, options = {}) options.each { |k, v| options[k] = v.to_s if [:controller, :action].include?(k) && v.is_a?(Symbol) } route = builder.build(path, options) routes << route route end def add_named_route(name, path, options = {}) # TODO - is options EVER used? name = options[:name_prefix] + name.to_s if options[:name_prefix] named_routes[name.to_sym] = add_route(path, options) end def options_as_params(options) # If an explicit :controller was given, always make :action explicit # too, so that action expiry works as expected for things like # # generate({:controller => 'content'}, {:controller => 'content', :action => 'show'}) # # (the above is from the unit tests). In the above case, because the # controller was explicitly given, but no action, the action is implied to # be "index", not the recalled action of "show". # # great fun, eh? options_as_params = options.clone options_as_params[:action] ||= 'index' if options[:controller] options_as_params[:action] = options_as_params[:action].to_s if options_as_params[:action] options_as_params end def build_expiry(options, recall) recall.inject({}) do |expiry, (key, recalled_value)| expiry[key] = (options.key?(key) && options[key].to_param != recalled_value.to_param) expiry end end # Generate the path indicated by the arguments, and return an array of # the keys that were not used to generate it. def extra_keys(options, recall={}) generate_extras(options, recall).last end def generate_extras(options, recall={}) generate(options, recall, :generate_extras) end def generate(options, recall = {}, method=:generate) named_route_name = options.delete(:use_route) generate_all = options.delete(:generate_all) if named_route_name named_route = named_routes[named_route_name] options = named_route.parameter_shell.merge(options) end options = options_as_params(options) expire_on = build_expiry(options, recall) if options[:controller] options[:controller] = options[:controller].to_s end # if the controller has changed, make sure it changes relative to the # current controller module, if any. In other words, if we're currently # on admin/get, and the new controller is 'set', the new controller # should really be admin/set. if !named_route && expire_on[:controller] && options[:controller] && options[:controller][0] != ?/ old_parts = recall[:controller].split('/') new_parts = options[:controller].split('/') parts = old_parts[0..-(new_parts.length + 1)] + new_parts options[:controller] = parts.join('/') end # drop the leading '/' on the controller name options[:controller] = options[:controller][1..-1] if options[:controller] && options[:controller][0] == ?/ merged = recall.merge(options) if named_route path = named_route.generate(options, merged, expire_on) if path.nil? raise_named_route_error(options, named_route, named_route_name) else return path end else merged[:action] ||= 'index' options[:action] ||= 'index' controller = merged[:controller] action = merged[:action] raise RoutingError, "Need controller and action!" unless controller && action if generate_all # Used by caching to expire all paths for a resource return routes.collect do |route| route.__send__(method, options, merged, expire_on) end.compact end # don't use the recalled keys when determining which routes to check future_routes, deprecated_routes = routes_by_controller[controller][action][options.reject {|k,v| !v}.keys.sort_by { |x| x.object_id }] routes = Routing.generate_best_match ? deprecated_routes : future_routes routes.each_with_index do |route, index| results = route.__send__(method, options, merged, expire_on) if results && (!results.is_a?(Array) || results.first) return results end end end raise RoutingError, "No route matches #{options.inspect}" end # try to give a helpful error message when named route generation fails def raise_named_route_error(options, named_route, named_route_name) diff = named_route.requirements.diff(options) unless diff.empty? raise RoutingError, "#{named_route_name}_url failed to generate from #{options.inspect}, expected: #{named_route.requirements.inspect}, diff: #{named_route.requirements.diff(options).inspect}" else required_segments = named_route.segments.select {|seg| (!seg.optional?) && (!seg.is_a?(DividerSegment)) } required_keys_or_values = required_segments.map { |seg| seg.key rescue seg.value } # we want either the key or the value from the segment raise RoutingError, "#{named_route_name}_url failed to generate from #{options.inspect} - you may have ambiguous routes, or you may need to supply additional parameters for this route. content_url has the following required parameters: #{required_keys_or_values.inspect} - are they all satisfied?" end end def call(env) request = Request.new(env) app = Routing::Routes.recognize(request) app.call(env).to_a end def recognize(request) params = recognize_path(request.path, extract_request_environment(request)) request.path_parameters = params.with_indifferent_access "#{params[:controller].to_s.camelize}Controller".constantize end def recognize_path(path, environment={}) raise "Not optimized! Check that routing/recognition_optimisation overrides RouteSet#recognize_path." end def routes_by_controller @routes_by_controller ||= Hash.new do |controller_hash, controller| controller_hash[controller] = Hash.new do |action_hash, action| action_hash[action] = Hash.new do |key_hash, keys| key_hash[keys] = [ routes_for_controller_and_action_and_keys(controller, action, keys), deprecated_routes_for_controller_and_action_and_keys(controller, action, keys) ] end end end end def routes_for(options, merged, expire_on) raise "Need controller and action!" unless controller && action controller = merged[:controller] merged = options if expire_on[:controller] action = merged[:action] || 'index' routes_by_controller[controller][action][merged.keys][1] end def routes_for_controller_and_action(controller, action) ActiveSupport::Deprecation.warn "routes_for_controller_and_action() has been deprecated. Please use routes_for()" selected = routes.select do |route| route.matches_controller_and_action? controller, action end (selected.length == routes.length) ? routes : selected end def routes_for_controller_and_action_and_keys(controller, action, keys) routes.select do |route| route.matches_controller_and_action? controller, action end end def deprecated_routes_for_controller_and_action_and_keys(controller, action, keys) selected = routes.select do |route| route.matches_controller_and_action? controller, action end selected.sort_by do |route| (keys - route.significant_keys).length end end # Subclasses and plugins may override this method to extract further attributes # from the request, for use by route conditions and such. def extract_request_environment(request) { :method => request.method } end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/segments.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/segments.rb
module ActionController module Routing class Segment #:nodoc: RESERVED_PCHAR = ':@&=+$,;' SAFE_PCHAR = "#{URI::REGEXP::PATTERN::UNRESERVED}#{RESERVED_PCHAR}" if RUBY_VERSION >= '1.9' UNSAFE_PCHAR = Regexp.new("[^#{SAFE_PCHAR}]", false).freeze else UNSAFE_PCHAR = Regexp.new("[^#{SAFE_PCHAR}]", false, 'N').freeze end # TODO: Convert :is_optional accessor to read only attr_accessor :is_optional alias_method :optional?, :is_optional def initialize @is_optional = false end def number_of_captures Regexp.new(regexp_chunk).number_of_captures end def extraction_code nil end # Continue generating string for the prior segments. def continue_string_structure(prior_segments) if prior_segments.empty? interpolation_statement(prior_segments) else new_priors = prior_segments[0..-2] prior_segments.last.string_structure(new_priors) end end def interpolation_chunk URI.escape(value, UNSAFE_PCHAR) end # Return a string interpolation statement for this segment and those before it. def interpolation_statement(prior_segments) chunks = prior_segments.collect { |s| s.interpolation_chunk } chunks << interpolation_chunk "\"#{chunks * ''}\"#{all_optionals_available_condition(prior_segments)}" end def string_structure(prior_segments) optional? ? continue_string_structure(prior_segments) : interpolation_statement(prior_segments) end # Return an if condition that is true if all the prior segments can be generated. # If there are no optional segments before this one, then nil is returned. def all_optionals_available_condition(prior_segments) optional_locals = prior_segments.collect { |s| s.local_name if s.optional? && s.respond_to?(:local_name) }.compact optional_locals.empty? ? nil : " if #{optional_locals * ' && '}" end # Recognition def match_extraction(next_capture) nil end # Warning # Returns true if this segment is optional? because of a default. If so, then # no warning will be emitted regarding this segment. def optionality_implied? false end end class StaticSegment < Segment #:nodoc: attr_reader :value, :raw alias_method :raw?, :raw def initialize(value = nil, options = {}) super() @value = value @raw = options[:raw] if options.key?(:raw) @is_optional = options[:optional] if options.key?(:optional) end def interpolation_chunk raw? ? value : super end def regexp_chunk chunk = Regexp.escape(value) optional? ? Regexp.optionalize(chunk) : chunk end def number_of_captures 0 end def build_pattern(pattern) escaped = Regexp.escape(value) if optional? && ! pattern.empty? "(?:#{Regexp.optionalize escaped}\\Z|#{escaped}#{Regexp.unoptionalize pattern})" elsif optional? Regexp.optionalize escaped else escaped + pattern end end def to_s value end end class DividerSegment < StaticSegment #:nodoc: def initialize(value = nil, options = {}) super(value, {:raw => true, :optional => true}.merge(options)) end def optionality_implied? true end end class DynamicSegment < Segment #:nodoc: attr_reader :key # TODO: Convert these accessors to read only attr_accessor :default, :regexp def initialize(key = nil, options = {}) super() @key = key @default = options[:default] if options.key?(:default) @regexp = options[:regexp] if options.key?(:regexp) @is_optional = true if options[:optional] || options.key?(:default) end def to_s ":#{key}" end # The local variable name that the value of this segment will be extracted to. def local_name "#{key}_value" end def extract_value "#{local_name} = hash[:#{key}] && hash[:#{key}].to_param #{"|| #{default.inspect}" if default}" end def value_check if default # Then we know it won't be nil "#{value_regexp.inspect} =~ #{local_name}" if regexp elsif optional? # If we have a regexp check that the value is not given, or that it matches. # If we have no regexp, return nil since we do not require a condition. "#{local_name}.nil? || #{value_regexp.inspect} =~ #{local_name}" if regexp else # Then it must be present, and if we have a regexp, it must match too. "#{local_name} #{"&& #{value_regexp.inspect} =~ #{local_name}" if regexp}" end end def expiry_statement "expired, hash = true, options if !expired && expire_on[:#{key}]" end def extraction_code s = extract_value vc = value_check s << "\nreturn [nil,nil] unless #{vc}" if vc s << "\n#{expiry_statement}" end def interpolation_chunk(value_code = local_name) "\#{URI.escape(#{value_code}.to_s, ActionController::Routing::Segment::UNSAFE_PCHAR)}" end def string_structure(prior_segments) if optional? # We have a conditional to do... # If we should not appear in the url, just write the code for the prior # segments. This occurs if our value is the default value, or, if we are # optional, if we have nil as our value. "if #{local_name} == #{default.inspect}\n" + continue_string_structure(prior_segments) + "\nelse\n" + # Otherwise, write the code up to here "#{interpolation_statement(prior_segments)}\nend" else interpolation_statement(prior_segments) end end def value_regexp Regexp.new "\\A#{regexp.to_s}\\Z" if regexp end def regexp_chunk regexp ? regexp_string : default_regexp_chunk end def regexp_string regexp_has_modifiers? ? "(#{regexp.to_s})" : "(#{regexp.source})" end def default_regexp_chunk "([^#{Routing::SEPARATORS.join}]+)" end def number_of_captures regexp ? regexp.number_of_captures + 1 : 1 end def build_pattern(pattern) pattern = "#{regexp_chunk}#{pattern}" optional? ? Regexp.optionalize(pattern) : pattern end def match_extraction(next_capture) # All non code-related keys (such as :id, :slug) are URI-unescaped as # path parameters. default_value = default ? default.inspect : nil %[ value = if (m = match[#{next_capture}]) URI.unescape(m) else #{default_value} end params[:#{key}] = value if value ] end def optionality_implied? [:action, :id].include? key end def regexp_has_modifiers? regexp.options & (Regexp::IGNORECASE | Regexp::EXTENDED) != 0 end end class ControllerSegment < DynamicSegment #:nodoc: def regexp_chunk possible_names = Routing.possible_controllers.collect { |name| Regexp.escape name } "(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))" end # Don't URI.escape the controller name since it may contain slashes. def interpolation_chunk(value_code = local_name) "\#{#{value_code}.to_s}" end # Make sure controller names like Admin/Content are correctly normalized to # admin/content def extract_value "#{local_name} = (hash[:#{key}] #{"|| #{default.inspect}" if default}).downcase" end def match_extraction(next_capture) if default "params[:#{key}] = match[#{next_capture}] ? match[#{next_capture}].downcase : '#{default}'" else "params[:#{key}] = match[#{next_capture}].downcase if match[#{next_capture}]" end end end class PathSegment < DynamicSegment #:nodoc: def interpolation_chunk(value_code = local_name) "\#{#{value_code}}" end def extract_value "#{local_name} = hash[:#{key}] && Array(hash[:#{key}]).collect { |path_component| URI.escape(path_component.to_param, ActionController::Routing::Segment::UNSAFE_PCHAR) }.to_param #{"|| #{default.inspect}" if default}" end def default '' end def default=(path) raise RoutingError, "paths cannot have non-empty default values" unless path.blank? end def match_extraction(next_capture) "params[:#{key}] = PathSegment::Result.new_escaped((match[#{next_capture}]#{" || " + default.inspect if default}).split('/'))#{" if match[" + next_capture + "]" if !default}" end def default_regexp_chunk "(.*)" end def number_of_captures regexp ? regexp.number_of_captures : 1 end def optionality_implied? true end class Result < ::Array #:nodoc: def to_s() join '/' end def self.new_escaped(strings) new strings.collect {|str| URI.unescape str} end end end # The OptionalFormatSegment allows for any resource route to have an optional # :format, which decreases the amount of routes created by 50%. class OptionalFormatSegment < DynamicSegment def initialize(key = nil, options = {}) super(:format, {:optional => true}.merge(options)) end def interpolation_chunk "." + super end def regexp_chunk '/|(\.[^/?\.]+)?' end def to_s '(.:format)?' end def extract_value "#{local_name} = options[:#{key}] && options[:#{key}].to_s.downcase" end #the value should not include the period (.) def match_extraction(next_capture) %[ if (m = match[#{next_capture}]) params[:#{key}] = URI.unescape(m.from(1)) end ] end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/builder.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/builder.rb
module ActionController module Routing class RouteBuilder #:nodoc: attr_reader :separators, :optional_separators attr_reader :separator_regexp, :nonseparator_regexp, :interval_regexp def initialize @separators = Routing::SEPARATORS @optional_separators = %w( / ) @separator_regexp = /[#{Regexp.escape(separators.join)}]/ @nonseparator_regexp = /\A([^#{Regexp.escape(separators.join)}]+)/ @interval_regexp = /(.*?)(#{separator_regexp}|$)/ end # Accepts a "route path" (a string defining a route), and returns the array # of segments that corresponds to it. Note that the segment array is only # partially initialized--the defaults and requirements, for instance, need # to be set separately, via the +assign_route_options+ method, and the # <tt>optional?</tt> method for each segment will not be reliable until after # +assign_route_options+ is called, as well. def segments_for_route_path(path) rest, segments = path, [] until rest.empty? segment, rest = segment_for(rest) segments << segment end segments end # A factory method that returns a new segment instance appropriate for the # format of the given string. def segment_for(string) segment = case string when /\A\.(:format)?\// OptionalFormatSegment.new when /\A:(\w+)/ key = $1.to_sym key == :controller ? ControllerSegment.new(key) : DynamicSegment.new(key) when /\A\*(\w+)/ PathSegment.new($1.to_sym, :optional => true) when /\A\?(.*?)\?/ StaticSegment.new($1, :optional => true) when nonseparator_regexp StaticSegment.new($1) when separator_regexp DividerSegment.new($&, :optional => optional_separators.include?($&)) end [segment, $~.post_match] end # Split the given hash of options into requirement and default hashes. The # segments are passed alongside in order to distinguish between default values # and requirements. def divide_route_options(segments, options) options = options.except(:path_prefix, :name_prefix) if options[:namespace] options[:controller] = "#{options.delete(:namespace).sub(/\/$/, '')}/#{options[:controller]}" end requirements = (options.delete(:requirements) || {}).dup defaults = (options.delete(:defaults) || {}).dup conditions = (options.delete(:conditions) || {}).dup validate_route_conditions(conditions) path_keys = segments.collect { |segment| segment.key if segment.respond_to?(:key) }.compact options.each do |key, value| hash = (path_keys.include?(key) && ! value.is_a?(Regexp)) ? defaults : requirements hash[key] = value end [defaults, requirements, conditions] end # Takes a hash of defaults and a hash of requirements, and assigns them to # the segments. Any unused requirements (which do not correspond to a segment) # are returned as a hash. def assign_route_options(segments, defaults, requirements) route_requirements = {} # Requirements that do not belong to a segment segment_named = Proc.new do |key| segments.detect { |segment| segment.key == key if segment.respond_to?(:key) } end requirements.each do |key, requirement| segment = segment_named[key] if segment raise TypeError, "#{key}: requirements on a path segment must be regular expressions" unless requirement.is_a?(Regexp) if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" end if requirement.multiline? raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" end segment.regexp = requirement else route_requirements[key] = requirement end end defaults.each do |key, default| segment = segment_named[key] raise ArgumentError, "#{key}: No matching segment exists; cannot assign default" unless segment segment.is_optional = true segment.default = default.to_param if default end assign_default_route_options(segments) ensure_required_segments(segments) route_requirements end # Assign default options, such as 'index' as a default for <tt>:action</tt>. This # method must be run *after* user supplied requirements and defaults have # been applied to the segments. def assign_default_route_options(segments) segments.each do |segment| next unless segment.is_a? DynamicSegment case segment.key when :action if segment.regexp.nil? || segment.regexp.match('index').to_s == 'index' segment.default ||= 'index' segment.is_optional = true end when :id if segment.default.nil? && segment.regexp.nil? || segment.regexp =~ '' segment.is_optional = true end end end end # Makes sure that there are no optional segments that precede a required # segment. If any are found that precede a required segment, they are # made required. def ensure_required_segments(segments) allow_optional = true segments.reverse_each do |segment| allow_optional &&= segment.optional? if !allow_optional && segment.optional? unless segment.optionality_implied? warn "Route segment \"#{segment.to_s}\" cannot be optional because it precedes a required segment. This segment will be required." end segment.is_optional = false elsif allow_optional && segment.respond_to?(:default) && segment.default # if a segment has a default, then it is optional segment.is_optional = true end end end # Construct and return a route with the given path and options. def build(path, options) # Wrap the path with slashes path = "/#{path}" unless path[0] == ?/ path = "#{path}/" unless path[-1] == ?/ prefix = options[:path_prefix].to_s.gsub(/^\//,'') path = "/#{prefix}#{path}" unless prefix.blank? segments = segments_for_route_path(path) defaults, requirements, conditions = divide_route_options(segments, options) requirements = assign_route_options(segments, defaults, requirements) # TODO: Segments should be frozen on initialize segments.each { |segment| segment.freeze } route = Route.new(segments, requirements, conditions) if !route.significant_keys.include?(:controller) raise ArgumentError, "Illegal route: the :controller must be specified!" end route.freeze end private def validate_route_conditions(conditions) if method = conditions[:method] [method].flatten.each do |m| if m == :head raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers" end unless HTTP_METHODS.include?(m.to_sym) raise ArgumentError, "Invalid HTTP method specified in route conditions: #{conditions.inspect}" end end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/routing/recognition_optimisation.rb
provider/vendor/rails/actionpack/lib/action_controller/routing/recognition_optimisation.rb
module ActionController module Routing # BEFORE: 0.191446860631307 ms/url # AFTER: 0.029847304022858 ms/url # Speed up: 6.4 times # # Route recognition is slow due to one-by-one iterating over # a whole routeset (each map.resources generates at least 14 routes) # and matching weird regexps on each step. # # We optimize this by skipping all URI segments that 100% sure can't # be matched, moving deeper in a tree of routes (where node == segment) # until first possible match is accured. In such case, we start walking # a flat list of routes, matching them with accurate matcher. # So, first step: search a segment tree for the first relevant index. # Second step: iterate routes starting with that index. # # How tree is walked? We can do a recursive tests, but it's smarter: # We just create a tree of if-s and elsif-s matching segments. # # We have segments of 3 flavors: # 1) nil (no segment, route finished) # 2) const-dot-dynamic (like "/posts.:xml", "/preview.:size.jpg") # 3) const (like "/posts", "/comments") # 4) dynamic ("/:id", "file.:size.:extension") # # We split incoming string into segments and iterate over them. # When segment is nil, we drop immediately, on a current node index. # When segment is equal to some const, we step into branch. # If none constants matched, we step into 'dynamic' branch (it's a last). # If we can't match anything, we drop to last index on a level. # # Note: we maintain the original routes order, so we finish building # steps on a first dynamic segment. # # # Example. Given the routes: # 0 /posts/ # 1 /posts/:id # 2 /posts/:id/comments # 3 /posts/blah # 4 /users/ # 5 /users/:id # 6 /users/:id/profile # # request_uri = /users/123 # # There will be only 4 iterations: # 1) segm test for /posts prefix, skip all /posts/* routes # 2) segm test for /users/ # 3) segm test for /users/:id # (jump to list index = 5) # 4) full test for /users/:id => here we are! class RouteSet def recognize_path(path, environment={}) result = recognize_optimized(path, environment) and return result # Route was not recognized. Try to find out why (maybe wrong verb). allows = HTTP_METHODS.select { |verb| routes.find { |r| r.recognize(path, environment.merge(:method => verb)) } } if environment[:method] && !HTTP_METHODS.include?(environment[:method]) raise NotImplemented.new(*allows) elsif !allows.empty? raise MethodNotAllowed.new(*allows) else raise RoutingError, "No route matches #{path.inspect} with #{environment.inspect}" end end def segment_tree(routes) tree = [0] i = -1 routes.each do |route| i += 1 # not fast, but runs only once segments = to_plain_segments(route.segments.inject("") { |str,s| str << s.to_s }) node = tree segments.each do |seg| seg = :dynamic if seg && seg[0] == ?: node << [seg, [i]] if node.empty? || node[node.size - 1][0] != seg node = node[node.size - 1][1] end end tree end def generate_code(list, padding=' ', level = 0) # a digit return padding + "#{list[0]}\n" if list.size == 1 && !(Array === list[0]) body = padding + "(seg = segments[#{level}]; \n" i = 0 was_nil = false list.each do |item| if Array === item i += 1 start = (i == 1) tag, sub = item if tag == :dynamic body += padding + "#{start ? 'if' : 'elsif'} true\n" body += generate_code(sub, padding + " ", level + 1) break elsif tag == nil && !was_nil was_nil = true body += padding + "#{start ? 'if' : 'elsif'} seg.nil?\n" body += generate_code(sub, padding + " ", level + 1) else body += padding + "#{start ? 'if' : 'elsif'} seg == '#{tag}'\n" body += generate_code(sub, padding + " ", level + 1) end end end body += padding + "else\n" body += padding + " #{list[0]}\n" body += padding + "end)\n" body end # this must be really fast def to_plain_segments(str) str = str.dup str.sub!(/^\/+/,'') str.sub!(/\/+$/,'') segments = str.split(/\.[^\/]+\/+|\/+|\.[^\/]+\Z/) # cut off ".format" also segments << nil segments end private def write_recognize_optimized! tree = segment_tree(routes) body = generate_code(tree) remove_recognize_optimized! instance_eval %{ def recognize_optimized(path, env) segments = to_plain_segments(path) index = #{body} return nil unless index while index < routes.size result = routes[index].recognize(path, env) and return result index += 1 end nil end }, '(recognize_optimized)', 1 end def clear_recognize_optimized! remove_recognize_optimized! write_recognize_optimized! end def remove_recognize_optimized! if respond_to?(:recognize_optimized) class << self remove_method :recognize_optimized end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner.rb
$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner" module HTML autoload :CDATA, 'html/node' autoload :Document, 'html/document' autoload :FullSanitizer, 'html/sanitizer' autoload :LinkSanitizer, 'html/sanitizer' autoload :Node, 'html/node' autoload :Sanitizer, 'html/sanitizer' autoload :Selector, 'html/selector' autoload :Tag, 'html/node' autoload :Text, 'html/node' autoload :Tokenizer, 'html/tokenizer' autoload :Version, 'html/version' autoload :WhiteListSanitizer, 'html/sanitizer' end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
#-- # Copyright (c) 2006 Assaf Arkin (http://labnotes.org) # Under MIT and/or CC By license. #++ module HTML # Selects HTML elements using CSS 2 selectors. # # The +Selector+ class uses CSS selector expressions to match and select # HTML elements. # # For example: # selector = HTML::Selector.new "form.login[action=/login]" # creates a new selector that matches any +form+ element with the class # +login+ and an attribute +action+ with the value <tt>/login</tt>. # # === Matching Elements # # Use the #match method to determine if an element matches the selector. # # For simple selectors, the method returns an array with that element, # or +nil+ if the element does not match. For complex selectors (see below) # the method returns an array with all matched elements, of +nil+ if no # match found. # # For example: # if selector.match(element) # puts "Element is a login form" # end # # === Selecting Elements # # Use the #select method to select all matching elements starting with # one element and going through all children in depth-first order. # # This method returns an array of all matching elements, an empty array # if no match is found # # For example: # selector = HTML::Selector.new "input[type=text]" # matches = selector.select(element) # matches.each do |match| # puts "Found text field with name #{match.attributes['name']}" # end # # === Expressions # # Selectors can match elements using any of the following criteria: # * <tt>name</tt> -- Match an element based on its name (tag name). # For example, <tt>p</tt> to match a paragraph. You can use <tt>*</tt> # to match any element. # * <tt>#</tt><tt>id</tt> -- Match an element based on its identifier (the # <tt>id</tt> attribute). For example, <tt>#</tt><tt>page</tt>. # * <tt>.class</tt> -- Match an element based on its class name, all # class names if more than one specified. # * <tt>[attr]</tt> -- Match an element that has the specified attribute. # * <tt>[attr=value]</tt> -- Match an element that has the specified # attribute and value. (More operators are supported see below) # * <tt>:pseudo-class</tt> -- Match an element based on a pseudo class, # such as <tt>:nth-child</tt> and <tt>:empty</tt>. # * <tt>:not(expr)</tt> -- Match an element that does not match the # negation expression. # # When using a combination of the above, the element name comes first # followed by identifier, class names, attributes, pseudo classes and # negation in any order. Do not separate these parts with spaces! # Space separation is used for descendant selectors. # # For example: # selector = HTML::Selector.new "form.login[action=/login]" # The matched element must be of type +form+ and have the class +login+. # It may have other classes, but the class +login+ is required to match. # It must also have an attribute called +action+ with the value # <tt>/login</tt>. # # This selector will match the following element: # <form class="login form" method="post" action="/login"> # but will not match the element: # <form method="post" action="/logout"> # # === Attribute Values # # Several operators are supported for matching attributes: # * <tt>name</tt> -- The element must have an attribute with that name. # * <tt>name=value</tt> -- The element must have an attribute with that # name and value. # * <tt>name^=value</tt> -- The attribute value must start with the # specified value. # * <tt>name$=value</tt> -- The attribute value must end with the # specified value. # * <tt>name*=value</tt> -- The attribute value must contain the # specified value. # * <tt>name~=word</tt> -- The attribute value must contain the specified # word (space separated). # * <tt>name|=word</tt> -- The attribute value must start with specified # word. # # For example, the following two selectors match the same element: # #my_id # [id=my_id] # and so do the following two selectors: # .my_class # [class~=my_class] # # === Alternatives, siblings, children # # Complex selectors use a combination of expressions to match elements: # * <tt>expr1 expr2</tt> -- Match any element against the second expression # if it has some parent element that matches the first expression. # * <tt>expr1 > expr2</tt> -- Match any element against the second expression # if it is the child of an element that matches the first expression. # * <tt>expr1 + expr2</tt> -- Match any element against the second expression # if it immediately follows an element that matches the first expression. # * <tt>expr1 ~ expr2</tt> -- Match any element against the second expression # that comes after an element that matches the first expression. # * <tt>expr1, expr2</tt> -- Match any element against the first expression, # or against the second expression. # # Since children and sibling selectors may match more than one element given # the first element, the #match method may return more than one match. # # === Pseudo classes # # Pseudo classes were introduced in CSS 3. They are most often used to select # elements in a given position: # * <tt>:root</tt> -- Match the element only if it is the root element # (no parent element). # * <tt>:empty</tt> -- Match the element only if it has no child elements, # and no text content. # * <tt>:only-child</tt> -- Match the element if it is the only child (element) # of its parent element. # * <tt>:only-of-type</tt> -- Match the element if it is the only child (element) # of its parent element and its type. # * <tt>:first-child</tt> -- Match the element if it is the first child (element) # of its parent element. # * <tt>:first-of-type</tt> -- Match the element if it is the first child (element) # of its parent element of its type. # * <tt>:last-child</tt> -- Match the element if it is the last child (element) # of its parent element. # * <tt>:last-of-type</tt> -- Match the element if it is the last child (element) # of its parent element of its type. # * <tt>:nth-child(b)</tt> -- Match the element if it is the b-th child (element) # of its parent element. The value <tt>b</tt> specifies its index, starting with 1. # * <tt>:nth-child(an+b)</tt> -- Match the element if it is the b-th child (element) # in each group of <tt>a</tt> child elements of its parent element. # * <tt>:nth-child(-an+b)</tt> -- Match the element if it is the first child (element) # in each group of <tt>a</tt> child elements, up to the first <tt>b</tt> child # elements of its parent element. # * <tt>:nth-child(odd)</tt> -- Match element in the odd position (i.e. first, third). # Same as <tt>:nth-child(2n+1)</tt>. # * <tt>:nth-child(even)</tt> -- Match element in the even position (i.e. second, # fourth). Same as <tt>:nth-child(2n+2)</tt>. # * <tt>:nth-of-type(..)</tt> -- As above, but only counts elements of its type. # * <tt>:nth-last-child(..)</tt> -- As above, but counts from the last child. # * <tt>:nth-last-of-type(..)</tt> -- As above, but counts from the last child and # only elements of its type. # * <tt>:not(selector)</tt> -- Match the element only if the element does not # match the simple selector. # # As you can see, <tt>:nth-child<tt> pseudo class and its variant can get quite # tricky and the CSS specification doesn't do a much better job explaining it. # But after reading the examples and trying a few combinations, it's easy to # figure out. # # For example: # table tr:nth-child(odd) # Selects every second row in the table starting with the first one. # # div p:nth-child(4) # Selects the fourth paragraph in the +div+, but not if the +div+ contains # other elements, since those are also counted. # # div p:nth-of-type(4) # Selects the fourth paragraph in the +div+, counting only paragraphs, and # ignoring all other elements. # # div p:nth-of-type(-n+4) # Selects the first four paragraphs, ignoring all others. # # And you can always select an element that matches one set of rules but # not another using <tt>:not</tt>. For example: # p:not(.post) # Matches all paragraphs that do not have the class <tt>.post</tt>. # # === Substitution Values # # You can use substitution with identifiers, class names and element values. # A substitution takes the form of a question mark (<tt>?</tt>) and uses the # next value in the argument list following the CSS expression. # # The substitution value may be a string or a regular expression. All other # values are converted to strings. # # For example: # selector = HTML::Selector.new "#?", /^\d+$/ # matches any element whose identifier consists of one or more digits. # # See http://www.w3.org/TR/css3-selectors/ class Selector # An invalid selector. class InvalidSelectorError < StandardError #:nodoc: end class << self # :call-seq: # Selector.for_class(cls) => selector # # Creates a new selector for the given class name. def for_class(cls) self.new([".?", cls]) end # :call-seq: # Selector.for_id(id) => selector # # Creates a new selector for the given id. def for_id(id) self.new(["#?", id]) end end # :call-seq: # Selector.new(string, [values ...]) => selector # # Creates a new selector from a CSS 2 selector expression. # # The first argument is the selector expression. All other arguments # are used for value substitution. # # Throws InvalidSelectorError is the selector expression is invalid. def initialize(selector, *values) raise ArgumentError, "CSS expression cannot be empty" if selector.empty? @source = "" values = values[0] if values.size == 1 && values[0].is_a?(Array) # We need a copy to determine if we failed to parse, and also # preserve the original pass by-ref statement. statement = selector.strip.dup # Create a simple selector, along with negation. simple_selector(statement, values).each { |name, value| instance_variable_set("@#{name}", value) } @alternates = [] @depends = nil # Alternative selector. if statement.sub!(/^\s*,\s*/, "") second = Selector.new(statement, values) @alternates << second # If there are alternate selectors, we group them in the top selector. if alternates = second.instance_variable_get(:@alternates) second.instance_variable_set(:@alternates, []) @alternates.concat alternates end @source << " , " << second.to_s # Sibling selector: create a dependency into second selector that will # match element immediately following this one. elsif statement.sub!(/^\s*\+\s*/, "") second = next_selector(statement, values) @depends = lambda do |element, first| if element = next_element(element) second.match(element, first) end end @source << " + " << second.to_s # Adjacent selector: create a dependency into second selector that will # match all elements following this one. elsif statement.sub!(/^\s*~\s*/, "") second = next_selector(statement, values) @depends = lambda do |element, first| matches = [] while element = next_element(element) if subset = second.match(element, first) if first && !subset.empty? matches << subset.first break else matches.concat subset end end end matches.empty? ? nil : matches end @source << " ~ " << second.to_s # Child selector: create a dependency into second selector that will # match a child element of this one. elsif statement.sub!(/^\s*>\s*/, "") second = next_selector(statement, values) @depends = lambda do |element, first| matches = [] element.children.each do |child| if child.tag? && subset = second.match(child, first) if first && !subset.empty? matches << subset.first break else matches.concat subset end end end matches.empty? ? nil : matches end @source << " > " << second.to_s # Descendant selector: create a dependency into second selector that # will match all descendant elements of this one. Note, elsif statement =~ /^\s+\S+/ && statement != selector second = next_selector(statement, values) @depends = lambda do |element, first| matches = [] stack = element.children.reverse while node = stack.pop next unless node.tag? if subset = second.match(node, first) if first && !subset.empty? matches << subset.first break else matches.concat subset end elsif children = node.children stack.concat children.reverse end end matches.empty? ? nil : matches end @source << " " << second.to_s else # The last selector is where we check that we parsed # all the parts. unless statement.empty? || statement.strip.empty? raise ArgumentError, "Invalid selector: #{statement}" end end end # :call-seq: # match(element, first?) => array or nil # # Matches an element against the selector. # # For a simple selector this method returns an array with the # element if the element matches, nil otherwise. # # For a complex selector (sibling and descendant) this method # returns an array with all matching elements, nil if no match is # found. # # Use +first_only=true+ if you are only interested in the first element. # # For example: # if selector.match(element) # puts "Element is a login form" # end def match(element, first_only = false) # Match element if no element name or element name same as element name if matched = (!@tag_name || @tag_name == element.name) # No match if one of the attribute matches failed for attr in @attributes if element.attributes[attr[0]] !~ attr[1] matched = false break end end end # Pseudo class matches (nth-child, empty, etc). if matched for pseudo in @pseudo unless pseudo.call(element) matched = false break end end end # Negation. Same rules as above, but we fail if a match is made. if matched && @negation for negation in @negation if negation[:tag_name] == element.name matched = false else for attr in negation[:attributes] if element.attributes[attr[0]] =~ attr[1] matched = false break end end end if matched for pseudo in negation[:pseudo] if pseudo.call(element) matched = false break end end end break unless matched end end # If element matched but depends on another element (child, # sibling, etc), apply the dependent matches instead. if matched && @depends matches = @depends.call(element, first_only) else matches = matched ? [element] : nil end # If this selector is part of the group, try all the alternative # selectors (unless first_only). if !first_only || !matches @alternates.each do |alternate| break if matches && first_only if subset = alternate.match(element, first_only) if matches matches.concat subset else matches = subset end end end end matches end # :call-seq: # select(root) => array # # Selects and returns an array with all matching elements, beginning # with one node and traversing through all children depth-first. # Returns an empty array if no match is found. # # The root node may be any element in the document, or the document # itself. # # For example: # selector = HTML::Selector.new "input[type=text]" # matches = selector.select(element) # matches.each do |match| # puts "Found text field with name #{match.attributes['name']}" # end def select(root) matches = [] stack = [root] while node = stack.pop if node.tag? && subset = match(node, false) subset.each do |match| matches << match unless matches.any? { |item| item.equal?(match) } end elsif children = node.children stack.concat children.reverse end end matches end # Similar to #select but returns the first matching element. Returns +nil+ # if no element matches the selector. def select_first(root) stack = [root] while node = stack.pop if node.tag? && subset = match(node, true) return subset.first if !subset.empty? elsif children = node.children stack.concat children.reverse end end nil end def to_s #:nodoc: @source end # Return the next element after this one. Skips sibling text nodes. # # With the +name+ argument, returns the next element with that name, # skipping other sibling elements. def next_element(element, name = nil) if siblings = element.parent.children found = false siblings.each do |node| if node.equal?(element) found = true elsif found && node.tag? return node if (name.nil? || node.name == name) end end end nil end protected # Creates a simple selector given the statement and array of # substitution values. # # Returns a hash with the values +tag_name+, +attributes+, # +pseudo+ (classes) and +negation+. # # Called the first time with +can_negate+ true to allow # negation. Called a second time with false since negation # cannot be negated. def simple_selector(statement, values, can_negate = true) tag_name = nil attributes = [] pseudo = [] negation = [] # Element name. (Note that in negation, this can come at # any order, but for simplicity we allow if only first). statement.sub!(/^(\*|[[:alpha:]][\w\-]*)/) do |match| match.strip! tag_name = match.downcase unless match == "*" @source << match "" # Remove end # Get identifier, class, attribute name, pseudo or negation. while true # Element identifier. next if statement.sub!(/^#(\?|[\w\-]+)/) do |match| id = $1 if id == "?" id = values.shift end @source << "##{id}" id = Regexp.new("^#{Regexp.escape(id.to_s)}$") unless id.is_a?(Regexp) attributes << ["id", id] "" # Remove end # Class name. next if statement.sub!(/^\.([\w\-]+)/) do |match| class_name = $1 @source << ".#{class_name}" class_name = Regexp.new("(^|\s)#{Regexp.escape(class_name)}($|\s)") unless class_name.is_a?(Regexp) attributes << ["class", class_name] "" # Remove end # Attribute value. next if statement.sub!(/^\[\s*([[:alpha:]][\w\-:]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do |match| name, equality, value = $1, $2, $3 if value == "?" value = values.shift else # Handle single and double quotes. value.strip! if (value[0] == ?" || value[0] == ?') && value[0] == value[-1] value = value[1..-2] end end @source << "[#{name}#{equality}'#{value}']" attributes << [name.downcase.strip, attribute_match(equality, value)] "" # Remove end # Root element only. next if statement.sub!(/^:root/) do |match| pseudo << lambda do |element| element.parent.nil? || !element.parent.tag? end @source << ":root" "" # Remove end # Nth-child including last and of-type. next if statement.sub!(/^:nth-(last-)?(child|of-type)\((odd|even|(\d+|\?)|(-?\d*|\?)?n([+\-]\d+|\?)?)\)/) do |match| reverse = $1 == "last-" of_type = $2 == "of-type" @source << ":nth-#{$1}#{$2}(" case $3 when "odd" pseudo << nth_child(2, 1, of_type, reverse) @source << "odd)" when "even" pseudo << nth_child(2, 2, of_type, reverse) @source << "even)" when /^(\d+|\?)$/ # b only b = ($1 == "?" ? values.shift : $1).to_i pseudo << nth_child(0, b, of_type, reverse) @source << "#{b})" when /^(-?\d*|\?)?n([+\-]\d+|\?)?$/ a = ($1 == "?" ? values.shift : $1 == "" ? 1 : $1 == "-" ? -1 : $1).to_i b = ($2 == "?" ? values.shift : $2).to_i pseudo << nth_child(a, b, of_type, reverse) @source << (b >= 0 ? "#{a}n+#{b})" : "#{a}n#{b})") else raise ArgumentError, "Invalid nth-child #{match}" end "" # Remove end # First/last child (of type). next if statement.sub!(/^:(first|last)-(child|of-type)/) do |match| reverse = $1 == "last" of_type = $2 == "of-type" pseudo << nth_child(0, 1, of_type, reverse) @source << ":#{$1}-#{$2}" "" # Remove end # Only child (of type). next if statement.sub!(/^:only-(child|of-type)/) do |match| of_type = $1 == "of-type" pseudo << only_child(of_type) @source << ":only-#{$1}" "" # Remove end # Empty: no child elements or meaningful content (whitespaces # are ignored). next if statement.sub!(/^:empty/) do |match| pseudo << lambda do |element| empty = true for child in element.children if child.tag? || !child.content.strip.empty? empty = false break end end empty end @source << ":empty" "" # Remove end # Content: match the text content of the element, stripping # leading and trailing spaces. next if statement.sub!(/^:content\(\s*(\?|'[^']*'|"[^"]*"|[^)]*)\s*\)/) do |match| content = $1 if content == "?" content = values.shift elsif (content[0] == ?" || content[0] == ?') && content[0] == content[-1] content = content[1..-2] end @source << ":content('#{content}')" content = Regexp.new("^#{Regexp.escape(content.to_s)}$") unless content.is_a?(Regexp) pseudo << lambda do |element| text = "" for child in element.children unless child.tag? text << child.content end end text.strip =~ content end "" # Remove end # Negation. Create another simple selector to handle it. if statement.sub!(/^:not\(\s*/, "") raise ArgumentError, "Double negatives are not missing feature" unless can_negate @source << ":not(" negation << simple_selector(statement, values, false) raise ArgumentError, "Negation not closed" unless statement.sub!(/^\s*\)/, "") @source << ")" next end # No match: moving on. break end # Return hash. The keys are mapped to instance variables. {:tag_name=>tag_name, :attributes=>attributes, :pseudo=>pseudo, :negation=>negation} end # Create a regular expression to match an attribute value based # on the equality operator (=, ^=, |=, etc). def attribute_match(equality, value) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) case equality when "=" then # Match the attribute value in full Regexp.new("^#{regexp}$") when "~=" then # Match a space-separated word within the attribute value Regexp.new("(^|\s)#{regexp}($|\s)") when "^=" # Match the beginning of the attribute value Regexp.new("^#{regexp}") when "$=" # Match the end of the attribute value Regexp.new("#{regexp}$") when "*=" # Match substring of the attribute value regexp.is_a?(Regexp) ? regexp : Regexp.new(regexp) when "|=" then # Match the first space-separated item of the attribute value Regexp.new("^#{regexp}($|\s)") else raise InvalidSelectorError, "Invalid operation/value" unless value.empty? # Match all attributes values (existence check) // end end # Returns a lambda that can match an element against the nth-child # pseudo class, given the following arguments: # * +a+ -- Value of a part. # * +b+ -- Value of b part. # * +of_type+ -- True to test only elements of this type (of-type). # * +reverse+ -- True to count in reverse order (last-). def nth_child(a, b, of_type, reverse) # a = 0 means select at index b, if b = 0 nothing selected return lambda { |element| false } if a == 0 && b == 0 # a < 0 and b < 0 will never match against an index return lambda { |element| false } if a < 0 && b < 0 b = a + b + 1 if b < 0 # b < 0 just picks last element from each group b -= 1 unless b == 0 # b == 0 is same as b == 1, otherwise zero based lambda do |element| # Element must be inside parent element. return false unless element.parent && element.parent.tag? index = 0 # Get siblings, reverse if counting from last. siblings = element.parent.children siblings = siblings.reverse if reverse # Match element name if of-type, otherwise ignore name. name = of_type ? element.name : nil found = false for child in siblings # Skip text nodes/comments. if child.tag? && (name == nil || child.name == name) if a == 0 # Shortcut when a == 0 no need to go past count if index == b found = child.equal?(element) break end elsif a < 0 # Only look for first b elements break if index > b if child.equal?(element) found = (index % a) == 0 break end else # Otherwise, break if child found and count == an+b if child.equal?(element) found = (index % a) == b break end end index += 1 end end found end end # Creates a only child lambda. Pass +of-type+ to only look at # elements of its type. def only_child(of_type) lambda do |element| # Element must be inside parent element. return false unless element.parent && element.parent.tag? name = of_type ? element.name : nil other = false for child in element.parent.children # Skip text nodes/comments. if child.tag? && (name == nil || child.name == name) unless child.equal?(element) other = true break end end end !other end end # Called to create a dependent selector (sibling, descendant, etc). # Passes the remainder of the statement that will be reduced to zero # eventually, and array of substitution values. # # This method is called from four places, so it helps to put it here # for reuse. The only logic deals with the need to detect comma # separators (alternate) and apply them to the selector group of the # top selector. def next_selector(statement, values) second = Selector.new(statement, values) # If there are alternate selectors, we group them in the top selector. if alternates = second.instance_variable_get(:@alternates) second.instance_variable_set(:@alternates, []) @alternates.concat alternates end second end end # See HTML::Selector.new def self.selector(statement, *values) Selector.new(statement, *values) end class Tag def select(selector, *values) selector = HTML::Selector.new(selector, values) selector.select(self) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb
module HTML #:nodoc: module Version #:nodoc: MAJOR = 0 MINOR = 5 TINY = 3 STRING = [ MAJOR, MINOR, TINY ].join(".") end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
module HTML class Sanitizer def sanitize(text, options = {}) return text unless sanitizeable?(text) tokenize(text, options).join end def sanitizeable?(text) !(text.nil? || text.empty? || !text.index("<")) end protected def tokenize(text, options) tokenizer = HTML::Tokenizer.new(text) result = [] while token = tokenizer.next node = Node.parse(nil, 0, 0, token, false) process_node node, result, options end result end def process_node(node, result, options) result << node.to_s end end class FullSanitizer < Sanitizer def sanitize(text, options = {}) result = super # strip any comments, and if they have a newline at the end (ie. line with # only a comment) strip that too result.gsub!(/<!--(.*?)-->[\n]?/m, "") if result # Recurse - handle all dirty nested tags result == text ? result : sanitize(result, options) end def process_node(node, result, options) result << node.to_s if node.class == HTML::Text end end class LinkSanitizer < FullSanitizer cattr_accessor :included_tags, :instance_writer => false self.included_tags = Set.new(%w(a href)) def sanitizeable?(text) !(text.nil? || text.empty? || !((text.index("<a") || text.index("<href")) && text.index(">"))) end protected def process_node(node, result, options) result << node.to_s unless node.is_a?(HTML::Tag) && included_tags.include?(node.name) end end class WhiteListSanitizer < Sanitizer [:protocol_separator, :uri_attributes, :allowed_attributes, :allowed_tags, :allowed_protocols, :bad_tags, :allowed_css_properties, :allowed_css_keywords, :shorthand_css_properties].each do |attr| class_inheritable_accessor attr, :instance_writer => false end # A regular expression of the valid characters used to separate protocols like # the ':' in 'http://foo.com' self.protocol_separator = /:|(&#0*58)|(&#x70)|(%|&#37;)3A/ # Specifies a Set of HTML attributes that can have URIs. self.uri_attributes = Set.new(%w(href src cite action longdesc xlink:href lowsrc)) # Specifies a Set of 'bad' tags that the #sanitize helper will remove completely, as opposed # to just escaping harmless tags like &lt;font&gt; self.bad_tags = Set.new(%w(script)) # Specifies the default Set of tags that the #sanitize helper will allow unscathed. self.allowed_tags = Set.new(%w(strong em b i p code pre tt samp kbd var sub sup dfn cite big small address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dt dd abbr acronym a img blockquote del ins)) # Specifies the default Set of html attributes that the #sanitize helper will leave # in the allowed tag. self.allowed_attributes = Set.new(%w(href src width height alt cite datetime title class name xml:lang abbr)) # Specifies the default Set of acceptable css properties that #sanitize and #sanitize_css will accept. self.allowed_protocols = Set.new(%w(ed2k ftp http https irc mailto news gopher nntp telnet webcal xmpp callto feed svn urn aim rsync tag ssh sftp rtsp afs)) # Specifies the default Set of acceptable css keywords that #sanitize and #sanitize_css will accept. self.allowed_css_properties = Set.new(%w(azimuth background-color border-bottom-color border-collapse border-color border-left-color border-right-color border-top-color clear color cursor direction display elevation float font font-family font-size font-style font-variant font-weight height letter-spacing line-height overflow pause pause-after pause-before pitch pitch-range richness speak speak-header speak-numeral speak-punctuation speech-rate stress text-align text-decoration text-indent unicode-bidi vertical-align voice-family volume white-space width)) # Specifies the default Set of acceptable css keywords that #sanitize and #sanitize_css will accept. self.allowed_css_keywords = Set.new(%w(auto aqua black block blue bold both bottom brown center collapse dashed dotted fuchsia gray green !important italic left lime maroon medium none navy normal nowrap olive pointer purple red right solid silver teal top transparent underline white yellow)) # Specifies the default Set of allowed shorthand css properties for the #sanitize and #sanitize_css helpers. self.shorthand_css_properties = Set.new(%w(background border margin padding)) # Sanitizes a block of css code. Used by #sanitize when it comes across a style attribute def sanitize_css(style) # disallow urls style = style.to_s.gsub(/url\s*\(\s*[^\s)]+?\s*\)\s*/, ' ') # gauntlet if style !~ /^([:,;#%.\sa-zA-Z0-9!]|\w-\w|\'[\s\w]+\'|\"[\s\w]+\"|\([\d,\s]+\))*$/ || style !~ /^(\s*[-\w]+\s*:\s*[^:;]*(;|$)\s*)*$/ return '' end clean = [] style.scan(/([-\w]+)\s*:\s*([^:;]*)/) do |prop,val| if allowed_css_properties.include?(prop.downcase) clean << prop + ': ' + val + ';' elsif shorthand_css_properties.include?(prop.split('-')[0].downcase) unless val.split().any? do |keyword| !allowed_css_keywords.include?(keyword) && keyword !~ /^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$/ end clean << prop + ': ' + val + ';' end end end clean.join(' ') end protected def tokenize(text, options) options[:parent] = [] options[:attributes] ||= allowed_attributes options[:tags] ||= allowed_tags super end def process_node(node, result, options) result << case node when HTML::Tag if node.closing == :close options[:parent].shift else options[:parent].unshift node.name end process_attributes_for node, options options[:tags].include?(node.name) ? node : nil else bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "&lt;") end end def process_attributes_for(node, options) return unless node.attributes node.attributes.keys.each do |attr_name| value = node.attributes[attr_name].to_s if !options[:attributes].include?(attr_name) || contains_bad_protocols?(attr_name, value) node.attributes.delete(attr_name) else node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(CGI::unescapeHTML(value)) end end end def contains_bad_protocols?(attr_name, value) uri_attributes.include?(attr_name) && (value =~ /(^[^\/:]*):|(&#0*58)|(&#x70)|(%|&#37;)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first)) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
require 'strscan' module HTML #:nodoc: class Conditions < Hash #:nodoc: def initialize(hash) super() hash = { :content => hash } unless Hash === hash hash = keys_to_symbols(hash) hash.each do |k,v| case k when :tag, :content then # keys are valid, and require no further processing when :attributes then hash[k] = keys_to_strings(v) when :parent, :child, :ancestor, :descendant, :sibling, :before, :after hash[k] = Conditions.new(v) when :children hash[k] = v = keys_to_symbols(v) v.each do |k,v2| case k when :count, :greater_than, :less_than # keys are valid, and require no further processing when :only v[k] = Conditions.new(v2) else raise "illegal key #{k.inspect} => #{v2.inspect}" end end else raise "illegal key #{k.inspect} => #{v.inspect}" end end update hash end private def keys_to_strings(hash) hash.keys.inject({}) do |h,k| h[k.to_s] = hash[k] h end end def keys_to_symbols(hash) hash.keys.inject({}) do |h,k| raise "illegal key #{k.inspect}" unless k.respond_to?(:to_sym) h[k.to_sym] = hash[k] h end end end # The base class of all nodes, textual and otherwise, in an HTML document. class Node #:nodoc: # The array of children of this node. Not all nodes have children. attr_reader :children # The parent node of this node. All nodes have a parent, except for the # root node. attr_reader :parent # The line number of the input where this node was begun attr_reader :line # The byte position in the input where this node was begun attr_reader :position # Create a new node as a child of the given parent. def initialize(parent, line=0, pos=0) @parent = parent @children = [] @line, @position = line, pos end # Return a textual representation of the node. def to_s s = "" @children.each { |child| s << child.to_s } s end # Return false (subclasses must override this to provide specific matching # behavior.) +conditions+ may be of any type. def match(conditions) false end # Search the children of this node for the first node for which #find # returns non +nil+. Returns the result of the #find call that succeeded. def find(conditions) conditions = validate_conditions(conditions) @children.each do |child| node = child.find(conditions) return node if node end nil end # Search for all nodes that match the given conditions, and return them # as an array. def find_all(conditions) conditions = validate_conditions(conditions) matches = [] matches << self if match(conditions) @children.each do |child| matches.concat child.find_all(conditions) end matches end # Returns +false+. Subclasses may override this if they define a kind of # tag. def tag? false end def validate_conditions(conditions) Conditions === conditions ? conditions : Conditions.new(conditions) end def ==(node) return false unless self.class == node.class && children.size == node.children.size equivalent = true children.size.times do |i| equivalent &&= children[i] == node.children[i] end equivalent end class <<self def parse(parent, line, pos, content, strict=true) if content !~ /^<\S/ Text.new(parent, line, pos, content) else scanner = StringScanner.new(content) unless scanner.skip(/</) if strict raise "expected <" else return Text.new(parent, line, pos, content) end end if scanner.skip(/!\[CDATA\[/) unless scanner.skip_until(/\]\]>/) if strict raise "expected ]]> (got #{scanner.rest.inspect} for #{content})" else scanner.skip_until(/\Z/) end end return CDATA.new(parent, line, pos, scanner.pre_match.gsub(/<!\[CDATA\[/, '')) end closing = ( scanner.scan(/\//) ? :close : nil ) return Text.new(parent, line, pos, content) unless name = scanner.scan(/[\w:-]+/) name.downcase! unless closing scanner.skip(/\s*/) attributes = {} while attr = scanner.scan(/[-\w:]+/) value = true if scanner.scan(/\s*=\s*/) if delim = scanner.scan(/['"]/) value = "" while text = scanner.scan(/[^#{delim}\\]+|./) case text when "\\" then value << text value << scanner.getch when delim break else value << text end end else value = scanner.scan(/[^\s>\/]+/) end end attributes[attr.downcase] = value scanner.skip(/\s*/) end closing = ( scanner.scan(/\//) ? :self : nil ) end unless scanner.scan(/\s*>/) if strict raise "expected > (got #{scanner.rest.inspect} for #{content}, #{attributes.inspect})" else # throw away all text until we find what we're looking for scanner.skip_until(/>/) or scanner.terminate end end Tag.new(parent, line, pos, name, attributes, closing) end end end end # A node that represents text, rather than markup. class Text < Node #:nodoc: attr_reader :content # Creates a new text node as a child of the given parent, with the given # content. def initialize(parent, line, pos, content) super(parent, line, pos) @content = content end # Returns the content of this node. def to_s @content end # Returns +self+ if this node meets the given conditions. Text nodes support # conditions of the following kinds: # # * if +conditions+ is a string, it must be a substring of the node's # content # * if +conditions+ is a regular expression, it must match the node's # content # * if +conditions+ is a hash, it must contain a <tt>:content</tt> key that # is either a string or a regexp, and which is interpreted as described # above. def find(conditions) match(conditions) && self end # Returns non-+nil+ if this node meets the given conditions, or +nil+ # otherwise. See the discussion of #find for the valid conditions. def match(conditions) case conditions when String @content == conditions when Regexp @content =~ conditions when Hash conditions = validate_conditions(conditions) # Text nodes only have :content, :parent, :ancestor unless (conditions.keys - [:content, :parent, :ancestor]).empty? return false end match(conditions[:content]) else nil end end def ==(node) return false unless super content == node.content end end # A CDATA node is simply a text node with a specialized way of displaying # itself. class CDATA < Text #:nodoc: def to_s "<![CDATA[#{super}]]>" end end # A Tag is any node that represents markup. It may be an opening tag, a # closing tag, or a self-closing tag. It has a name, and may have a hash of # attributes. class Tag < Node #:nodoc: # Either +nil+, <tt>:close</tt>, or <tt>:self</tt> attr_reader :closing # Either +nil+, or a hash of attributes for this node. attr_reader :attributes # The name of this tag. attr_reader :name # Create a new node as a child of the given parent, using the given content # to describe the node. It will be parsed and the node name, attributes and # closing status extracted. def initialize(parent, line, pos, name, attributes, closing) super(parent, line, pos) @name = name @attributes = attributes @closing = closing end # A convenience for obtaining an attribute of the node. Returns +nil+ if # the node has no attributes. def [](attr) @attributes ? @attributes[attr] : nil end # Returns non-+nil+ if this tag can contain child nodes. def childless?(xml = false) return false if xml && @closing.nil? !@closing.nil? || @name =~ /^(img|br|hr|link|meta|area|base|basefont| col|frame|input|isindex|param)$/ox end # Returns a textual representation of the node def to_s if @closing == :close "</#{@name}>" else s = "<#{@name}" @attributes.each do |k,v| s << " #{k}" s << "=\"#{v}\"" if String === v end s << " /" if @closing == :self s << ">" @children.each { |child| s << child.to_s } s << "</#{@name}>" if @closing != :self && !@children.empty? s end end # If either the node or any of its children meet the given conditions, the # matching node is returned. Otherwise, +nil+ is returned. (See the # description of the valid conditions in the +match+ method.) def find(conditions) match(conditions) && self || super end # Returns +true+, indicating that this node represents an HTML tag. def tag? true end # Returns +true+ if the node meets any of the given conditions. The # +conditions+ parameter must be a hash of any of the following keys # (all are optional): # # * <tt>:tag</tt>: the node name must match the corresponding value # * <tt>:attributes</tt>: a hash. The node's values must match the # corresponding values in the hash. # * <tt>:parent</tt>: a hash. The node's parent must match the # corresponding hash. # * <tt>:child</tt>: a hash. At least one of the node's immediate children # must meet the criteria described by the hash. # * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must # meet the criteria described by the hash. # * <tt>:descendant</tt>: a hash. At least one of the node's descendants # must meet the criteria described by the hash. # * <tt>:sibling</tt>: a hash. At least one of the node's siblings must # meet the criteria described by the hash. # * <tt>:after</tt>: a hash. The node must be after any sibling meeting # the criteria described by the hash, and at least one sibling must match. # * <tt>:before</tt>: a hash. The node must be before any sibling meeting # the criteria described by the hash, and at least one sibling must match. # * <tt>:children</tt>: a hash, for counting children of a node. Accepts the # keys: # ** <tt>:count</tt>: either a number or a range which must equal (or # include) the number of children that match. # ** <tt>:less_than</tt>: the number of matching children must be less than # this number. # ** <tt>:greater_than</tt>: the number of matching children must be # greater than this number. # ** <tt>:only</tt>: another hash consisting of the keys to use # to match on the children, and only matching children will be # counted. # # Conditions are matched using the following algorithm: # # * if the condition is a string, it must be a substring of the value. # * if the condition is a regexp, it must match the value. # * if the condition is a number, the value must match number.to_s. # * if the condition is +true+, the value must not be +nil+. # * if the condition is +false+ or +nil+, the value must be +nil+. # # Usage: # # # test if the node is a "span" tag # node.match :tag => "span" # # # test if the node's parent is a "div" # node.match :parent => { :tag => "div" } # # # test if any of the node's ancestors are "table" tags # node.match :ancestor => { :tag => "table" } # # # test if any of the node's immediate children are "em" tags # node.match :child => { :tag => "em" } # # # test if any of the node's descendants are "strong" tags # node.match :descendant => { :tag => "strong" } # # # test if the node has between 2 and 4 span tags as immediate children # node.match :children => { :count => 2..4, :only => { :tag => "span" } } # # # get funky: test to see if the node is a "div", has a "ul" ancestor # # and an "li" parent (with "class" = "enum"), and whether or not it has # # a "span" descendant that contains # text matching /hello world/: # node.match :tag => "div", # :ancestor => { :tag => "ul" }, # :parent => { :tag => "li", # :attributes => { :class => "enum" } }, # :descendant => { :tag => "span", # :child => /hello world/ } def match(conditions) conditions = validate_conditions(conditions) # check content of child nodes if conditions[:content] if children.empty? return false unless match_condition("", conditions[:content]) else return false unless children.find { |child| child.match(conditions[:content]) } end end # test the name return false unless match_condition(@name, conditions[:tag]) if conditions[:tag] # test attributes (conditions[:attributes] || {}).each do |key, value| return false unless match_condition(self[key], value) end # test parent return false unless parent.match(conditions[:parent]) if conditions[:parent] # test children return false unless children.find { |child| child.match(conditions[:child]) } if conditions[:child] # test ancestors if conditions[:ancestor] return false unless catch :found do p = self throw :found, true if p.match(conditions[:ancestor]) while p = p.parent end end # test descendants if conditions[:descendant] return false unless children.find do |child| # test the child child.match(conditions[:descendant]) || # test the child's descendants child.match(:descendant => conditions[:descendant]) end end # count children if opts = conditions[:children] matches = children.select do |c| (c.kind_of?(HTML::Tag) and (c.closing == :self or ! c.childless?)) end matches = matches.select { |c| c.match(opts[:only]) } if opts[:only] opts.each do |key, value| next if key == :only case key when :count if Integer === value return false if matches.length != value else return false unless value.include?(matches.length) end when :less_than return false unless matches.length < value when :greater_than return false unless matches.length > value else raise "unknown count condition #{key}" end end end # test siblings if conditions[:sibling] || conditions[:before] || conditions[:after] siblings = parent ? parent.children : [] self_index = siblings.index(self) if conditions[:sibling] return false unless siblings.detect do |s| s != self && s.match(conditions[:sibling]) end end if conditions[:before] return false unless siblings[self_index+1..-1].detect do |s| s != self && s.match(conditions[:before]) end end if conditions[:after] return false unless siblings[0,self_index].detect do |s| s != self && s.match(conditions[:after]) end end end true end def ==(node) return false unless super return false unless closing == node.closing && self.name == node.name attributes == node.attributes end private # Match the given value to the given condition. def match_condition(value, condition) case condition when String value && value == condition when Regexp value && value.match(condition) when Numeric value == condition.to_s when true !value.nil? when false, nil value.nil? else false end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
require 'strscan' module HTML #:nodoc: # A simple HTML tokenizer. It simply breaks a stream of text into tokens, where each # token is a string. Each string represents either "text", or an HTML element. # # This currently assumes valid XHTML, which means no free < or > characters. # # Usage: # # tokenizer = HTML::Tokenizer.new(text) # while token = tokenizer.next # p token # end class Tokenizer #:nodoc: # The current (byte) position in the text attr_reader :position # The current line number attr_reader :line # Create a new Tokenizer for the given text. def initialize(text) @scanner = StringScanner.new(text) @position = 0 @line = 0 @current_line = 1 end # Return the next token in the sequence, or +nil+ if there are no more tokens in # the stream. def next return nil if @scanner.eos? @position = @scanner.pos @line = @current_line if @scanner.check(/<\S/) update_current_line(scan_tag) else update_current_line(scan_text) end end private # Treat the text at the current position as a tag, and scan it. Supports # comments, doctype tags, and regular tags, and ignores less-than and # greater-than characters within quoted strings. def scan_tag tag = @scanner.getch if @scanner.scan(/!--/) # comment tag << @scanner.matched tag << (@scanner.scan_until(/--\s*>/) || @scanner.scan_until(/\Z/)) elsif @scanner.scan(/!\[CDATA\[/) tag << @scanner.matched tag << (@scanner.scan_until(/\]\]>/) || @scanner.scan_until(/\Z/)) elsif @scanner.scan(/!/) # doctype tag << @scanner.matched tag << consume_quoted_regions else tag << consume_quoted_regions end tag end # Scan all text up to the next < character and return it. def scan_text "#{@scanner.getch}#{@scanner.scan(/[^<]*/)}" end # Counts the number of newlines in the text and updates the current line # accordingly. def update_current_line(text) text.scan(/\r?\n/) { @current_line += 1 } end # Skips over quoted strings, so that less-than and greater-than characters # within the strings are ignored. def consume_quoted_regions text = "" loop do match = @scanner.scan_until(/['"<>]/) or break delim = @scanner.matched if delim == "<" match = match.chop @scanner.pos -= 1 end text << match break if delim == "<" || delim == ">" # consume the quoted region while match = @scanner.scan_until(/[\\#{delim}]/) text << match break if @scanner.matched == delim text << @scanner.getch # skip the escaped character end end text end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
provider/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
require 'html/tokenizer' require 'html/node' require 'html/selector' require 'html/sanitizer' module HTML #:nodoc: # A top-level HTMl document. You give it a body of text, and it will parse that # text into a tree of nodes. class Document #:nodoc: # The root of the parsed document. attr_reader :root # Create a new Document from the given text. def initialize(text, strict=false, xml=false) tokenizer = Tokenizer.new(text) @root = Node.new(nil) node_stack = [ @root ] while token = tokenizer.next node = Node.parse(node_stack.last, tokenizer.line, tokenizer.position, token, strict) node_stack.last.children << node unless node.tag? && node.closing == :close if node.tag? if node_stack.length > 1 && node.closing == :close if node_stack.last.name == node.name if node_stack.last.children.empty? node_stack.last.children << Text.new(node_stack.last, node.line, node.position, "") end node_stack.pop else open_start = node_stack.last.position - 20 open_start = 0 if open_start < 0 close_start = node.position - 20 close_start = 0 if close_start < 0 msg = <<EOF.strip ignoring attempt to close #{node_stack.last.name} with #{node.name} opened at byte #{node_stack.last.position}, line #{node_stack.last.line} closed at byte #{node.position}, line #{node.line} attributes at open: #{node_stack.last.attributes.inspect} text around open: #{text[open_start,40].inspect} text around close: #{text[close_start,40].inspect} EOF strict ? raise(msg) : warn(msg) end elsif !node.childless?(xml) && node.closing != :close node_stack.push node end end end end # Search the tree for (and return) the first node that matches the given # conditions. The conditions are interpreted differently for different node # types, see HTML::Text#find and HTML::Tag#find. def find(conditions) @root.find(conditions) end # Search the tree for (and return) all nodes that match the given # conditions. The conditions are interpreted differently for different node # types, see HTML::Text#find and HTML::Tag#find. def find_all(conditions) @root.find_all(conditions) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/cgi_ext/query_extension.rb
provider/vendor/rails/actionpack/lib/action_controller/cgi_ext/query_extension.rb
require 'cgi' class CGI #:nodoc: module QueryExtension # Remove the old initialize_query method before redefining it. remove_method :initialize_query # Neuter CGI parameter parsing. def initialize_query # Fix some strange request environments. env_table['REQUEST_METHOD'] ||= 'GET' # POST assumes missing Content-Type is application/x-www-form-urlencoded. if env_table['CONTENT_TYPE'].blank? && env_table['REQUEST_METHOD'] == 'POST' env_table['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' end @cookies = CGI::Cookie::parse(env_table['HTTP_COOKIE'] || env_table['COOKIE']) @params = {} end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/cgi_ext/cookie.rb
provider/vendor/rails/actionpack/lib/action_controller/cgi_ext/cookie.rb
require 'delegate' CGI.module_eval { remove_const "Cookie" } # TODO: document how this differs from stdlib CGI::Cookie class CGI #:nodoc: class Cookie < DelegateClass(Array) attr_accessor :name, :value, :path, :domain, :expires attr_reader :secure, :http_only # Creates a new CGI::Cookie object. # # The contents of the cookie can be specified as a +name+ and one # or more +value+ arguments. Alternatively, the contents can # be specified as a single hash argument. The possible keywords of # this hash are as follows: # # * <tt>:name</tt> - The name of the cookie. Required. # * <tt>:value</tt> - The cookie's value or list of values. # * <tt>:path</tt> - The path for which this cookie applies. Defaults to the # base directory of the CGI script. # * <tt>:domain</tt> - The domain for which this cookie applies. # * <tt>:expires</tt> - The time at which this cookie expires, as a Time object. # * <tt>:secure</tt> - Whether this cookie is a secure cookie or not (defaults to # +false+). Secure cookies are only transmitted to HTTPS servers. # * <tt>:http_only</tt> - Whether this cookie can be accessed by client side scripts (e.g. document.cookie) or only over HTTP. # More details in http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx. Defaults to +false+. # # These keywords correspond to attributes of the cookie object. def initialize(name = '', *value) if name.kind_of?(String) @name = name @value = Array(value) @domain = nil @expires = nil @secure = false @http_only = false @path = nil else @name = name['name'] @value = (name['value'].kind_of?(String) ? [name['value']] : Array(name['value'])).delete_if(&:blank?) @domain = name['domain'] @expires = name['expires'] @secure = name['secure'] || false @http_only = name['http_only'] || false @path = name['path'] end raise ArgumentError, "`name' required" unless @name # simple support for IE unless @path %r|^(.*/)|.match(ENV['SCRIPT_NAME']) @path = ($1 or '') end super(@value) end # Sets whether the Cookie is a secure cookie or not. def secure=(val) @secure = val == true end # Sets whether the Cookie is an HTTP only cookie or not. def http_only=(val) @http_only = val == true end # Converts the Cookie to its string representation. def to_s buf = '' buf << @name << '=' buf << (@value.kind_of?(String) ? CGI::escape(@value) : @value.collect{|v| CGI::escape(v) }.join("&")) buf << '; domain=' << @domain if @domain buf << '; path=' << @path if @path buf << '; expires=' << CGI::rfc1123_date(@expires) if @expires buf << '; secure' if @secure buf << '; HttpOnly' if @http_only buf end # FIXME: work around broken 1.8.7 DelegateClass#respond_to? def respond_to?(method, include_private = false) return true if super(method) return __getobj__.respond_to?(method, include_private) end # Parses a raw cookie string into a hash of <tt>cookie-name => cookie-object</tt> # pairs. # # cookies = CGI::Cookie::parse("raw_cookie_string") # # => { "name1" => cookie1, "name2" => cookie2, ... } # def self.parse(raw_cookie) cookies = Hash.new([]) if raw_cookie raw_cookie.split(/;\s?/).each do |pairs| name, value = pairs.split('=',2) next unless name and value name = CGI::unescape(name) unless cookies.has_key?(name) cookies[name] = new(name, CGI::unescape(value)) end end end cookies end end # class Cookie end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/cgi_ext/stdinput.rb
provider/vendor/rails/actionpack/lib/action_controller/cgi_ext/stdinput.rb
require 'cgi' module ActionController module CgiExt # Publicize the CGI's internal input stream so we can lazy-read # request.body. Make it writable so we don't have to play $stdin games. module Stdinput def self.included(base) base.class_eval do remove_method :stdinput attr_accessor :stdinput end base.alias_method_chain :initialize, :stdinput end def initialize_with_stdinput(type = nil, stdinput = $stdin) @stdinput = stdinput @stdinput.set_encoding(Encoding::BINARY) if @stdinput.respond_to?(:set_encoding) initialize_without_stdinput(type || 'query') end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/assertions/dom_assertions.rb
provider/vendor/rails/actionpack/lib/action_controller/assertions/dom_assertions.rb
module ActionController module Assertions module DomAssertions # Test two HTML strings for equivalency (e.g., identical up to reordering of attributes) # # ==== Examples # # # assert that the referenced method generates the appropriate HTML string # assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com") # def assert_dom_equal(expected, actual, message = "") clean_backtrace do expected_dom = HTML::Document.new(expected).root actual_dom = HTML::Document.new(actual).root full_message = build_message(message, "<?> expected to be == to\n<?>.", expected_dom.to_s, actual_dom.to_s) assert_block(full_message) { expected_dom == actual_dom } end end # The negated form of +assert_dom_equivalent+. # # ==== Examples # # # assert that the referenced method does not generate the specified HTML string # assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com") # def assert_dom_not_equal(expected, actual, message = "") clean_backtrace do expected_dom = HTML::Document.new(expected).root actual_dom = HTML::Document.new(actual).root full_message = build_message(message, "<?> expected to be != to\n<?>.", expected_dom.to_s, actual_dom.to_s) assert_block(full_message) { expected_dom != actual_dom } end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/assertions/tag_assertions.rb
provider/vendor/rails/actionpack/lib/action_controller/assertions/tag_assertions.rb
module ActionController module Assertions # Pair of assertions to testing elements in the HTML output of the response. module TagAssertions # Asserts that there is a tag/node/element in the body of the response # that meets all of the given conditions. The +conditions+ parameter must # be a hash of any of the following keys (all are optional): # # * <tt>:tag</tt>: the node type must match the corresponding value # * <tt>:attributes</tt>: a hash. The node's attributes must match the # corresponding values in the hash. # * <tt>:parent</tt>: a hash. The node's parent must match the # corresponding hash. # * <tt>:child</tt>: a hash. At least one of the node's immediate children # must meet the criteria described by the hash. # * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must # meet the criteria described by the hash. # * <tt>:descendant</tt>: a hash. At least one of the node's descendants # must meet the criteria described by the hash. # * <tt>:sibling</tt>: a hash. At least one of the node's siblings must # meet the criteria described by the hash. # * <tt>:after</tt>: a hash. The node must be after any sibling meeting # the criteria described by the hash, and at least one sibling must match. # * <tt>:before</tt>: a hash. The node must be before any sibling meeting # the criteria described by the hash, and at least one sibling must match. # * <tt>:children</tt>: a hash, for counting children of a node. Accepts # the keys: # * <tt>:count</tt>: either a number or a range which must equal (or # include) the number of children that match. # * <tt>:less_than</tt>: the number of matching children must be less # than this number. # * <tt>:greater_than</tt>: the number of matching children must be # greater than this number. # * <tt>:only</tt>: another hash consisting of the keys to use # to match on the children, and only matching children will be # counted. # * <tt>:content</tt>: the textual content of the node must match the # given value. This will not match HTML tags in the body of a # tag--only text. # # Conditions are matched using the following algorithm: # # * if the condition is a string, it must be a substring of the value. # * if the condition is a regexp, it must match the value. # * if the condition is a number, the value must match number.to_s. # * if the condition is +true+, the value must not be +nil+. # * if the condition is +false+ or +nil+, the value must be +nil+. # # === Examples # # # Assert that there is a "span" tag # assert_tag :tag => "span" # # # Assert that there is a "span" tag with id="x" # assert_tag :tag => "span", :attributes => { :id => "x" } # # # Assert that there is a "span" tag using the short-hand # assert_tag :span # # # Assert that there is a "span" tag with id="x" using the short-hand # assert_tag :span, :attributes => { :id => "x" } # # # Assert that there is a "span" inside of a "div" # assert_tag :tag => "span", :parent => { :tag => "div" } # # # Assert that there is a "span" somewhere inside a table # assert_tag :tag => "span", :ancestor => { :tag => "table" } # # # Assert that there is a "span" with at least one "em" child # assert_tag :tag => "span", :child => { :tag => "em" } # # # Assert that there is a "span" containing a (possibly nested) # # "strong" tag. # assert_tag :tag => "span", :descendant => { :tag => "strong" } # # # Assert that there is a "span" containing between 2 and 4 "em" tags # # as immediate children # assert_tag :tag => "span", # :children => { :count => 2..4, :only => { :tag => "em" } } # # # Get funky: assert that there is a "div", with an "ul" ancestor # # and an "li" parent (with "class" = "enum"), and containing a # # "span" descendant that contains text matching /hello world/ # assert_tag :tag => "div", # :ancestor => { :tag => "ul" }, # :parent => { :tag => "li", # :attributes => { :class => "enum" } }, # :descendant => { :tag => "span", # :child => /hello world/ } # # <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work # with well-formed XHTML. They recognize a few tags as implicitly self-closing # (like br and hr and such) but will not work correctly with tags # that allow optional closing tags (p, li, td). <em>You must explicitly # close all of your tags to use these assertions.</em> def assert_tag(*opts) clean_backtrace do opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first tag = find_tag(opts) assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}" end end # Identical to +assert_tag+, but asserts that a matching tag does _not_ # exist. (See +assert_tag+ for a full discussion of the syntax.) # # === Examples # # Assert that there is not a "div" containing a "p" # assert_no_tag :tag => "div", :descendant => { :tag => "p" } # # # Assert that an unordered list is empty # assert_no_tag :tag => "ul", :descendant => { :tag => "li" } # # # Assert that there is not a "p" tag with between 1 to 3 "img" tags # # as immediate children # assert_no_tag :tag => "p", # :children => { :count => 1..3, :only => { :tag => "img" } } def assert_no_tag(*opts) clean_backtrace do opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first tag = find_tag(opts) assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}" end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/assertions/model_assertions.rb
provider/vendor/rails/actionpack/lib/action_controller/assertions/model_assertions.rb
module ActionController module Assertions module ModelAssertions # Ensures that the passed record is valid by Active Record standards and # returns any error messages if it is not. # # ==== Examples # # # assert that a newly created record is valid # model = Model.new # assert_valid(model) # def assert_valid(record) ::ActiveSupport::Deprecation.warn("assert_valid is deprecated. Use assert record.valid? instead", caller) clean_backtrace do assert record.valid?, record.errors.full_messages.join("\n") end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb
provider/vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb
#-- # Copyright (c) 2006 Assaf Arkin (http://labnotes.org) # Under MIT and/or CC By license. #++ module ActionController module Assertions unless const_defined?(:NO_STRIP) NO_STRIP = %w{pre script style textarea} end # Adds the +assert_select+ method for use in Rails functional # test cases, which can be used to make assertions on the response HTML of a controller # action. You can also call +assert_select+ within another +assert_select+ to # make assertions on elements selected by the enclosing assertion. # # Use +css_select+ to select elements without making an assertions, either # from the response HTML or elements selected by the enclosing assertion. # # In addition to HTML responses, you can make the following assertions: # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations. # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions. # * +assert_select_email+ - Assertions on the HTML body of an e-mail. # # Also see HTML::Selector to learn how to use selectors. module SelectorAssertions # :call-seq: # css_select(selector) => array # css_select(element, selector) => array # # Select and return all matching elements. # # If called with a single argument, uses that argument as a selector # to match all elements of the current page. Returns an empty array # if no match is found. # # If called with two arguments, uses the first argument as the base # element and the second argument as the selector. Attempts to match the # base element and any of its children. Returns an empty array if no # match is found. # # The selector may be a CSS selector expression (String), an expression # with substitution values (Array) or an HTML::Selector object. # # ==== Examples # # Selects all div tags # divs = css_select("div") # # # Selects all paragraph tags and does something interesting # pars = css_select("p") # pars.each do |par| # # Do something fun with paragraphs here... # end # # # Selects all list items in unordered lists # items = css_select("ul>li") # # # Selects all form tags and then all inputs inside the form # forms = css_select("form") # forms.each do |form| # inputs = css_select(form, "input") # ... # end # def css_select(*args) # See assert_select to understand what's going on here. arg = args.shift if arg.is_a?(HTML::Node) root = arg arg = args.shift elsif arg == nil raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?" elsif @selected matches = [] @selected.each do |selected| subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup)) subset.each do |match| matches << match unless matches.any? { |m| m.equal?(match) } end end return matches else root = response_from_page_or_rjs end case arg when String selector = HTML::Selector.new(arg, args) when Array selector = HTML::Selector.new(*arg) when HTML::Selector selector = arg else raise ArgumentError, "Expecting a selector as the first argument" end selector.select(root) end # :call-seq: # assert_select(selector, equality?, message?) # assert_select(element, selector, equality?, message?) # # An assertion that selects elements and makes one or more equality tests. # # If the first argument is an element, selects all matching elements # starting from (and including) that element and all its children in # depth-first order. # # If no element if specified, calling +assert_select+ selects from the # response HTML unless +assert_select+ is called from within an +assert_select+ block. # # When called with a block +assert_select+ passes an array of selected elements # to the block. Calling +assert_select+ from the block, with no element specified, # runs the assertion on the complete set of elements selected by the enclosing assertion. # Alternatively the array may be iterated through so that +assert_select+ can be called # separately for each element. # # # ==== Example # If the response contains two ordered lists, each with four list elements then: # assert_select "ol" do |elements| # elements.each do |element| # assert_select element, "li", 4 # end # end # # will pass, as will: # assert_select "ol" do # assert_select "li", 8 # end # # The selector may be a CSS selector expression (String), an expression # with substitution values, or an HTML::Selector object. # # === Equality Tests # # The equality test may be one of the following: # * <tt>true</tt> - Assertion is true if at least one element selected. # * <tt>false</tt> - Assertion is true if no element selected. # * <tt>String/Regexp</tt> - Assertion is true if the text value of at least # one element matches the string or regular expression. # * <tt>Integer</tt> - Assertion is true if exactly that number of # elements are selected. # * <tt>Range</tt> - Assertion is true if the number of selected # elements fit the range. # If no equality test specified, the assertion is true if at least one # element selected. # # To perform more than one equality tests, use a hash with the following keys: # * <tt>:text</tt> - Narrow the selection to elements that have this text # value (string or regexp). # * <tt>:html</tt> - Narrow the selection to elements that have this HTML # content (string or regexp). # * <tt>:count</tt> - Assertion is true if the number of selected elements # is equal to this value. # * <tt>:minimum</tt> - Assertion is true if the number of selected # elements is at least this value. # * <tt>:maximum</tt> - Assertion is true if the number of selected # elements is at most this value. # # If the method is called with a block, once all equality tests are # evaluated the block is called with an array of all matched elements. # # ==== Examples # # # At least one form element # assert_select "form" # # # Form element includes four input fields # assert_select "form input", 4 # # # Page title is "Welcome" # assert_select "title", "Welcome" # # # Page title is "Welcome" and there is only one title element # assert_select "title", {:count=>1, :text=>"Welcome"}, # "Wrong title or more than one title element" # # # Page contains no forms # assert_select "form", false, "This page must contain no forms" # # # Test the content and style # assert_select "body div.header ul.menu" # # # Use substitution values # assert_select "ol>li#?", /item-\d+/ # # # All input fields in the form have a name # assert_select "form input" do # assert_select "[name=?]", /.+/ # Not empty # end def assert_select(*args, &block) # Start with optional element followed by mandatory selector. arg = args.shift if arg.is_a?(HTML::Node) # First argument is a node (tag or text, but also HTML root), # so we know what we're selecting from. root = arg arg = args.shift elsif arg == nil # This usually happens when passing a node/element that # happens to be nil. raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?" elsif @selected root = HTML::Node.new(nil) root.children.concat @selected else # Otherwise just operate on the response document. root = response_from_page_or_rjs end # First or second argument is the selector: string and we pass # all remaining arguments. Array and we pass the argument. Also # accepts selector itself. case arg when String selector = HTML::Selector.new(arg, args) when Array selector = HTML::Selector.new(*arg) when HTML::Selector selector = arg else raise ArgumentError, "Expecting a selector as the first argument" end # Next argument is used for equality tests. equals = {} case arg = args.shift when Hash equals = arg when String, Regexp equals[:text] = arg when Integer equals[:count] = arg when Range equals[:minimum] = arg.begin equals[:maximum] = arg.end when FalseClass equals[:count] = 0 when NilClass, TrueClass equals[:minimum] = 1 else raise ArgumentError, "I don't understand what you're trying to match" end # By default we're looking for at least one match. if equals[:count] equals[:minimum] = equals[:maximum] = equals[:count] else equals[:minimum] = 1 unless equals[:minimum] end # Last argument is the message we use if the assertion fails. message = args.shift #- message = "No match made with selector #{selector.inspect}" unless message if args.shift raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type" end matches = selector.select(root) # If text/html, narrow down to those elements that match it. content_mismatch = nil if match_with = equals[:text] matches.delete_if do |match| text = "" text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding) stack = match.children.reverse while node = stack.pop if node.tag? stack.concat node.children.reverse else content = node.content content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding) text << content end end text.strip! unless NO_STRIP.include?(match.name) unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text) true end end elsif match_with = equals[:html] matches.delete_if do |match| html = match.children.map(&:to_s).join html.strip! unless NO_STRIP.include?(match.name) unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s) content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html) true end end end # Expecting foo found bar element only if found zero, not if # found one but expecting two. message ||= content_mismatch if matches.empty? # Test minimum/maximum occurrence. min, max = equals[:minimum], equals[:maximum] message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.) assert matches.size >= min, message if min assert matches.size <= max, message if max # If a block is given call that block. Set @selected to allow # nested assert_select, which can be nested several levels deep. if block_given? && !matches.empty? begin in_scope, @selected = @selected, matches yield matches ensure @selected = in_scope end end # Returns all matches elements. matches end def count_description(min, max) #:nodoc: pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')} if min && max && (max != min) "between #{min} and #{max} elements" elsif min && !(min == 1 && max == 1) "at least #{min} #{pluralize['element', min]}" elsif max "at most #{max} #{pluralize['element', max]}" end end # :call-seq: # assert_select_rjs(id?) { |elements| ... } # assert_select_rjs(statement, id?) { |elements| ... } # assert_select_rjs(:insert, position, id?) { |elements| ... } # # Selects content from the RJS response. # # === Narrowing down # # With no arguments, asserts that one or more elements are updated or # inserted by RJS statements. # # Use the +id+ argument to narrow down the assertion to only statements # that update or insert an element with that identifier. # # Use the first argument to narrow down assertions to only statements # of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>, # <tt>:show</tt>, <tt>:hide</tt>, <tt>:toggle</tt>, <tt>:remove</tt> and # <tt>:insert_html</tt>. # # Use the argument <tt>:insert</tt> followed by an insertion position to narrow # down the assertion to only statements that insert elements in that # position. Possible values are <tt>:top</tt>, <tt>:bottom</tt>, <tt>:before</tt> # and <tt>:after</tt>. # # Using the <tt>:remove</tt> statement, you will be able to pass a block, but it will # be ignored as there is no HTML passed for this statement. # # === Using blocks # # Without a block, +assert_select_rjs+ merely asserts that the response # contains one or more RJS statements that replace or update content. # # With a block, +assert_select_rjs+ also selects all elements used in # these statements and passes them to the block. Nested assertions are # supported. # # Calling +assert_select_rjs+ with no arguments and using nested asserts # asserts that the HTML content is returned by one or more RJS statements. # Using +assert_select+ directly makes the same assertion on the content, # but without distinguishing whether the content is returned in an HTML # or JavaScript. # # ==== Examples # # # Replacing the element foo. # # page.replace 'foo', ... # assert_select_rjs :replace, "foo" # # # Replacing with the chained RJS proxy. # # page[:foo].replace ... # assert_select_rjs :chained_replace, 'foo' # # # Inserting into the element bar, top position. # assert_select_rjs :insert, :top, "bar" # # # Remove the element bar # assert_select_rjs :remove, "bar" # # # Changing the element foo, with an image. # assert_select_rjs "foo" do # assert_select "img[src=/images/logo.gif"" # end # # # RJS inserts or updates a list with four items. # assert_select_rjs do # assert_select "ol>li", 4 # end # # # The same, but shorter. # assert_select "ol>li", 4 def assert_select_rjs(*args, &block) rjs_type = args.first.is_a?(Symbol) ? args.shift : nil id = args.first.is_a?(String) ? args.shift : nil # If the first argument is a symbol, it's the type of RJS statement we're looking # for (update, replace, insertion, etc). Otherwise, we're looking for just about # any RJS statement. if rjs_type if rjs_type == :insert position = args.shift id = args.shift insertion = "insert_#{position}".to_sym raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion] statement = "(#{RJS_STATEMENTS[insertion]})" else raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type] statement = "(#{RJS_STATEMENTS[rjs_type]})" end else statement = "#{RJS_STATEMENTS[:any]}" end # Next argument we're looking for is the element identifier. If missing, we pick # any element, otherwise we replace it in the statement. pattern = Regexp.new( id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement ) # Duplicate the body since the next step involves destroying it. matches = nil case rjs_type when :remove, :show, :hide, :toggle matches = @response.body.match(pattern) else @response.body.gsub(pattern) do |match| html = unescape_rjs(match) matches ||= [] matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? } "" end end if matches assert_block("") { true } # to count the assertion if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type) begin in_scope, @selected = @selected, matches yield matches ensure @selected = in_scope end end matches else # RJS statement not found. case rjs_type when :remove, :show, :hide, :toggle flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered." else flunk_message = "No RJS statement that replaces or inserts HTML content." end flunk args.shift || flunk_message end end # :call-seq: # assert_select_encoded(element?) { |elements| ... } # # Extracts the content of an element, treats it as encoded HTML and runs # nested assertion on it. # # You typically call this method within another assertion to operate on # all currently selected elements. You can also pass an element or array # of elements. # # The content of each element is un-encoded, and wrapped in the root # element +encoded+. It then calls the block with all un-encoded elements. # # ==== Examples # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix) # assert_select_feed :atom, 1.0 do # # Select each entry item and then the title item # assert_select "entry>title" do # # Run assertions on the encoded title elements # assert_select_encoded do # assert_select "b" # end # end # end # # # # Selects all paragraph tags from within the description of an RSS feed # assert_select_feed :rss, 2.0 do # # Select description element of each feed item. # assert_select "channel>item>description" do # # Run assertions on the encoded elements. # assert_select_encoded do # assert_select "p" # end # end # end def assert_select_encoded(element = nil, &block) case element when Array elements = element when HTML::Node elements = [element] when nil unless elements = @selected raise ArgumentError, "First argument is optional, but must be called from a nested assert_select" end else raise ArgumentError, "Argument is optional, and may be node or array of nodes" end fix_content = lambda do |node| # Gets around a bug in the Rails 1.1 HTML parser. node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) } end selected = elements.map do |element| text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root css_select(root, "encoded:root", &block)[0] end begin old_selected, @selected = @selected, selected assert_select ":root", &block ensure @selected = old_selected end end # :call-seq: # assert_select_email { } # # Extracts the body of an email and runs nested assertions on it. # # You must enable deliveries for this assertion to work, use: # ActionMailer::Base.perform_deliveries = true # # ==== Examples # # assert_select_email do # assert_select "h1", "Email alert" # end # # assert_select_email do # items = assert_select "ol>li" # items.each do # # Work with items here... # end # end # def assert_select_email(&block) deliveries = ActionMailer::Base.deliveries assert !deliveries.empty?, "No e-mail in delivery list" for delivery in deliveries for part in delivery.parts if part["Content-Type"].to_s =~ /^text\/html\W/ root = HTML::Document.new(part.body).root assert_select root, ":root", &block end end end end protected unless const_defined?(:RJS_STATEMENTS) RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\"" RJS_ANY_ID = "\"([^\"])*\"" RJS_STATEMENTS = { :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)", :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)", :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)", :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)" } [:remove, :show, :hide, :toggle].each do |action| RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)" end RJS_INSERTIONS = ["top", "bottom", "before", "after"] RJS_INSERTIONS.each do |insertion| RJS_STATEMENTS["insert_#{insertion}".to_sym] = "Element.insert\\(#{RJS_ANY_ID}, \\{ #{insertion}: #{RJS_PATTERN_HTML} \\}\\)" end RJS_STATEMENTS[:insert_html] = "Element.insert\\(#{RJS_ANY_ID}, \\{ (#{RJS_INSERTIONS.join('|')}): #{RJS_PATTERN_HTML} \\}\\)" RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})") RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/ end # +assert_select+ and +css_select+ call this to obtain the content in the HTML # page, or from all the RJS statements, depending on the type of response. def response_from_page_or_rjs() content_type = @response.content_type if content_type && Mime::JS =~ content_type body = @response.body.dup root = HTML::Node.new(nil) while true next if body.sub!(RJS_STATEMENTS[:any]) do |match| html = unescape_rjs(match) matches = HTML::Document.new(html).root.children.select { |n| n.tag? } root.children.concat matches "" end break end root else html_document.root end end # Unescapes a RJS string. def unescape_rjs(rjs_string) # RJS encodes double quotes and line breaks. unescaped= rjs_string.gsub('\"', '"') unescaped.gsub!(/\\\//, '/') unescaped.gsub!('\n', "\n") unescaped.gsub!('\076', '>') unescaped.gsub!('\074', '<') # RJS encodes non-ascii characters. unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')} unescaped end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/assertions/routing_assertions.rb
provider/vendor/rails/actionpack/lib/action_controller/assertions/routing_assertions.rb
module ActionController module Assertions # Suite of assertions to test routes generated by Rails and the handling of requests made to them. module RoutingAssertions # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash) # match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+. # # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes # requiring a specific HTTP method. The hash should contain a :path with the incoming request path # and a :method containing the required HTTP verb. # # # assert that POSTing to /items will call the create action on ItemsController # assert_recognizes {:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post} # # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the # extras argument, appending the query string on the path directly will not work. For example: # # # assert that a path of '/items/list/1?view=print' returns the correct options # assert_recognizes {:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" } # # The +message+ parameter allows you to pass in an error message that is displayed upon failure. # # ==== Examples # # Check the default route (i.e., the index action) # assert_recognizes {:controller => 'items', :action => 'index'}, 'items' # # # Test a specific action # assert_recognizes {:controller => 'items', :action => 'list'}, 'items/list' # # # Test an action with a parameter # assert_recognizes {:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1' # # # Test a custom route # assert_recognizes {:controller => 'items', :action => 'show', :id => '1'}, 'view/item1' # # # Check a Simply RESTful generated route # assert_recognizes list_items_url, 'items/list' def assert_recognizes(expected_options, path, extras={}, message=nil) if path.is_a? Hash request_method = path[:method] path = path[:path] else request_method = nil end clean_backtrace do ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? request = recognized_request_for(path, request_method) expected_options = expected_options.clone extras.each_key { |key| expected_options.delete key } unless extras.nil? expected_options.stringify_keys! routing_diff = expected_options.diff(request.path_parameters) msg = build_message(message, "The recognized options <?> did not match <?>, difference: <?>", request.path_parameters, expected_options, expected_options.diff(request.path_parameters)) assert_block(msg) { request.path_parameters == expected_options } end end # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+. # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures. # # The +defaults+ parameter is unused. # # ==== Examples # # Asserts that the default action is generated for a route with no action # assert_generates "/items", :controller => "items", :action => "index" # # # Tests that the list action is properly routed # assert_generates "/items/list", :controller => "items", :action => "list" # # # Tests the generation of a route with a parameter # assert_generates "/items/list/1", { :controller => "items", :action => "list", :id => "1" } # # # Asserts that the generated route gives us our custom route # assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" } def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) clean_backtrace do expected_path = "/#{expected_path}" unless expected_path[0] == ?/ # Load routes.rb if it hasn't been loaded. ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults) found_extras = options.reject {|k, v| ! extra_keys.include? k} msg = build_message(message, "found extras <?>, not <?>", found_extras, extras) assert_block(msg) { found_extras == extras } msg = build_message(message, "The generated path <?> did not match <?>", generated_path, expected_path) assert_block(msg) { expected_path == generated_path } end end # Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates # <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+ # and +assert_generates+ into one step. # # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The # +message+ parameter allows you to specify a custom error message to display upon failure. # # ==== Examples # # Assert a basic route: a controller with the default action (index) # assert_routing '/home', :controller => 'home', :action => 'index' # # # Test a route generated with a specific controller, action, and parameter (id) # assert_routing '/entries/show/23', :controller => 'entries', :action => 'show', id => 23 # # # Assert a basic route (controller + default action), with an error message if it fails # assert_routing '/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly' # # # Tests a route, providing a defaults hash # assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"} # # # Tests a route with a HTTP method # assert_routing { :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" } def assert_routing(path, options, defaults={}, extras={}, message=nil) assert_recognizes(options, path, extras, message) controller, default_controller = options[:controller], defaults[:controller] if controller && controller.include?(?/) && default_controller && default_controller.include?(?/) options[:controller] = "/#{controller}" end assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message) end private # Recognizes the route for a given path. def recognized_request_for(path, request_method = nil) path = "/#{path}" unless path.first == '/' # Assume given controller request = ActionController::TestRequest.new request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method request.path = path ActionController::Routing::Routes.recognize(request) request end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/assertions/response_assertions.rb
provider/vendor/rails/actionpack/lib/action_controller/assertions/response_assertions.rb
module ActionController module Assertions # A small suite of assertions that test responses from Rails applications. module ResponseAssertions # Asserts that the response is one of the following types: # # * <tt>:success</tt> - Status code was 200 # * <tt>:redirect</tt> - Status code was in the 300-399 range # * <tt>:missing</tt> - Status code was 404 # * <tt>:error</tt> - Status code was in the 500-599 range # # You can also pass an explicit status number like assert_response(501) # or its symbolic equivalent assert_response(:not_implemented). # See ActionController::StatusCodes for a full list. # # ==== Examples # # # assert that the response was a redirection # assert_response :redirect # # # assert that the response code was status code 401 (unauthorized) # assert_response 401 # def assert_response(type, message = nil) clean_backtrace do if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?") assert_block("") { true } # to count the assertion elsif type.is_a?(Fixnum) && @response.response_code == type assert_block("") { true } # to count the assertion elsif type.is_a?(Symbol) && @response.response_code == ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE[type] assert_block("") { true } # to count the assertion else if @response.error? exception = @response.template.instance_variable_get(:@exception) exception_message = exception && exception.message assert_block(build_message(message, "Expected response to be a <?>, but was <?>\n<?>", type, @response.response_code, exception_message.to_s)) { false } else assert_block(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code)) { false } end end end end # Assert that the redirection options passed in match those of the redirect called in the latest action. # This match can be partial, such that assert_redirected_to(:controller => "weblog") will also # match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on. # # ==== Examples # # # assert that the redirection was to the "index" action on the WeblogController # assert_redirected_to :controller => "weblog", :action => "index" # # # assert that the redirection was to the named route login_url # assert_redirected_to login_url # # # assert that the redirection was to the url for @customer # assert_redirected_to @customer # def assert_redirected_to(options = {}, message=nil) clean_backtrace do assert_response(:redirect, message) return true if options == @response.redirected_to # Support partial arguments for hash redirections if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash) if options.all? {|(key, value)| @response.redirected_to[key] == value} callstack = caller.dup callstack.slice!(0, 2) ::ActiveSupport::Deprecation.warn("Using assert_redirected_to with partial hash arguments is deprecated. Specify the full set arguments instead", callstack) return true end end redirected_to_after_normalisation = normalize_argument_to_redirection(@response.redirected_to) options_after_normalisation = normalize_argument_to_redirection(options) if redirected_to_after_normalisation != options_after_normalisation flunk "Expected response to be a redirect to <#{options_after_normalisation}> but was a redirect to <#{redirected_to_after_normalisation}>" end end end # Asserts that the request was rendered with the appropriate template file or partials # # ==== Examples # # # assert that the "new" view template was rendered # assert_template "new" # # # assert that the "new" view template was rendered with Symbol # assert_template :new # # # assert that the "_customer" partial was rendered twice # assert_template :partial => '_customer', :count => 2 # # # assert that no partials were rendered # assert_template :partial => false # def assert_template(options = {}, message = nil) clean_backtrace do case options when NilClass, String, Symbol rendered = @response.rendered[:template].to_s msg = build_message(message, "expecting <?> but rendering with <?>", options, rendered) assert_block(msg) do if options.nil? @response.rendered[:template].blank? else rendered.to_s.match(options.to_s) end end when Hash if expected_partial = options[:partial] partials = @response.rendered[:partials] if expected_count = options[:count] found = partials.detect { |p, _| p.to_s.match(expected_partial) } actual_count = found.nil? ? 0 : found.second msg = build_message(message, "expecting ? to be rendered ? time(s) but rendered ? time(s)", expected_partial, expected_count, actual_count) assert(actual_count == expected_count.to_i, msg) else msg = build_message(message, "expecting partial <?> but action rendered <?>", options[:partial], partials.keys) assert(partials.keys.any? { |p| p.to_s.match(expected_partial) }, msg) end else assert @response.rendered[:partials].empty?, "Expected no partials to be rendered" end else raise ArgumentError end end end private # Proxy to to_param if the object will respond to it. def parameterize(value) value.respond_to?(:to_param) ? value.to_param : value end def normalize_argument_to_redirection(fragment) after_routing = @controller.url_for(fragment) if after_routing =~ %r{^\w+://.*} after_routing else # FIXME - this should probably get removed. if after_routing.first != '/' after_routing = '/' + after_routing end @request.protocol + @request.host_with_port + after_routing end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb
provider/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb
begin require_library_or_gem 'memcache' module ActionController module Session class MemCacheStore < AbstractStore def initialize(app, options = {}) # Support old :expires option options[:expire_after] ||= options[:expires] super @default_options = { :namespace => 'rack:session', :memcache_server => 'localhost:11211' }.merge(@default_options) @pool = options[:cache] || MemCache.new(@default_options[:memcache_server], @default_options) unless @pool.servers.any? { |s| s.alive? } raise "#{self} unable to find server during initialization." end @mutex = Mutex.new super end private def get_session(env, sid) sid ||= generate_sid begin session = @pool.get(sid) || {} rescue MemCache::MemCacheError, Errno::ECONNREFUSED session = {} end [sid, session] end def set_session(env, sid, session_data) options = env['rack.session.options'] expiry = options[:expire_after] || 0 @pool.set(sid, session_data, expiry) return true rescue MemCache::MemCacheError, Errno::ECONNREFUSED return false end end end end rescue LoadError # MemCache wasn't available so neither can the store be end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/session/abstract_store.rb
provider/vendor/rails/actionpack/lib/action_controller/session/abstract_store.rb
require 'rack/utils' module ActionController module Session class AbstractStore ENV_SESSION_KEY = 'rack.session'.freeze ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze HTTP_COOKIE = 'HTTP_COOKIE'.freeze SET_COOKIE = 'Set-Cookie'.freeze class SessionHash < Hash def initialize(by, env) super() @by = by @env = env @loaded = false end def session_id ActiveSupport::Deprecation.warn( "ActionController::Session::AbstractStore::SessionHash#session_id " + "has been deprecated. Please use request.session_options[:id] instead.", caller) @env[ENV_SESSION_OPTIONS_KEY][:id] end def [](key) load! unless @loaded super end def []=(key, value) load! unless @loaded super end def to_hash h = {}.replace(self) h.delete_if { |k,v| v.nil? } h end def data ActiveSupport::Deprecation.warn( "ActionController::Session::AbstractStore::SessionHash#data " + "has been deprecated. Please use #to_hash instead.", caller) to_hash end def inspect load! unless @loaded super end private def loaded? @loaded end def load! stale_session_check! do id, session = @by.send(:load_session, @env) (@env[ENV_SESSION_OPTIONS_KEY] ||= {})[:id] = id replace(session) @loaded = true end end def stale_session_check! yield rescue ArgumentError => argument_error if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} begin # Note that the regexp does not allow $1 to end with a ':' $1.constantize rescue LoadError, NameError => const_error raise ActionController::SessionRestoreError, "Session contains objects whose class definition isn\\'t available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: \#{const_error.message} [\#{const_error.class}])\n" end retry else raise end end end DEFAULT_OPTIONS = { :key => '_session_id', :path => '/', :domain => nil, :expire_after => nil, :secure => false, :httponly => true, :cookie_only => true } def initialize(app, options = {}) # Process legacy CGI options options = options.symbolize_keys if options.has_key?(:session_path) options[:path] = options.delete(:session_path) end if options.has_key?(:session_key) options[:key] = options.delete(:session_key) end if options.has_key?(:session_http_only) options[:httponly] = options.delete(:session_http_only) end @app = app @default_options = DEFAULT_OPTIONS.merge(options) @key = @default_options[:key] @cookie_only = @default_options[:cookie_only] end def call(env) session = SessionHash.new(self, env) env[ENV_SESSION_KEY] = session env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup response = @app.call(env) session_data = env[ENV_SESSION_KEY] options = env[ENV_SESSION_OPTIONS_KEY] if !session_data.is_a?(AbstractStore::SessionHash) || session_data.send(:loaded?) || options[:expire_after] session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.send(:loaded?) sid = options[:id] || generate_sid unless set_session(env, sid, session_data.to_hash) return response end cookie = Rack::Utils.escape(@key) + '=' + Rack::Utils.escape(sid) cookie << "; domain=#{options[:domain]}" if options[:domain] cookie << "; path=#{options[:path]}" if options[:path] if options[:expire_after] expiry = Time.now + options[:expire_after] cookie << "; expires=#{expiry.httpdate}" end cookie << "; Secure" if options[:secure] cookie << "; HttpOnly" if options[:httponly] headers = response[1] unless headers[SET_COOKIE].blank? headers[SET_COOKIE] << "\n#{cookie}" else headers[SET_COOKIE] = cookie end end response end private def generate_sid ActiveSupport::SecureRandom.hex(16) end def load_session(env) request = Rack::Request.new(env) sid = request.cookies[@key] unless @cookie_only sid ||= request.params[@key] end sid, session = get_session(env, sid) [sid, session] end def get_session(env, sid) raise '#get_session needs to be implemented.' end def set_session(env, sid, session_data) raise '#set_session needs to be implemented.' end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/session/cookie_store.rb
provider/vendor/rails/actionpack/lib/action_controller/session/cookie_store.rb
module ActionController module Session # This cookie-based session store is the Rails default. Sessions typically # contain at most a user_id and flash message; both fit within the 4K cookie # size limit. Cookie-based sessions are dramatically faster than the # alternatives. # # If you have more than 4K of session data or don't want your data to be # visible to the user, pick another session store. # # CookieOverflow is raised if you attempt to store more than 4K of data. # # A message digest is included with the cookie to ensure data integrity: # a user cannot alter his +user_id+ without knowing the secret key # included in the hash. New apps are generated with a pregenerated secret # in config/environment.rb. Set your own for old apps you're upgrading. # # Session options: # # * <tt>:secret</tt>: An application-wide key string or block returning a # string called per generated digest. The block is called with the # CGI::Session instance as an argument. It's important that the secret # is not vulnerable to a dictionary attack. Therefore, you should choose # a secret consisting of random numbers and letters and more than 30 # characters. Examples: # # :secret => '449fe2e7daee471bffae2fd8dc02313d' # :secret => Proc.new { User.current_user.secret_key } # # * <tt>:digest</tt>: The message digest algorithm used to verify session # integrity defaults to 'SHA1' but may be any digest provided by OpenSSL, # such as 'MD5', 'RIPEMD160', 'SHA256', etc. # # To generate a secret key for an existing application, run # "rake secret" and set the key in config/environment.rb. # # Note that changing digest or secret invalidates all existing sessions! class CookieStore # Cookies can typically store 4096 bytes. MAX = 4096 SECRET_MIN_LENGTH = 30 # characters DEFAULT_OPTIONS = { :key => '_session_id', :domain => nil, :path => "/", :expire_after => nil, :httponly => true }.freeze ENV_SESSION_KEY = "rack.session".freeze ENV_SESSION_OPTIONS_KEY = "rack.session.options".freeze HTTP_SET_COOKIE = "Set-Cookie".freeze # Raised when storing more than 4K of session data. class CookieOverflow < StandardError; end def initialize(app, options = {}) # Process legacy CGI options options = options.symbolize_keys if options.has_key?(:session_path) options[:path] = options.delete(:session_path) end if options.has_key?(:session_key) options[:key] = options.delete(:session_key) end if options.has_key?(:session_http_only) options[:httponly] = options.delete(:session_http_only) end @app = app # The session_key option is required. ensure_session_key(options[:key]) @key = options.delete(:key).freeze # The secret option is required. ensure_secret_secure(options[:secret]) @secret = options.delete(:secret).freeze @digest = options.delete(:digest) || 'SHA1' @verifier = verifier_for(@secret, @digest) @default_options = DEFAULT_OPTIONS.merge(options).freeze freeze end def call(env) env[ENV_SESSION_KEY] = AbstractStore::SessionHash.new(self, env) env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup status, headers, body = @app.call(env) session_data = env[ENV_SESSION_KEY] options = env[ENV_SESSION_OPTIONS_KEY] if !session_data.is_a?(AbstractStore::SessionHash) || session_data.send(:loaded?) || options[:expire_after] session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.send(:loaded?) session_data = marshal(session_data.to_hash) raise CookieOverflow if session_data.size > MAX cookie = Hash.new cookie[:value] = session_data unless options[:expire_after].nil? cookie[:expires] = Time.now + options[:expire_after] end cookie = build_cookie(@key, cookie.merge(options)) unless headers[HTTP_SET_COOKIE].blank? headers[HTTP_SET_COOKIE] << "\n#{cookie}" else headers[HTTP_SET_COOKIE] = cookie end end [status, headers, body] end private # Should be in Rack::Utils soon def build_cookie(key, value) case value when Hash domain = "; domain=" + value[:domain] if value[:domain] path = "; path=" + value[:path] if value[:path] # According to RFC 2109, we need dashes here. # N.B.: cgi.rb uses spaces... expires = "; expires=" + value[:expires].clone.gmtime. strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires] secure = "; secure" if value[:secure] httponly = "; HttpOnly" if value[:httponly] value = value[:value] end value = [value] unless Array === value cookie = Rack::Utils.escape(key) + "=" + value.map { |v| Rack::Utils.escape(v) }.join("&") + "#{domain}#{path}#{expires}#{secure}#{httponly}" end def load_session(env) request = Rack::Request.new(env) session_data = request.cookies[@key] data = unmarshal(session_data) || persistent_session_id!({}) [data[:session_id], data] end # Marshal a session hash into safe cookie data. Include an integrity hash. def marshal(session) @verifier.generate(persistent_session_id!(session)) end # Unmarshal cookie data to a hash and verify its integrity. def unmarshal(cookie) persistent_session_id!(@verifier.verify(cookie)) if cookie rescue ActiveSupport::MessageVerifier::InvalidSignature nil end def ensure_session_key(key) if key.blank? raise ArgumentError, 'A key is required to write a ' + 'cookie containing the session data. Use ' + 'config.action_controller.session = { :key => ' + '"_myapp_session", :secret => "some secret phrase" } in ' + 'config/environment.rb' end end # To prevent users from using something insecure like "Password" we make sure that the # secret they've provided is at least 30 characters in length. def ensure_secret_secure(secret) # There's no way we can do this check if they've provided a proc for the # secret. return true if secret.is_a?(Proc) if secret.blank? raise ArgumentError, "A secret is required to generate an " + "integrity hash for cookie session data. Use " + "config.action_controller.session = { :key => " + "\"_myapp_session\", :secret => \"some secret phrase of at " + "least #{SECRET_MIN_LENGTH} characters\" } " + "in config/environment.rb" end if secret.length < SECRET_MIN_LENGTH raise ArgumentError, "Secret should be something secure, " + "like \"#{ActiveSupport::SecureRandom.hex(16)}\". The value you " + "provided, \"#{secret}\", is shorter than the minimum length " + "of #{SECRET_MIN_LENGTH} characters" end end def verifier_for(secret, digest) key = secret.respond_to?(:call) ? secret.call : secret ActiveSupport::MessageVerifier.new(key, digest) end def generate_sid ActiveSupport::SecureRandom.hex(16) end def persistent_session_id!(data) (data ||= {}).merge!(inject_persistent_session_id(data)) end def inject_persistent_session_id(data) requires_session_id?(data) ? { :session_id => generate_sid } : {} end def requires_session_id?(data) if data data.respond_to?(:key?) && !data.key?(:session_id) else true end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/caching/actions.rb
provider/vendor/rails/actionpack/lib/action_controller/caching/actions.rb
require 'set' module ActionController #:nodoc: module Caching # Action caching is similar to page caching by the fact that the entire output of the response is cached, but unlike page caching, # every request still goes through the Action Pack. The key benefit of this is that filters are run before the cache is served, which # allows for authentication and other restrictions on whether someone is allowed to see the cache. Example: # # class ListsController < ApplicationController # before_filter :authenticate, :except => :public # caches_page :public # caches_action :index, :show, :feed # end # # In this example, the public action doesn't require authentication, so it's possible to use the faster page caching method. But both the # show and feed action are to be shielded behind the authenticate filter, so we need to implement those as action caches. # # Action caching internally uses the fragment caching and an around filter to do the job. The fragment cache is named according to both # the current host and the path. So a page that is accessed at http://david.somewhere.com/lists/show/1 will result in a fragment named # "david.somewhere.com/lists/show/1". This allows the cacher to differentiate between "david.somewhere.com/lists/" and # "jamis.somewhere.com/lists/" -- which is a helpful way of assisting the subdomain-as-account-key pattern. # # Different representations of the same resource, e.g. <tt>http://david.somewhere.com/lists</tt> and <tt>http://david.somewhere.com/lists.xml</tt> # are treated like separate requests and so are cached separately. Keep in mind when expiring an action cache that <tt>:action => 'lists'</tt> is not the same # as <tt>:action => 'list', :format => :xml</tt>. # # You can set modify the default action cache path by passing a :cache_path option. This will be passed directly to ActionCachePath.path_for. This is handy # for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance. # # And you can also use :if (or :unless) to pass a Proc that specifies when the action should be cached. # # Finally, if you are using memcached, you can also pass :expires_in. # # class ListsController < ApplicationController # before_filter :authenticate, :except => :public # caches_page :public # caches_action :index, :if => Proc.new { |c| !c.request.format.json? } # cache if is not a JSON request # caches_action :show, :cache_path => { :project => 1 }, :expires_in => 1.hour # caches_action :feed, :cache_path => Proc.new { |controller| # controller.params[:user_id] ? # controller.send(:user_list_url, controller.params[:user_id], controller.params[:id]) : # controller.send(:list_url, controller.params[:id]) } # end # # If you pass :layout => false, it will only cache your action content. It is useful when your layout has dynamic information. # module Actions def self.included(base) #:nodoc: base.extend(ClassMethods) base.class_eval do attr_accessor :rendered_action_cache, :action_cache_path end end module ClassMethods # Declares that +actions+ should be cached. # See ActionController::Caching::Actions for details. def caches_action(*actions) return unless cache_configured? options = actions.extract_options! filter_options = { :only => actions, :if => options.delete(:if), :unless => options.delete(:unless) } cache_filter = ActionCacheFilter.new(:layout => options.delete(:layout), :cache_path => options.delete(:cache_path), :store_options => options) around_filter(filter_options) do |controller, action| cache_filter.filter(controller, action) end end end protected def expire_action(options = {}) return unless cache_configured? if options[:action].is_a?(Array) options[:action].dup.each do |action| expire_fragment(ActionCachePath.path_for(self, options.merge({ :action => action }), false)) end else expire_fragment(ActionCachePath.path_for(self, options, false)) end end class ActionCacheFilter #:nodoc: def initialize(options, &block) @options = options end def filter(controller, action) should_continue = before(controller) action.call if should_continue after(controller) end def before(controller) cache_path = ActionCachePath.new(controller, path_options_for(controller, @options.slice(:cache_path))) if cache = controller.read_fragment(cache_path.path, @options[:store_options]) controller.rendered_action_cache = true set_content_type!(controller, cache_path.extension) options = { :text => cache } options.merge!(:layout => true) if cache_layout? controller.__send__(:render, options) false else controller.action_cache_path = cache_path end end def after(controller) return if controller.rendered_action_cache || !caching_allowed(controller) action_content = cache_layout? ? content_for_layout(controller) : controller.response.body controller.write_fragment(controller.action_cache_path.path, action_content, @options[:store_options]) end private def set_content_type!(controller, extension) controller.response.content_type = Mime::Type.lookup_by_extension(extension).to_s if extension end def path_options_for(controller, options) ((path_options = options[:cache_path]).respond_to?(:call) ? path_options.call(controller) : path_options) || {} end def caching_allowed(controller) controller.request.get? && controller.response.status.to_i == 200 end def cache_layout? @options[:layout] == false end def content_for_layout(controller) controller.response.layout && controller.response.template.instance_variable_get('@cached_content_for_layout') end end class ActionCachePath attr_reader :path, :extension class << self def path_for(controller, options, infer_extension = true) new(controller, options, infer_extension).path end end # When true, infer_extension will look up the cache path extension from the request's path & format. # This is desirable when reading and writing the cache, but not when expiring the cache - # expire_action should expire the same files regardless of the request format. def initialize(controller, options = {}, infer_extension = true) if infer_extension extract_extension(controller.request) options = options.reverse_merge(:format => @extension) if options.is_a?(Hash) end path = controller.url_for(options).split('://').last normalize!(path) add_extension!(path, @extension) @path = URI.unescape(path) end private def normalize!(path) path << 'index' if path[-1] == ?/ end def add_extension!(path, extension) path << ".#{extension}" if extension and !path.ends_with?(extension) end def extract_extension(request) # Don't want just what comes after the last '.' to accommodate multi part extensions # such as tar.gz. @extension = request.path[/^[^.]+\.(.+)$/, 1] || request.cache_format end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/caching/sweeping.rb
provider/vendor/rails/actionpack/lib/action_controller/caching/sweeping.rb
module ActionController #:nodoc: module Caching # Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change. # They do this by being half-observers, half-filters and implementing callbacks for both roles. A Sweeper example: # # class ListSweeper < ActionController::Caching::Sweeper # observe List, Item # # def after_save(record) # list = record.is_a?(List) ? record : record.list # expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id) # expire_action(:controller => "lists", :action => "all") # list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) } # end # end # # The sweeper is assigned in the controllers that wish to have its job performed using the <tt>cache_sweeper</tt> class method: # # class ListsController < ApplicationController # caches_action :index, :show, :public, :feed # cache_sweeper :list_sweeper, :only => [ :edit, :destroy, :share ] # end # # In the example above, four actions are cached and three actions are responsible for expiring those caches. # # You can also name an explicit class in the declaration of a sweeper, which is needed if the sweeper is in a module: # # class ListsController < ApplicationController # caches_action :index, :show, :public, :feed # cache_sweeper OpenBar::Sweeper, :only => [ :edit, :destroy, :share ] # end module Sweeping def self.included(base) #:nodoc: base.extend(ClassMethods) end module ClassMethods #:nodoc: def cache_sweeper(*sweepers) configuration = sweepers.extract_options! sweepers.each do |sweeper| ActiveRecord::Base.observers << sweeper if defined?(ActiveRecord) and defined?(ActiveRecord::Base) sweeper_instance = (sweeper.is_a?(Symbol) ? Object.const_get(sweeper.to_s.classify) : sweeper).instance if sweeper_instance.is_a?(Sweeper) around_filter(sweeper_instance, :only => configuration[:only]) else after_filter(sweeper_instance, :only => configuration[:only]) end end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/caching/sweeper.rb
provider/vendor/rails/actionpack/lib/action_controller/caching/sweeper.rb
require 'active_record' module ActionController #:nodoc: module Caching class Sweeper < ActiveRecord::Observer #:nodoc: attr_accessor :controller def before(controller) self.controller = controller callback(:before) if controller.perform_caching end def after(controller) callback(:after) if controller.perform_caching # Clean up, so that the controller can be collected after this request self.controller = nil end protected # gets the action cache path for the given options. def action_path_for(options) ActionController::Caching::Actions::ActionCachePath.path_for(controller, options) end # Retrieve instance variables set in the controller. def assigns(key) controller.instance_variable_get("@#{key}") end private def callback(timing) controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}" action_callback_method_name = "#{controller_callback_method_name}_#{controller.action_name}" __send__(controller_callback_method_name) if respond_to?(controller_callback_method_name, true) __send__(action_callback_method_name) if respond_to?(action_callback_method_name, true) end def method_missing(method, *arguments, &block) return if @controller.nil? @controller.__send__(method, *arguments, &block) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/caching/pages.rb
provider/vendor/rails/actionpack/lib/action_controller/caching/pages.rb
require 'fileutils' require 'uri' module ActionController #:nodoc: module Caching # Page caching is an approach to caching where the entire action output of is stored as a HTML file that the web server # can serve without going through Action Pack. This is the fastest way to cache your content as opposed to going dynamically # through the process of generating the content. Unfortunately, this incredible speed-up is only available to stateless pages # where all visitors are treated the same. Content management systems -- including weblogs and wikis -- have many pages that are # a great fit for this approach, but account-based systems where people log in and manipulate their own data are often less # likely candidates. # # Specifying which actions to cache is done through the <tt>caches_page</tt> class method: # # class WeblogController < ActionController::Base # caches_page :show, :new # end # # This will generate cache files such as <tt>weblog/show/5.html</tt> and <tt>weblog/new.html</tt>, # which match the URLs used to trigger the dynamic generation. This is how the web server is able # pick up a cache file when it exists and otherwise let the request pass on to Action Pack to generate it. # # Expiration of the cache is handled by deleting the cached file, which results in a lazy regeneration approach where the cache # is not restored before another hit is made against it. The API for doing so mimics the options from +url_for+ and friends: # # class WeblogController < ActionController::Base # def update # List.update(params[:list][:id], params[:list]) # expire_page :action => "show", :id => params[:list][:id] # redirect_to :action => "show", :id => params[:list][:id] # end # end # # Additionally, you can expire caches using Sweepers that act on changes in the model to determine when a cache is supposed to be # expired. module Pages def self.included(base) #:nodoc: base.extend(ClassMethods) base.class_eval do @@page_cache_directory = defined?(Rails.public_path) ? Rails.public_path : "" ## # :singleton-method: # The cache directory should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. # For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>RAILS_ROOT + "/public"</tt>). Changing # this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your # web server to look in the new location for cached files. cattr_accessor :page_cache_directory @@page_cache_extension = '.html' ## # :singleton-method: # Most Rails requests do not have an extension, such as <tt>/weblog/new</tt>. In these cases, the page caching mechanism will add one in # order to make it easy for the cached files to be picked up properly by the web server. By default, this cache extension is <tt>.html</tt>. # If you want something else, like <tt>.php</tt> or <tt>.shtml</tt>, just set Base.page_cache_extension. In cases where a request already has an # extension, such as <tt>.xml</tt> or <tt>.rss</tt>, page caching will not add an extension. This allows it to work well with RESTful apps. cattr_accessor :page_cache_extension end end module ClassMethods # Expires the page that was cached with the +path+ as a key. Example: # expire_page "/lists/show" def expire_page(path) return unless perform_caching benchmark "Expired page: #{page_cache_file(path)}" do File.delete(page_cache_path(path)) if File.exist?(page_cache_path(path)) end end # Manually cache the +content+ in the key determined by +path+. Example: # cache_page "I'm the cached content", "/lists/show" def cache_page(content, path) return unless perform_caching benchmark "Cached page: #{page_cache_file(path)}" do FileUtils.makedirs(File.dirname(page_cache_path(path))) File.open(page_cache_path(path), "wb+") { |f| f.write(content) } end end # Caches the +actions+ using the page-caching approach that'll store the cache in a path within the page_cache_directory that # matches the triggering url. # # Usage: # # # cache the index action # caches_page :index # # # cache the index action except for JSON requests # caches_page :index, :if => Proc.new { |c| !c.request.format.json? } def caches_page(*actions) return unless perform_caching options = actions.extract_options! after_filter({:only => actions}.merge(options)) { |c| c.cache_page } end private def page_cache_file(path) name = (path.empty? || path == "/") ? "/index" : URI.unescape(path.chomp('/')) name << page_cache_extension unless (name.split('/').last || name).include? '.' return name end def page_cache_path(path) page_cache_directory + page_cache_file(path) end end # Expires the page that was cached with the +options+ as a key. Example: # expire_page :controller => "lists", :action => "show" def expire_page(options = {}) return unless perform_caching if options.is_a?(Hash) if options[:action].is_a?(Array) options[:action].dup.each do |action| self.class.expire_page(url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :action => action))) end else self.class.expire_page(url_for(options.merge(:only_path => true, :skip_relative_url_root => true))) end else self.class.expire_page(options) end end # Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used # If no options are provided, the requested url is used. Example: # cache_page "I'm the cached content", :controller => "lists", :action => "show" def cache_page(content = nil, options = nil) return unless perform_caching && caching_allowed path = case options when Hash url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :format => params[:format])) when String options else request.path end self.class.cache_page(content || response.body, path) end private def caching_allowed request.get? && response.status.to_i == 200 end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_controller/caching/fragments.rb
provider/vendor/rails/actionpack/lib/action_controller/caching/fragments.rb
module ActionController #:nodoc: module Caching # Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when # certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple # parties. The caching is done using the cache helper available in the Action View. A template with caching might look something like: # # <b>Hello <%= @name %></b> # <% cache do %> # All the topics in the system: # <%= render :partial => "topic", :collection => Topic.find(:all) %> # <% end %> # # This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would # be able to invalidate it using <tt>expire_fragment(:controller => "topics", :action => "list")</tt>. # # This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using # <tt>caches_action</tt>, so we also have the option to qualify the name of the cached fragment with something like: # # <% cache(:action => "list", :action_suffix => "all_topics") do %> # # That would result in a name such as "/topics/list/all_topics", avoiding conflicts with the action cache and with any fragments that use a # different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique # cache names that we can refer to when we need to expire the cache. # # The expiration call for this example is: # # expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics") module Fragments # Given a key (as described in <tt>expire_fragment</tt>), returns a key suitable for use in reading, # writing, or expiring a cached fragment. If the key is a hash, the generated key is the return # value of url_for on that hash (without the protocol). All keys are prefixed with "views/" and uses # ActiveSupport::Cache.expand_cache_key for the expansion. def fragment_cache_key(key) ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views) end def fragment_for(buffer, name = {}, options = nil, &block) #:nodoc: if perform_caching if cache = read_fragment(name, options) buffer.concat(cache) else pos = buffer.length block.call write_fragment(name, buffer[pos..-1], options) end else block.call end end # Writes <tt>content</tt> to the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats) def write_fragment(key, content, options = nil) return content unless cache_configured? key = fragment_cache_key(key) self.class.benchmark "Cached fragment miss: #{key}" do cache_store.write(key, content, options) end content end # Reads a cached fragment from the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats) def read_fragment(key, options = nil) return unless cache_configured? key = fragment_cache_key(key) self.class.benchmark "Cached fragment hit: #{key}" do cache_store.read(key, options) end end # Check if a cached fragment from the location signified by <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats) def fragment_exist?(key, options = nil) return unless cache_configured? key = fragment_cache_key(key) self.class.benchmark "Cached fragment exists?: #{key}" do cache_store.exist?(key, options) end end # Removes fragments from the cache. # # +key+ can take one of three forms: # * String - This would normally take the form of a path, like # <tt>"pages/45/notes"</tt>. # * Hash - Treated as an implicit call to +url_for+, like # <tt>{:controller => "pages", :action => "notes", :id => 45}</tt> # * Regexp - Will remove any fragment that matches, so # <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you # don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because # the actual filename matched looks like # <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is # only supported on caches that can iterate over all keys (unlike # memcached). # # +options+ is passed through to the cache store's <tt>delete</tt> # method (or <tt>delete_matched</tt>, for Regexp keys.) def expire_fragment(key, options = nil) return unless cache_configured? key = key.is_a?(Regexp) ? key : fragment_cache_key(key) if key.is_a?(Regexp) self.class.benchmark "Expired fragments matching: #{key.source}" do cache_store.delete_matched(key, options) end else self.class.benchmark "Expired fragment: #{key}" do cache_store.delete(key, options) end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/test_case.rb
provider/vendor/rails/actionpack/lib/action_view/test_case.rb
require 'active_support/test_case' module ActionView class Base alias_method :initialize_without_template_tracking, :initialize def initialize(*args) @_rendered = { :template => nil, :partials => Hash.new(0) } initialize_without_template_tracking(*args) end end module Renderable alias_method :render_without_template_tracking, :render def render(view, local_assigns = {}) if respond_to?(:path) && !is_a?(InlineTemplate) rendered = view.instance_variable_get(:@_rendered) rendered[:partials][self] += 1 if is_a?(RenderablePartial) rendered[:template] ||= self end render_without_template_tracking(view, local_assigns) end end class TestCase < ActiveSupport::TestCase include ActionController::TestCase::Assertions include ActionController::TestProcess class_inheritable_accessor :helper_class @@helper_class = nil class << self def tests(helper_class) self.helper_class = helper_class end def helper_class if current_helper_class = read_inheritable_attribute(:helper_class) current_helper_class else self.helper_class = determine_default_helper_class(name) end end def determine_default_helper_class(name) name.sub(/Test$/, '').constantize rescue NameError nil end end include ActionView::Helpers include ActionController::PolymorphicRoutes include ActionController::RecordIdentifier setup :setup_with_helper_class def setup_with_helper_class if helper_class && !self.class.ancestors.include?(helper_class) self.class.send(:include, helper_class) end self.output_buffer = '' end class TestController < ActionController::Base attr_accessor :request, :response, :params def initialize @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @params = {} send(:initialize_current_url) end end protected attr_accessor :output_buffer private def method_missing(selector, *args) controller = TestController.new return controller.__send__(selector, *args) if ActionController::Routing::Routes.named_routes.helpers.include?(selector) super end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/renderable_partial.rb
provider/vendor/rails/actionpack/lib/action_view/renderable_partial.rb
module ActionView # NOTE: The template that this mixin is being included into is frozen # so you cannot set or modify any instance variables module RenderablePartial #:nodoc: extend ActiveSupport::Memoizable def variable_name name.sub(/\A_/, '').to_sym end memoize :variable_name def counter_name "#{variable_name}_counter".to_sym end memoize :counter_name def render(view, local_assigns = {}) if defined? ActionController ActionController::Base.benchmark("Rendered #{path_without_format_and_extension}", Logger::DEBUG, false) do super end else super end end def render_partial(view, object = nil, local_assigns = {}, as = nil) object ||= local_assigns[:object] || local_assigns[variable_name] if object.nil? && view.respond_to?(:controller) ivar = :"@#{variable_name}" object = if view.controller.instance_variable_defined?(ivar) ActiveSupport::Deprecation::DeprecatedObjectProxy.new( view.controller.instance_variable_get(ivar), "#{ivar} will no longer be implicitly assigned to #{variable_name}") end end # Ensure correct object is reassigned to other accessors local_assigns[:object] = local_assigns[variable_name] = object local_assigns[as] = object if as render_template(view, local_assigns) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers.rb
provider/vendor/rails/actionpack/lib/action_view/helpers.rb
module ActionView #:nodoc: module Helpers #:nodoc: autoload :ActiveRecordHelper, 'action_view/helpers/active_record_helper' autoload :AssetTagHelper, 'action_view/helpers/asset_tag_helper' autoload :AtomFeedHelper, 'action_view/helpers/atom_feed_helper' autoload :BenchmarkHelper, 'action_view/helpers/benchmark_helper' autoload :CacheHelper, 'action_view/helpers/cache_helper' autoload :CaptureHelper, 'action_view/helpers/capture_helper' autoload :DateHelper, 'action_view/helpers/date_helper' autoload :DebugHelper, 'action_view/helpers/debug_helper' autoload :FormHelper, 'action_view/helpers/form_helper' autoload :FormOptionsHelper, 'action_view/helpers/form_options_helper' autoload :FormTagHelper, 'action_view/helpers/form_tag_helper' autoload :JavaScriptHelper, 'action_view/helpers/javascript_helper' autoload :NumberHelper, 'action_view/helpers/number_helper' autoload :PrototypeHelper, 'action_view/helpers/prototype_helper' autoload :RecordIdentificationHelper, 'action_view/helpers/record_identification_helper' autoload :RecordTagHelper, 'action_view/helpers/record_tag_helper' autoload :SanitizeHelper, 'action_view/helpers/sanitize_helper' autoload :ScriptaculousHelper, 'action_view/helpers/scriptaculous_helper' autoload :TagHelper, 'action_view/helpers/tag_helper' autoload :TextHelper, 'action_view/helpers/text_helper' autoload :TranslationHelper, 'action_view/helpers/translation_helper' autoload :UrlHelper, 'action_view/helpers/url_helper' def self.included(base) base.extend(ClassMethods) end module ClassMethods include SanitizeHelper::ClassMethods end include ActiveRecordHelper include AssetTagHelper include AtomFeedHelper include BenchmarkHelper include CacheHelper include CaptureHelper include DateHelper include DebugHelper include FormHelper include FormOptionsHelper include FormTagHelper include JavaScriptHelper include NumberHelper include PrototypeHelper include RecordIdentificationHelper include RecordTagHelper include SanitizeHelper include ScriptaculousHelper include TagHelper include TextHelper include TranslationHelper include UrlHelper end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/paths.rb
provider/vendor/rails/actionpack/lib/action_view/paths.rb
module ActionView #:nodoc: class PathSet < Array #:nodoc: def self.type_cast(obj) if obj.is_a?(String) if Base.cache_template_loading? Template::EagerPath.new(obj.to_s) else ReloadableTemplate::ReloadablePath.new(obj.to_s) end else obj end end def initialize(*args) super(*args).map! { |obj| self.class.type_cast(obj) } end def <<(obj) super(self.class.type_cast(obj)) end def concat(array) super(array.map! { |obj| self.class.type_cast(obj) }) end def insert(index, obj) super(index, self.class.type_cast(obj)) end def push(*objs) super(*objs.map { |obj| self.class.type_cast(obj) }) end def unshift(*objs) super(*objs.map { |obj| self.class.type_cast(obj) }) end def load! each(&:load!) end def find_template(original_template_path, format = nil, html_fallback = true) return original_template_path if original_template_path.respond_to?(:render) template_path = original_template_path.sub(/^\//, '') each do |load_path| if format && (template = load_path["#{template_path}.#{I18n.locale}.#{format}"]) return template elsif format && (template = load_path["#{template_path}.#{format}"]) return template elsif template = load_path["#{template_path}.#{I18n.locale}"] return template elsif template = load_path[template_path] return template # Try to find html version if the format is javascript elsif format == :js && html_fallback && template = load_path["#{template_path}.#{I18n.locale}.html"] return template elsif format == :js && html_fallback && template = load_path["#{template_path}.html"] return template end end return Template.new(original_template_path) if File.file?(original_template_path) raise MissingTemplate.new(self, original_template_path, format) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/renderable.rb
provider/vendor/rails/actionpack/lib/action_view/renderable.rb
# encoding: utf-8 module ActionView # NOTE: The template that this mixin is being included into is frozen # so you cannot set or modify any instance variables module Renderable #:nodoc: extend ActiveSupport::Memoizable def filename 'compiled-template' end def handler Template.handler_class_for_extension(extension) end memoize :handler def compiled_source handler.call(self) end def method_name_without_locals ['_run', extension, method_segment].compact.join('_') end memoize :method_name_without_locals def render(view, local_assigns = {}) compile(local_assigns) view.with_template self do view.send(:_evaluate_assigns_and_ivars) view.send(:_set_controller_content_type, mime_type) if respond_to?(:mime_type) view.send(method_name(local_assigns), local_assigns) do |*names| ivar = :@_proc_for_layout if !view.instance_variable_defined?(:"@content_for_#{names.first}") && view.instance_variable_defined?(ivar) && (proc = view.instance_variable_get(ivar)) view.capture(*names, &proc) elsif view.instance_variable_defined?(ivar = :"@content_for_#{names.first || :layout}") view.instance_variable_get(ivar) end end end end def method_name(local_assigns) if local_assigns && local_assigns.any? method_name = method_name_without_locals.dup method_name << "_locals_#{local_assigns.keys.map { |k| k.to_s }.sort.join('_')}" else method_name = method_name_without_locals end method_name.to_sym end private # Compile and evaluate the template's code (if necessary) def compile(local_assigns) render_symbol = method_name(local_assigns) if !Base::CompiledTemplates.method_defined?(render_symbol) || recompile? compile!(render_symbol, local_assigns) end end def compile!(render_symbol, local_assigns) locals_code = local_assigns.keys.map { |key| "#{key} = local_assigns[:#{key}];" }.join source = <<-end_src def #{render_symbol}(local_assigns) old_output_buffer = output_buffer;#{locals_code};#{compiled_source} ensure self.output_buffer = old_output_buffer end end_src begin ActionView::Base::CompiledTemplates.module_eval(source, filename, 0) rescue Errno::ENOENT => e raise e # Missing template file, re-raise for Base to rescue rescue Exception => e # errors from template code if logger = defined?(ActionController) && Base.logger logger.debug "ERROR: compiling #{render_symbol} RAISED #{e}" logger.debug "Function body: #{source}" logger.debug "Backtrace: #{e.backtrace.join("\n")}" end raise ActionView::TemplateError.new(self, {}, e) end end def recompile? false end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/base.rb
provider/vendor/rails/actionpack/lib/action_view/base.rb
module ActionView #:nodoc: class ActionViewError < StandardError #:nodoc: end class MissingTemplate < ActionViewError #:nodoc: attr_reader :path def initialize(paths, path, template_format = nil) @path = path full_template_path = path.include?('.') ? path : "#{path}.erb" display_paths = paths.compact.join(":") template_type = (path =~ /layouts/i) ? 'layout' : 'template' super("Missing #{template_type} #{full_template_path} in view path #{display_paths}") end end # Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERb # (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> (or <tt>.rxml</tt>) extension then Jim Weirich's Builder::XmlMarkup library is used. # If the template file has a <tt>.rjs</tt> extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator. # # = ERb # # You trigger ERb by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the # following loop for names: # # <b>Names of all the people</b> # <% for person in @people %> # Name: <%= person.name %><br/> # <% end %> # # The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this # is not just a usage suggestion. Regular output functions like print or puts won't work with ERb templates. So this would be wrong: # # Hi, Mr. <% puts "Frodo" %> # # If you absolutely must write from within a function, you can use the TextHelper#concat. # # <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>. # # == Using sub templates # # Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The # classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts): # # <%= render "shared/header" %> # Something really specific and terrific # <%= render "shared/footer" %> # # As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the # result of the rendering. The output embedding writes it to the current template. # # But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance # variables defined using the regular embedding tags. Like this: # # <% @page_title = "A Wonderful Hello" %> # <%= render "shared/header" %> # # Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag: # # <title><%= @page_title %></title> # # == Passing local variables to sub templates # # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values: # # <%= render "shared/header", { :headline => "Welcome", :person => person } %> # # These can now be accessed in <tt>shared/header</tt> with: # # Headline: <%= headline %> # First name: <%= person.first_name %> # # If you need to find out whether a certain local variable has been assigned a value in a particular render call, # you need to use the following pattern: # # <% if local_assigns.has_key? :headline %> # Headline: <%= headline %> # <% end %> # # Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction. # # == Template caching # # By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will # check the file's modification time and recompile it. # # == Builder # # Builder templates are a more programmatic alternative to ERb. They are especially useful for generating XML content. An XmlMarkup object # named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension. # # Here are some basic examples: # # xml.em("emphasized") # => <em>emphasized</em> # xml.em { xml.b("emph & bold") } # => <em><b>emph &amp; bold</b></em> # xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a> # xml.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\> # # NOTE: order of attributes is not specified. # # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following: # # xml.div { # xml.h1(@person.name) # xml.p(@person.bio) # } # # would produce something like: # # <div> # <h1>David Heinemeier Hansson</h1> # <p>A product of Danish Design during the Winter of '79...</p> # </div> # # A full-length RSS example actually used on Basecamp: # # xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do # xml.channel do # xml.title(@feed_title) # xml.link(@url) # xml.description "Basecamp: Recent items" # xml.language "en-us" # xml.ttl "40" # # for item in @recent_items # xml.item do # xml.title(item_title(item)) # xml.description(item_description(item)) if item_description(item) # xml.pubDate(item_pubDate(item)) # xml.guid(@person.firm.account.url + @recent_items.url(item)) # xml.link(@person.firm.account.url + @recent_items.url(item)) # # xml.tag!("dc:creator", item.author_name) if item_has_creator?(item) # end # end # end # end # # More builder documentation can be found at http://builder.rubyforge.org. # # == JavaScriptGenerator # # JavaScriptGenerator templates end in <tt>.rjs</tt>. Unlike conventional templates which are used to # render the results of an action, these templates generate instructions on how to modify an already rendered page. This makes it easy to # modify multiple elements on your page in one declarative Ajax response. Actions with these templates are called in the background with Ajax # and make updates to the page where the request originated from. # # An instance of the JavaScriptGenerator object named +page+ is automatically made available to your template, which is implicitly wrapped in an ActionView::Helpers::PrototypeHelper#update_page block. # # When an <tt>.rjs</tt> action is called with +link_to_remote+, the generated JavaScript is automatically evaluated. Example: # # link_to_remote :url => {:action => 'delete'} # # The subsequently rendered <tt>delete.rjs</tt> might look like: # # page.replace_html 'sidebar', :partial => 'sidebar' # page.remove "person-#{@person.id}" # page.visual_effect :highlight, 'user-list' # # This refreshes the sidebar, removes a person element and highlights the user list. # # See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details. class Base include Helpers, Partials, ::ERB::Util extend ActiveSupport::Memoizable attr_accessor :base_path, :assigns, :template_extension attr_accessor :controller attr_writer :template_format attr_accessor :output_buffer class << self delegate :erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB' delegate :logger, :to => 'ActionController::Base' end @@debug_rjs = false ## # :singleton-method: # Specify whether RJS responses should be wrapped in a try/catch block # that alert()s the caught exception (and then re-raises it). cattr_accessor :debug_rjs # Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed. # Automatically reloading templates are not thread safe and should only be used in development mode. @@cache_template_loading = nil cattr_accessor :cache_template_loading def self.cache_template_loading? ActionController::Base.allow_concurrency || (cache_template_loading.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading) end attr_internal :request delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers, :flash, :logger, :action_name, :controller_name, :to => :controller module CompiledTemplates #:nodoc: # holds compiled template code end include CompiledTemplates def self.process_view_paths(value) ActionView::PathSet.new(Array(value)) end attr_reader :helpers class ProxyModule < Module def initialize(receiver) @receiver = receiver end def include(*args) super(*args) @receiver.extend(*args) end end def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc: @assigns = assigns_for_first_render @assigns_added = nil @controller = controller @helpers = ProxyModule.new(self) self.view_paths = view_paths @_first_render = nil @_current_render = nil end attr_reader :view_paths def view_paths=(paths) @view_paths = self.class.process_view_paths(paths) # we might be using ReloadableTemplates, so we need to let them know this a new request @view_paths.load! end # Returns the result of a render that's dictated by the options hash. The primary options are: # # * <tt>:partial</tt> - See ActionView::Partials. # * <tt>:update</tt> - Calls update_page with the block given. # * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those. # * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller. # * <tt>:text</tt> - Renders the text passed in out. # # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter # as the locals hash. def render(options = {}, local_assigns = {}, &block) #:nodoc: local_assigns ||= {} case options when Hash options = options.reverse_merge(:locals => {}) if options[:layout] _render_with_layout(options, local_assigns, &block) elsif options[:file] template = self.view_paths.find_template(options[:file], template_format) template.render_template(self, options[:locals]) elsif options[:partial] render_partial(options) elsif options[:inline] InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals]) elsif options[:text] options[:text] end when :update update_page(&block) else render_partial(:partial => options, :locals => local_assigns) end end # The format to be used when choosing between multiple templates with # the same name but differing formats. See +Request#template_format+ # for more details. def template_format if defined? @template_format @template_format elsif controller && controller.respond_to?(:request) @template_format = controller.request.template_format.to_sym else @template_format = :html end end # Access the current template being rendered. # Returns a ActionView::Template object. def template @_current_render end def template=(template) #:nodoc: @_first_render ||= template @_current_render = template end def with_template(current_template) last_template, self.template = template, current_template yield ensure self.template = last_template end private # Evaluates the local assigns and controller ivars, pushes them to the view. def _evaluate_assigns_and_ivars #:nodoc: unless @assigns_added @assigns.each { |key, value| instance_variable_set("@#{key}", value) } _copy_ivars_from_controller @assigns_added = true end end def _copy_ivars_from_controller #:nodoc: if @controller variables = @controller.instance_variable_names variables -= @controller.protected_instance_variables if @controller.respond_to?(:protected_instance_variables) variables.each { |name| instance_variable_set(name, @controller.instance_variable_get(name)) } end end def _set_controller_content_type(content_type) #:nodoc: if controller.respond_to?(:response) controller.response.content_type ||= content_type end end def _render_with_layout(options, local_assigns, &block) #:nodoc: partial_layout = options.delete(:layout) if block_given? begin @_proc_for_layout = block concat(render(options.merge(:partial => partial_layout))) ensure @_proc_for_layout = nil end else begin original_content_for_layout = @content_for_layout if defined?(@content_for_layout) @content_for_layout = render(options) if (options[:inline] || options[:file] || options[:text]) @cached_content_for_layout = @content_for_layout render(:file => partial_layout, :locals => local_assigns) else render(options.merge(:partial => partial_layout)) end ensure @content_for_layout = original_content_for_layout end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template_handler.rb
provider/vendor/rails/actionpack/lib/action_view/template_handler.rb
# Legacy TemplateHandler stub module ActionView module TemplateHandlers #:nodoc: module Compilable def self.included(base) base.extend(ClassMethods) end module ClassMethods def call(template) new.compile(template) end end def compile(template) raise "Need to implement #{self.class.name}#compile(template)" end end end class TemplateHandler def self.call(template) "#{name}.new(self).render(template, local_assigns)" end def initialize(view = nil) @view = view end def render(template, local_assigns) raise "Need to implement #{self.class.name}#render(template, local_assigns)" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template.rb
provider/vendor/rails/actionpack/lib/action_view/template.rb
module ActionView #:nodoc: class Template class Path attr_reader :path, :paths delegate :hash, :inspect, :to => :path def initialize(path) raise ArgumentError, "path already is a Path class" if path.is_a?(Path) @path = (path.ends_with?(File::SEPARATOR) ? path.to(-2) : path).freeze end def to_s if defined?(RAILS_ROOT) path.to_s.sub(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') else path.to_s end end def to_str path.to_str end def ==(path) to_str == path.to_str end def eql?(path) to_str == path.to_str end # Returns a ActionView::Template object for the given path string. The # input path should be relative to the view path directory, # +hello/index.html.erb+. This method also has a special exception to # match partial file names without a handler extension. So # +hello/index.html+ will match the first template it finds with a # known template extension, +hello/index.html.erb+. Template extensions # should not be confused with format extensions +html+, +js+, +xml+, # etc. A format must be supplied to match a formated file. +hello/index+ # will never match +hello/index.html.erb+. def [](path) end def load! end def self.new_and_loaded(path) returning new(path) do |path| path.load! end end private def relative_path_for_template_file(full_file_path) full_file_path.split("#{@path}/").last end end class EagerPath < Path def load! return if @loaded @paths = {} templates_in_path do |template| template.load! template.accessible_paths.each do |path| @paths[path] = template end end @paths.freeze @loaded = true end def [](path) load! unless @loaded @paths[path] end private def templates_in_path (Dir.glob("#{@path}/**/*/**") | Dir.glob("#{@path}/**")).each do |file| yield create_template(file) unless File.directory?(file) end end def create_template(file) Template.new(relative_path_for_template_file(file), self) end end extend TemplateHandlers extend ActiveSupport::Memoizable include Renderable # Templates that are exempt from layouts @@exempt_from_layout = Set.new([/\.rjs$/]) # Don't render layouts for templates with the given extensions. def self.exempt_from_layout(*extensions) regexps = extensions.collect do |extension| extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/ end @@exempt_from_layout.merge(regexps) end attr_accessor :template_path, :filename, :load_path, :base_path attr_accessor :locale, :name, :format, :extension delegate :to_s, :to => :path def initialize(template_path, load_path = nil) @template_path, @load_path = template_path.dup, load_path @base_path, @name, @locale, @format, @extension = split(template_path) @base_path.to_s.gsub!(/\/$/, '') # Push to split method # Extend with partial super powers extend RenderablePartial if @name =~ /^_/ end def accessible_paths paths = [] if valid_extension?(extension) paths << path paths << path_without_extension if multipart? formats = format.split(".") paths << "#{path_without_format_and_extension}.#{formats.first}" paths << "#{path_without_format_and_extension}.#{formats.second}" end else # template without explicit template handler should only be reachable through its exact path paths << template_path end paths end def format_and_extension (extensions = [format, extension].compact.join(".")).blank? ? nil : extensions end memoize :format_and_extension def multipart? format && format.include?('.') end def content_type format.gsub('.', '/') end def mime_type Mime::Type.lookup_by_extension(format) if format && defined?(::Mime) end memoize :mime_type def path [base_path, [name, locale, format, extension].compact.join('.')].compact.join('/') end memoize :path def path_without_extension [base_path, [name, locale, format].compact.join('.')].compact.join('/') end memoize :path_without_extension def path_without_format_and_extension [base_path, [name, locale].compact.join('.')].compact.join('/') end memoize :path_without_format_and_extension def relative_path path = File.expand_path(filename) path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT) path end memoize :relative_path def exempt_from_layout? @@exempt_from_layout.any? { |exempted| path =~ exempted } end def filename # no load_path means this is an "absolute pathed" template load_path ? File.join(load_path, template_path) : template_path end memoize :filename def source File.read(filename) end memoize :source def method_segment relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord } end memoize :method_segment def render_template(view, local_assigns = {}) render(view, local_assigns) rescue Exception => e raise e unless filename if TemplateError === e e.sub_template_of(self) raise e else raise TemplateError.new(self, view.assigns, e) end end def load! freeze end private def valid_extension?(extension) !Template.registered_template_handler(extension).nil? end def valid_locale?(locale) locale && I18n.available_locales.include?(locale.to_sym) end # Returns file split into an array # [base_path, name, locale, format, extension] def split(file) if m = file.to_s.match(/^(.*\/)?([^\.]+)\.(.*)$/) [m[1], m[2], *parse_extensions(m[3])] end end # returns parsed extensions as an array # [locale, format, extension] def parse_extensions(extensions) exts = extensions.split(".") if extension = valid_extension?(exts.last) && exts.pop || nil locale = valid_locale?(exts.first) && exts.shift || nil format = exts.join('.') if exts.any? # join('.') is needed for multipart templates else # no extension, just format format = exts.last end [locale, format, extension] end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template_error.rb
provider/vendor/rails/actionpack/lib/action_view/template_error.rb
module ActionView # The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a # bunch of intimate details and uses it to report a very precise exception message. class TemplateError < ActionViewError #:nodoc: SOURCE_CODE_RADIUS = 3 attr_reader :original_exception def initialize(template, assigns, original_exception) @template, @assigns, @original_exception = template, assigns.dup, original_exception @backtrace = compute_backtrace end def file_name @template.relative_path end def message ActiveSupport::Deprecation.silence { original_exception.message } end def clean_backtrace if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) Rails.backtrace_cleaner.clean(original_exception.backtrace) else original_exception.backtrace end end def sub_template_message if @sub_templates "Trace of template inclusion: " + @sub_templates.collect { |template| template.relative_path }.join(", ") else "" end end def source_extract(indentation = 0) return unless num = line_number num = num.to_i source_code = @template.source.split("\n") start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min indent = ' ' * indentation line_counter = start_on_line return unless source_code = source_code[start_on_line..end_on_line] source_code.sum do |line| line_counter += 1 "#{indent}#{line_counter}: #{line}\n" end end def sub_template_of(template_path) @sub_templates ||= [] @sub_templates << template_path end def line_number @line_number ||= if file_name regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/ $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp } end end def to_s "\n#{self.class} (#{message}) #{source_location}:\n" + "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n" end # don't do anything nontrivial here. Any raised exception from here becomes fatal # (and can't be rescued). def backtrace @backtrace end private def compute_backtrace [ "#{source_location.capitalize}\n\n#{source_extract(4)}\n " + clean_backtrace.join("\n ") ] end def source_location if line_number "on line ##{line_number} of " else 'in ' end + file_name end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template_handlers.rb
provider/vendor/rails/actionpack/lib/action_view/template_handlers.rb
module ActionView #:nodoc: module TemplateHandlers #:nodoc: autoload :ERB, 'action_view/template_handlers/erb' autoload :RJS, 'action_view/template_handlers/rjs' autoload :Builder, 'action_view/template_handlers/builder' def self.extended(base) base.register_default_template_handler :erb, TemplateHandlers::ERB base.register_template_handler :rjs, TemplateHandlers::RJS base.register_template_handler :builder, TemplateHandlers::Builder # TODO: Depreciate old template extensions base.register_template_handler :rhtml, TemplateHandlers::ERB base.register_template_handler :rxml, TemplateHandlers::Builder end @@template_handlers = {} @@default_template_handlers = nil # Register a class that knows how to handle template files with the given # extension. This can be used to implement new template types. # The constructor for the class must take the ActiveView::Base instance # as a parameter, and the class must implement a +render+ method that # takes the contents of the template to render as well as the Hash of # local assigns available to the template. The +render+ method ought to # return the rendered template as a string. def register_template_handler(extension, klass) @@template_handlers[extension.to_sym] = klass end def template_handler_extensions @@template_handlers.keys.map(&:to_s).sort end def registered_template_handler(extension) extension && @@template_handlers[extension.to_sym] end def register_default_template_handler(extension, klass) register_template_handler(extension, klass) @@default_template_handlers = klass end def handler_class_for_extension(extension) registered_template_handler(extension) || @@default_template_handlers end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/inline_template.rb
provider/vendor/rails/actionpack/lib/action_view/inline_template.rb
module ActionView #:nodoc: class InlineTemplate #:nodoc: include Renderable attr_reader :source, :extension, :method_segment def initialize(source, type = nil) @source = source @extension = type @method_segment = "inline_#{@source.hash.abs}" end private # Always recompile inline templates def recompile? true end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/reloadable_template.rb
provider/vendor/rails/actionpack/lib/action_view/reloadable_template.rb
module ActionView #:nodoc: class ReloadableTemplate < Template class TemplateDeleted < ActionView::ActionViewError end class ReloadablePath < Template::Path def initialize(path) super @paths = {} new_request! end def new_request! @disk_cache = {} end alias_method :load!, :new_request! def [](path) if found_template = @paths[path] begin found_template.reset_cache_if_stale! rescue TemplateDeleted unregister_template(found_template) self[path] end else load_all_templates_from_dir(templates_dir_from_path(path)) # don't ever hand out a template without running a stale check (new_template = @paths[path]) && new_template.reset_cache_if_stale! end end private def register_template_from_file(template_full_file_path) if !@paths[relative_path = relative_path_for_template_file(template_full_file_path)] && File.file?(template_full_file_path) register_template(ReloadableTemplate.new(relative_path, self)) end end def register_template(template) template.accessible_paths.each do |path| @paths[path] = template end end # remove (probably deleted) template from cache def unregister_template(template) template.accessible_paths.each do |template_path| @paths.delete(template_path) if @paths[template_path] == template end # fill in any newly created gaps @paths.values.uniq.each do |template| template.accessible_paths.each {|path| @paths[path] ||= template} end end # load all templates from the directory of the requested template def load_all_templates_from_dir(dir) # hit disk only once per template-dir/request @disk_cache[dir] ||= template_files_from_dir(dir).each {|template_file| register_template_from_file(template_file)} end def templates_dir_from_path(path) dirname = File.dirname(path) File.join(@path, dirname == '.' ? '' : dirname) end # get all the template filenames from the dir def template_files_from_dir(dir) Dir.glob(File.join(dir, '*')) end end module Unfreezable def freeze; self; end end def initialize(*args) super # we don't ever want to get frozen extend Unfreezable end def mtime File.mtime(filename) end attr_accessor :previously_last_modified def stale? previously_last_modified.nil? || previously_last_modified < mtime rescue Errno::ENOENT => e undef_my_compiled_methods! raise TemplateDeleted end def reset_cache_if_stale! if stale? flush_cache 'source', 'compiled_source' undef_my_compiled_methods! @previously_last_modified = mtime end self end # remove any compiled methods that look like they might belong to me def undef_my_compiled_methods! ActionView::Base::CompiledTemplates.public_instance_methods.grep(/#{Regexp.escape(method_name_without_locals)}(?:_locals_)?/).each do |m| ActionView::Base::CompiledTemplates.send(:remove_method, m) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/partials.rb
provider/vendor/rails/actionpack/lib/action_view/partials.rb
module ActionView # There's also a convenience method for rendering sub templates within the current controller that depends on a # single object (we call this kind of sub templates for partials). It relies on the fact that partials should # follow the naming convention of being prefixed with an underscore -- as to separate them from regular # templates that could be rendered on their own. # # In a template for Advertiser#account: # # <%= render :partial => "account" %> # # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable # +account+ to the template for display. # # In another template for Advertiser#buy, we could have: # # <%= render :partial => "account", :locals => { :account => @buyer } %> # # <% for ad in @advertisements %> # <%= render :partial => "ad", :locals => { :ad => ad } %> # <% end %> # # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. # # == Rendering a collection of partials # # The example of partial use describes a familiar pattern where a template needs to iterate over an array and # render a sub template for each of the elements. This pattern has been implemented as a single method that # accepts an array and renders a partial by the same name as the elements contained within. So the three-lined # example in "Using partials" can be rewritten with a single line: # # <%= render :partial => "ad", :collection => @advertisements %> # # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An # iteration counter will automatically be made available to the template with a name of the form # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+. # # NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also # just keep domain objects, like Active Records, in there. # # == Rendering shared partials # # Two controllers can share a set of partials and render them like this: # # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> # # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. # # == Rendering objects with the RecordIdentifier # # Instead of explicitly naming the location of a partial, you can also let the RecordIdentifier do the work if # you're following its conventions for RecordIdentifier#partial_path. Examples: # # # @account is an Account instance, so it uses the RecordIdentifier to replace # # <%= render :partial => "accounts/account", :locals => { :account => @buyer } %> # <%= render :partial => @account %> # # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace # # <%= render :partial => "posts/post", :collection => @posts %> # <%= render :partial => @posts %> # # == Rendering the default case # # If you're not going to be using any of the options like collections or layouts, you can also use the short-hand # defaults of render to render partials. Examples: # # # Instead of <%= render :partial => "account" %> # <%= render "account" %> # # # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %> # <%= render "account", :account => @buyer %> # # # @account is an Account instance, so it uses the RecordIdentifier to replace # # <%= render :partial => "accounts/account", :locals => { :account => @account } %> # <%= render(@account) %> # # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace # # <%= render :partial => "posts/post", :collection => @posts %> # <%= render(@posts) %> # # == Rendering partials with layouts # # Partials can have their own layouts applied to them. These layouts are different than the ones that are # specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types # of users: # # <%# app/views/users/index.html.erb &> # Here's the administrator: # <%= render :partial => "user", :layout => "administrator", :locals => { :user => administrator } %> # # Here's the editor: # <%= render :partial => "user", :layout => "editor", :locals => { :user => editor } %> # # <%# app/views/users/_user.html.erb &> # Name: <%= user.name %> # # <%# app/views/users/_administrator.html.erb &> # <div id="administrator"> # Budget: $<%= user.budget %> # <%= yield %> # </div> # # <%# app/views/users/_editor.html.erb &> # <div id="editor"> # Deadline: <%= user.deadline %> # <%= yield %> # </div> # # ...this will return: # # Here's the administrator: # <div id="administrator"> # Budget: $<%= user.budget %> # Name: <%= user.name %> # </div> # # Here's the editor: # <div id="editor"> # Deadline: <%= user.deadline %> # Name: <%= user.name %> # </div> # # You can also apply a layout to a block within any template: # # <%# app/views/users/_chief.html.erb &> # <% render(:layout => "administrator", :locals => { :user => chief }) do %> # Title: <%= chief.title %> # <% end %> # # ...this will return: # # <div id="administrator"> # Budget: $<%= user.budget %> # Title: <%= chief.name %> # </div> # # As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout. # # If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass # an array to layout and treat it as an enumerable. # # <%# app/views/users/_user.html.erb &> # <div class="user"> # Budget: $<%= user.budget %> # <%= yield user %> # </div> # # <%# app/views/users/index.html.erb &> # <% render :layout => @users do |user| %> # Title: <%= user.title %> # <% end %> # # This will render the layout for each user and yield to the block, passing the user, each time. # # You can also yield multiple times in one layout and use block arguments to differentiate the sections. # # <%# app/views/users/_user.html.erb &> # <div class="user"> # <%= yield user, :header %> # Budget: $<%= user.budget %> # <%= yield user, :footer %> # </div> # # <%# app/views/users/index.html.erb &> # <% render :layout => @users do |user, section| %> # <%- case section when :header -%> # Title: <%= user.title %> # <%- when :footer -%> # Deadline: <%= user.deadline %> # <%- end -%> # <% end %> module Partials extend ActiveSupport::Memoizable private def render_partial(options = {}) #:nodoc: local_assigns = options[:locals] || {} case partial_path = options[:partial] when String, Symbol, NilClass if options.has_key?(:collection) render_partial_collection(options) else _pick_partial_template(partial_path).render_partial(self, options[:object], local_assigns) end when ActionView::Helpers::FormBuilder builder_partial_path = partial_path.class.to_s.demodulize.underscore.sub(/_builder$/, '') local_assigns.merge!(builder_partial_path.to_sym => partial_path) render_partial(:partial => builder_partial_path, :object => options[:object], :locals => local_assigns) else if Array === partial_path || (defined?(ActiveRecord) && (ActiveRecord::Associations::AssociationCollection === partial_path || ActiveRecord::NamedScope::Scope === partial_path)) render_partial_collection(options.except(:partial).merge(:collection => partial_path)) else object = partial_path render_partial( :partial => ActionController::RecordIdentifier.partial_path(object, controller.class.controller_path), :object => object, :locals => local_assigns ) end end end def render_partial_collection(options = {}) #:nodoc: return nil if options[:collection].blank? partial = options[:partial] spacer = options[:spacer_template] ? render(:partial => options[:spacer_template]) : '' local_assigns = options[:locals] ? options[:locals].clone : {} as = options[:as] index = 0 options[:collection].map do |object| _partial_path ||= partial || ActionController::RecordIdentifier.partial_path(object, controller.class.controller_path) template = _pick_partial_template(_partial_path) local_assigns[template.counter_name] = index result = template.render_partial(self, object, local_assigns.dup, as) index += 1 result end.join(spacer) end def _pick_partial_template(partial_path) #:nodoc: if partial_path.include?('/') path = File.join(File.dirname(partial_path), "_#{File.basename(partial_path)}") elsif controller path = "#{controller.class.controller_path}/_#{partial_path}" else path = "_#{partial_path}" end self.view_paths.find_template(path, self.template_format) end memoize :_pick_partial_template end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb
require 'cgi' require 'action_view/helpers/date_helper' require 'action_view/helpers/tag_helper' require 'action_view/helpers/form_tag_helper' module ActionView module Helpers # Form helpers are designed to make working with models much easier # compared to using just standard HTML elements by providing a set of # methods for creating forms based on your models. This helper generates # the HTML for forms, providing a method for each sort of input # (e.g., text, password, select, and so on). When the form is submitted # (i.e., when the user hits the submit button or <tt>form.submit</tt> is # called via JavaScript), the form inputs will be bundled into the # <tt>params</tt> object and passed back to the controller. # # There are two types of form helpers: those that specifically work with # model attributes and those that don't. This helper deals with those that # work with model attributes; to see an example of form helpers that don't # work with model attributes, check the ActionView::Helpers::FormTagHelper # documentation. # # The core method of this helper, form_for, gives you the ability to create # a form for a model instance; for example, let's say that you have a model # <tt>Person</tt> and want to create a new instance of it: # # # Note: a @person variable will have been created in the controller. # # For example: @person = Person.new # <% form_for :person, @person, :url => { :action => "create" } do |f| %> # <%= f.text_field :first_name %> # <%= f.text_field :last_name %> # <%= submit_tag 'Create' %> # <% end %> # # The HTML generated for this would be: # # <form action="/persons/create" method="post"> # <input id="person_first_name" name="person[first_name]" size="30" type="text" /> # <input id="person_last_name" name="person[last_name]" size="30" type="text" /> # <input name="commit" type="submit" value="Create" /> # </form> # # If you are using a partial for your form fields, you can use this shortcut: # # <% form_for :person, @person, :url => { :action => "create" } do |f| %> # <%= render :partial => f %> # <%= submit_tag 'Create' %> # <% end %> # # This example will render the <tt>people/_form</tt> partial, setting a # local variable called <tt>form</tt> which references the yielded # FormBuilder. The <tt>params</tt> object created when this form is # submitted would look like: # # {"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}} # # The params hash has a nested <tt>person</tt> value, which can therefore # be accessed with <tt>params[:person]</tt> in the controller. If were # editing/updating an instance (e.g., <tt>Person.find(1)</tt> rather than # <tt>Person.new</tt> in the controller), the objects attribute values are # filled into the form (e.g., the <tt>person_first_name</tt> field would # have that person's first name in it). # # If the object name contains square brackets the id for the object will be # inserted. For example: # # <%= text_field "person[]", "name" %> # # ...will generate the following ERb. # # <input type="text" id="person_<%= @person.id %>_name" name="person[<%= @person.id %>][name]" value="<%= @person.name %>" /> # # If the helper is being used to generate a repetitive sequence of similar # form elements, for example in a partial used by # <tt>render_collection_of_partials</tt>, the <tt>index</tt> option may # come in handy. Example: # # <%= text_field "person", "name", "index" => 1 %> # # ...becomes... # # <input type="text" id="person_1_name" name="person[1][name]" value="<%= @person.name %>" /> # # An <tt>index</tt> option may also be passed to <tt>form_for</tt> and # <tt>fields_for</tt>. This automatically applies the <tt>index</tt> to # all the nested fields. # # There are also methods for helping to build form tags in # link:classes/ActionView/Helpers/FormOptionsHelper.html, # link:classes/ActionView/Helpers/DateHelper.html, and # link:classes/ActionView/Helpers/ActiveRecordHelper.html module FormHelper # Creates a form and a scope around a specific model object that is used # as a base for questioning about values for the fields. # # Rails provides succinct resource-oriented form generation with +form_for+ # like this: # # <% form_for @offer do |f| %> # <%= f.label :version, 'Version' %>: # <%= f.text_field :version %><br /> # <%= f.label :author, 'Author' %>: # <%= f.text_field :author %><br /> # <% end %> # # There, +form_for+ is able to generate the rest of RESTful form # parameters based on introspection on the record, but to understand what # it does we need to dig first into the alternative generic usage it is # based upon. # # === Generic form_for # # The generic way to call +form_for+ yields a form builder around a # model: # # <% form_for :person, :url => { :action => "update" } do |f| %> # <%= f.error_messages %> # First name: <%= f.text_field :first_name %><br /> # Last name : <%= f.text_field :last_name %><br /> # Biography : <%= f.text_area :biography %><br /> # Admin? : <%= f.check_box :admin %><br /> # <% end %> # # There, the first argument is a symbol or string with the name of the # object the form is about, and also the name of the instance variable # the object is stored in. # # The form builder acts as a regular form helper that somehow carries the # model. Thus, the idea is that # # <%= f.text_field :first_name %> # # gets expanded to # # <%= text_field :person, :first_name %> # # If the instance variable is not <tt>@person</tt> you can pass the actual # record as the second argument: # # <% form_for :person, person, :url => { :action => "update" } do |f| %> # ... # <% end %> # # In that case you can think # # <%= f.text_field :first_name %> # # gets expanded to # # <%= text_field :person, :first_name, :object => person %> # # You can even display error messages of the wrapped model this way: # # <%= f.error_messages %> # # In any of its variants, the rightmost argument to +form_for+ is an # optional hash of options: # # * <tt>:url</tt> - The URL the form is submitted to. It takes the same # fields you pass to +url_for+ or +link_to+. In particular you may pass # here a named route directly as well. Defaults to the current action. # * <tt>:html</tt> - Optional HTML attributes for the form tag. # # Worth noting is that the +form_for+ tag is called in a ERb evaluation # block, not an ERb output block. So that's <tt><% %></tt>, not # <tt><%= %></tt>. # # Also note that +form_for+ doesn't create an exclusive scope. It's still # possible to use both the stand-alone FormHelper methods and methods # from FormTagHelper. For example: # # <% form_for :person, @person, :url => { :action => "update" } do |f| %> # First name: <%= f.text_field :first_name %> # Last name : <%= f.text_field :last_name %> # Biography : <%= text_area :person, :biography %> # Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %> # <% end %> # # This also works for the methods in FormOptionHelper and DateHelper that # are designed to work with an object as base, like # FormOptionHelper#collection_select and DateHelper#datetime_select. # # === Resource-oriented style # # As we said above, in addition to manually configuring the +form_for+ # call, you can rely on automated resource identification, which will use # the conventions and named routes of that approach. This is the # preferred way to use +form_for+ nowadays. # # For example, if <tt>@post</tt> is an existing record you want to edit # # <% form_for @post do |f| %> # ... # <% end %> # # is equivalent to something like: # # <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %> # ... # <% end %> # # And for new records # # <% form_for(Post.new) do |f| %> # ... # <% end %> # # expands to # # <% form_for :post, Post.new, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %> # ... # <% end %> # # You can also overwrite the individual conventions, like this: # # <% form_for(@post, :url => super_post_path(@post)) do |f| %> # ... # <% end %> # # And for namespaced routes, like +admin_post_url+: # # <% form_for([:admin, @post]) do |f| %> # ... # <% end %> # # === Customized form builders # # You can also build forms using a customized FormBuilder class. Subclass # FormBuilder and override or define some more helpers, then use your # custom builder. For example, let's say you made a helper to # automatically add labels to form inputs. # # <% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %> # <%= f.text_field :first_name %> # <%= f.text_field :last_name %> # <%= text_area :person, :biography %> # <%= check_box_tag "person[admin]", @person.company.admin? %> # <% end %> # # In this case, if you use this: # # <%= render :partial => f %> # # The rendered template is <tt>people/_labelling_form</tt> and the local # variable referencing the form builder is called # <tt>labelling_form</tt>. # # The custom FormBuilder class is automatically merged with the options # of a nested fields_for call, unless it's explicitely set. # # In many cases you will want to wrap the above in another helper, so you # could do something like the following: # # def labelled_form_for(record_or_name_or_array, *args, &proc) # options = args.extract_options! # form_for(record_or_name_or_array, *(args << options.merge(:builder => LabellingFormBuilder)), &proc) # end # # If you don't need to attach a form to a model instance, then check out # FormTagHelper#form_tag. def form_for(record_or_name_or_array, *args, &proc) raise ArgumentError, "Missing block" unless block_given? options = args.extract_options! case record_or_name_or_array when String, Symbol object_name = record_or_name_or_array when Array object = record_or_name_or_array.last object_name = ActionController::RecordIdentifier.singular_class_name(object) apply_form_for_options!(record_or_name_or_array, options) args.unshift object else object = record_or_name_or_array object_name = ActionController::RecordIdentifier.singular_class_name(object) apply_form_for_options!([object], options) args.unshift object end concat(form_tag(options.delete(:url) || {}, options.delete(:html) || {})) fields_for(object_name, *(args << options), &proc) concat('</form>') end def apply_form_for_options!(object_or_array, options) #:nodoc: object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array html_options = if object.respond_to?(:new_record?) && object.new_record? { :class => dom_class(object, :new), :id => dom_id(object), :method => :post } else { :class => dom_class(object, :edit), :id => dom_id(object, :edit), :method => :put } end options[:html] ||= {} options[:html].reverse_merge!(html_options) options[:url] ||= polymorphic_path(object_or_array) end # Creates a scope around a specific model object like form_for, but # doesn't create the form tags themselves. This makes fields_for suitable # for specifying additional model objects in the same form. # # === Generic Examples # # <% form_for @person, :url => { :action => "update" } do |person_form| %> # First name: <%= person_form.text_field :first_name %> # Last name : <%= person_form.text_field :last_name %> # # <% fields_for @person.permission do |permission_fields| %> # Admin? : <%= permission_fields.check_box :admin %> # <% end %> # <% end %> # # ...or if you have an object that needs to be represented as a different # parameter, like a Client that acts as a Person: # # <% fields_for :person, @client do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # # ...or if you don't have an object, just a name of the parameter: # # <% fields_for :person do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # # Note: This also works for the methods in FormOptionHelper and # DateHelper that are designed to work with an object as base, like # FormOptionHelper#collection_select and DateHelper#datetime_select. # # === Nested Attributes Examples # # When the object belonging to the current scope has a nested attribute # writer for a certain attribute, fields_for will yield a new scope # for that attribute. This allows you to create forms that set or change # the attributes of a parent object and its associations in one go. # # Nested attribute writers are normal setter methods named after an # association. The most common way of defining these writers is either # with +accepts_nested_attributes_for+ in a model definition or by # defining a method with the proper name. For example: the attribute # writer for the association <tt>:address</tt> is called # <tt>address_attributes=</tt>. # # Whether a one-to-one or one-to-many style form builder will be yielded # depends on whether the normal reader method returns a _single_ object # or an _array_ of objects. # # ==== One-to-one # # Consider a Person class which returns a _single_ Address from the # <tt>address</tt> reader method and responds to the # <tt>address_attributes=</tt> writer method: # # class Person # def address # @address # end # # def address_attributes=(attributes) # # Process the attributes hash # end # end # # This model can now be used with a nested fields_for, like so: # # <% form_for @person, :url => { :action => "update" } do |person_form| %> # ... # <% person_form.fields_for :address do |address_fields| %> # Street : <%= address_fields.text_field :street %> # Zip code: <%= address_fields.text_field :zip_code %> # <% end %> # <% end %> # # When address is already an association on a Person you can use # +accepts_nested_attributes_for+ to define the writer method for you: # # class Person < ActiveRecord::Base # has_one :address # accepts_nested_attributes_for :address # end # # If you want to destroy the associated model through the form, you have # to enable it first using the <tt>:allow_destroy</tt> option for # +accepts_nested_attributes_for+: # # class Person < ActiveRecord::Base # has_one :address # accepts_nested_attributes_for :address, :allow_destroy => true # end # # Now, when you use a form element with the <tt>_delete</tt> parameter, # with a value that evaluates to +true+, you will destroy the associated # model (eg. 1, '1', true, or 'true'): # # <% form_for @person, :url => { :action => "update" } do |person_form| %> # ... # <% person_form.fields_for :address do |address_fields| %> # ... # Delete: <%= address_fields.check_box :_delete %> # <% end %> # <% end %> # # ==== One-to-many # # Consider a Person class which returns an _array_ of Project instances # from the <tt>projects</tt> reader method and responds to the # <tt>projects_attributes=</tt> writer method: # # class Person # def projects # [@project1, @project2] # end # # def projects_attributes=(attributes) # # Process the attributes hash # end # end # # This model can now be used with a nested fields_for. The block given to # the nested fields_for call will be repeated for each instance in the # collection: # # <% form_for @person, :url => { :action => "update" } do |person_form| %> # ... # <% person_form.fields_for :projects do |project_fields| %> # <% if project_fields.object.active? %> # Name: <%= project_fields.text_field :name %> # <% end %> # <% end %> # <% end %> # # It's also possible to specify the instance to be used: # # <% form_for @person, :url => { :action => "update" } do |person_form| %> # ... # <% @person.projects.each do |project| %> # <% if project.active? %> # <% person_form.fields_for :projects, project do |project_fields| %> # Name: <%= project_fields.text_field :name %> # <% end %> # <% end %> # <% end %> # <% end %> # # When projects is already an association on Person you can use # +accepts_nested_attributes_for+ to define the writer method for you: # # class Person < ActiveRecord::Base # has_many :projects # accepts_nested_attributes_for :projects # end # # If you want to destroy any of the associated models through the # form, you have to enable it first using the <tt>:allow_destroy</tt> # option for +accepts_nested_attributes_for+: # # class Person < ActiveRecord::Base # has_many :projects # accepts_nested_attributes_for :projects, :allow_destroy => true # end # # This will allow you to specify which models to destroy in the # attributes hash by adding a form element for the <tt>_delete</tt> # parameter with a value that evaluates to +true+ # (eg. 1, '1', true, or 'true'): # # <% form_for @person, :url => { :action => "update" } do |person_form| %> # ... # <% person_form.fields_for :projects do |project_fields| %> # Delete: <%= project_fields.check_box :_delete %> # <% end %> # <% end %> def fields_for(record_or_name_or_array, *args, &block) raise ArgumentError, "Missing block" unless block_given? options = args.extract_options! case record_or_name_or_array when String, Symbol object_name = record_or_name_or_array object = args.first else object = record_or_name_or_array object_name = ActionController::RecordIdentifier.singular_class_name(object) end builder = options[:builder] || ActionView::Base.default_form_builder yield builder.new(object_name, object, self, options, block) end # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). The text of label will default to the attribute name unless you specify # it explicitly. Additional options on the label tag can be passed as a hash with +options+. These options will be tagged # onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to # target labels for radio_button tags (where the value is used in the ID of the input tag). # # ==== Examples # label(:post, :title) # # => <label for="post_title">Title</label> # # label(:post, :title, "A short title") # # => <label for="post_title">A short title</label> # # label(:post, :title, "A short title", :class => "title_label") # # => <label for="post_title" class="title_label">A short title</label> # # label(:post, :privacy, "Public Post", :value => "public") # # => <label for="post_privacy_public">Public Post</label> # def label(object_name, method, text = nil, options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_label_tag(text, options) end # Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example # shown. # # ==== Examples # text_field(:post, :title, :size => 20) # # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" /> # # text_field(:post, :title, :class => "create_input") # # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" /> # # text_field(:session, :user, :onchange => "if $('session[user]').value == 'admin' { alert('Your login can not be admin!'); }") # # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange = "if $('session[user]').value == 'admin' { alert('Your login can not be admin!'); }"/> # # text_field(:snippet, :code, :size => 20, :class => 'code_input') # # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" /> # def text_field(object_name, method, options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("text", options) end # Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example # shown. # # ==== Examples # password_field(:login, :pass, :size => 20) # # => <input type="text" id="login_pass" name="login[pass]" size="20" value="#{@login.pass}" /> # # password_field(:account, :secret, :class => "form_input") # # => <input type="text" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" /> # # password_field(:user, :password, :onchange => "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }") # # => <input type="text" id="user_password" name="user[password]" value="#{@user.password}" onchange = "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }"/> # # password_field(:account, :pin, :size => 20, :class => 'form_input') # # => <input type="text" id="account_pin" name="account[pin]" size="20" value="#{@account.pin}" class="form_input" /> # def password_field(object_name, method, options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("password", options) end # Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example # shown. # # ==== Examples # hidden_field(:signup, :pass_confirm) # # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" /> # # hidden_field(:post, :tag_list) # # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" /> # # hidden_field(:user, :token) # # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" /> def hidden_field(object_name, method, options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("hidden", options) end # Returns an file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example # shown. # # ==== Examples # file_field(:user, :avatar) # # => <input type="file" id="user_avatar" name="user[avatar]" /> # # file_field(:post, :attached, :accept => 'text/html') # # => <input type="file" id="post_attached" name="post[attached]" /> # # file_field(:attachment, :file, :class => 'file_input') # # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" /> # def file_field(object_name, method, options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("file", options) end # Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+) # on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a # hash with +options+. # # ==== Examples # text_area(:post, :body, :cols => 20, :rows => 40) # # => <textarea cols="20" rows="40" id="post_body" name="post[body]"> # # #{@post.body} # # </textarea> # # text_area(:comment, :text, :size => "20x30") # # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]"> # # #{@comment.text} # # </textarea> # # text_area(:application, :notes, :cols => 40, :rows => 15, :class => 'app_input') # # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input"> # # #{@application.notes} # # </textarea> # # text_area(:entry, :body, :size => "20x20", :disabled => 'disabled') # # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled"> # # #{@entry.body} # # </textarea> def text_area(object_name, method, options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_text_area_tag(options) end # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object. # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked. # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1 # while the default +unchecked_value+ is set to 0 which is convenient for boolean values. # # ==== Gotcha # # The HTML specification says unchecked check boxes are not successful, and # thus web browsers do not send them. Unfortunately this introduces a gotcha: # if an Invoice model has a +paid+ flag, and in the form that edits a paid # invoice the user unchecks its check box, no +paid+ parameter is sent. So, # any mass-assignment idiom like # # @invoice.update_attributes(params[:invoice]) # # wouldn't update the flag. # # To prevent this the helper generates a hidden field with the same name as # the checkbox after the very check box. So, the client either sends only the # hidden field (representing the check box is unchecked), or both fields. # Since the HTML specification says key/value pairs have to be sent in the # same order they appear in the form and Rails parameters extraction always # gets the first occurrence of any given key, that works in ordinary forms. # # Unfortunately that workaround does not work when the check box goes # within an array-like parameter, as in # # <% fields_for "project[invoice_attributes][]", invoice, :index => nil do |form| %> # <%= form.check_box :paid %> # ... # <% end %> # # because parameter name repetition is precisely what Rails seeks to distinguish # the elements of the array. # # ==== Examples # # Let's say that @post.validated? is 1: # check_box("post", "validated") # # => <input type="checkbox" id="post_validated" name="post[validated]" value="1" /> # # <input name="post[validated]" type="hidden" value="0" /> # # # Let's say that @puppy.gooddog is "no": # check_box("puppy", "gooddog", {}, "yes", "no") # # => <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" /> # # <input name="puppy[gooddog]" type="hidden" value="no" /> # # check_box("eula", "accepted", { :class => 'eula_check' }, "yes", "no") # # => <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" /> # # <input name="eula[accepted]" type="hidden" value="no" /> # def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0") InstanceTag.new(object_name, method, self, options.delete(:object)).to_check_box_tag(options, checked_value, unchecked_value) end # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the # radio button will be checked. # # To force the radio button to be checked pass <tt>:checked => true</tt> in the # +options+ hash. You may pass HTML options there as well. # # ==== Examples # # Let's say that @post.category returns "rails": # radio_button("post", "category", "rails") # radio_button("post", "category", "java") # # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" /> # # <input type="radio" id="post_category_java" name="post[category]" value="java" /> # # radio_button("user", "receive_newsletter", "yes") # radio_button("user", "receive_newsletter", "no") # # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" /> # # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" /> def radio_button(object_name, method, tag_value, options = {})
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb
require 'cgi' require 'erb' require 'action_view/helpers/form_helper' module ActionView module Helpers # Provides a number of methods for turning different kinds of containers into a set of option tags. # == Options # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash: # # * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element. # # For example, # # select("post", "category", Post::CATEGORIES, {:include_blank => true}) # # could become: # # <select name="post[category]"> # <option></option> # <option>joke</option> # <option>poem</option> # </select> # # Another common case is a select tag for an <tt>belongs_to</tt>-associated object. # # Example with @post.person_id => 2: # # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'}) # # could become: # # <select name="post[person_id]"> # <option value="">None</option> # <option value="1">David</option> # <option value="2" selected="selected">Sam</option> # <option value="3">Tobias</option> # </select> # # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string. # # Example: # # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'}) # # could become: # # <select name="post[person_id]"> # <option value="">Select Person</option> # <option value="1">David</option> # <option value="2">Sam</option> # <option value="3">Tobias</option> # </select> # # Like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this # option to be in the +html_options+ parameter. # # Example: # # select("album[]", "genre", %w[rap rock country], {}, { :index => nil }) # # becomes: # # <select name="album[][genre]" id="album__genre"> # <option value="rap">rap</option> # <option value="rock">rock</option> # <option value="country">country</option> # </select> # # * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output. # # Example: # # select("post", "category", Post::CATEGORIES, {:disabled => 'restricted'}) # # could become: # # <select name="post[category]"> # <option></option> # <option>joke</option> # <option>poem</option> # <option disabled="disabled">restricted</option> # </select> # # When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled. # # Example: # # collection_select(:post, :category_id, Category.all, :id, :name, {:disabled => lambda{|category| category.archived? }}) # # If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return: # <select name="post[category_id]"> # <option value="1" disabled="disabled">2008 stuff</option> # <option value="2" disabled="disabled">Christmas</option> # <option value="3">Jokes</option> # <option value="4">Poems</option> # </select> # module FormOptionsHelper include ERB::Util # Create a select tag and a series of contained option tags for the provided object and method. # The option currently held by the object will be selected, provided that the object is available. # See options_for_select for the required format of the choices parameter. # # Example with @post.person_id => 1: # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true }) # # could become: # # <select name="post[person_id]"> # <option value=""></option> # <option value="1" selected="selected">David</option> # <option value="2">Sam</option> # <option value="3">Tobias</option> # </select> # # This can be used to provide a default set of options in the standard way: before rendering the create form, a # new model instance is assigned the default options and bound to @model_name. Usually this model is not saved # to the database. Instead, a second model object is created when the create request is received. # This allows the user to submit a form page more than once with the expected results of creating multiple records. # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms. # # By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection # or <tt>:selected => nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option # tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled. def select(object, method, choices, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_select_tag(choices, options, html_options) end # Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt> # or <tt>:include_blank</tt> in the +options+ hash. # # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member # of +collection+. The return values are used as the +value+ attribute and contents of each # <tt><option></tt> tag, respectively. # # Example object structure for use with this method: # class Post < ActiveRecord::Base # belongs_to :author # end # class Author < ActiveRecord::Base # has_many :posts # def name_with_initial # "#{first_name.first}. #{last_name}" # end # end # # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>): # collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true}) # # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return: # <select name="post[author_id]"> # <option value="">Please select</option> # <option value="1" selected="selected">D. Heinemeier Hansson</option> # <option value="2">D. Thomas</option> # <option value="3">M. Clark</option> # </select> def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_collection_select_tag(collection, value_method, text_method, options, html_options) end # Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt> # or <tt>:include_blank</tt> in the +options+ hash. # # Parameters: # * +object+ - The instance of the class to be used for the select tag # * +method+ - The attribute of +object+ corresponding to the select tag # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags. # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an # array of child objects representing the <tt><option></tt> tags. # * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag. # * +option_key_method+ - The name of a method which, when called on a child object of a member of # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag. # * +option_value_method+ - The name of a method which, when called on a child object of a member of # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag. # # Example object structure for use with this method: # class Continent < ActiveRecord::Base # has_many :countries # # attribs: id, name # end # class Country < ActiveRecord::Base # belongs_to :continent # # attribs: id, name, continent_id # end # class City < ActiveRecord::Base # belongs_to :country # # attribs: id, name, country_id # end # # Sample usage: # grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name) # # Possible output: # <select name="city[country_id]"> # <optgroup label="Africa"> # <option value="1">South Africa</option> # <option value="3">Somalia</option> # </optgroup> # <optgroup label="Europe"> # <option value="7" selected="selected">Denmark</option> # <option value="2">Ireland</option> # </optgroup> # </select> # def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_grouped_collection_select_tag(collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options) end # Return select and option tags for the given object and method, using # #time_zone_options_for_select to generate the list of option tags. # # In addition to the <tt>:include_blank</tt> option documented above, # this method also supports a <tt>:model</tt> option, which defaults # to TimeZone. This may be used by users to specify a different time # zone model object. (See +time_zone_options_for_select+ for more # information.) # # You can also supply an array of TimeZone objects # as +priority_zones+, so that they will be listed above the rest of the # (long) list. (You can use TimeZone.us_zones as a convenience for # obtaining a list of the US time zones, or a Regexp to select the zones # of your choice) # # Finally, this method supports a <tt>:default</tt> option, which selects # a default TimeZone if the object's time zone is +nil+. # # Examples: # time_zone_select( "user", "time_zone", nil, :include_blank => true) # # time_zone_select( "user", "time_zone", nil, :default => "Pacific Time (US & Canada)" ) # # time_zone_select( "user", 'time_zone', TimeZone.us_zones, :default => "Pacific Time (US & Canada)") # # time_zone_select( "user", 'time_zone', [ TimeZone['Alaska'], TimeZone['Hawaii'] ]) # # time_zone_select( "user", 'time_zone', /Australia/) # # time_zone_select( "user", "time_zone", TZInfo::Timezone.all.sort, :model => TZInfo::Timezone) def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options) end # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+ # may also be an array of values to be selected when using a multiple select. # # Examples (call, result): # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]]) # <option value="$">Dollar</option>\n<option value="DKK">Kroner</option> # # options_for_select([ "VISA", "MasterCard" ], "MasterCard") # <option>VISA</option>\n<option selected="selected">MasterCard</option> # # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40") # <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option> # # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"]) # <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option> # # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags. # # Examples: # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum") # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> # # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"]) # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> # # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum") # <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> # # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. def options_for_select(container, selected = nil) return container if String === container container = container.to_a if Hash === container selected, disabled = extract_selected_and_disabled(selected) options_for_select = container.inject([]) do |options, element| text, value = option_text_and_value(element) selected_attribute = ' selected="selected"' if option_value_selected?(value, selected) disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled) options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}>#{html_escape(text.to_s)}</option>) end options_for_select.join("\n") end # Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. # Example: # options_from_collection_for_select(@people, 'id', 'name') # This will output the same HTML as if you did this: # <option value="#{person.id}">#{person.name}</option> # # This is more often than not used inside a #select_tag like this example: # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name') # # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+ # will be selected option tag(s). # # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous # function are the selected values. # # +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required. # # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options. # Failure to do this will produce undesired results. Example: # options_from_collection_for_select(@people, 'id', 'name', '1') # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string) # options_from_collection_for_select(@people, 'id', 'name', 1) # should produce the desired results. def options_from_collection_for_select(collection, value_method, text_method, selected = nil) options = collection.map do |element| [element.send(text_method), element.send(value_method)] end selected, disabled = extract_selected_and_disabled(selected) select_deselect = {} select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected) select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled) options_for_select(options, select_deselect) end # Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but # groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments. # # Parameters: # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags. # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an # array of child objects representing the <tt><option></tt> tags. # * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag. # * +option_key_method+ - The name of a method which, when called on a child object of a member of # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag. # * +option_value_method+ - The name of a method which, when called on a child object of a member of # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag. # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags, # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are # to be specified. # # Example object structure for use with this method: # class Continent < ActiveRecord::Base # has_many :countries # # attribs: id, name # end # class Country < ActiveRecord::Base # belongs_to :continent # # attribs: id, name, continent_id # end # # Sample usage: # option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3) # # Possible output: # <optgroup label="Africa"> # <option value="1">Egypt</option> # <option value="4">Rwanda</option> # ... # </optgroup> # <optgroup label="Asia"> # <option value="3" selected="selected">China</option> # <option value="12">India</option> # <option value="5">Japan</option> # ... # </optgroup> # # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to # wrap the output in an appropriate <tt><select></tt> tag. def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil) collection.inject("") do |options_for_select, group| group_label_string = eval("group.#{group_label_method}") options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">" options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key) options_for_select += '</optgroup>' end end # Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but # wraps them with <tt><optgroup></tt> tags. # # Parameters: # * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the # <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a # nested array of text-value pairs. See <tt>options_for_select</tt> for more info. # Ex. ["North America",[["United States","US"],["Canada","CA"]]] # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags, # which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options # as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>. # * +prompt+ - set to true or a prompt string. When the select element doesn’t have a value yet, this # prepends an option with a generic prompt — "Please select" — or the given prompt string. # # Sample usage (Array): # grouped_options = [ # ['North America', # [['United States','US'],'Canada']], # ['Europe', # ['Denmark','Germany','France']] # ] # grouped_options_for_select(grouped_options) # # Sample usage (Hash): # grouped_options = { # 'North America' => [['United States','US], 'Canada'], # 'Europe' => ['Denmark','Germany','France'] # } # grouped_options_for_select(grouped_options) # # Possible output: # <optgroup label="Europe"> # <option value="Denmark">Denmark</option> # <option value="Germany">Germany</option> # <option value="France">France</option> # </optgroup> # <optgroup label="North America"> # <option value="US">United States</option> # <option value="Canada">Canada</option> # </optgroup> # # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to # wrap the output in an appropriate <tt><select></tt> tag. def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil) body = '' body << content_tag(:option, prompt, :value => "") if prompt grouped_options = grouped_options.sort if grouped_options.is_a?(Hash) grouped_options.each do |group| body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0]) end body end # Returns a string of option tags for pretty much any time zone in the # world. Supply a TimeZone name as +selected+ to have it marked as the # selected option tag. You can also supply an array of TimeZone objects # as +priority_zones+, so that they will be listed above the rest of the # (long) list. (You can use TimeZone.us_zones as a convenience for # obtaining a list of the US time zones, or a Regexp to select the zones # of your choice) # # The +selected+ parameter must be either +nil+, or a string that names # a TimeZone. # # By default, +model+ is the TimeZone constant (which can be obtained # in Active Record as a value object). The only requirement is that the # +model+ parameter be an object that responds to +all+, and returns # an array of objects that represent time zones. # # NOTE: Only the option tags are returned, you have to wrap this call in # a regular HTML select tag. def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone) zone_options = "" zones = model.all convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } } if priority_zones if priority_zones.is_a?(Regexp) priority_zones = model.all.find_all {|z| z =~ priority_zones} end zone_options += options_for_select(convert_zones[priority_zones], selected) zone_options += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" zones = zones.reject { |z| priority_zones.include?( z ) } end zone_options += options_for_select(convert_zones[zones], selected) zone_options end private def option_text_and_value(option) # Options are [text, value] pairs or strings used for both. if !option.is_a?(String) and option.respond_to?(:first) and option.respond_to?(:last) [option.first, option.last] else [option, option] end end def option_value_selected?(value, selected) if selected.respond_to?(:include?) && !selected.is_a?(String) selected.include? value else value == selected end end def extract_selected_and_disabled(selected) if selected.is_a?(Hash) [selected[:selected], selected[:disabled]] else [selected, nil] end end def extract_values_from_collection(collection, value_method, selected) if selected.is_a?(Proc) collection.map do |element| element.send(value_method) if selected.call(element) end.compact else selected end end end class InstanceTag #:nodoc: include FormOptionsHelper def to_select_tag(choices, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) value = value(object) selected_value = options.has_key?(:selected) ? options[:selected] : value disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil content_tag("select", add_options(options_for_select(choices, :selected => selected_value, :disabled => disabled_value), options, selected_value), html_options) end def to_collection_select_tag(collection, value_method, text_method, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) value = value(object) disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil selected_value = options.has_key?(:selected) ? options[:selected] : value content_tag( "select", add_options(options_from_collection_for_select(collection, value_method, text_method, :selected => selected_value, :disabled => disabled_value), options, value), html_options ) end def to_grouped_collection_select_tag(collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) value = value(object) content_tag( "select", add_options(option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, value), options, value), html_options ) end def to_time_zone_select_tag(priority_zones, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) value = value(object) content_tag("select", add_options( time_zone_options_for_select(value || options[:default], priority_zones, options[:model] || ActiveSupport::TimeZone), options, value ), html_options ) end private def add_options(option_tags, options, value = nil) if options[:include_blank] option_tags = "<option value=\"\">#{options[:include_blank] if options[:include_blank].kind_of?(String)}</option>\n" + option_tags end if value.blank? && options[:prompt] prompt = options[:prompt].kind_of?(String) ? options[:prompt] : I18n.translate('support.select.prompt', :default => 'Please select') "<option value=\"\">#{prompt}</option>\n" + option_tags else option_tags end end end class FormBuilder def select(method, choices, options = {}, html_options = {}) @template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options)) end def collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) @template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options)) end def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) @template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options)) end def time_zone_select(method, priority_zones = nil, options = {}, html_options = {}) @template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options)) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb
module ActionView module Helpers # CaptureHelper exposes methods to let you extract generated markup which # can be used in other parts of a template or layout file. # It provides a method to capture blocks into variables through capture and # a way to capture a block of markup for use in a layout through content_for. module CaptureHelper # The capture method allows you to extract part of a template into a # variable. You can then use this variable anywhere in your templates or layout. # # ==== Examples # The capture method can be used in ERb templates... # # <% @greeting = capture do %> # Welcome to my shiny new web page! The date and time is # <%= Time.now %> # <% end %> # # ...and Builder (RXML) templates. # # @timestamp = capture do # "The current timestamp is #{Time.now}." # end # # You can then use that variable anywhere else. For example: # # <html> # <head><title><%= @greeting %></title></head> # <body> # <b><%= @greeting %></b> # </body></html> # def capture(*args, &block) # Return captured buffer in erb. if block_called_from_erb?(block) with_output_buffer { block.call(*args) } else # Return block result otherwise, but protect buffer also. with_output_buffer { return block.call(*args) } end end # Calling content_for stores a block of markup in an identifier for later use. # You can make subsequent calls to the stored content in other templates or the layout # by passing the identifier as an argument to <tt>yield</tt>. # # ==== Examples # # <% content_for :not_authorized do %> # alert('You are not authorized to do that!') # <% end %> # # You can then use <tt>yield :not_authorized</tt> anywhere in your templates. # # <%= yield :not_authorized if current_user.nil? %> # # You can also use this syntax alongside an existing call to <tt>yield</tt> in a layout. For example: # # <%# This is the layout %> # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> # <head> # <title>My Website</title> # <%= yield :script %> # </head> # <body> # <%= yield %> # </body> # </html> # # And now, we'll create a view that has a content_for call that # creates the <tt>script</tt> identifier. # # <%# This is our view %> # Please login! # # <% content_for :script do %> # <script type="text/javascript">alert('You are not authorized to view this page!')</script> # <% end %> # # Then, in another view, you could to do something like this: # # <%= link_to_remote 'Logout', :action => 'logout' %> # # <% content_for :script do %> # <%= javascript_include_tag :defaults %> # <% end %> # # That will place <script> tags for Prototype, Scriptaculous, and application.js (if it exists) # on the page; this technique is useful if you'll only be using these scripts in a few views. # # Note that content_for concatenates the blocks it is given for a particular # identifier in order. For example: # # <% content_for :navigation do %> # <li><%= link_to 'Home', :action => 'index' %></li> # <% end %> # # <%# Add some other content, or use a different template: %> # # <% content_for :navigation do %> # <li><%= link_to 'Login', :action => 'login' %></li> # <% end %> # # Then, in another template or layout, this code would render both links in order: # # <ul><%= yield :navigation %></ul> # # Lastly, simple content can be passed as a parameter: # # <% content_for :script, javascript_include_tag(:defaults) %> # # WARNING: content_for is ignored in caches. So you shouldn't use it # for elements that will be fragment cached. # # The deprecated way of accessing a content_for block is to use an instance variable # named <tt>@content_for_#{name_of_the_content_block}</tt>. The preferred usage is now # <tt><%= yield :footer %></tt>. def content_for(name, content = nil, &block) ivar = "@content_for_#{name}" content = capture(&block) if block_given? instance_variable_set(ivar, "#{instance_variable_get(ivar)}#{content}") nil end # Use an alternate output buffer for the duration of the block. # Defaults to a new empty string. def with_output_buffer(buf = '') #:nodoc: self.output_buffer, old_buffer = buf, output_buffer yield output_buffer ensure self.output_buffer = old_buffer end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb
#require 'action_view/helpers/javascript_helper' module ActionView module Helpers #:nodoc: # Provides a set of methods for making links and getting URLs that # depend on the routing subsystem (see ActionController::Routing). # This allows you to use the same format for links in views # and controllers. module UrlHelper include JavaScriptHelper # Returns the URL for the set of +options+ provided. This takes the # same options as +url_for+ in Action Controller (see the # documentation for ActionController::Base#url_for). Note that by default # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative /controller/action # instead of the fully qualified URL like http://example.com/controller/action. # # When called from a view, url_for returns an HTML escaped url. If you # need an unescaped url, pass <tt>:escape => false</tt> in the +options+. # # ==== Options # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path. # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified). # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this # is currently not recommended since it breaks caching. # * <tt>:host</tt> - Overrides the default (current) host if provided. # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided. # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present). # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present). # * <tt>:escape</tt> - Determines whether the returned URL will be HTML escaped or not (<tt>true</tt> by default). # # ==== Relying on named routes # # If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter, # you'll trigger the named route for that record. The lookup will happen on the name of the class. So passing # a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as # admin_workshop_path you'll have to call that explicitly (it's impossible for url_for to guess that route). # # ==== Examples # <%= url_for(:action => 'index') %> # # => /blog/ # # <%= url_for(:action => 'find', :controller => 'books') %> # # => /books/find # # <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %> # # => https://www.railsapplication.com/members/login/ # # <%= url_for(:action => 'play', :anchor => 'player') %> # # => /messages/play/#player # # <%= url_for(:action => 'checkout', :anchor => 'tax&ship') %> # # => /testing/jump/#tax&amp;ship # # <%= url_for(:action => 'checkout', :anchor => 'tax&ship', :escape => false) %> # # => /testing/jump/#tax&ship # # <%= url_for(Workshop.new) %> # # relies on Workshop answering a new_record? call (and in this case returning true) # # => /workshops # # <%= url_for(@workshop) %> # # calls @workshop.to_s # # => /workshops/5 # # <%= url_for("http://www.example.com") %> # # => http://www.example.com # # <%= url_for(:back) %> # # if request.env["HTTP_REFERER"] is set to "http://www.example.com" # # => http://www.example.com # # <%= url_for(:back) %> # # if request.env["HTTP_REFERER"] is not set or is blank # # => javascript:history.back() def url_for(options = {}) options ||= {} url = case options when String escape = true options when Hash options = { :only_path => options[:host].nil? }.update(options.symbolize_keys) escape = options.key?(:escape) ? options.delete(:escape) : true @controller.send(:url_for, options) when :back escape = false @controller.request.env["HTTP_REFERER"] || 'javascript:history.back()' else escape = false polymorphic_path(options) end escape ? escape_once(url) : url end # Creates a link tag of the given +name+ using a URL created by the set # of +options+. See the valid options in the documentation for # url_for. It's also possible to pass a string instead # of an options hash to get a link tag that uses the value of the string as the # href for the link, or use <tt>:back</tt> to link to the referrer - a JavaScript back # link will be used in place of a referrer if none exists. If nil is passed as # a name, the link itself will become the name. # # ==== Signatures # # link_to(name, options = {}, html_options = nil) # link_to(options = {}, html_options = nil) do # # name # end # # ==== Options # * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm # prompt with the question specified. If the user accepts, the link is # processed normally, otherwise no action is taken. # * <tt>:popup => true || array of window options</tt> - This will force the # link to open in a popup window. By passing true, a default browser window # will be opened with the URL. You can also specify an array of options # that are passed-thru to JavaScripts window.open method. # * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically # create an HTML form and immediately submit the form for processing using # the HTTP verb specified. Useful for having links perform a POST operation # in dangerous actions like deleting a record (which search bots can follow # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>. # Note that if the user has JavaScript disabled, the request will fall back # to using GET. If you are relying on the POST behavior, you should check # for it in your controller's action by using the request object's methods # for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>. # * The +html_options+ will accept a hash of html attributes for the link tag. # # Note that if the user has JavaScript disabled, the request will fall back # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript disabled # clicking the link will have no effect. If you are relying on the POST # behavior, your should check for it in your controller's action by using the # request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>. # # You can mix and match the +html_options+ with the exception of # <tt>:popup</tt> and <tt>:method</tt> which will raise an ActionView::ActionViewError # exception. # # ==== Examples # Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments # and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base # your application on resources and use # # link_to "Profile", profile_path(@profile) # # => <a href="/profiles/1">Profile</a> # # or the even pithier # # link_to "Profile", @profile # # => <a href="/profiles/1">Profile</a> # # in place of the older more verbose, non-resource-oriented # # link_to "Profile", :controller => "profiles", :action => "show", :id => @profile # # => <a href="/profiles/show/1">Profile</a> # # Similarly, # # link_to "Profiles", profiles_path # # => <a href="/profiles">Profiles</a> # # is better than # # link_to "Profiles", :controller => "profiles" # # => <a href="/profiles">Profiles</a> # # You can use a block as well if your link target is hard to fit into the name parameter. ERb example: # # <% link_to(@profile) do %> # <strong><%= @profile.name %></strong> -- <span>Check it out!!</span> # <% end %> # # => <a href="/profiles/1"><strong>David</strong> -- <span>Check it out!!</span></a> # # Classes and ids for CSS are easy to produce: # # link_to "Articles", articles_path, :id => "news", :class => "article" # # => <a href="/articles" class="article" id="news">Articles</a> # # Be careful when using the older argument style, as an extra literal hash is needed: # # link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article" # # => <a href="/articles" class="article" id="news">Articles</a> # # Leaving the hash off gives the wrong link: # # link_to "WRONG!", :controller => "articles", :id => "news", :class => "article" # # => <a href="/articles/index/news?class=article">WRONG!</a> # # +link_to+ can also produce links with anchors or query strings: # # link_to "Comment wall", profile_path(@profile, :anchor => "wall") # # => <a href="/profiles/1#wall">Comment wall</a> # # link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails" # # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a> # # link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux") # # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a> # # The three options specific to +link_to+ (<tt>:confirm</tt>, <tt>:popup</tt>, and <tt>:method</tt>) are used as follows: # # link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?" # # => <a href="http://www.rubyonrails.org/" onclick="return confirm('Are you sure?');">Visit Other Site</a> # # link_to "Help", { :action => "help" }, :popup => true # # => <a href="/testing/help/" onclick="window.open(this.href);return false;">Help</a> # # link_to "View Image", @image, :popup => ['new_window_name', 'height=300,width=600'] # # => <a href="/images/9" onclick="window.open(this.href,'new_window_name','height=300,width=600');return false;">View Image</a> # # link_to "Delete Image", @image, :confirm => "Are you sure?", :method => :delete # # => <a href="/images/9" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); # f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href; # var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); # m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete Image</a> def link_to(*args, &block) if block_given? options = args.first || {} html_options = args.second concat(link_to(capture(&block), options, html_options)) else name = args.first options = args.second || {} html_options = args.third url = url_for(options) if html_options html_options = html_options.stringify_keys href = html_options['href'] convert_options_to_javascript!(html_options, url) tag_options = tag_options(html_options) else tag_options = nil end href_attr = "href=\"#{url}\"" unless href "<a #{href_attr}#{tag_options}>#{name || url}</a>" end end # Generates a form containing a single button that submits to the URL created # by the set of +options+. This is the safest method to ensure links that # cause changes to your data are not triggered by search bots or accelerators. # If the HTML button does not work with your layout, you can also consider # using the link_to method with the <tt>:method</tt> modifier as described in # the link_to documentation. # # The generated FORM element has a class name of <tt>button-to</tt> # to allow styling of the form itself and its children. You can control # the form submission and input element behavior using +html_options+. # This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers # described in the link_to documentation. If no <tt>:method</tt> modifier # is given, it will default to performing a POST operation. You can also # disable the button by passing <tt>:disabled => true</tt> in +html_options+. # If you are using RESTful routes, you can pass the <tt>:method</tt> # to change the HTTP verb used to submit the form. # # ==== Options # The +options+ hash accepts the same options at url_for. # # There are a few special +html_options+: # * <tt>:method</tt> - Specifies the anchor name to be appended to the path. # * <tt>:disabled</tt> - Specifies the anchor name to be appended to the path. # * <tt>:confirm</tt> - This will add a JavaScript confirm # prompt with the question specified. If the user accepts, the link is # processed normally, otherwise no action is taken. # # ==== Examples # <%= button_to "New", :action => "new" %> # # => "<form method="post" action="/controller/new" class="button-to"> # # <div><input value="New" type="submit" /></div> # # </form>" # # button_to "Delete Image", { :action => "delete", :id => @image.id }, # :confirm => "Are you sure?", :method => :delete # # => "<form method="post" action="/images/delete/1" class="button-to"> # # <div> # # <input type="hidden" name="_method" value="delete" /> # # <input onclick="return confirm('Are you sure?');" # # value="Delete" type="submit" /> # # </div> # # </form>" def button_to(name, options = {}, html_options = {}) html_options = html_options.stringify_keys convert_boolean_attributes!(html_options, %w( disabled )) method_tag = '' if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s) method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s) end form_method = method.to_s == 'get' ? 'get' : 'post' request_token_tag = '' if form_method == 'post' && protect_against_forgery? request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) end if confirm = html_options.delete("confirm") html_options["onclick"] = "return #{confirm_javascript_function(confirm)};" end url = options.is_a?(String) ? options : self.url_for(options) name ||= url html_options.merge!("type" => "submit", "value" => name) "<form method=\"#{form_method}\" action=\"#{escape_once url}\" class=\"button-to\"><div>" + method_tag + tag("input", html_options) + request_token_tag + "</div></form>" end # Creates a link tag of the given +name+ using a URL created by the set of # +options+ unless the current request URI is the same as the links, in # which case only the name is returned (or the given block is yielded, if # one exists). You can give link_to_unless_current a block which will # specialize the default behavior (e.g., show a "Start Here" link rather # than the link's text). # # ==== Examples # Let's say you have a navigation menu... # # <ul id="navbar"> # <li><%= link_to_unless_current("Home", { :action => "index" }) %></li> # <li><%= link_to_unless_current("About Us", { :action => "about" }) %></li> # </ul> # # If in the "about" action, it will render... # # <ul id="navbar"> # <li><a href="/controller/index">Home</a></li> # <li>About Us</li> # </ul> # # ...but if in the "index" action, it will render: # # <ul id="navbar"> # <li>Home</li> # <li><a href="/controller/about">About Us</a></li> # </ul> # # The implicit block given to link_to_unless_current is evaluated if the current # action is the action given. So, if we had a comments page and wanted to render a # "Go Back" link instead of a link to the comments page, we could do something like this... # # <%= # link_to_unless_current("Comment", { :controller => 'comments', :action => 'new}) do # link_to("Go back", { :controller => 'posts', :action => 'index' }) # end # %> def link_to_unless_current(name, options = {}, html_options = {}, &block) link_to_unless current_page?(options), name, options, html_options, &block end # Creates a link tag of the given +name+ using a URL created by the set of # +options+ unless +condition+ is true, in which case only the name is # returned. To specialize the default behavior (i.e., show a login link rather # than just the plaintext link text), you can pass a block that # accepts the name or the full argument list for link_to_unless. # # ==== Examples # <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %> # # If the user is logged in... # # => <a href="/controller/reply/">Reply</a> # # <%= # link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name| # link_to(name, { :controller => "accounts", :action => "signup" }) # end # %> # # If the user is logged in... # # => <a href="/controller/reply/">Reply</a> # # If not... # # => <a href="/accounts/signup">Reply</a> def link_to_unless(condition, name, options = {}, html_options = {}, &block) if condition if block_given? block.arity <= 1 ? yield(name) : yield(name, options, html_options) else name end else link_to(name, options, html_options) end end # Creates a link tag of the given +name+ using a URL created by the set of # +options+ if +condition+ is true, in which case only the name is # returned. To specialize the default behavior, you can pass a block that # accepts the name or the full argument list for link_to_unless (see the examples # in link_to_unless). # # ==== Examples # <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %> # # If the user isn't logged in... # # => <a href="/sessions/new/">Login</a> # # <%= # link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do # link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user }) # end # %> # # If the user isn't logged in... # # => <a href="/sessions/new/">Login</a> # # If they are logged in... # # => <a href="/accounts/show/3">my_username</a> def link_to_if(condition, name, options = {}, html_options = {}, &block) link_to_unless !condition, name, options, html_options, &block end # Creates a mailto link tag to the specified +email_address+, which is # also used as the name of the link unless +name+ is specified. Additional # HTML attributes for the link can be passed in +html_options+. # # mail_to has several methods for hindering email harvesters and customizing # the email itself by passing special keys to +html_options+. # # ==== Options # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex". # Passing "javascript" will dynamically create and encode the mailto: link then # eval it into the DOM of the page. This method will not show the link on # the page if the user has JavaScript disabled. Passing "hex" will hex # encode the +email_address+ before outputting the mailto: link. # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the # +email_address+ is used for the link label. You can use this option to # obfuscate the +email_address+ by substituting the @ sign with the string # given as the value. # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the # +email_address+ is used for the link label. You can use this option to # obfuscate the +email_address+ by substituting the . in the email with the # string given as the value. # * <tt>:subject</tt> - Preset the subject line of the email. # * <tt>:body</tt> - Preset the body of the email. # * <tt>:cc</tt> - Carbon Copy addition recipients on the email. # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email. # # ==== Examples # mail_to "me@domain.com" # # => <a href="mailto:me@domain.com">me@domain.com</a> # # mail_to "me@domain.com", "My email", :encode => "javascript" # # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script> # # mail_to "me@domain.com", "My email", :encode => "hex" # # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a> # # mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email" # # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a> # # mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com", # :subject => "This is an example email" # # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a> def mail_to(email_address, name = nil, html_options = {}) html_options = html_options.stringify_keys encode = html_options.delete("encode").to_s cc, bcc, subject, body = html_options.delete("cc"), html_options.delete("bcc"), html_options.delete("subject"), html_options.delete("body") string = '' extras = '' extras << "cc=#{CGI.escape(cc).gsub("+", "%20")}&" unless cc.nil? extras << "bcc=#{CGI.escape(bcc).gsub("+", "%20")}&" unless bcc.nil? extras << "body=#{CGI.escape(body).gsub("+", "%20")}&" unless body.nil? extras << "subject=#{CGI.escape(subject).gsub("+", "%20")}&" unless subject.nil? extras = "?" << extras.gsub!(/&?$/,"") unless extras.empty? email_address = email_address.to_s email_address_obfuscated = email_address.dup email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.has_key?("replace_at") email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.has_key?("replace_dot") if encode == "javascript" "document.write('#{content_tag("a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:"+email_address+extras }))}');".each_byte do |c| string << sprintf("%%%x", c) end "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>" elsif encode == "hex" email_address_encoded = '' email_address_obfuscated.each_byte do |c| email_address_encoded << sprintf("&#%d;", c) end protocol = 'mailto:' protocol.each_byte { |c| string << sprintf("&#%d;", c) } email_address.each_byte do |c| char = c.chr string << (char =~ /\w/ ? sprintf("%%%x", c) : char) end content_tag "a", name || email_address_encoded, html_options.merge({ "href" => "#{string}#{extras}" }) else content_tag "a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:#{email_address}#{extras}" }) end end # True if the current request URI was generated by the given +options+. # # ==== Examples # Let's say we're in the <tt>/shop/checkout?order=desc</tt> action. # # current_page?(:action => 'process') # # => false # # current_page?(:controller => 'shop', :action => 'checkout') # # => true # # current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc') # # => false # # current_page?(:action => 'checkout') # # => true # # current_page?(:controller => 'library', :action => 'checkout') # # => false # # Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action. # # current_page?(:action => 'process') # # => false # # current_page?(:controller => 'shop', :action => 'checkout') # # => true # # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'1') # # => true # # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'2') # # => false # # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc') # # => false # # current_page?(:action => 'checkout') # # => true # # current_page?(:controller => 'library', :action => 'checkout') # # => false def current_page?(options) url_string = CGI.unescapeHTML(url_for(options)) request = @controller.request # We ignore any extra parameters in the request_uri if the # submitted url doesn't have any either. This lets the function # work with things like ?order=asc if url_string.index("?") request_uri = request.request_uri else request_uri = request.request_uri.split('?').first end if url_string =~ /^\w+:\/\// url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}" else url_string == request_uri end end private def convert_options_to_javascript!(html_options, url = '') confirm, popup = html_options.delete("confirm"), html_options.delete("popup") method, href = html_options.delete("method"), html_options['href'] html_options["onclick"] = case when popup && method raise ActionView::ActionViewError, "You can't use :popup and :method in the same link" when confirm && popup "if (#{confirm_javascript_function(confirm)}) { #{popup_javascript_function(popup)} };return false;" when confirm && method "if (#{confirm_javascript_function(confirm)}) { #{method_javascript_function(method, url, href)} };return false;" when confirm "return #{confirm_javascript_function(confirm)};" when method "#{method_javascript_function(method, url, href)}return false;" when popup "#{popup_javascript_function(popup)}return false;" else html_options["onclick"] end end def confirm_javascript_function(confirm) "confirm('#{escape_javascript(confirm)}')" end def popup_javascript_function(popup) popup.is_a?(Array) ? "window.open(this.href,'#{popup.first}','#{popup.last}');" : "window.open(this.href);" end def method_javascript_function(method, url = '', href = nil) action = (href && url.size > 0) ? "'#{url}'" : 'this.href' submit_function = "var f = document.createElement('form'); f.style.display = 'none'; " + "this.parentNode.appendChild(f); f.method = 'POST'; f.action = #{action};" unless method == :post submit_function << "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); " submit_function << "m.setAttribute('name', '_method'); m.setAttribute('value', '#{method}'); f.appendChild(m);" end if protect_against_forgery? submit_function << "var s = document.createElement('input'); s.setAttribute('type', 'hidden'); " submit_function << "s.setAttribute('name', '#{request_forgery_protection_token}'); s.setAttribute('value', '#{escape_javascript form_authenticity_token}'); f.appendChild(s);" end submit_function << "f.submit();" end # Processes the _html_options_ hash, converting the boolean # attributes from true/false form into the form required by # HTML/XHTML. (An attribute is considered to be boolean if # its name is listed in the given _bool_attrs_ array.) # # More specifically, for each boolean attribute in _html_options_ # given as: # # "attr" => bool_value # # if the associated _bool_value_ evaluates to true, it is # replaced with the attribute's name; otherwise the attribute is # removed from the _html_options_ hash. (See the XHTML 1.0 spec, # section 4.5 "Attribute Minimization" for more: # http://www.w3.org/TR/xhtml1/#h-4.5) # # Returns the updated _html_options_ hash, which is also modified # in place. # # Example: # # convert_boolean_attributes!( html_options, # %w( checked disabled readonly ) ) def convert_boolean_attributes!(html_options, bool_attrs) bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) } html_options end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb
require 'set' require 'active_support/json' module ActionView module Helpers # Prototype[http://www.prototypejs.org/] is a JavaScript library that provides # DOM[http://en.wikipedia.org/wiki/Document_Object_Model] manipulation, # Ajax[http://www.adaptivepath.com/publications/essays/archives/000385.php] # functionality, and more traditional object-oriented facilities for JavaScript. # This module provides a set of helpers to make it more convenient to call # functions from Prototype using Rails, including functionality to call remote # Rails methods (that is, making a background request to a Rails action) using Ajax. # This means that you can call actions in your controllers without # reloading the page, but still update certain parts of it using # injections into the DOM. A common use case is having a form that adds # a new element to a list without reloading the page or updating a shopping # cart total when a new item is added. # # == Usage # To be able to use these helpers, you must first include the Prototype # JavaScript framework in your pages. # # javascript_include_tag 'prototype' # # (See the documentation for # ActionView::Helpers::JavaScriptHelper for more information on including # this and other JavaScript files in your Rails templates.) # # Now you're ready to call a remote action either through a link... # # link_to_remote "Add to cart", # :url => { :action => "add", :id => product.id }, # :update => { :success => "cart", :failure => "error" } # # ...through a form... # # <% form_remote_tag :url => '/shipping' do -%> # <div><%= submit_tag 'Recalculate Shipping' %></div> # <% end -%> # # ...periodically... # # periodically_call_remote(:url => 'update', :frequency => '5', :update => 'ticker') # # ...or through an observer (i.e., a form or field that is observed and calls a remote # action when changed). # # <%= observe_field(:searchbox, # :url => { :action => :live_search }), # :frequency => 0.5, # :update => :hits, # :with => 'query' # %> # # As you can see, there are numerous ways to use Prototype's Ajax functions (and actually more than # are listed here); check out the documentation for each method to find out more about its usage and options. # # === Common Options # See link_to_remote for documentation of options common to all Ajax # helpers; any of the options specified by link_to_remote can be used # by the other helpers. # # == Designing your Rails actions for Ajax # When building your action handlers (that is, the Rails actions that receive your background requests), it's # important to remember a few things. First, whatever your action would normally return to the browser, it will # return to the Ajax call. As such, you typically don't want to render with a layout. This call will cause # the layout to be transmitted back to your page, and, if you have a full HTML/CSS, will likely mess a lot of things up. # You can turn the layout off on particular actions by doing the following: # # class SiteController < ActionController::Base # layout "standard", :except => [:ajax_method, :more_ajax, :another_ajax] # end # # Optionally, you could do this in the method you wish to lack a layout: # # render :layout => false # # You can tell the type of request from within your action using the <tt>request.xhr?</tt> (XmlHttpRequest, the # method that Ajax uses to make background requests) method. # def name # # Is this an XmlHttpRequest request? # if (request.xhr?) # render :text => @name.to_s # else # # No? Then render an action. # render :action => 'view_attribute', :attr => @name # end # end # # The else clause can be left off and the current action will render with full layout and template. An extension # to this solution was posted to Ryan Heneise's blog at ArtOfMission["http://www.artofmission.com/"]. # # layout proc{ |c| c.request.xhr? ? false : "application" } # # Dropping this in your ApplicationController turns the layout off for every request that is an "xhr" request. # # If you are just returning a little data or don't want to build a template for your output, you may opt to simply # render text output, like this: # # render :text => 'Return this from my method!' # # Since whatever the method returns is injected into the DOM, this will simply inject some text (or HTML, if you # tell it to). This is usually how small updates, such updating a cart total or a file count, are handled. # # == Updating multiple elements # See JavaScriptGenerator for information on updating multiple elements # on the page in an Ajax response. module PrototypeHelper unless const_defined? :CALLBACKS CALLBACKS = Set.new([ :create, :uninitialized, :loading, :loaded, :interactive, :complete, :failure, :success ] + (100..599).to_a) AJAX_OPTIONS = Set.new([ :before, :after, :condition, :url, :asynchronous, :method, :insertion, :position, :form, :with, :update, :script, :type ]).merge(CALLBACKS) end # Returns a link to a remote action defined by <tt>options[:url]</tt> # (using the url_for format) that's called in the background using # XMLHttpRequest. The result of that request can then be inserted into a # DOM object whose id can be specified with <tt>options[:update]</tt>. # Usually, the result would be a partial prepared by the controller with # render :partial. # # Examples: # # Generates: <a href="#" onclick="new Ajax.Updater('posts', '/blog/destroy/3', {asynchronous:true, evalScripts:true}); # # return false;">Delete this post</a> # link_to_remote "Delete this post", :update => "posts", # :url => { :action => "destroy", :id => post.id } # # # Generates: <a href="#" onclick="new Ajax.Updater('emails', '/mail/list_emails', {asynchronous:true, evalScripts:true}); # # return false;"><img alt="Refresh" src="/images/refresh.png?" /></a> # link_to_remote(image_tag("refresh"), :update => "emails", # :url => { :action => "list_emails" }) # # You can override the generated HTML options by specifying a hash in # <tt>options[:html]</tt>. # # link_to_remote "Delete this post", :update => "posts", # :url => post_url(@post), :method => :delete, # :html => { :class => "destructive" } # # You can also specify a hash for <tt>options[:update]</tt> to allow for # easy redirection of output to an other DOM element if a server-side # error occurs: # # Example: # # Generates: <a href="#" onclick="new Ajax.Updater({success:'posts',failure:'error'}, '/blog/destroy/5', # # {asynchronous:true, evalScripts:true}); return false;">Delete this post</a> # link_to_remote "Delete this post", # :url => { :action => "destroy", :id => post.id }, # :update => { :success => "posts", :failure => "error" } # # Optionally, you can use the <tt>options[:position]</tt> parameter to # influence how the target DOM element is updated. It must be one of # <tt>:before</tt>, <tt>:top</tt>, <tt>:bottom</tt>, or <tt>:after</tt>. # # The method used is by default POST. You can also specify GET or you # can simulate PUT or DELETE over POST. All specified with <tt>options[:method]</tt> # # Example: # # Generates: <a href="#" onclick="new Ajax.Request('/person/4', {asynchronous:true, evalScripts:true, method:'delete'}); # # return false;">Destroy</a> # link_to_remote "Destroy", :url => person_url(:id => person), :method => :delete # # By default, these remote requests are processed asynchronous during # which various JavaScript callbacks can be triggered (for progress # indicators and the likes). All callbacks get access to the # <tt>request</tt> object, which holds the underlying XMLHttpRequest. # # To access the server response, use <tt>request.responseText</tt>, to # find out the HTTP status, use <tt>request.status</tt>. # # Example: # # Generates: <a href="#" onclick="new Ajax.Request('/words/undo?n=33', {asynchronous:true, evalScripts:true, # # onComplete:function(request){undoRequestCompleted(request)}}); return false;">hello</a> # word = 'hello' # link_to_remote word, # :url => { :action => "undo", :n => word_counter }, # :complete => "undoRequestCompleted(request)" # # The callbacks that may be specified are (in order): # # <tt>:loading</tt>:: Called when the remote document is being # loaded with data by the browser. # <tt>:loaded</tt>:: Called when the browser has finished loading # the remote document. # <tt>:interactive</tt>:: Called when the user can interact with the # remote document, even though it has not # finished loading. # <tt>:success</tt>:: Called when the XMLHttpRequest is completed, # and the HTTP status code is in the 2XX range. # <tt>:failure</tt>:: Called when the XMLHttpRequest is completed, # and the HTTP status code is not in the 2XX # range. # <tt>:complete</tt>:: Called when the XMLHttpRequest is complete # (fires after success/failure if they are # present). # # You can further refine <tt>:success</tt> and <tt>:failure</tt> by # adding additional callbacks for specific status codes. # # Example: # # Generates: <a href="#" onclick="new Ajax.Request('/testing/action', {asynchronous:true, evalScripts:true, # # on404:function(request){alert('Not found...? Wrong URL...?')}, # # onFailure:function(request){alert('HTTP Error ' + request.status + '!')}}); return false;">hello</a> # link_to_remote word, # :url => { :action => "action" }, # 404 => "alert('Not found...? Wrong URL...?')", # :failure => "alert('HTTP Error ' + request.status + '!')" # # A status code callback overrides the success/failure handlers if # present. # # If you for some reason or another need synchronous processing (that'll # block the browser while the request is happening), you can specify # <tt>options[:type] = :synchronous</tt>. # # You can customize further browser side call logic by passing in # JavaScript code snippets via some optional parameters. In their order # of use these are: # # <tt>:confirm</tt>:: Adds confirmation dialog. # <tt>:condition</tt>:: Perform remote request conditionally # by this expression. Use this to # describe browser-side conditions when # request should not be initiated. # <tt>:before</tt>:: Called before request is initiated. # <tt>:after</tt>:: Called immediately after request was # initiated and before <tt>:loading</tt>. # <tt>:submit</tt>:: Specifies the DOM element ID that's used # as the parent of the form elements. By # default this is the current form, but # it could just as well be the ID of a # table row or any other DOM element. # <tt>:with</tt>:: A JavaScript expression specifying # the parameters for the XMLHttpRequest. # Any expressions should return a valid # URL query string. # # Example: # # :with => "'name=' + $('name').value" # # You can generate a link that uses AJAX in the general case, while # degrading gracefully to plain link behavior in the absence of # JavaScript by setting <tt>html_options[:href]</tt> to an alternate URL. # Note the extra curly braces around the <tt>options</tt> hash separate # it as the second parameter from <tt>html_options</tt>, the third. # # Example: # link_to_remote "Delete this post", # { :update => "posts", :url => { :action => "destroy", :id => post.id } }, # :href => url_for(:action => "destroy", :id => post.id) def link_to_remote(name, options = {}, html_options = nil) link_to_function(name, remote_function(options), html_options || options.delete(:html)) end # Creates a button with an onclick event which calls a remote action # via XMLHttpRequest # The options for specifying the target with :url # and defining callbacks is the same as link_to_remote. def button_to_remote(name, options = {}, html_options = {}) button_to_function(name, remote_function(options), html_options) end # Periodically calls the specified url (<tt>options[:url]</tt>) every # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to # update a specified div (<tt>options[:update]</tt>) with the results # of the remote call. The options for specifying the target with <tt>:url</tt> # and defining callbacks is the same as link_to_remote. # Examples: # # Call get_averages and put its results in 'avg' every 10 seconds # # Generates: # # new PeriodicalExecuter(function() {new Ajax.Updater('avg', '/grades/get_averages', # # {asynchronous:true, evalScripts:true})}, 10) # periodically_call_remote(:url => { :action => 'get_averages' }, :update => 'avg') # # # Call invoice every 10 seconds with the id of the customer # # If it succeeds, update the invoice DIV; if it fails, update the error DIV # # Generates: # # new PeriodicalExecuter(function() {new Ajax.Updater({success:'invoice',failure:'error'}, # # '/testing/invoice/16', {asynchronous:true, evalScripts:true})}, 10) # periodically_call_remote(:url => { :action => 'invoice', :id => customer.id }, # :update => { :success => "invoice", :failure => "error" } # # # Call update every 20 seconds and update the new_block DIV # # Generates: # # new PeriodicalExecuter(function() {new Ajax.Updater('news_block', 'update', {asynchronous:true, evalScripts:true})}, 20) # periodically_call_remote(:url => 'update', :frequency => '20', :update => 'news_block') # def periodically_call_remote(options = {}) frequency = options[:frequency] || 10 # every ten seconds by default code = "new PeriodicalExecuter(function() {#{remote_function(options)}}, #{frequency})" javascript_tag(code) end # Returns a form tag that will submit using XMLHttpRequest in the # background instead of the regular reloading POST arrangement. Even # though it's using JavaScript to serialize the form elements, the form # submission will work just like a regular submission as viewed by the # receiving side (all elements available in <tt>params</tt>). The options for # specifying the target with <tt>:url</tt> and defining callbacks is the same as # +link_to_remote+. # # A "fall-through" target for browsers that doesn't do JavaScript can be # specified with the <tt>:action</tt>/<tt>:method</tt> options on <tt>:html</tt>. # # Example: # # Generates: # # <form action="/some/place" method="post" onsubmit="new Ajax.Request('', # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;"> # form_remote_tag :html => { :action => # url_for(:controller => "some", :action => "place") } # # The Hash passed to the <tt>:html</tt> key is equivalent to the options (2nd) # argument in the FormTagHelper.form_tag method. # # By default the fall-through action is the same as the one specified in # the <tt>:url</tt> (and the default method is <tt>:post</tt>). # # form_remote_tag also takes a block, like form_tag: # # Generates: # # <form action="/" method="post" onsubmit="new Ajax.Request('/', # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); # # return false;"> <div><input name="commit" type="submit" value="Save" /></div> # # </form> # <% form_remote_tag :url => '/posts' do -%> # <div><%= submit_tag 'Save' %></div> # <% end -%> def form_remote_tag(options = {}, &block) options[:form] = true options[:html] ||= {} options[:html][:onsubmit] = (options[:html][:onsubmit] ? options[:html][:onsubmit] + "; " : "") + "#{remote_function(options)}; return false;" form_tag(options[:html].delete(:action) || url_for(options[:url]), options[:html], &block) end # Creates a form that will submit using XMLHttpRequest in the background # instead of the regular reloading POST arrangement and a scope around a # specific resource that is used as a base for questioning about # values for the fields. # # === Resource # # Example: # <% remote_form_for(@post) do |f| %> # ... # <% end %> # # This will expand to be the same as: # # <% remote_form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %> # ... # <% end %> # # === Nested Resource # # Example: # <% remote_form_for([@post, @comment]) do |f| %> # ... # <% end %> # # This will expand to be the same as: # # <% remote_form_for :comment, @comment, :url => post_comment_path(@post, @comment), :html => { :method => :put, :class => "edit_comment", :id => "edit_comment_45" } do |f| %> # ... # <% end %> # # If you don't need to attach a form to a resource, then check out form_remote_tag. # # See FormHelper#form_for for additional semantics. def remote_form_for(record_or_name_or_array, *args, &proc) options = args.extract_options! case record_or_name_or_array when String, Symbol object_name = record_or_name_or_array when Array object = record_or_name_or_array.last object_name = ActionController::RecordIdentifier.singular_class_name(object) apply_form_for_options!(record_or_name_or_array, options) args.unshift object else object = record_or_name_or_array object_name = ActionController::RecordIdentifier.singular_class_name(record_or_name_or_array) apply_form_for_options!(object, options) args.unshift object end concat(form_remote_tag(options)) fields_for(object_name, *(args << options), &proc) concat('</form>') end alias_method :form_remote_for, :remote_form_for # Returns a button input tag with the element name of +name+ and a value (i.e., display text) of +value+ # that will submit form using XMLHttpRequest in the background instead of a regular POST request that # reloads the page. # # # Create a button that submits to the create action # # # # Generates: <input name="create_btn" onclick="new Ajax.Request('/testing/create', # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)}); # # return false;" type="button" value="Create" /> # <%= submit_to_remote 'create_btn', 'Create', :url => { :action => 'create' } %> # # # Submit to the remote action update and update the DIV succeed or fail based # # on the success or failure of the request # # # # Generates: <input name="update_btn" onclick="new Ajax.Updater({success:'succeed',failure:'fail'}, # # '/testing/update', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)}); # # return false;" type="button" value="Update" /> # <%= submit_to_remote 'update_btn', 'Update', :url => { :action => 'update' }, # :update => { :success => "succeed", :failure => "fail" } # # <tt>options</tt> argument is the same as in form_remote_tag. def submit_to_remote(name, value, options = {}) options[:with] ||= 'Form.serialize(this.form)' html_options = options.delete(:html) || {} html_options[:name] = name button_to_remote(value, options, html_options) end # Returns '<tt>eval(request.responseText)</tt>' which is the JavaScript function # that +form_remote_tag+ can call in <tt>:complete</tt> to evaluate a multiple # update return document using +update_element_function+ calls. def evaluate_remote_response "eval(request.responseText)" end # Returns the JavaScript needed for a remote function. # Takes the same arguments as link_to_remote. # # Example: # # Generates: <select id="options" onchange="new Ajax.Updater('options', # # '/testing/update_options', {asynchronous:true, evalScripts:true})"> # <select id="options" onchange="<%= remote_function(:update => "options", # :url => { :action => :update_options }) %>"> # <option value="0">Hello</option> # <option value="1">World</option> # </select> def remote_function(options) javascript_options = options_for_ajax(options) update = '' if options[:update] && options[:update].is_a?(Hash) update = [] update << "success:'#{options[:update][:success]}'" if options[:update][:success] update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure] update = '{' + update.join(',') + '}' elsif options[:update] update << "'#{options[:update]}'" end function = update.empty? ? "new Ajax.Request(" : "new Ajax.Updater(#{update}, " url_options = options[:url] url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash) function << "'#{escape_javascript(url_for(url_options))}'" function << ", #{javascript_options})" function = "#{options[:before]}; #{function}" if options[:before] function = "#{function}; #{options[:after]}" if options[:after] function = "if (#{options[:condition]}) { #{function}; }" if options[:condition] function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm] return function end # Observes the field with the DOM ID specified by +field_id+ and calls a # callback when its contents have changed. The default callback is an # Ajax call. By default the value of the observed field is sent as a # parameter with the Ajax call. # # Example: # # Generates: new Form.Element.Observer('suggest', 0.25, function(element, value) {new Ajax.Updater('suggest', # # '/testing/find_suggestion', {asynchronous:true, evalScripts:true, parameters:'q=' + value})}) # <%= observe_field :suggest, :url => { :action => :find_suggestion }, # :frequency => 0.25, # :update => :suggest, # :with => 'q' # %> # # Required +options+ are either of: # <tt>:url</tt>:: +url_for+-style options for the action to call # when the field has changed. # <tt>:function</tt>:: Instead of making a remote call to a URL, you # can specify javascript code to be called instead. # Note that the value of this option is used as the # *body* of the javascript function, a function definition # with parameters named element and value will be generated for you # for example: # observe_field("glass", :frequency => 1, :function => "alert('Element changed')") # will generate: # new Form.Element.Observer('glass', 1, function(element, value) {alert('Element changed')}) # The element parameter is the DOM element being observed, and the value is its value at the # time the observer is triggered. # # Additional options are: # <tt>:frequency</tt>:: The frequency (in seconds) at which changes to # this field will be detected. Not setting this # option at all or to a value equal to or less than # zero will use event based observation instead of # time based observation. # <tt>:update</tt>:: Specifies the DOM ID of the element whose # innerHTML should be updated with the # XMLHttpRequest response text. # <tt>:with</tt>:: A JavaScript expression specifying the parameters # for the XMLHttpRequest. The default is to send the # key and value of the observed field. Any custom # expressions should return a valid URL query string. # The value of the field is stored in the JavaScript # variable +value+. # # Examples # # :with => "'my_custom_key=' + value" # :with => "'person[name]=' + prompt('New name')" # :with => "Form.Element.serialize('other-field')" # # Finally # :with => 'name' # is shorthand for # :with => "'name=' + value" # This essentially just changes the key of the parameter. # # Additionally, you may specify any of the options documented in the # <em>Common options</em> section at the top of this document. # # Example: # # # Sends params: {:title => 'Title of the book'} when the book_title input # # field is changed. # observe_field 'book_title', # :url => 'http://example.com/books/edit/1', # :with => 'title' # # def observe_field(field_id, options = {}) if options[:frequency] && options[:frequency] > 0 build_observer('Form.Element.Observer', field_id, options) else build_observer('Form.Element.EventObserver', field_id, options) end end # Observes the form with the DOM ID specified by +form_id+ and calls a # callback when its contents have changed. The default callback is an # Ajax call. By default all fields of the observed field are sent as # parameters with the Ajax call. # # The +options+ for +observe_form+ are the same as the options for # +observe_field+. The JavaScript variable +value+ available to the # <tt>:with</tt> option is set to the serialized form by default. def observe_form(form_id, options = {}) if options[:frequency] build_observer('Form.Observer', form_id, options) else build_observer('Form.EventObserver', form_id, options) end end # All the methods were moved to GeneratorMethods so that # #include_helpers_from_context has nothing to overwrite. class JavaScriptGenerator #:nodoc: def initialize(context, &block) #:nodoc: @context, @lines = context, [] include_helpers_from_context @context.with_output_buffer(@lines) do @context.instance_exec(self, &block) end end private def include_helpers_from_context extend @context.helpers if @context.respond_to?(:helpers) extend GeneratorMethods end # JavaScriptGenerator generates blocks of JavaScript code that allow you # to change the content and presentation of multiple DOM elements. Use # this in your Ajax response bodies, either in a <script> tag or as plain # JavaScript sent with a Content-type of "text/javascript". # # Create new instances with PrototypeHelper#update_page or with # ActionController::Base#render, then call +insert_html+, +replace_html+, # +remove+, +show+, +hide+, +visual_effect+, or any other of the built-in # methods on the yielded generator in any order you like to modify the # content and appearance of the current page. # # Example: # # # Generates: # # new Element.insert("list", { bottom: "<li>Some item</li>" }); # # new Effect.Highlight("list"); # # ["status-indicator", "cancel-link"].each(Element.hide); # update_page do |page| # page.insert_html :bottom, 'list', "<li>#{@item.name}</li>" # page.visual_effect :highlight, 'list' # page.hide 'status-indicator', 'cancel-link' # end # # # Helper methods can be used in conjunction with JavaScriptGenerator. # When a helper method is called inside an update block on the +page+ # object, that method will also have access to a +page+ object. # # Example: # # module ApplicationHelper # def update_time # page.replace_html 'time', Time.now.to_s(:db) # page.visual_effect :highlight, 'time' # end # end # # # Controller action # def poll # render(:update) { |page| page.update_time } # end # # Calls to JavaScriptGenerator not matching a helper method below # generate a proxy to the JavaScript Class named by the method called. # # Examples: # # # Generates: # # Foo.init(); # update_page do |page| # page.foo.init # end # # # Generates: # # Event.observe('one', 'click', function () { # # $('two').show(); # # }); # update_page do |page| # page.event.observe('one', 'click') do |p| # p[:two].show # end # end # # You can also use PrototypeHelper#update_page_tag instead of # PrototypeHelper#update_page to wrap the generated JavaScript in a # <script> tag. module GeneratorMethods def to_s #:nodoc: returning javascript = @lines * $/ do if ActionView::Base.debug_rjs source = javascript.dup javascript.replace "try {\n#{source}\n} catch (e) " javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }" end end end # Returns a element reference by finding it through +id+ in the DOM. This element can then be # used for further method calls. Examples: # # page['blank_slate'] # => $('blank_slate');
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/record_tag_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/record_tag_helper.rb
module ActionView module Helpers module RecordTagHelper # Produces a wrapper DIV element with id and class parameters that # relate to the specified Active Record object. Usage example: # # <% div_for(@person, :class => "foo") do %> # <%=h @person.name %> # <% end %> # # produces: # # <div id="person_123" class="person foo"> Joe Bloggs </div> # def div_for(record, *args, &block) content_tag_for(:div, record, *args, &block) end # content_tag_for creates an HTML element with id and class parameters # that relate to the specified Active Record object. For example: # # <% content_tag_for(:tr, @person) do %> # <td><%=h @person.first_name %></td> # <td><%=h @person.last_name %></td> # <% end %> # # would produce the following HTML (assuming @person is an instance of # a Person object, with an id value of 123): # # <tr id="person_123" class="person">....</tr> # # If you require the HTML id attribute to have a prefix, you can specify it: # # <% content_tag_for(:tr, @person, :foo) do %> ... # # produces: # # <tr id="foo_person_123" class="person">... # # content_tag_for also accepts a hash of options, which will be converted to # additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined # with the default class name for your object. For example: # # <% content_tag_for(:li, @person, :class => "bar") %>... # # produces: # # <li id="person_123" class="person bar">... # def content_tag_for(tag_name, record, *args, &block) prefix = args.first.is_a?(Hash) ? nil : args.shift options = args.extract_options! options.merge!({ :class => "#{dom_class(record)} #{options[:class]}".strip, :id => dom_id(record, prefix) }) content_tag(tag_name, options, &block) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/cache_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/cache_helper.rb
module ActionView module Helpers # This helper to exposes a method for caching of view fragments. # See ActionController::Caching::Fragments for usage instructions. module CacheHelper # A method for caching fragments of a view rather than an entire # action or page. This technique is useful caching pieces like # menus, lists of news topics, static HTML fragments, and so on. # This method takes a block that contains the content you wish # to cache. See ActionController::Caching::Fragments for more # information. # # ==== Examples # If you wanted to cache a navigation menu, you could do the # following. # # <% cache do %> # <%= render :partial => "menu" %> # <% end %> # # You can also cache static content... # # <% cache do %> # <p>Hello users! Welcome to our website!</p> # <% end %> # # ...and static content mixed with RHTML content. # # <% cache do %> # Topics: # <%= render :partial => "topics", :collection => @topic_list %> # <i>Topics listed alphabetically</i> # <% end %> def cache(name = {}, options = nil, &block) @controller.fragment_for(output_buffer, name, options, &block) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
require 'cgi' require 'action_view/helpers/form_helper' module ActionView class Base @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" } cattr_accessor :field_error_proc end module Helpers # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the +form+ # method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This # is a great way of making the record quickly available for editing, but likely to prove lackluster for a complicated real-world form. # In that case, it's better to use the +input+ method and the specialized +form+ methods in link:classes/ActionView/Helpers/FormHelper.html module ActiveRecordHelper # Returns a default input tag for the type of object returned by the method. For example, if <tt>@post</tt> # has an attribute +title+ mapped to a +VARCHAR+ column that holds "Hello World": # # input("post", "title") # # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> def input(record_name, method, options = {}) InstanceTag.new(record_name, method, self).to_tag(options) end # Returns an entire form with all needed input tags for a specified Active Record object. For example, if <tt>@post</tt> # has attributes named +title+ of type +VARCHAR+ and +body+ of type +TEXT+ then # # form("post") # # would yield a form like the following (modulus formatting): # # <form action='/posts/create' method='post'> # <p> # <label for="post_title">Title</label><br /> # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> # </p> # <p> # <label for="post_body">Body</label><br /> # <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea> # </p> # <input name="commit" type="submit" value="Create" /> # </form> # # It's possible to specialize the form builder by using a different action name and by supplying another # block renderer. For example, if <tt>@entry</tt> has an attribute +message+ of type +VARCHAR+ then # # form("entry", # :action => "sign", # :input_block => Proc.new { |record, column| # "#{column.human_name}: #{input(record, column.name)}<br />" # }) # # would yield a form like the following (modulus formatting): # # <form action="/entries/sign" method="post"> # Message: # <input id="entry_message" name="entry[message]" size="30" type="text" /><br /> # <input name="commit" type="submit" value="Sign" /> # </form> # # It's also possible to add additional content to the form by giving it a block, such as: # # form("entry", :action => "sign") do |form| # form << content_tag("b", "Department") # form << collection_select("department", "id", @departments, "id", "name") # end # # The following options are available: # # * <tt>:action</tt> - The action used when submitting the form (default: +create+ if a new record, otherwise +update+). # * <tt>:input_block</tt> - Specialize the output using a different block, see above. # * <tt>:method</tt> - The method used when submitting the form (default: +post+). # * <tt>:multipart</tt> - Whether to change the enctype of the form to "multipart/form-data", used when uploading a file (default: +false+). # * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update"). def form(record_name, options = {}) record = instance_variable_get("@#{record_name}") options = options.symbolize_keys options[:action] ||= record.new_record? ? "create" : "update" action = url_for(:action => options[:action], :id => record) submit_value = options[:submit_value] || options[:action].gsub(/[^\w]/, '').capitalize contents = form_tag({:action => action}, :method =>(options[:method] || 'post'), :enctype => options[:multipart] ? 'multipart/form-data': nil) contents << hidden_field(record_name, :id) unless record.new_record? contents << all_input_tags(record, record_name, options) yield contents if block_given? contents << submit_tag(submit_value) contents << '</form>' end # Returns a string containing the error message attached to the +method+ on the +object+ if one exists. # This error message is wrapped in a <tt>DIV</tt> tag, which can be extended to include a <tt>:prepend_text</tt> # and/or <tt>:append_text</tt> (to properly explain the error), and a <tt>:css_class</tt> to style it # accordingly. +object+ should either be the name of an instance variable or the actual object. The method can be # passed in either as a string or a symbol. # As an example, let's say you have a model <tt>@post</tt> that has an error message on the +title+ attribute: # # <%= error_message_on "post", "title" %> # # => <div class="formError">can't be empty</div> # # <%= error_message_on @post, :title %> # # => <div class="formError">can't be empty</div> # # <%= error_message_on "post", "title", # :prepend_text => "Title simply ", # :append_text => " (or it won't work).", # :css_class => "inputError" %> def error_message_on(object, method, *args) options = args.extract_options! unless args.empty? ActiveSupport::Deprecation.warn('error_message_on takes an option hash instead of separate ' + 'prepend_text, append_text, and css_class arguments', caller) options[:prepend_text] = args[0] || '' options[:append_text] = args[1] || '' options[:css_class] = args[2] || 'formError' end options.reverse_merge!(:prepend_text => '', :append_text => '', :css_class => 'formError') if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && (errors = obj.errors.on(method)) content_tag("div", "#{options[:prepend_text]}#{ERB::Util.html_escape(errors.is_a?(Array) ? errors.first : errors)}#{options[:append_text]}", :class => options[:css_class] ) else '' end end # Returns a string with a <tt>DIV</tt> containing all of the error messages for the objects located as instance variables by the names # given. If more than one object is specified, the errors for the objects are displayed in the order that the object names are # provided. # # This <tt>DIV</tt> can be tailored by the following options: # # * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2"). # * <tt>:id</tt> - The id of the error div (default: "errorExplanation"). # * <tt>:class</tt> - The class of the error div (default: "errorExplanation"). # * <tt>:object</tt> - The object (or array of objects) for which to display errors, # if you need to escape the instance variable convention. # * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer. # If <tt>:object_name</tt> is not set, the name of the first object will be used. # * <tt>:header_message</tt> - The message in the header of the error div. Pass +nil+ # or an empty string to avoid the header message altogether. (Default: "X errors # prohibited this object from being saved"). # * <tt>:message</tt> - The explanation message after the header message and before # the error list. Pass +nil+ or an empty string to avoid the explanation message # altogether. (Default: "There were problems with the following fields:"). # # To specify the display for one object, you simply provide its name as a parameter. # For example, for the <tt>@user</tt> model: # # error_messages_for 'user' # # To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which # will be the name used in the header message: # # error_messages_for 'user_common', 'user', :object_name => 'user' # # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> parameter which gives the actual # object (or array of objects to use): # # error_messages_for 'user', :object => @question.user # # NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what # you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt> # instance yourself and set it up. View the source of this method to see how easy it is. def error_messages_for(*params) options = params.extract_options!.symbolize_keys if object = options.delete(:object) objects = [object].flatten else objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact end count = objects.inject(0) {|sum, object| sum + object.errors.count } unless count.zero? html = {} [:id, :class].each do |key| if options.include?(key) value = options[key] html[key] = value unless value.blank? else html[key] = 'errorExplanation' end end options[:object_name] ||= params.first I18n.with_options :locale => options[:locale], :scope => [:activerecord, :errors, :template] do |locale| header_message = if options.include?(:header_message) options[:header_message] else object_name = options[:object_name].to_s.gsub('_', ' ') object_name = I18n.t(object_name, :default => object_name, :scope => [:activerecord, :models], :count => 1) locale.t :header, :count => count, :model => object_name end message = options.include?(:message) ? options[:message] : locale.t(:body) error_messages = objects.sum {|object| object.errors.full_messages.map {|msg| content_tag(:li, ERB::Util.html_escape(msg)) } }.join contents = '' contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank? contents << content_tag(:p, message) unless message.blank? contents << content_tag(:ul, error_messages) content_tag(:div, contents, html) end else '' end end private def all_input_tags(record, record_name, options) input_block = options[:input_block] || default_input_block record.class.content_columns.collect{ |column| input_block.call(record_name, column) }.join("\n") end def default_input_block Proc.new { |record, column| %(<p><label for="#{record}_#{column.name}">#{column.human_name}</label><br />#{input(record, column.name)}</p>) } end end class InstanceTag #:nodoc: def to_tag(options = {}) case column_type when :string field_type = @method_name.include?("password") ? "password" : "text" to_input_field_tag(field_type, options) when :text to_text_area_tag(options) when :integer, :float, :decimal to_input_field_tag("text", options) when :date to_date_select_tag(options) when :datetime, :timestamp to_datetime_select_tag(options) when :time to_time_select_tag(options) when :boolean to_boolean_select_tag(options) end end alias_method :tag_without_error_wrapping, :tag def tag(name, options) if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name)) else tag_without_error_wrapping(name, options) end end alias_method :content_tag_without_error_wrapping, :content_tag def content_tag(name, value, options) if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name)) else content_tag_without_error_wrapping(name, value, options) end end alias_method :to_date_select_tag_without_error_wrapping, :to_date_select_tag def to_date_select_tag(options = {}, html_options = {}) if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(to_date_select_tag_without_error_wrapping(options, html_options), object.errors.on(@method_name)) else to_date_select_tag_without_error_wrapping(options, html_options) end end alias_method :to_datetime_select_tag_without_error_wrapping, :to_datetime_select_tag def to_datetime_select_tag(options = {}, html_options = {}) if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(to_datetime_select_tag_without_error_wrapping(options, html_options), object.errors.on(@method_name)) else to_datetime_select_tag_without_error_wrapping(options, html_options) end end alias_method :to_time_select_tag_without_error_wrapping, :to_time_select_tag def to_time_select_tag(options = {}, html_options = {}) if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(to_time_select_tag_without_error_wrapping(options, html_options), object.errors.on(@method_name)) else to_time_select_tag_without_error_wrapping(options, html_options) end end def error_wrapping(html_tag, has_error) has_error ? Base.field_error_proc.call(html_tag, self) : html_tag end def error_message object.errors.on(@method_name) end def column_type object.send(:column_for_attribute, @method_name).type end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb
require 'action_view/helpers/tag_helper' module ActionView module Helpers #:nodoc: # The TextHelper module provides a set of methods for filtering, formatting # and transforming strings, which can reduce the amount of inline Ruby code in # your views. These helper methods extend ActionView making them callable # within your template files. module TextHelper # The preferred method of outputting text in your views is to use the # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods # do not operate as expected in an eRuby code block. If you absolutely must # output text within a non-output code block (i.e., <% %>), you can use the concat method. # # ==== Examples # <% # concat "hello" # # is the equivalent of <%= "hello" %> # # if (logged_in == true): # concat "Logged in!" # else # concat link_to('login', :action => login) # end # # will either display "Logged in!" or a login link # %> def concat(string, unused_binding = nil) if unused_binding ActiveSupport::Deprecation.warn("The binding argument of #concat is no longer needed. Please remove it from your views and helpers.", caller) end output_buffer << string end # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt> # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...") # for a total length not exceeding <tt>:length</tt>. # # ==== Examples # # truncate("Once upon a time in a world far far away") # # => Once upon a time in a world... # # truncate("Once upon a time in a world far far away", :length => 14) # # => Once upon a... # # truncate("And they found that many people were sleeping better.", :length => 25, "(clipped)") # # => And they found t(clipped) # # truncate("And they found that many people were sleeping better.", :omission => "... (continued)", :length => 25) # # => And they f... (continued) # # You can still use <tt>truncate</tt> with the old API that accepts the # +length+ as its optional second and the +ellipsis+ as its # optional third parameter: # truncate("Once upon a time in a world far far away", 14) # # => Once upon a... # # truncate("And they found that many people were sleeping better.", 25, "... (continued)") # # => And they f... (continued) def truncate(text, *args) options = args.extract_options! unless args.empty? ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' + 'length and omission arguments', caller) options[:length] = args[0] || 30 options[:omission] = args[1] || "..." end options.reverse_merge!(:length => 30, :omission => "...") if text l = options[:length] - options[:omission].mb_chars.length chars = text.mb_chars (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s end end # Highlights one or more +phrases+ everywhere in +text+ by inserting it into # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt> # as a single-quoted string with \1 where the phrase is to be inserted (defaults to # '<strong class="highlight">\1</strong>') # # ==== Examples # highlight('You searched for: rails', 'rails') # # => You searched for: <strong class="highlight">rails</strong> # # highlight('You searched for: ruby, rails, dhh', 'actionpack') # # => You searched for: ruby, rails, dhh # # highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\1</em>') # # => You searched <em>for</em>: <em>rails</em> # # highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>') # # => You searched for: <a href="search?q=rails">rails</a> # # You can still use <tt>highlight</tt> with the old API that accepts the # +highlighter+ as its optional third parameter: # highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a> def highlight(text, phrases, *args) options = args.extract_options! unless args.empty? options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>' end options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>') if text.blank? || phrases.blank? text else match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') text.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter]) end end # Extracts an excerpt from +text+ that matches the first instance of +phrase+. # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string # will be stripped in any case. If the +phrase+ isn't found, nil is returned. # # ==== Examples # excerpt('This is an example', 'an', :radius => 5) # # => ...s is an exam... # # excerpt('This is an example', 'is', :radius => 5) # # => This is a... # # excerpt('This is an example', 'is') # # => This is an example # # excerpt('This next thing is an example', 'ex', :radius => 2) # # => ...next... # # excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ') # # => <chop> is also an example # # You can still use <tt>excerpt</tt> with the old API that accepts the # +radius+ as its optional third and the +ellipsis+ as its # optional forth parameter: # excerpt('This is an example', 'an', 5) # => ...s is an exam... # excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example def excerpt(text, phrase, *args) options = args.extract_options! unless args.empty? options[:radius] = args[0] || 100 options[:omission] = args[1] || "..." end options.reverse_merge!(:radius => 100, :omission => "...") if text && phrase phrase = Regexp.escape(phrase) if found_pos = text.mb_chars =~ /(#{phrase})/i start_pos = [ found_pos - options[:radius], 0 ].max end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min prefix = start_pos > 0 ? options[:omission] : "" postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : "" prefix + text.mb_chars[start_pos..end_pos].strip + postfix else nil end end end # Attempts to pluralize the +singular+ word unless +count+ is 1. If # +plural+ is supplied, it will use that when count is > 1, otherwise # it will use the Inflector to determine the plural form # # ==== Examples # pluralize(1, 'person') # # => 1 person # # pluralize(2, 'person') # # => 2 people # # pluralize(3, 'person', 'users') # # => 3 users # # pluralize(0, 'person') # # => 0 people def pluralize(count, singular, plural = nil) "#{count || 0} " + ((count == 1 || count == '1') ? singular : (plural || singular.pluralize)) end # Wraps the +text+ into lines no longer than +line_width+ width. This method # breaks on the first whitespace character that does not exceed +line_width+ # (which is 80 by default). # # ==== Examples # # word_wrap('Once upon a time') # # => Once upon a time # # word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...') # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\n a successor to the throne turned out to be more trouble than anyone could have\n imagined... # # word_wrap('Once upon a time', :line_width => 8) # # => Once upon\na time # # word_wrap('Once upon a time', :line_width => 1) # # => Once\nupon\na\ntime # # You can still use <tt>word_wrap</tt> with the old API that accepts the # +line_width+ as its optional second parameter: # word_wrap('Once upon a time', 8) # => Once upon\na time def word_wrap(text, *args) options = args.extract_options! unless args.blank? options[:line_width] = args[0] || 80 end options.reverse_merge!(:line_width => 80) text.split("\n").collect do |line| line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line end * "\n" end # Returns the text with all the Textile[http://www.textism.com/tools/textile] codes turned into HTML tags. # # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile]. # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] # is available</i>. # # ==== Examples # textilize("*This is Textile!* Rejoice!") # # => "<p><strong>This is Textile!</strong> Rejoice!</p>" # # textilize("I _love_ ROR(Ruby on Rails)!") # # => "<p>I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!</p>" # # textilize("h2. Textile makes markup -easy- simple!") # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>" # # textilize("Visit the Rails website "here":http://www.rubyonrails.org/.) # # => "<p>Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>.</p>" # # textilize("This is worded <strong>strongly</strong>") # # => "<p>This is worded <strong>strongly</strong></p>" # # textilize("This is worded <strong>strongly</strong>", :filter_html) # # => "<p>This is worded &lt;strong&gt;strongly&lt;/strong&gt;</p>" # def textilize(text, *options) options ||= [:hard_breaks] if text.blank? "" else textilized = RedCloth.new(text, options) textilized.to_html end end # Returns the text with all the Textile codes turned into HTML tags, # but without the bounding <p> tag that RedCloth adds. # # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile]. # <i>This method is requires RedCloth[http://whytheluckystiff.net/ruby/redcloth/] # to be available</i>. # # ==== Examples # textilize_without_paragraph("*This is Textile!* Rejoice!") # # => "<strong>This is Textile!</strong> Rejoice!" # # textilize_without_paragraph("I _love_ ROR(Ruby on Rails)!") # # => "I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!" # # textilize_without_paragraph("h2. Textile makes markup -easy- simple!") # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>" # # textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.) # # => "Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>." def textilize_without_paragraph(text) textiled = textilize(text) if textiled[0..2] == "<p>" then textiled = textiled[3..-1] end if textiled[-4..-1] == "</p>" then textiled = textiled[0..-5] end return textiled end # Returns the text with all the Markdown codes turned into HTML tags. # <i>This method requires BlueCloth[http://www.deveiate.org/projects/BlueCloth] or another # Markdown library to be installed.</i>. # # ==== Examples # markdown("We are using __Markdown__ now!") # # => "<p>We are using <strong>Markdown</strong> now!</p>" # # markdown("We like to _write_ `code`, not just _read_ it!") # # => "<p>We like to <em>write</em> <code>code</code>, not just <em>read</em> it!</p>" # # markdown("The [Markdown website](http://daringfireball.net/projects/markdown/) has more information.") # # => "<p>The <a href="http://daringfireball.net/projects/markdown/">Markdown website</a> # # has more information.</p>" # # markdown('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")') # # => '<p><img src="http://rubyonrails.com/images/rails.png" alt="The ROR logo" title="Ruby on Rails" /></p>' def markdown(text) text.blank? ? "" : Markdown.new(text).to_html end # Returns +text+ transformed into HTML using simple formatting rules. # Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a # paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is # considered as a linebreak and a <tt><br /></tt> tag is appended. This # method does not remove the newlines from the +text+. # # You can pass any HTML attributes into <tt>html_options</tt>. These # will be added to all created paragraphs. # ==== Examples # my_text = "Here is some basic text...\n...with a line break." # # simple_format(my_text) # # => "<p>Here is some basic text...\n<br />...with a line break.</p>" # # more_text = "We want to put a paragraph...\n\n...right there." # # simple_format(more_text) # # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>" # # simple_format("Look ma! A class!", :class => 'description') # # => "<p class='description'>Look ma! A class!</p>" def simple_format(text, html_options={}) start_tag = tag('p', html_options, true) text = text.to_s.dup text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br text.insert 0, start_tag text << "</p>" end # Turns all URLs and e-mail addresses into clickable links. The <tt>:link</tt> option # will limit what should be linked. You can add HTML attributes to the links using # <tt>:href_options</tt>. Possible values for <tt>:link</tt> are <tt>:all</tt> (default), # <tt>:email_addresses</tt>, and <tt>:urls</tt>. If a block is given, each URL and # e-mail address is yielded and the result is used as the link text. # # ==== Examples # auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com") # # => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and # # say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>" # # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :urls) # # => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a> # # or e-mail david@loudthinking.com" # # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :email_addresses) # # => "Visit http://www.loudthinking.com/ or e-mail <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>" # # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com." # auto_link(post_body, :href_options => { :target => '_blank' }) do |text| # truncate(text, 15) # end # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>. # Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>." # # # You can still use <tt>auto_link</tt> with the old API that accepts the # +link+ as its optional second parameter and the +html_options+ hash # as its optional third parameter: # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com." # auto_link(post_body, :urls) # => Once upon\na time # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\">http://www.myblog.com</a>. # Please e-mail me at me@email.com." # # auto_link(post_body, :all, :target => "_blank") # => Once upon\na time # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.myblog.com</a>. # Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>." def auto_link(text, *args, &block)#link = :all, href_options = {}, &block) return '' if text.blank? options = args.size == 2 ? {} : args.extract_options! # this is necessary because the old auto_link API has a Hash as its last parameter unless args.empty? options[:link] = args[0] || :all options[:html] = args[1] || {} end options.reverse_merge!(:link => :all, :html => {}) case options[:link].to_sym when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], &block), options[:html], &block) when :email_addresses then auto_link_email_addresses(text, options[:html], &block) when :urls then auto_link_urls(text, options[:html], &block) end end # Creates a Cycle object whose _to_s_ method cycles through elements of an # array every time it is called. This can be used for example, to alternate # classes for table rows. You can use named cycles to allow nesting in loops. # Passing a Hash as the last parameter with a <tt>:name</tt> key will create a # named cycle. The default name for a cycle without a +:name+ key is # <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle # and passing the name of the cycle. The current cycle string can be obtained # anytime using the current_cycle method. # # ==== Examples # # Alternate CSS classes for even and odd numbers... # @items = [1,2,3,4] # <table> # <% @items.each do |item| %> # <tr class="<%= cycle("even", "odd") -%>"> # <td>item</td> # </tr> # <% end %> # </table> # # # # Cycle CSS classes for rows, and text colors for values within each row # @items = x = [{:first => 'Robert', :middle => 'Daniel', :last => 'James'}, # {:first => 'Emily', :middle => 'Shannon', :maiden => 'Pike', :last => 'Hicks'}, # {:first => 'June', :middle => 'Dae', :last => 'Jones'}] # <% @items.each do |item| %> # <tr class="<%= cycle("even", "odd", :name => "row_class") -%>"> # <td> # <% item.values.each do |value| %> # <%# Create a named cycle "colors" %> # <span style="color:<%= cycle("red", "green", "blue", :name => "colors") -%>"> # <%= value %> # </span> # <% end %> # <% reset_cycle("colors") %> # </td> # </tr> # <% end %> def cycle(first_value, *values) if (values.last.instance_of? Hash) params = values.pop name = params[:name] else name = "default" end values.unshift(first_value) cycle = get_cycle(name) if (cycle.nil? || cycle.values != values) cycle = set_cycle(name, Cycle.new(*values)) end return cycle.to_s end # Returns the current cycle string after a cycle has been started. Useful # for complex table highlighing or any other design need which requires # the current cycle string in more than one place. # # ==== Example # # Alternate background colors # @items = [1,2,3,4] # <% @items.each do |item| %> # <div style="background-color:<%= cycle("red","white","blue") %>"> # <span style="background-color:<%= current_cycle %>"><%= item %></span> # </div> # <% end %> def current_cycle(name = "default") cycle = get_cycle(name) cycle.current_value unless cycle.nil? end # Resets a cycle so that it starts from the first element the next time # it is called. Pass in +name+ to reset a named cycle. # # ==== Example # # Alternate CSS classes for even and odd numbers... # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]] # <table> # <% @items.each do |item| %> # <tr class="<%= cycle("even", "odd") -%>"> # <% item.each do |value| %> # <span style="color:<%= cycle("#333", "#666", "#999", :name => "colors") -%>"> # <%= value %> # </span> # <% end %> # # <% reset_cycle("colors") %> # </tr> # <% end %> # </table> def reset_cycle(name = "default") cycle = get_cycle(name) cycle.reset unless cycle.nil? end class Cycle #:nodoc: attr_reader :values def initialize(first_value, *values) @values = values.unshift(first_value) reset end def reset @index = 0 end def current_value @values[previous_index].to_s end def to_s value = @values[@index].to_s @index = next_index return value end private def next_index step_index(1) end def previous_index step_index(-1) end def step_index(n) (@index + n) % @values.size end end private # The cycle helpers need to store the cycles in a place that is # guaranteed to be reset every time a page is rendered, so it # uses an instance variable of ActionView::Base. def get_cycle(name) @_cycles = Hash.new unless defined?(@_cycles) return @_cycles[name] end def set_cycle(name, cycle_object) @_cycles = Hash.new unless defined?(@_cycles) @_cycles[name] = cycle_object end AUTO_LINK_RE = %r{ ( https?:// | www\. ) [^\s<]+ }x unless const_defined?(:AUTO_LINK_RE) BRACKETS = { ']' => '[', ')' => '(', '}' => '{' } # Turns all urls into clickable links. If a block is given, each url # is yielded and the result is used as the link text. def auto_link_urls(text, html_options = {}) link_attributes = html_options.stringify_keys text.gsub(AUTO_LINK_RE) do href = $& punctuation = '' left, right = $`, $' # detect already linked URLs and URLs in the middle of a tag if left =~ /<[^>]+$/ && right =~ /^[^>]*>/ # do not change string; URL is alreay linked href else # don't include trailing punctuation character as part of the URL if href.sub!(/[^\w\/-]$/, '') and punctuation = $& and opening = BRACKETS[punctuation] if href.scan(opening).size > href.scan(punctuation).size href << punctuation punctuation = '' end end link_text = block_given?? yield(href) : href href = 'http://' + href unless href.index('http') == 0 content_tag(:a, h(link_text), link_attributes.merge('href' => href)) + punctuation end end end # Turns all email addresses into clickable links. If a block is given, # each email is yielded and the result is used as the link text. def auto_link_email_addresses(text, html_options = {}) body = text.dup text.gsub(/([\w\.!#\$%\-+.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do text = $1 if body.match(/<a\b[^>]*>(.*)(#{Regexp.escape(text)})(.*)<\/a>/) text else display_text = (block_given?) ? yield(text) : text mail_to text, display_text, html_options end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb
require 'action_view/helpers/tag_helper' require 'action_view/helpers/prototype_helper' module ActionView module Helpers # Provides functionality for working with JavaScript in your views. # # == Ajax, controls and visual effects # # * For information on using Ajax, see # ActionView::Helpers::PrototypeHelper. # * For information on using controls and visual effects, see # ActionView::Helpers::ScriptaculousHelper. # # == Including the JavaScript libraries into your pages # # Rails includes the Prototype JavaScript framework and the Scriptaculous # JavaScript controls and visual effects library. If you wish to use # these libraries and their helpers (ActionView::Helpers::PrototypeHelper # and ActionView::Helpers::ScriptaculousHelper), you must do one of the # following: # # * Use <tt><%= javascript_include_tag :defaults %></tt> in the HEAD # section of your page (recommended): This function will return # references to the JavaScript files created by the +rails+ command in # your <tt>public/javascripts</tt> directory. Using it is recommended as # the browser can then cache the libraries instead of fetching all the # functions anew on every request. # * Use <tt><%= javascript_include_tag 'prototype' %></tt>: As above, but # will only include the Prototype core library, which means you are able # to use all basic AJAX functionality. For the Scriptaculous-based # JavaScript helpers, like visual effects, autocompletion, drag and drop # and so on, you should use the method described above. # # For documentation on +javascript_include_tag+ see # ActionView::Helpers::AssetTagHelper. module JavaScriptHelper unless const_defined? :JAVASCRIPT_PATH JAVASCRIPT_PATH = File.join(File.dirname(__FILE__), 'javascripts') end include PrototypeHelper # Returns a link of the given +name+ that will trigger a JavaScript +function+ using the # onclick handler and return false after the fact. # # The first argument +name+ is used as the link text. # # The next arguments are optional and may include the javascript function definition and a hash of html_options. # # The +function+ argument can be omitted in favor of an +update_page+ # block, which evaluates to a string when the template is rendered # (instead of making an Ajax request first). # # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button" # # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil # # # Examples: # link_to_function "Greeting", "alert('Hello world!')" # Produces: # <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a> # # link_to_function(image_tag("delete"), "if (confirm('Really?')) do_delete()") # Produces: # <a onclick="if (confirm('Really?')) do_delete(); return false;" href="#"> # <img src="/images/delete.png?" alt="Delete"/> # </a> # # link_to_function("Show me more", nil, :id => "more_link") do |page| # page[:details].visual_effect :toggle_blind # page[:more_link].replace_html "Show me less" # end # Produces: # <a href="#" id="more_link" onclick="try { # $(&quot;details&quot;).visualEffect(&quot;toggle_blind&quot;); # $(&quot;more_link&quot;).update(&quot;Show me less&quot;); # } # catch (e) { # alert('RJS error:\n\n' + e.toString()); # alert('$(\&quot;details\&quot;).visualEffect(\&quot;toggle_blind\&quot;); # \n$(\&quot;more_link\&quot;).update(\&quot;Show me less\&quot;);'); # throw e # }; # return false;">Show me more</a> # def link_to_function(name, *args, &block) html_options = args.extract_options!.symbolize_keys function = block_given? ? update_page(&block) : args[0] || '' onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;" href = html_options[:href] || '#' content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick)) end # Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the # onclick handler. # # The first argument +name+ is used as the button's value or display text. # # The next arguments are optional and may include the javascript function definition and a hash of html_options. # # The +function+ argument can be omitted in favor of an +update_page+ # block, which evaluates to a string when the template is rendered # (instead of making an Ajax request first). # # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button" # # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil # # Examples: # button_to_function "Greeting", "alert('Hello world!')" # button_to_function "Delete", "if (confirm('Really?')) do_delete()" # button_to_function "Details" do |page| # page[:details].visual_effect :toggle_slide # end # button_to_function "Details", :class => "details_button" do |page| # page[:details].visual_effect :toggle_slide # end def button_to_function(name, *args, &block) html_options = args.extract_options!.symbolize_keys function = block_given? ? update_page(&block) : args[0] || '' onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};" tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick)) end JS_ESCAPE_MAP = { '\\' => '\\\\', '</' => '<\/', "\r\n" => '\n', "\n" => '\n', "\r" => '\n', '"' => '\\"', "'" => "\\'" } # Escape carrier returns and single and double quotes for JavaScript segments. def escape_javascript(javascript) if javascript javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] } else '' end end # Returns a JavaScript tag with the +content+ inside. Example: # javascript_tag "alert('All is good')" # # Returns: # <script type="text/javascript"> # //<![CDATA[ # alert('All is good') # //]]> # </script> # # +html_options+ may be a hash of attributes for the <script> tag. Example: # javascript_tag "alert('All is good')", :defer => 'defer' # # => <script defer="defer" type="text/javascript">alert('All is good')</script> # # Instead of passing the content as an argument, you can also use a block # in which case, you pass your +html_options+ as the first parameter. # <% javascript_tag :defer => 'defer' do -%> # alert('All is good') # <% end -%> def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block) content = if block_given? html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash) capture(&block) else content_or_options_with_block end tag = content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => Mime::JS)) if block_called_from_erb?(block) concat(tag) else tag end end def javascript_cdata_section(content) #:nodoc: "\n//#{cdata_section("\n#{content}\n//")}\n" end protected def options_for_javascript(options) if options.empty? '{}' else "{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}" end end def array_or_string_for_javascript(option) if option.kind_of?(Array) "['#{option.join('\',\'')}']" elsif !option.nil? "'#{option}'" end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb
module ActionView module Helpers # Provides a set of methods for making it easier to debug Rails objects. module DebugHelper # Returns a YAML representation of +object+ wrapped with <pre> and </pre>. # If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead. # Useful for inspecting an object at the time of rendering. # # ==== Example # # @user = User.new({ :username => 'testing', :password => 'xyz', :age => 42}) %> # debug(@user) # # => # <pre class='debug_dump'>--- !ruby/object:User # attributes: # &nbsp; updated_at: # &nbsp; username: testing # # &nbsp; age: 42 # &nbsp; password: xyz # &nbsp; created_at: # attributes_cache: {} # # new_record: true # </pre> def debug(object) begin Marshal::dump(object) "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", "&nbsp; ")}</pre>" rescue Exception => e # errors from Marshal or YAML # Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback "<code class='debug_dump'>#{h(object.inspect)}</code>" end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/record_identification_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/record_identification_helper.rb
module ActionView module Helpers module RecordIdentificationHelper # See ActionController::RecordIdentifier.partial_path -- this is just a delegate to that for convenient access in the view. def partial_path(*args, &block) ActionController::RecordIdentifier.partial_path(*args, &block) end # See ActionController::RecordIdentifier.dom_class -- this is just a delegate to that for convenient access in the view. def dom_class(*args, &block) ActionController::RecordIdentifier.dom_class(*args, &block) end # See ActionController::RecordIdentifier.dom_id -- this is just a delegate to that for convenient access in the view. def dom_id(*args, &block) ActionController::RecordIdentifier.dom_id(*args, &block) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb
require 'cgi' require 'action_view/helpers/url_helper' require 'action_view/helpers/tag_helper' module ActionView module Helpers #:nodoc: # This module provides methods for generating HTML that links views to assets such # as images, javascripts, stylesheets, and feeds. These methods do not verify # the assets exist before linking to them: # # image_tag("rails.png") # # => <img alt="Rails src="/images/rails.png?1230601161" /> # stylesheet_link_tag("application") # # => <link href="/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> # # === Using asset hosts # # By default, Rails links to these assets on the current host in the public # folder, but you can direct Rails to link to assets from a dedicated asset # server by setting ActionController::Base.asset_host in the application # configuration, typically in <tt>config/environments/production.rb</tt>. # For example, you'd define <tt>assets.example.com</tt> to be your asset # host this way: # # ActionController::Base.asset_host = "assets.example.com" # # Helpers take that into account: # # image_tag("rails.png") # # => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" /> # stylesheet_link_tag("application") # # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> # # Browsers typically open at most two simultaneous connections to a single # host, which means your assets often have to wait for other assets to finish # downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the # +asset_host+. For example, "assets%d.example.com". If that wildcard is # present Rails distributes asset requests among the corresponding four hosts # "assets0.example.com", ..., "assets3.example.com". With this trick browsers # will open eight simultaneous connections rather than two. # # image_tag("rails.png") # # => <img alt="Rails" src="http://assets0.example.com/images/rails.png?1230601161" /> # stylesheet_link_tag("application") # # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> # # To do this, you can either setup four actual hosts, or you can use wildcard # DNS to CNAME the wildcard to a single asset host. You can read more about # setting up your DNS CNAME records from your ISP. # # Note: This is purely a browser performance optimization and is not meant # for server load balancing. See http://www.die.net/musings/page_load_time/ # for background. # # Alternatively, you can exert more control over the asset host by setting # +asset_host+ to a proc like this: # # ActionController::Base.asset_host = Proc.new { |source| # "http://assets#{rand(2) + 1}.example.com" # } # image_tag("rails.png") # # => <img alt="Rails" src="http://assets0.example.com/images/rails.png?1230601161" /> # stylesheet_link_tag("application") # # => <link href="http://assets1.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> # # The example above generates "http://assets1.example.com" and # "http://assets2.example.com" randomly. This option is useful for example if # you need fewer/more than four hosts, custom host names, etc. # # As you see the proc takes a +source+ parameter. That's a string with the # absolute path of the asset with any extensions and timestamps in place, # for example "/images/rails.png?1230601161". # # ActionController::Base.asset_host = Proc.new { |source| # if source.starts_with?('/images') # "http://images.example.com" # else # "http://assets.example.com" # end # } # image_tag("rails.png") # # => <img alt="Rails" src="http://images.example.com/images/rails.png?1230601161" /> # stylesheet_link_tag("application") # # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> # # Alternatively you may ask for a second parameter +request+. That one is # particularly useful for serving assets from an SSL-protected page. The # example proc below disables asset hosting for HTTPS connections, while # still sending assets for plain HTTP requests from asset hosts. If you don't # have SSL certificates for each of the asset hosts this technique allows you # to avoid warnings in the client about mixed media. # # ActionController::Base.asset_host = Proc.new { |source, request| # if request.ssl? # "#{request.protocol}#{request.host_with_port}" # else # "#{request.protocol}assets.example.com" # end # } # # You can also implement a custom asset host object that responds to +call+ # and takes either one or two parameters just like the proc. # # config.action_controller.asset_host = AssetHostingWithMinimumSsl.new( # "http://asset%d.example.com", "https://asset1.example.com" # ) # # === Using asset timestamps # # By default, Rails appends asset's timestamps to all asset paths. This allows # you to set a cache-expiration date for the asset far into the future, but # still be able to instantly invalidate it by simply updating the file (and # hence updating the timestamp, which then updates the URL as the timestamp # is part of that, which in turn busts the cache). # # It's the responsibility of the web server you use to set the far-future # expiration date on cache assets that you need to take advantage of this # feature. Here's an example for Apache: # # # Asset Expiration # ExpiresActive On # <FilesMatch "\.(ico|gif|jpe?g|png|js|css)$"> # ExpiresDefault "access plus 1 year" # </FilesMatch> # # Also note that in order for this to work, all your application servers must # return the same timestamps. This means that they must have their clocks # synchronized. If one of them drifts out of sync, you'll see different # timestamps at random and the cache won't work. In that case the browser # will request the same assets over and over again even thought they didn't # change. You can use something like Live HTTP Headers for Firefox to verify # that the cache is indeed working. module AssetTagHelper ASSETS_DIR = defined?(Rails.public_path) ? Rails.public_path : "public" JAVASCRIPTS_DIR = "#{ASSETS_DIR}/javascripts" STYLESHEETS_DIR = "#{ASSETS_DIR}/stylesheets" JAVASCRIPT_DEFAULT_SOURCES = ['prototype', 'effects', 'dragdrop', 'controls'].freeze unless const_defined?(:JAVASCRIPT_DEFAULT_SOURCES) # Returns a link tag that browsers and news readers can use to auto-detect # an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or # <tt>:atom</tt>. Control the link options in url_for format using the # +url_options+. You can modify the LINK tag itself in +tag_options+. # # ==== Options # * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate" # * <tt>:type</tt> - Override the auto-generated mime type # * <tt>:title</tt> - Specify the title of the link, defaults to the +type+ # # ==== Examples # auto_discovery_link_tag # => # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" /> # auto_discovery_link_tag(:atom) # => # <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" /> # auto_discovery_link_tag(:rss, {:action => "feed"}) # => # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" /> # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # => # <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" /> # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # => # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" /> # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # => # <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" /> def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {}) tag( "link", "rel" => tag_options[:rel] || "alternate", "type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s, "title" => tag_options[:title] || type.to_s.upcase, "href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options ) end # Computes the path to a javascript asset in the public javascripts directory. # If the +source+ filename has no extension, .js will be appended. # Full paths from the document root will be passed through. # Used internally by javascript_include_tag to build the script path. # # ==== Examples # javascript_path "xmlhr" # => /javascripts/xmlhr.js # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js # javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js def javascript_path(source) compute_public_path(source, 'javascripts', 'js') end alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route # Returns an html script tag for each of the +sources+ provided. You # can pass in the filename (.js extension is optional) of javascript files # that exist in your public/javascripts directory for inclusion into the # current page or you can pass the full path relative to your document # root. To include the Prototype and Scriptaculous javascript libraries in # your application, pass <tt>:defaults</tt> as the source. When using # <tt>:defaults</tt>, if an application.js file exists in your public # javascripts directory, it will be included as well. You can modify the # html attributes of the script tag by passing a hash as the last argument. # # ==== Examples # javascript_include_tag "xmlhr" # => # <script type="text/javascript" src="/javascripts/xmlhr.js"></script> # # javascript_include_tag "xmlhr.js" # => # <script type="text/javascript" src="/javascripts/xmlhr.js"></script> # # javascript_include_tag "common.javascript", "/elsewhere/cools" # => # <script type="text/javascript" src="/javascripts/common.javascript"></script> # <script type="text/javascript" src="/elsewhere/cools.js"></script> # # javascript_include_tag "http://www.railsapplication.com/xmlhr" # => # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script> # # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # => # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script> # # javascript_include_tag :defaults # => # <script type="text/javascript" src="/javascripts/prototype.js"></script> # <script type="text/javascript" src="/javascripts/effects.js"></script> # ... # <script type="text/javascript" src="/javascripts/application.js"></script> # # * = The application.js file is only referenced if it exists # # Though it's not really recommended practice, if you need to extend the default JavaScript set for any reason # (e.g., you're going to be using a certain .js file in every action), then take a look at the register_javascript_include_default method. # # You can also include all javascripts in the javascripts directory using <tt>:all</tt> as the source: # # javascript_include_tag :all # => # <script type="text/javascript" src="/javascripts/prototype.js"></script> # <script type="text/javascript" src="/javascripts/effects.js"></script> # ... # <script type="text/javascript" src="/javascripts/application.js"></script> # <script type="text/javascript" src="/javascripts/shop.js"></script> # <script type="text/javascript" src="/javascripts/checkout.js"></script> # # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to # all subsequently included files. # # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>: # # javascript_include_tag :all, :recursive => true # # == Caching multiple javascripts into one # # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be # compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development # environment). # # ==== Examples # javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is false => # <script type="text/javascript" src="/javascripts/prototype.js"></script> # <script type="text/javascript" src="/javascripts/effects.js"></script> # ... # <script type="text/javascript" src="/javascripts/application.js"></script> # <script type="text/javascript" src="/javascripts/shop.js"></script> # <script type="text/javascript" src="/javascripts/checkout.js"></script> # # javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is true => # <script type="text/javascript" src="/javascripts/all.js"></script> # # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when ActionController::Base.perform_caching is false => # <script type="text/javascript" src="/javascripts/prototype.js"></script> # <script type="text/javascript" src="/javascripts/cart.js"></script> # <script type="text/javascript" src="/javascripts/checkout.js"></script> # # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when ActionController::Base.perform_caching is true => # <script type="text/javascript" src="/javascripts/shop.js"></script> # # The <tt>:recursive</tt> option is also available for caching: # # javascript_include_tag :all, :cache => true, :recursive => true def javascript_include_tag(*sources) options = sources.extract_options!.stringify_keys concat = options.delete("concat") cache = concat || options.delete("cache") recursive = options.delete("recursive") if concat || (ActionController::Base.perform_caching && cache) joined_javascript_name = (cache == true ? "all" : cache) + ".js" joined_javascript_path = File.join(joined_javascript_name[/^#{File::SEPARATOR}/] ? ASSETS_DIR : JAVASCRIPTS_DIR, joined_javascript_name) unless ActionController::Base.perform_caching && File.exists?(joined_javascript_path) write_asset_file_contents(joined_javascript_path, compute_javascript_paths(sources, recursive)) end javascript_src_tag(joined_javascript_name, options) else expand_javascript_sources(sources, recursive).collect { |source| javascript_src_tag(source, options) }.join("\n") end end @@javascript_expansions = { :defaults => JAVASCRIPT_DEFAULT_SOURCES.dup } # Register one or more javascript files to be included when <tt>symbol</tt> # is passed to <tt>javascript_include_tag</tt>. This method is typically intended # to be called from plugin initialization to register javascript files # that the plugin installed in <tt>public/javascripts</tt>. # # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"] # # javascript_include_tag :monkey # => # <script type="text/javascript" src="/javascripts/head.js"></script> # <script type="text/javascript" src="/javascripts/body.js"></script> # <script type="text/javascript" src="/javascripts/tail.js"></script> def self.register_javascript_expansion(expansions) @@javascript_expansions.merge!(expansions) end @@stylesheet_expansions = {} # Register one or more stylesheet files to be included when <tt>symbol</tt> # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended # to be called from plugin initialization to register stylesheet files # that the plugin installed in <tt>public/stylesheets</tt>. # # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"] # # stylesheet_link_tag :monkey # => # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" /> def self.register_stylesheet_expansion(expansions) @@stylesheet_expansions.merge!(expansions) end # Register one or more additional JavaScript files to be included when # <tt>javascript_include_tag :defaults</tt> is called. This method is # typically intended to be called from plugin initialization to register additional # .js files that the plugin installed in <tt>public/javascripts</tt>. def self.register_javascript_include_default(*sources) @@javascript_expansions[:defaults].concat(sources) end def self.reset_javascript_include_default #:nodoc: @@javascript_expansions[:defaults] = JAVASCRIPT_DEFAULT_SOURCES.dup end # Computes the path to a stylesheet asset in the public stylesheets directory. # If the +source+ filename has no extension, <tt>.css</tt> will be appended. # Full paths from the document root will be passed through. # Used internally by +stylesheet_link_tag+ to build the stylesheet path. # # ==== Examples # stylesheet_path "style" # => /stylesheets/style.css # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css # stylesheet_path "/dir/style.css" # => /dir/style.css # stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css # stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css def stylesheet_path(source) compute_public_path(source, 'stylesheets', 'css') end alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route # Returns a stylesheet link tag for the sources specified as arguments. If # you don't specify an extension, <tt>.css</tt> will be appended automatically. # You can modify the link attributes by passing a hash as the last argument. # # ==== Examples # stylesheet_link_tag "style" # => # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "style.css" # => # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "http://www.railsapplication.com/style.css" # => # <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "style", :media => "all" # => # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "style", :media => "print" # => # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "random.styles", "/css/stylish" # => # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" /> # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" /> # # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source: # # stylesheet_link_tag :all # => # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" /> # # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>: # # stylesheet_link_tag :all, :recursive => true # # == Caching multiple stylesheets into one # # You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be # compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching # is set to true (which is the case by default for the Rails production environment, but not for the development # environment). Examples: # # ==== Examples # stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false => # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is true => # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when ActionController::Base.perform_caching is false => # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when ActionController::Base.perform_caching is true => # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" /> # # The <tt>:recursive</tt> option is also available for caching: # # stylesheet_link_tag :all, :cache => true, :recursive => true # # To force concatenation (even in development mode) set <tt>:concat</tt> to true. This is useful if # you have too many stylesheets for IE to load. # # stylesheet_link_tag :all, :concat => true # def stylesheet_link_tag(*sources) options = sources.extract_options!.stringify_keys concat = options.delete("concat") cache = concat || options.delete("cache") recursive = options.delete("recursive") if concat || (ActionController::Base.perform_caching && cache) joined_stylesheet_name = (cache == true ? "all" : cache) + ".css" joined_stylesheet_path = File.join(joined_stylesheet_name[/^#{File::SEPARATOR}/] ? ASSETS_DIR : STYLESHEETS_DIR, joined_stylesheet_name) unless ActionController::Base.perform_caching && File.exists?(joined_stylesheet_path) write_asset_file_contents(joined_stylesheet_path, compute_stylesheet_paths(sources, recursive)) end stylesheet_tag(joined_stylesheet_name, options) else expand_stylesheet_sources(sources, recursive).collect { |source| stylesheet_tag(source, options) }.join("\n") end end # Computes the path to an image asset in the public images directory. # Full paths from the document root will be passed through. # Used internally by +image_tag+ to build the image path. # # ==== Examples # image_path("edit") # => /images/edit # image_path("edit.png") # => /images/edit.png # image_path("icons/edit.png") # => /images/icons/edit.png # image_path("/icons/edit.png") # => /icons/edit.png # image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png def image_path(source) compute_public_path(source, 'images') end alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route # Returns an html image tag for the +source+. The +source+ can be a full # path or a file that exists in your public images directory. # # ==== Options # You can add HTML attributes using the +options+. The +options+ supports # three additional keys for convenience and conformance: # # * <tt>:alt</tt> - If no alt text is given, the file name part of the # +source+ is used (capitalized and without the extension) # * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes # width="30" and height="45". <tt>:size</tt> will be ignored if the # value is not in the correct format. # * <tt>:mouseover</tt> - Set an alternate image to be used when the onmouseover # event is fired, and sets the original image to be replaced onmouseout. # This can be used to implement an easy image toggle that fires on onmouseover. # # ==== Examples # image_tag("icon") # => # <img src="/images/icon" alt="Icon" /> # image_tag("icon.png") # => # <img src="/images/icon.png" alt="Icon" /> # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # => # <img src="/images/icon.png" width="16" height="10" alt="Edit Entry" /> # image_tag("/icons/icon.gif", :size => "16x16") # => # <img src="/icons/icon.gif" width="16" height="16" alt="Icon" /> # image_tag("/icons/icon.gif", :height => '32', :width => '32') # => # <img alt="Icon" height="32" src="/icons/icon.gif" width="32" /> # image_tag("/icons/icon.gif", :class => "menu_icon") # => # <img alt="Icon" class="menu_icon" src="/icons/icon.gif" /> # image_tag("mouse.png", :mouseover => "/images/mouse_over.png") # => # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" /> # image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # => # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" /> def image_tag(source, options = {}) options.symbolize_keys! options[:src] = path_to_image(source) options[:alt] ||= File.basename(options[:src], '.*').split('.').first.to_s.capitalize if size = options.delete(:size) options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$} end if mouseover = options.delete(:mouseover) options[:onmouseover] = "this.src='#{image_path(mouseover)}'" options[:onmouseout] = "this.src='#{image_path(options[:src])}'" end tag("img", options) end def self.cache_asset_timestamps @@cache_asset_timestamps end # You can enable or disable the asset tag timestamps cache. # With the cache enabled, the asset tag helper methods will make fewer # expense file system calls. However this prevents you from modifying # any asset files while the server is running. # # ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false def self.cache_asset_timestamps=(value) @@cache_asset_timestamps = value end @@cache_asset_timestamps = true private # Add the the extension +ext+ if not present. Return full URLs otherwise untouched. # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL # roots. Rewrite the asset path for cache-busting asset ids. Include # asset host, if configured, with the correct request protocol. def compute_public_path(source, dir, ext = nil, include_host = true) has_request = @controller.respond_to?(:request) source_ext = File.extname(source)[1..-1] if ext && (source_ext.blank? || (ext != source_ext && File.exist?(File.join(ASSETS_DIR, dir, "#{source}.#{ext}")))) source += ".#{ext}" end unless source =~ %r{^[-a-z]+://} source = "/#{dir}/#{source}" unless source[0] == ?/ source = rewrite_asset_path(source) if has_request && include_host unless source =~ %r{^#{ActionController::Base.relative_url_root}/} source = "#{ActionController::Base.relative_url_root}#{source}" end end end if include_host && source !~ %r{^[-a-z]+://} host = compute_asset_host(source) if has_request && !host.blank? && host !~ %r{^[-a-z]+://} host = "#{@controller.request.protocol}#{host}" end "#{host}#{source}" else source end end # Pick an asset host for this source. Returns +nil+ if no host is set, # the host if no wildcard is set, the host interpolated with the # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4), # or the value returned from invoking the proc if it's a proc or the value from # invoking call if it's an object responding to call. def compute_asset_host(source) if host = ActionController::Base.asset_host if host.is_a?(Proc) || host.respond_to?(:call) case host.is_a?(Proc) ? host.arity : host.method(:call).arity when 2 request = @controller.respond_to?(:request) && @controller.request host.call(source, request) else host.call(source) end else (host =~ /%d/) ? host % (source.hash % 4) : host end end end @@asset_timestamps_cache = {} @@asset_timestamps_cache_guard = Mutex.new # Use the RAILS_ASSET_ID environment variable or the source's # modification time as its cache-busting asset id. def rails_asset_id(source) if asset_id = ENV["RAILS_ASSET_ID"] asset_id else if @@cache_asset_timestamps && (asset_id = @@asset_timestamps_cache[source]) asset_id else path = File.join(ASSETS_DIR, source) asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : '' if @@cache_asset_timestamps @@asset_timestamps_cache_guard.synchronize do @@asset_timestamps_cache[source] = asset_id end end asset_id end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/translation_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/translation_helper.rb
require 'action_view/helpers/tag_helper' module ActionView module Helpers module TranslationHelper # Delegates to I18n#translate but also performs two additional functions. First, it'll catch MissingTranslationData exceptions # and turn them into inline spans that contains the missing key, such that you can see in a view what is missing where. # # Second, it'll scope the key by the current partial if the key starts with a period. So if you call translate(".foo") from the # people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo"). This makes it less repetitive # to translate many keys within the same partials and gives you a simple framework for scoping them consistently. If you don't # prepend the key with a period, nothing is converted. def translate(key, options = {}) options[:raise] = true I18n.translate(scope_key_by_partial(key), options) rescue I18n::MissingTranslationData => e keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope]) content_tag('span', keys.join(', '), :class => 'translation_missing') end alias :t :translate # Delegates to I18n.localize with no additional functionality. def localize(*args) I18n.localize *args end alias :l :localize private def scope_key_by_partial(key) if key.to_s.first == "." template.path_without_format_and_extension.gsub(%r{/_?}, ".") + key.to_s else key end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/scriptaculous_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/scriptaculous_helper.rb
require 'action_view/helpers/javascript_helper' require 'active_support/json' module ActionView module Helpers # Provides a set of helpers for calling Scriptaculous JavaScript # functions, including those which create Ajax controls and visual effects. # # To be able to use these helpers, you must include the Prototype # JavaScript framework and the Scriptaculous JavaScript library in your # pages. See the documentation for ActionView::Helpers::JavaScriptHelper # for more information on including the necessary JavaScript. # # The Scriptaculous helpers' behavior can be tweaked with various options. # See the documentation at http://script.aculo.us for more information on # using these helpers in your application. module ScriptaculousHelper unless const_defined? :TOGGLE_EFFECTS TOGGLE_EFFECTS = [:toggle_appear, :toggle_slide, :toggle_blind] end # Returns a JavaScript snippet to be used on the Ajax callbacks for # starting visual effects. # # Example: # <%= link_to_remote "Reload", :update => "posts", # :url => { :action => "reload" }, # :complete => visual_effect(:highlight, "posts", :duration => 0.5) # # If no +element_id+ is given, it assumes "element" which should be a local # variable in the generated JavaScript execution context. This can be # used for example with +drop_receiving_element+: # # <%= drop_receiving_element (...), :loading => visual_effect(:fade) %> # # This would fade the element that was dropped on the drop receiving # element. # # For toggling visual effects, you can use <tt>:toggle_appear</tt>, <tt>:toggle_slide</tt>, and # <tt>:toggle_blind</tt> which will alternate between appear/fade, slidedown/slideup, and # blinddown/blindup respectively. # # You can change the behaviour with various options, see # http://script.aculo.us for more documentation. def visual_effect(name, element_id = false, js_options = {}) element = element_id ? ActiveSupport::JSON.encode(element_id) : "element" js_options[:queue] = if js_options[:queue].is_a?(Hash) '{' + js_options[:queue].map {|k, v| k == :limit ? "#{k}:#{v}" : "#{k}:'#{v}'" }.join(',') + '}' elsif js_options[:queue] "'#{js_options[:queue]}'" end if js_options[:queue] [:endcolor, :direction, :startcolor, :scaleMode, :restorecolor].each do |option| js_options[option] = "'#{js_options[option]}'" if js_options[option] end if TOGGLE_EFFECTS.include? name.to_sym "Effect.toggle(#{element},'#{name.to_s.gsub(/^toggle_/,'')}',#{options_for_javascript(js_options)});" else "new Effect.#{name.to_s.camelize}(#{element},#{options_for_javascript(js_options)});" end end # Makes the element with the DOM ID specified by +element_id+ sortable # by drag-and-drop and make an Ajax call whenever the sort order has # changed. By default, the action called gets the serialized sortable # element as parameters. # # Example: # # <%= sortable_element("my_list", :url => { :action => "order" }) %> # # In the example, the action gets a "my_list" array parameter # containing the values of the ids of elements the sortable consists # of, in the current order. # # Important: For this to work, the sortable elements must have id # attributes in the form "string_identifier". For example, "item_1". Only # the identifier part of the id attribute will be serialized. # # Additional +options+ are: # # * <tt>:format</tt> - A regular expression to determine what to send as the # serialized id to the server (the default is <tt>/^[^_]*_(.*)$/</tt>). # # * <tt>:constraint</tt> - Whether to constrain the dragging to either # <tt>:horizontal</tt> or <tt>:vertical</tt> (or false to make it unconstrained). # # * <tt>:overlap</tt> - Calculate the item overlap in the <tt>:horizontal</tt> # or <tt>:vertical</tt> direction. # # * <tt>:tag</tt> - Which children of the container element to treat as # sortable (default is <tt>li</tt>). # # * <tt>:containment</tt> - Takes an element or array of elements to treat as # potential drop targets (defaults to the original target element). # # * <tt>:only</tt> - A CSS class name or array of class names used to filter # out child elements as candidates. # # * <tt>:scroll</tt> - Determines whether to scroll the list during drag # operations if the list runs past the visual border. # # * <tt>:tree</tt> - Determines whether to treat nested lists as part of the # main sortable list. This means that you can create multi-layer lists, # and not only sort items at the same level, but drag and sort items # between levels. # # * <tt>:hoverclass</tt> - If set, the Droppable will have this additional CSS class # when an accepted Draggable is hovered over it. # # * <tt>:handle</tt> - Sets whether the element should only be draggable by an # embedded handle. The value may be a string referencing a CSS class value # (as of script.aculo.us V1.5). The first child/grandchild/etc. element # found within the element that has this CSS class value will be used as # the handle. # # * <tt>:ghosting</tt> - Clones the element and drags the clone, leaving # the original in place until the clone is dropped (default is <tt>false</tt>). # # * <tt>:dropOnEmpty</tt> - If true the Sortable container will be made into # a Droppable, that can receive a Draggable (as according to the containment # rules) as a child element when there are no more elements inside (default # is <tt>false</tt>). # # * <tt>:onChange</tt> - Called whenever the sort order changes while dragging. When # dragging from one Sortable to another, the callback is called once on each # Sortable. Gets the affected element as its parameter. # # * <tt>:onUpdate</tt> - Called when the drag ends and the Sortable's order is # changed in any way. When dragging from one Sortable to another, the callback # is called once on each Sortable. Gets the container as its parameter. # # See http://script.aculo.us for more documentation. def sortable_element(element_id, options = {}) javascript_tag(sortable_element_js(element_id, options).chop!) end def sortable_element_js(element_id, options = {}) #:nodoc: options[:with] ||= "Sortable.serialize(#{ActiveSupport::JSON.encode(element_id)})" options[:onUpdate] ||= "function(){" + remote_function(options) + "}" options.delete_if { |key, value| PrototypeHelper::AJAX_OPTIONS.include?(key) } [:tag, :overlap, :constraint, :handle].each do |option| options[option] = "'#{options[option]}'" if options[option] end options[:containment] = array_or_string_for_javascript(options[:containment]) if options[:containment] options[:only] = array_or_string_for_javascript(options[:only]) if options[:only] %(Sortable.create(#{ActiveSupport::JSON.encode(element_id)}, #{options_for_javascript(options)});) end # Makes the element with the DOM ID specified by +element_id+ draggable. # # Example: # <%= draggable_element("my_image", :revert => true) # # You can change the behaviour with various options, see # http://script.aculo.us for more documentation. def draggable_element(element_id, options = {}) javascript_tag(draggable_element_js(element_id, options).chop!) end def draggable_element_js(element_id, options = {}) #:nodoc: %(new Draggable(#{ActiveSupport::JSON.encode(element_id)}, #{options_for_javascript(options)});) end # Makes the element with the DOM ID specified by +element_id+ receive # dropped draggable elements (created by +draggable_element+). # and make an AJAX call. By default, the action called gets the DOM ID # of the element as parameter. # # Example: # <%= drop_receiving_element("my_cart", :url => # { :controller => "cart", :action => "add" }) %> # # You can change the behaviour with various options, see # http://script.aculo.us for more documentation. # # Some of these +options+ include: # * <tt>:accept</tt> - Set this to a string or an array of strings describing the # allowable CSS classes that the +draggable_element+ must have in order # to be accepted by this +drop_receiving_element+. # # * <tt>:confirm</tt> - Adds a confirmation dialog. Example: # # :confirm => "Are you sure you want to do this?" # # * <tt>:hoverclass</tt> - If set, the +drop_receiving_element+ will have # this additional CSS class when an accepted +draggable_element+ is # hovered over it. # # * <tt>:onDrop</tt> - Called when a +draggable_element+ is dropped onto # this element. Override this callback with a JavaScript expression to # change the default drop behaviour. Example: # # :onDrop => "function(draggable_element, droppable_element, event) { alert('I like bananas') }" # # This callback gets three parameters: The Draggable element, the Droppable # element and the Event object. You can extract additional information about # the drop - like if the Ctrl or Shift keys were pressed - from the Event object. # # * <tt>:with</tt> - A JavaScript expression specifying the parameters for # the XMLHttpRequest. Any expressions should return a valid URL query string. def drop_receiving_element(element_id, options = {}) javascript_tag(drop_receiving_element_js(element_id, options).chop!) end def drop_receiving_element_js(element_id, options = {}) #:nodoc: options[:with] ||= "'id=' + encodeURIComponent(element.id)" options[:onDrop] ||= "function(element){" + remote_function(options) + "}" options.delete_if { |key, value| PrototypeHelper::AJAX_OPTIONS.include?(key) } options[:accept] = array_or_string_for_javascript(options[:accept]) if options[:accept] options[:hoverclass] = "'#{options[:hoverclass]}'" if options[:hoverclass] # Confirmation happens during the onDrop callback, so it can be removed from the options options.delete(:confirm) if options[:confirm] %(Droppables.add(#{ActiveSupport::JSON.encode(element_id)}, #{options_for_javascript(options)});) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/tag_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/tag_helper.rb
require 'action_view/erb/util' require 'set' module ActionView module Helpers #:nodoc: # Provides methods to generate HTML tags programmatically when you can't use # a Builder. By default, they output XHTML compliant tags. module TagHelper include ERB::Util BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked).to_set BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym)) # Returns an empty HTML tag of type +name+ which by default is XHTML # compliant. Set +open+ to true to create an open tag compatible # with HTML 4.0 and below. Add HTML attributes by passing an attributes # hash to +options+. Set +escape+ to false to disable attribute value # escaping. # # ==== Options # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use # symbols or strings for the attribute names. # # ==== Examples # tag("br") # # => <br /> # # tag("br", nil, true) # # => <br> # # tag("input", { :type => 'text', :disabled => true }) # # => <input type="text" disabled="disabled" /> # # tag("img", { :src => "open & shut.png" }) # # => <img src="open &amp; shut.png" /> # # tag("img", { :src => "open &amp; shut.png" }, false, false) # # => <img src="open &amp; shut.png" /> def tag(name, options = nil, open = false, escape = true) "<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}" end # Returns an HTML block tag of type +name+ surrounding the +content+. Add # HTML attributes by passing an attributes hash to +options+. # Instead of passing the content as an argument, you can also use a block # in which case, you pass your +options+ as the second parameter. # Set escape to false to disable attribute value escaping. # # ==== Options # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use # symbols or strings for the attribute names. # # ==== Examples # content_tag(:p, "Hello world!") # # => <p>Hello world!</p> # content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong") # # => <div class="strong"><p>Hello world!</p></div> # content_tag("select", options, :multiple => true) # # => <select multiple="multiple">...options...</select> # # <% content_tag :div, :class => "strong" do -%> # Hello world! # <% end -%> # # => <div class="strong">Hello world!</div> def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block) if block_given? options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash) content_tag = content_tag_string(name, capture(&block), options, escape) if block_called_from_erb?(block) concat(content_tag) else content_tag end else content_tag_string(name, content_or_options_with_block, options, escape) end end # Returns a CDATA section with the given +content+. CDATA sections # are used to escape blocks of text containing characters which would # otherwise be recognized as markup. CDATA sections begin with the string # <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>. # # ==== Examples # cdata_section("<hello world>") # # => <![CDATA[<hello world>]]> # # cdata_section(File.read("hello_world.txt")) # # => <![CDATA[<hello from a text file]]> def cdata_section(content) "<![CDATA[#{content}]]>" end # Returns an escaped version of +html+ without affecting existing escaped entities. # # ==== Examples # escape_once("1 < 2 &amp; 3") # # => "1 &lt; 2 &amp; 3" # # escape_once("&lt;&lt; Accept & Checkout") # # => "&lt;&lt; Accept &amp; Checkout" def escape_once(html) ActiveSupport::Multibyte.clean(html.to_s).gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |special| ERB::Util::HTML_ESCAPE[special] } end private BLOCK_CALLED_FROM_ERB = 'defined? __in_erb_template' if RUBY_VERSION < '1.9.0' # Check whether we're called from an erb template. # We'd return a string in any other case, but erb <%= ... %> # can't take an <% end %> later on, so we have to use <% ... %> # and implicitly concat. def block_called_from_erb?(block) block && eval(BLOCK_CALLED_FROM_ERB, block) end else def block_called_from_erb?(block) block && eval(BLOCK_CALLED_FROM_ERB, block.binding) end end def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options "<#{name}#{tag_options}>#{content}</#{name}>" end def tag_options(options, escape = true) unless options.blank? attrs = [] if escape options.each_pair do |key, value| if BOOLEAN_ATTRIBUTES.include?(key) attrs << %(#{key}="#{key}") if value else attrs << %(#{key}="#{escape_once(value)}") if !value.nil? end end else attrs = options.map { |key, value| %(#{key}="#{value}") } end " #{attrs.sort * ' '}" unless attrs.empty? end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/sanitize_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/sanitize_helper.rb
require 'action_view/helpers/tag_helper' module ActionView module Helpers #:nodoc: # The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements. # These helper methods extend ActionView making them callable within your template files. module SanitizeHelper # This +sanitize+ helper will html encode all tags and strip all attributes that aren't specifically allowed. # It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any # tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out # the extensive test suite. # # <%= sanitize @article.body %> # # You can add or remove tags/attributes if you want to customize it a bit. See ActionView::Base for full docs on the # available options. You can add tags/attributes for single uses of +sanitize+ by passing either the <tt>:attributes</tt> or <tt>:tags</tt> options: # # Normal Use # # <%= sanitize @article.body %> # # Custom Use (only the mentioned tags and attributes are allowed, nothing else) # # <%= sanitize @article.body, :tags => %w(table tr td), :attributes => %w(id class style) # # Add table tags to the default allowed tags # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td' # end # # Remove tags to the default allowed tags # # Rails::Initializer.run do |config| # config.after_initialize do # ActionView::Base.sanitized_allowed_tags.delete 'div' # end # end # # Change allowed default attributes # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style' # end # # Please note that sanitizing user-provided text does not guarantee that the # resulting markup is valid (conforming to a document type) or even well-formed. # The output may still contain e.g. unescaped '<', '>', '&' characters and # confuse browsers. # def sanitize(html, options = {}) self.class.white_list_sanitizer.sanitize(html, options) end # Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute. def sanitize_css(style) self.class.white_list_sanitizer.sanitize_css(style) end # Strips all HTML tags from the +html+, including comments. This uses the # html-scanner tokenizer and so its HTML parsing ability is limited by # that of html-scanner. # # ==== Examples # # strip_tags("Strip <i>these</i> tags!") # # => Strip these tags! # # strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...") # # => Bold no more! See more here... # # strip_tags("<div id='top-bar'>Welcome to my website!</div>") # # => Welcome to my website! def strip_tags(html) self.class.full_sanitizer.sanitize(html) end # Strips all link tags from +text+ leaving just the link text. # # ==== Examples # strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>') # # => Ruby on Rails # # strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.') # # => Please e-mail me at me@email.com. # # strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.') # # => Blog: Visit def strip_links(html) self.class.link_sanitizer.sanitize(html) end module ClassMethods #:nodoc: attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer def sanitized_protocol_separator white_list_sanitizer.protocol_separator end def sanitized_uri_attributes white_list_sanitizer.uri_attributes end def sanitized_bad_tags white_list_sanitizer.bad_tags end def sanitized_allowed_tags white_list_sanitizer.allowed_tags end def sanitized_allowed_attributes white_list_sanitizer.allowed_attributes end def sanitized_allowed_css_properties white_list_sanitizer.allowed_css_properties end def sanitized_allowed_css_keywords white_list_sanitizer.allowed_css_keywords end def sanitized_shorthand_css_properties white_list_sanitizer.shorthand_css_properties end def sanitized_allowed_protocols white_list_sanitizer.allowed_protocols end def sanitized_protocol_separator=(value) white_list_sanitizer.protocol_separator = value end # Gets the HTML::FullSanitizer instance used by +strip_tags+. Replace with # any object that responds to +sanitize+. # # Rails::Initializer.run do |config| # config.action_view.full_sanitizer = MySpecialSanitizer.new # end # def full_sanitizer @full_sanitizer ||= HTML::FullSanitizer.new end # Gets the HTML::LinkSanitizer instance used by +strip_links+. Replace with # any object that responds to +sanitize+. # # Rails::Initializer.run do |config| # config.action_view.link_sanitizer = MySpecialSanitizer.new # end # def link_sanitizer @link_sanitizer ||= HTML::LinkSanitizer.new end # Gets the HTML::WhiteListSanitizer instance used by sanitize and +sanitize_css+. # Replace with any object that responds to +sanitize+. # # Rails::Initializer.run do |config| # config.action_view.white_list_sanitizer = MySpecialSanitizer.new # end # def white_list_sanitizer @white_list_sanitizer ||= HTML::WhiteListSanitizer.new end # Adds valid HTML attributes that the +sanitize+ helper checks for URIs. # # Rails::Initializer.run do |config| # config.action_view.sanitized_uri_attributes = 'lowsrc', 'target' # end # def sanitized_uri_attributes=(attributes) HTML::WhiteListSanitizer.uri_attributes.merge(attributes) end # Adds to the Set of 'bad' tags for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_bad_tags = 'embed', 'object' # end # def sanitized_bad_tags=(attributes) HTML::WhiteListSanitizer.bad_tags.merge(attributes) end # Adds to the Set of allowed tags for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td' # end # def sanitized_allowed_tags=(attributes) HTML::WhiteListSanitizer.allowed_tags.merge(attributes) end # Adds to the Set of allowed HTML attributes for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_attributes = 'onclick', 'longdesc' # end # def sanitized_allowed_attributes=(attributes) HTML::WhiteListSanitizer.allowed_attributes.merge(attributes) end # Adds to the Set of allowed CSS properties for the #sanitize and +sanitize_css+ helpers. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_css_properties = 'expression' # end # def sanitized_allowed_css_properties=(attributes) HTML::WhiteListSanitizer.allowed_css_properties.merge(attributes) end # Adds to the Set of allowed CSS keywords for the +sanitize+ and +sanitize_css+ helpers. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_css_keywords = 'expression' # end # def sanitized_allowed_css_keywords=(attributes) HTML::WhiteListSanitizer.allowed_css_keywords.merge(attributes) end # Adds to the Set of allowed shorthand CSS properties for the +sanitize+ and +sanitize_css+ helpers. # # Rails::Initializer.run do |config| # config.action_view.sanitized_shorthand_css_properties = 'expression' # end # def sanitized_shorthand_css_properties=(attributes) HTML::WhiteListSanitizer.shorthand_css_properties.merge(attributes) end # Adds to the Set of allowed protocols for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_protocols = 'ssh', 'feed' # end # def sanitized_allowed_protocols=(attributes) HTML::WhiteListSanitizer.allowed_protocols.merge(attributes) end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb
require "date" require 'action_view/helpers/tag_helper' module ActionView module Helpers # The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the # select-type methods share a number of common options that are as follows: # # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" # would give birthday[month] instead of date[month] if passed to the select_month method. # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date. # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true, # the select_month method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of # "date[month]". module DateHelper # Reports the approximate distance in time between two Time or Date objects or integers as seconds. # Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs # Distances are reported based on the following table: # # 0 <-> 29 secs # => less than a minute # 30 secs <-> 1 min, 29 secs # => 1 minute # 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes # 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour # 89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours # 23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs # => 1 day # 47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days # 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months # 1 yr <-> 2 yrs minus 1 secs # => about 1 year # 2 yrs <-> max time or date # => over [2..X] years # # With <tt>include_seconds</tt> = true and the difference < 1 minute 29 seconds: # 0-4 secs # => less than 5 seconds # 5-9 secs # => less than 10 seconds # 10-19 secs # => less than 20 seconds # 20-39 secs # => half a minute # 40-59 secs # => less than a minute # 60-89 secs # => 1 minute # # ==== Examples # from_time = Time.now # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute # distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds # distance_of_time_in_words(from_time, 3.years.from_now) # => over 3 years # distance_of_time_in_words(from_time, from_time + 60.hours) # => about 3 days # distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute # distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year # distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => over 4 years # # to_time = Time.now + 6.years + 19.days # distance_of_time_in_words(from_time, to_time, true) # => over 6 years # distance_of_time_in_words(to_time, from_time, true) # => over 6 years # distance_of_time_in_words(Time.now, Time.now) # => less than a minute # def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {}) from_time = from_time.to_time if from_time.respond_to?(:to_time) to_time = to_time.to_time if to_time.respond_to?(:to_time) distance_in_minutes = (((to_time - from_time).abs)/60).round distance_in_seconds = ((to_time - from_time).abs).round I18n.with_options :locale => options[:locale], :scope => :'datetime.distance_in_words' do |locale| case distance_in_minutes when 0..1 return distance_in_minutes == 0 ? locale.t(:less_than_x_minutes, :count => 1) : locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds case distance_in_seconds when 0..4 then locale.t :less_than_x_seconds, :count => 5 when 5..9 then locale.t :less_than_x_seconds, :count => 10 when 10..19 then locale.t :less_than_x_seconds, :count => 20 when 20..39 then locale.t :half_a_minute when 40..59 then locale.t :less_than_x_minutes, :count => 1 else locale.t :x_minutes, :count => 1 end when 2..44 then locale.t :x_minutes, :count => distance_in_minutes when 45..89 then locale.t :about_x_hours, :count => 1 when 90..1439 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round when 1440..2879 then locale.t :x_days, :count => 1 when 2880..43199 then locale.t :x_days, :count => (distance_in_minutes / 1440).round when 43200..86399 then locale.t :about_x_months, :count => 1 when 86400..525599 then locale.t :x_months, :count => (distance_in_minutes / 43200).round when 525600..1051199 then locale.t :about_x_years, :count => 1 else locale.t :over_x_years, :count => (distance_in_minutes / 525600).round end end end # Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>. # # ==== Examples # time_ago_in_words(3.minutes.from_now) # => 3 minutes # time_ago_in_words(Time.now - 15.hours) # => 15 hours # time_ago_in_words(Time.now) # => less than a minute # # from_time = Time.now - 3.days - 14.minutes - 25.seconds # => 3 days def time_ago_in_words(from_time, include_seconds = false) distance_of_time_in_words(from_time, Time.now, include_seconds) end alias_method :distance_of_time_in_words_to_now, :time_ago_in_words # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based # attribute (identified by +method+) on an object assigned to the template (identified by +object+). You can # the output in the +options+ hash. # # ==== Options # * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g. # "2" instead of "February"). # * <tt>:use_short_month</tt> - Set to true if you want to use the abbreviated month name instead of the full # name (e.g. "Feb" instead of "February"). # * <tt>:add_month_number</tt> - Set to true if you want to show both, the month's number and name (e.g. # "2 - February" instead of "February"). # * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names. # Note: You can also use Rails' new i18n functionality for this. # * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing). # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>. # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>. # * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day # as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the # first of the given month in order to not create invalid dates like 31 February. # * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month # as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true. # * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year # as a hidden field instead of showing a select field. # * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> do # customize the order in which the select fields are shown. If you leave out any of the symbols, the respective # select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails). # * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty # dates. # * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil. # * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled. # * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings # for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>. # Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds) # or the given prompt string. # # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set. # # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. # # ==== Examples # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute # date_select("post", "written_on") # # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute, # # with the year in the year drop down box starting at 1995. # date_select("post", "written_on", :start_year => 1995) # # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute, # # with the year in the year drop down box starting at 1995, numbers used for months instead of words, # # and without a day select box. # date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true, # :discard_day => true, :include_blank => true) # # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute # # with the fields ordered as day, month, year rather than month, day, year. # date_select("post", "written_on", :order => [:day, :month, :year]) # # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute # # lacking a year field. # date_select("user", "birthday", :order => [:month, :day]) # # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute # # which is initially set to the date 3 days from the current date # date_select("post", "written_on", :default => 3.days.from_now) # # # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute # # that will have a default day of 20. # date_select("credit_card", "bill_due", :default => { :day => 20 }) # # # Generates a date select with custom prompts # date_select("post", "written_on", :prompt => { :day => 'Select day', :month => 'Select month', :year => 'Select year' }) # # The selects are prepared for multi-parameter assignment to an Active Record object. # # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that # all month choices are valid. def date_select(object_name, method, options = {}, html_options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_date_select_tag(options, html_options) end # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a # specified time-based attribute (identified by +method+) on an object assigned to the template (identified by # +object+). You can include the seconds with <tt>:include_seconds</tt>. # # This method will also generate 3 input hidden tags, for the actual year, month and day unless the option # <tt>:ignore_date</tt> is set to +true+. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # ==== Examples # # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute # time_select("post", "sunrise") # # # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted # # attribute # time_select("order", "submitted") # # # Creates a time select tag that, when POSTed, will be stored in the mail variable in the sent_at attribute # time_select("mail", "sent_at") # # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in # # the sunrise attribute. # time_select("post", "start_time", :include_seconds => true) # # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the entry variables in # # the submission_time attribute. # time_select("entry", "submission_time", :include_seconds => true) # # # You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45. # time_select 'game', 'game_time', {:minute_step => 15} # # # Creates a time select tag with a custom prompt. Use :prompt => true for generic prompts. # time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'}) # time_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours # time_select("post", "written_on", :prompt => true) # generic prompts for all # # The selects are prepared for multi-parameter assignment to an Active Record object. # # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that # all month choices are valid. def time_select(object_name, method, options = {}, html_options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_time_select_tag(options, html_options) end # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a # specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified # by +object+). Examples: # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # ==== Examples # # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on # # attribute # datetime_select("post", "written_on") # # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the # # post variable in the written_on attribute. # datetime_select("post", "written_on", :start_year => 1995) # # # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will # # be stored in the trip variable in the departing attribute. # datetime_select("trip", "departing", :default => 3.days.from_now) # # # Generates a datetime select that discards the type that, when POSTed, will be stored in the post variable # # as the written_on attribute. # datetime_select("post", "written_on", :discard_type => true) # # # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts. # datetime_select("post", "written_on", :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # datetime_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours # datetime_select("post", "written_on", :prompt => true) # generic prompts for all # # The selects are prepared for multi-parameter assignment to an Active Record object. def datetime_select(object_name, method, options = {}, html_options = {}) InstanceTag.new(object_name, method, self, options.delete(:object)).to_datetime_select_tag(options, html_options) end # Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the # +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with # an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not # supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add # <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to # control visual display of the elements. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # ==== Examples # my_date_time = Time.now + 4.days # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # select_datetime(my_date_time) # # # Generates a datetime select that defaults to today (no specified datetime) # select_datetime() # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # with the fields ordered year, month, day rather than month, day, year. # select_datetime(my_date_time, :order => [:year, :month, :day]) # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # with a '/' between each date field. # select_datetime(my_date_time, :date_separator => '/') # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # with a date fields separated by '/', time fields separated by '' and the date and time fields # # separated by a comma (','). # select_datetime(my_date_time, :date_separator => '/', :time_separator => '', :datetime_separator => ',') # # # Generates a datetime select that discards the type of the field and defaults to the datetime in # # my_date_time (four days after today) # select_datetime(my_date_time, :discard_type => true) # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # prefixed with 'payday' rather than 'date' # select_datetime(my_date_time, :prefix => 'payday') # # # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts. # select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours # select_datetime(my_date_time, :prompt => true) # generic prompts for all # def select_datetime(datetime = Time.current, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_datetime end # Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+. # It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, # it will be appended onto the <tt>:order</tt> passed in. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # ==== Examples # my_date = Time.today + 6.days # # # Generates a date select that defaults to the date in my_date (six days after today) # select_date(my_date) # # # Generates a date select that defaults to today (no specified date) # select_date() # # # Generates a date select that defaults to the date in my_date (six days after today) # # with the fields ordered year, month, day rather than month, day, year. # select_date(my_date, :order => [:year, :month, :day]) # # # Generates a date select that discards the type of the field and defaults to the date in # # my_date (six days after today) # select_date(my_date, :discard_type => true) # # # Generates a date select that defaults to the date in my_date, # # which has fields separated by '/' # select_date(my_date, :date_separator => '/') # # # Generates a date select that defaults to the datetime in my_date (six days after today) # # prefixed with 'payday' rather than 'date' # select_date(my_date, :prefix => 'payday') # # # Generates a date select with a custom prompt. Use :prompt=>true for generic prompts. # select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours # select_date(my_date, :prompt => true) # generic prompts for all # def select_date(date = Date.current, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_date end # Returns a set of html select-tags (one for hour and minute) # You can set <tt>:time_separator</tt> key to format the output, and # the <tt>:include_seconds</tt> option to include an input for seconds. # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # # ==== Examples # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds # # # Generates a time select that defaults to the time in my_time # select_time(my_time) # # # Generates a time select that defaults to the current time (no specified time) # select_time() # # # Generates a time select that defaults to the time in my_time, # # which has fields separated by ':' # select_time(my_time, :time_separator => ':') # # # Generates a time select that defaults to the time in my_time, # # that also includes an input for seconds # select_time(my_time, :include_seconds => true) # # # Generates a time select that defaults to the time in my_time, that has fields # # separated by ':' and includes an input for seconds # select_time(my_time, :time_separator => ':', :include_seconds => true) # # # Generates a time select with a custom prompt. Use :prompt=>true for generic prompts. # select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours # select_time(my_time, :prompt => true) # generic prompts for all # def select_time(datetime = Time.current, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_time end # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. # The <tt>second</tt> can also be substituted for a second number. # Override the field name using the <tt>:field_name</tt> option, 'second' by default. # # ==== Examples # my_time = Time.now + 16.minutes # # # Generates a select field for seconds that defaults to the seconds for the time in my_time # select_second(my_time) # # # Generates a select field for seconds that defaults to the number given # select_second(33) # # # Generates a select field for seconds that defaults to the seconds for the time in my_time # # that is named 'interval' rather than 'second' # select_second(my_time, :field_name => 'interval') # # # Generates a select field for seconds with a custom prompt. Use :prompt=>true for a # # generic prompt. # select_minute(14, :prompt => 'Choose seconds') # def select_second(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_second end # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. # Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute # selected. The <tt>minute</tt> can also be substituted for a minute number. # Override the field name using the <tt>:field_name</tt> option, 'minute' by default. # # ==== Examples # my_time = Time.now + 6.hours # # # Generates a select field for minutes that defaults to the minutes for the time in my_time # select_minute(my_time) # # # Generates a select field for minutes that defaults to the number given # select_minute(14) # # # Generates a select field for minutes that defaults to the minutes for the time in my_time # # that is named 'stride' rather than 'second' # select_minute(my_time, :field_name => 'stride') # # # Generates a select field for minutes with a custom prompt. Use :prompt=>true for a # # generic prompt. # select_minute(14, :prompt => 'Choose minutes') # def select_minute(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_minute end # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. # The <tt>hour</tt> can also be substituted for a hour number. # Override the field name using the <tt>:field_name</tt> option, 'hour' by default. # # ==== Examples # my_time = Time.now + 6.hours # # # Generates a select field for hours that defaults to the hour for the time in my_time # select_hour(my_time) # # # Generates a select field for hours that defaults to the number given # select_hour(13) # # # Generates a select field for hours that defaults to the minutes for the time in my_time # # that is named 'stride' rather than 'second' # select_hour(my_time, :field_name => 'stride') # # # Generates a select field for hours with a custom prompt. Use :prompt => true for a # # generic prompt. # select_hour(13, :prompt =>'Choose hour') # def select_hour(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_hour end # Returns a select tag with options for each of the days 1 through 31 with the current day selected. # The <tt>date</tt> can also be substituted for a hour number. # Override the field name using the <tt>:field_name</tt> option, 'day' by default. # # ==== Examples # my_date = Time.today + 2.days # # # Generates a select field for days that defaults to the day for the date in my_date # select_day(my_time) # # # Generates a select field for days that defaults to the number given # select_day(5) # # # Generates a select field for days that defaults to the day for the date in my_date # # that is named 'due' rather than 'day' # select_day(my_time, :field_name => 'due') # # # Generates a select field for days with a custom prompt. Use :prompt => true for a # # generic prompt. # select_day(5, :prompt => 'Choose day') # def select_day(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_day end # Returns a select tag with options for each of the months January through December with the current month # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation # instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you # want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer # to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want # to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names. # Override the field name using the <tt>:field_name</tt> option, 'month' by default. # # ==== Examples # # Generates a select field for months that defaults to the current month that # # will use keys like "January", "March". # select_month(Date.today) # # # Generates a select field for months that defaults to the current month that # # is named "start" rather than "month" # select_month(Date.today, :field_name => 'start') # # # Generates a select field for months that defaults to the current month that # # will use keys like "1", "3". # select_month(Date.today, :use_month_numbers => true) # # # Generates a select field for months that defaults to the current month that # # will use keys like "1 - January", "3 - March". # select_month(Date.today, :add_month_numbers => true) # # # Generates a select field for months that defaults to the current month that # # will use keys like "Jan", "Mar". # select_month(Date.today, :use_short_month => true) # # # Generates a select field for months that defaults to the current month that # # will use keys like "Januar", "Marts." # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) # # # Generates a select field for months with a custom prompt. Use :prompt => true for a # # generic prompt. # select_month(14, :prompt => 'Choose month') # def select_month(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_month end # Returns a select tag with options for each of the five years on each side of the current, which is selected. # The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the # +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or # greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number. # Override the field name using the <tt>:field_name</tt> option, 'year' by default. # # ==== Examples
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb
require 'cgi' require 'action_view/helpers/tag_helper' module ActionView module Helpers # Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like # FormHelper does. Instead, you provide the names and values manually. # # NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying # <tt>:disabled => true</tt> will give <tt>disabled="disabled"</tt>. module FormTagHelper # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like # ActionController::Base#url_for. The method for the form defaults to POST. # # ==== Options # * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data". # * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post". # If "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt> # is added to simulate the verb over post. # * A list of parameters to feed to the URL the form will be posted to. # # ==== Examples # form_tag('/posts') # # => <form action="/posts" method="post"> # # form_tag('/posts/1', :method => :put) # # => <form action="/posts/1" method="put"> # # form_tag('/upload', :multipart => true) # # => <form action="/upload" method="post" enctype="multipart/form-data"> # # <% form_tag '/posts' do -%> # <div><%= submit_tag 'Save' %></div> # <% end -%> # # => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form> def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block) html_options = html_options_for_form(url_for_options, options, *parameters_for_url) if block_given? form_tag_in_block(html_options, &block) else form_tag_html(html_options) end end # Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple # choice selection box. # # Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or # associated records. <tt>option_tags</tt> is a string containing the option tags for the select box. # # ==== Options # * <tt>:multiple</tt> - If set to true the selection will allow multiple choices. # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * Any other key creates standard HTML attributes for the tag. # # ==== Examples # select_tag "people", "<option>David</option>" # # => <select id="people" name="people"><option>David</option></select> # # select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>" # # => <select id="count" name="count"><option>1</option><option>2</option> # # <option>3</option><option>4</option></select> # # select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>", :multiple => true # # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option> # # <option>Green</option><option>Blue</option></select> # # select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>" # # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option> # # <option>Out</option></select> # # select_tag "access", "<option>Read</option><option>Write</option>", :multiple => true, :class => 'form_input' # # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option> # # <option>Write</option></select> # # select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>", :disabled => true # # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option> # # <option>Paris</option><option>Rome</option></select> def select_tag(name, option_tags = nil, options = {}) html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) end # Creates a standard text field; use these text fields to input smaller chunks of text like a username # or a search query. # # ==== Options # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * <tt>:size</tt> - The number of visible characters that will fit in the input. # * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter. # * Any other key creates standard HTML attributes for the tag. # # ==== Examples # text_field_tag 'name' # # => <input id="name" name="name" type="text" /> # # text_field_tag 'query', 'Enter your search query here' # # => <input id="query" name="query" type="text" value="Enter your search query here" /> # # text_field_tag 'request', nil, :class => 'special_input' # # => <input class="special_input" id="request" name="request" type="text" /> # # text_field_tag 'address', '', :size => 75 # # => <input id="address" name="address" size="75" type="text" value="" /> # # text_field_tag 'zip', nil, :maxlength => 5 # # => <input id="zip" maxlength="5" name="zip" type="text" /> # # text_field_tag 'payment_amount', '$0.00', :disabled => true # # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" /> # # text_field_tag 'ip', '0.0.0.0', :maxlength => 15, :size => 20, :class => "ip-input" # # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" /> def text_field_tag(name, value = nil, options = {}) tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys) end # Creates a label field # # ==== Options # * Creates standard HTML attributes for the tag. # # ==== Examples # label_tag 'name' # # => <label for="name">Name</label> # # label_tag 'name', 'Your name' # # => <label for="name">Your Name</label> # # label_tag 'name', nil, :class => 'small_label' # # => <label for="name" class="small_label">Name</label> def label_tag(name, text = nil, options = {}) content_tag :label, text || name.to_s.humanize, { "for" => sanitize_to_id(name) }.update(options.stringify_keys) end # Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or # data that should be hidden from the user. # # ==== Options # * Creates standard HTML attributes for the tag. # # ==== Examples # hidden_field_tag 'tags_list' # # => <input id="tags_list" name="tags_list" type="hidden" /> # # hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@' # # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" /> # # hidden_field_tag 'collected_input', '', :onchange => "alert('Input collected!')" # # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')" # # type="hidden" value="" /> def hidden_field_tag(name, value = nil, options = {}) text_field_tag(name, value, options.stringify_keys.update("type" => "hidden")) end # Creates a file upload field. If you are using file uploads then you will also need # to set the multipart option for the form tag: # # <% form_tag '/upload', :multipart => true do %> # <label for="file">File to Upload</label> <%= file_field_tag "file" %> # <%= submit_tag %> # <% end %> # # The specified URL will then be passed a File object containing the selected file, or if the field # was left blank, a StringIO object. # # ==== Options # * Creates standard HTML attributes for the tag. # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # # ==== Examples # file_field_tag 'attachment' # # => <input id="attachment" name="attachment" type="file" /> # # file_field_tag 'avatar', :class => 'profile-input' # # => <input class="profile-input" id="avatar" name="avatar" type="file" /> # # file_field_tag 'picture', :disabled => true # # => <input disabled="disabled" id="picture" name="picture" type="file" /> # # file_field_tag 'resume', :value => '~/resume.doc' # # => <input id="resume" name="resume" type="file" value="~/resume.doc" /> # # file_field_tag 'user_pic', :accept => 'image/png,image/gif,image/jpeg' # # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" /> # # file_field_tag 'file', :accept => 'text/html', :class => 'upload', :value => 'index.html' # # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" /> def file_field_tag(name, options = {}) text_field_tag(name, nil, options.update("type" => "file")) end # Creates a password field, a masked text field that will hide the users input behind a mask character. # # ==== Options # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * <tt>:size</tt> - The number of visible characters that will fit in the input. # * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter. # * Any other key creates standard HTML attributes for the tag. # # ==== Examples # password_field_tag 'pass' # # => <input id="pass" name="pass" type="password" /> # # password_field_tag 'secret', 'Your secret here' # # => <input id="secret" name="secret" type="password" value="Your secret here" /> # # password_field_tag 'masked', nil, :class => 'masked_input_field' # # => <input class="masked_input_field" id="masked" name="masked" type="password" /> # # password_field_tag 'token', '', :size => 15 # # => <input id="token" name="token" size="15" type="password" value="" /> # # password_field_tag 'key', nil, :maxlength => 16 # # => <input id="key" maxlength="16" name="key" type="password" /> # # password_field_tag 'confirm_pass', nil, :disabled => true # # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" /> # # password_field_tag 'pin', '1234', :maxlength => 4, :size => 6, :class => "pin-input" # # => <input class="pin-input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" /> def password_field_tag(name = "password", value = nil, options = {}) text_field_tag(name, value, options.update("type" => "password")) end # Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. # # ==== Options # * <tt>:size</tt> - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10"). # * <tt>:rows</tt> - Specify the number of rows in the textarea # * <tt>:cols</tt> - Specify the number of columns in the textarea # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * <tt>:escape</tt> - By default, the contents of the text input are HTML escaped. # If you need unescaped contents, set this to false. # * Any other key creates standard HTML attributes for the tag. # # ==== Examples # text_area_tag 'post' # # => <textarea id="post" name="post"></textarea> # # text_area_tag 'bio', @user.bio # # => <textarea id="bio" name="bio">This is my biography.</textarea> # # text_area_tag 'body', nil, :rows => 10, :cols => 25 # # => <textarea cols="25" id="body" name="body" rows="10"></textarea> # # text_area_tag 'body', nil, :size => "25x10" # # => <textarea name="body" id="body" cols="25" rows="10"></textarea> # # text_area_tag 'description', "Description goes here.", :disabled => true # # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea> # # text_area_tag 'comment', nil, :class => 'comment_input' # # => <textarea class="comment_input" id="comment" name="comment"></textarea> def text_area_tag(name, content = nil, options = {}) options.stringify_keys! if size = options.delete("size") options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split) end escape = options.key?("escape") ? options.delete("escape") : true content = html_escape(content) if escape content_tag :textarea, content, { "name" => name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) end # Creates a check box form input tag. # # ==== Options # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * Any other key creates standard HTML options for the tag. # # ==== Examples # check_box_tag 'accept' # # => <input id="accept" name="accept" type="checkbox" value="1" /> # # check_box_tag 'rock', 'rock music' # # => <input id="rock" name="rock" type="checkbox" value="rock music" /> # # check_box_tag 'receive_email', 'yes', true # # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" /> # # check_box_tag 'tos', 'yes', false, :class => 'accept_tos' # # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" /> # # check_box_tag 'eula', 'accepted', false, :disabled => true # # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" /> def check_box_tag(name, value = "1", checked = false, options = {}) html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys) html_options["checked"] = "checked" if checked tag :input, html_options end # Creates a radio button; use groups of radio buttons named the same to allow users to # select from a group of options. # # ==== Options # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * Any other key creates standard HTML options for the tag. # # ==== Examples # radio_button_tag 'gender', 'male' # # => <input id="gender_male" name="gender" type="radio" value="male" /> # # radio_button_tag 'receive_updates', 'no', true # # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" /> # # radio_button_tag 'time_slot', "3:00 p.m.", false, :disabled => true # # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." /> # # radio_button_tag 'color', "green", true, :class => "color_input" # # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" /> def radio_button_tag(name, value, checked = false, options = {}) pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase pretty_name = name.to_s.gsub(/\[/, "_").gsub(/\]/, "") html_options = { "type" => "radio", "name" => name, "id" => "#{pretty_name}_#{pretty_tag_value}", "value" => value }.update(options.stringify_keys) html_options["checked"] = "checked" if checked tag :input, html_options end # Creates a submit button with the text <tt>value</tt> as the caption. # # ==== Options # * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm # prompt with the question specified. If the user accepts, the form is # processed normally, otherwise no action is taken. # * <tt>:disabled</tt> - If true, the user will not be able to use this input. # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a disabled version # of the submit button when the form is submitted. # * Any other key creates standard HTML options for the tag. # # ==== Examples # submit_tag # # => <input name="commit" type="submit" value="Save changes" /> # # submit_tag "Edit this article" # # => <input name="commit" type="submit" value="Edit this article" /> # # submit_tag "Save edits", :disabled => true # # => <input disabled="disabled" name="commit" type="submit" value="Save edits" /> # # submit_tag "Complete sale", :disable_with => "Please wait..." # # => <input name="commit" onclick="this.disabled=true;this.value='Please wait...';this.form.submit();" # # type="submit" value="Complete sale" /> # # submit_tag nil, :class => "form_submit" # # => <input class="form_submit" name="commit" type="submit" /> # # submit_tag "Edit", :disable_with => "Editing...", :class => "edit-button" # # => <input class="edit-button" onclick="this.disabled=true;this.value='Editing...';this.form.submit();" # # name="commit" type="submit" value="Edit" /> def submit_tag(value = "Save changes", options = {}) options.stringify_keys! if disable_with = options.delete("disable_with") disable_with = "this.value='#{disable_with}'" disable_with << ";#{options.delete('onclick')}" if options['onclick'] options["onclick"] = "if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }" options["onclick"] << "else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';" options["onclick"] << "hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }" options["onclick"] << "this.setAttribute('originalValue', this.value);this.disabled = true;#{disable_with};" options["onclick"] << "result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());" options["onclick"] << "if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" end if confirm = options.delete("confirm") options["onclick"] ||= 'return true;' options["onclick"] = "if (!#{confirm_javascript_function(confirm)}) return false; #{options['onclick']}" end tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys) end # Displays an image which when clicked will submit the form. # # <tt>source</tt> is passed to AssetTagHelper#image_path # # ==== Options # * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm # prompt with the question specified. If the user accepts, the form is # processed normally, otherwise no action is taken. # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. # * Any other key creates standard HTML options for the tag. # # ==== Examples # image_submit_tag("login.png") # # => <input src="/images/login.png" type="image" /> # # image_submit_tag("purchase.png", :disabled => true) # # => <input disabled="disabled" src="/images/purchase.png" type="image" /> # # image_submit_tag("search.png", :class => 'search-button') # # => <input class="search-button" src="/images/search.png" type="image" /> # # image_submit_tag("agree.png", :disabled => true, :class => "agree-disagree-button") # # => <input class="agree-disagree-button" disabled="disabled" src="/images/agree.png" type="image" /> def image_submit_tag(source, options = {}) options.stringify_keys! if confirm = options.delete("confirm") options["onclick"] ||= '' options["onclick"] += "return #{confirm_javascript_function(confirm)};" end tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options.stringify_keys) end # Creates a field set for grouping HTML form elements. # # <tt>legend</tt> will become the fieldset's title (optional as per W3C). # <tt>options</tt> accept the same values as tag. # # === Examples # <% field_set_tag do %> # <p><%= text_field_tag 'name' %></p> # <% end %> # # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset> # # <% field_set_tag 'Your details' do %> # <p><%= text_field_tag 'name' %></p> # <% end %> # # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset> # # <% field_set_tag nil, :class => 'format' do %> # <p><%= text_field_tag 'name' %></p> # <% end %> # # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset> def field_set_tag(legend = nil, options = nil, &block) content = capture(&block) concat(tag(:fieldset, options, true)) concat(content_tag(:legend, legend)) unless legend.blank? concat(content) concat("</fieldset>") end private def html_options_for_form(url_for_options, options, *parameters_for_url) returning options.stringify_keys do |html_options| html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart") html_options["action"] = url_for(url_for_options, *parameters_for_url) end end def extra_tags_for_form(html_options) case method = html_options.delete("method").to_s when /^get$/i # must be case-insentive, but can't use downcase as might be nil html_options["method"] = "get" '' when /^post$/i, "", nil html_options["method"] = "post" protect_against_forgery? ? content_tag(:div, token_tag, :style => 'margin:0;padding:0;display:inline') : '' else html_options["method"] = "post" content_tag(:div, tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag, :style => 'margin:0;padding:0;display:inline') end end def form_tag_html(html_options) extra_tags = extra_tags_for_form(html_options) tag(:form, html_options, true) + extra_tags end def form_tag_in_block(html_options, &block) content = capture(&block) concat(form_tag_html(html_options)) concat(content) concat("</form>") end def token_tag unless protect_against_forgery? '' else tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) end end # see http://www.w3.org/TR/html4/types.html#type-name def sanitize_to_id(name) name.to_s.gsub(']','').gsub(/[^-a-zA-Z0-9:.]/, "_") end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/atom_feed_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/atom_feed_helper.rb
require 'set' # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERb or any other # template languages). module ActionView module Helpers #:nodoc: module AtomFeedHelper # Full usage example: # # config/routes.rb: # ActionController::Routing::Routes.draw do |map| # map.resources :posts # map.root :controller => "posts" # end # # app/controllers/posts_controller.rb: # class PostsController < ApplicationController::Base # # GET /posts.html # # GET /posts.atom # def index # @posts = Post.find(:all) # # respond_to do |format| # format.html # format.atom # end # end # end # # app/views/posts/index.atom.builder: # atom_feed do |feed| # feed.title("My great blog!") # feed.updated(@posts.first.created_at) # # for post in @posts # feed.entry(post) do |entry| # entry.title(post.title) # entry.content(post.body, :type => 'html') # # entry.author do |author| # author.name("DHH") # end # end # end # end # # The options for atom_feed are: # # * <tt>:language</tt>: Defaults to "en-US". # * <tt>:root_url</tt>: The HTML alternative that this feed is doubling for. Defaults to / on the current host. # * <tt>:url</tt>: The URL for this feed. Defaults to the current URL. # * <tt>:id</tt>: The id for this feed. Defaults to "tag:#{request.host},#{options[:schema_date]}:#{request.request_uri.split(".")[0]}" # * <tt>:schema_date</tt>: The date at which the tag scheme for the feed was first used. A good default is the year you # created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified, # 2005 is used (as an "I don't care" value). # * <tt>:instruct</tt>: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]} # # Other namespaces can be added to the root element: # # app/views/posts/index.atom.builder: # atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app', # 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed| # feed.title("My great blog!") # feed.updated((@posts.first.created_at)) # feed.tag!(openSearch:totalResults, 10) # # for post in @posts # feed.entry(post) do |entry| # entry.title(post.title) # entry.content(post.body, :type => 'html') # entry.tag!('app:edited', Time.now) # # entry.author do |author| # author.name("DHH") # end # end # end # end # # The Atom spec defines five elements (content rights title subtitle # summary) which may directly contain xhtml content if :type => 'xhtml' # is specified as an attribute. If so, this helper will take care of # the enclosing div and xhtml namespace declaration. Example usage: # # entry.summary :type => 'xhtml' do |xhtml| # xhtml.p pluralize(order.line_items.count, "line item") # xhtml.p "Shipped to #{order.address}" # xhtml.p "Paid by #{order.pay_type}" # end # # # atom_feed yields an AtomFeedBuilder instance. Nested elements yield # an AtomBuilder instance. def atom_feed(options = {}, &block) if options[:schema_date] options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime) else options[:schema_date] = "2005" # The Atom spec copyright date end xml = options.delete(:xml) || eval("xml", block.binding) xml.instruct! if options[:instruct] options[:instruct].each do |target,attrs| if attrs.respond_to?(:keys) xml.instruct!(target, attrs) elsif attrs.respond_to?(:each) attrs.each { |attr_group| xml.instruct!(target, attr_group) } end end end feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => 'http://www.w3.org/2005/Atom'} feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)} xml.feed(feed_opts) do xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.request_uri.split(".")[0]}") xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || (request.protocol + request.host_with_port)) xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url] || request.url) yield AtomFeedBuilder.new(xml, self, options) end end class AtomBuilder XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set def initialize(xml) @xml = xml end private # Delegate to xml builder, first wrapping the element in a xhtml # namespaced div element if the method and arguments indicate # that an xhtml_block? is desired. def method_missing(method, *arguments, &block) if xhtml_block?(method, arguments) @xml.__send__(method, *arguments) do @xml.div(:xmlns => 'http://www.w3.org/1999/xhtml') do |xhtml| block.call(xhtml) end end else @xml.__send__(method, *arguments, &block) end end # True if the method name matches one of the five elements defined # in the Atom spec as potentially containing XHTML content and # if :type => 'xhtml' is, in fact, specified. def xhtml_block?(method, arguments) if XHTML_TAG_NAMES.include?(method.to_s) last = arguments.last last.is_a?(Hash) && last[:type].to_s == 'xhtml' end end end class AtomFeedBuilder < AtomBuilder def initialize(xml, view, feed_options = {}) @xml, @view, @feed_options = xml, view, feed_options end # Accepts a Date or Time object and inserts it in the proper format. If nil is passed, current time in UTC is used. def updated(date_or_time = nil) @xml.updated((date_or_time || Time.now.utc).xmlschema) end # Creates an entry tag for a specific record and prefills the id using class and id. # # Options: # # * <tt>:published</tt>: Time first published. Defaults to the created_at attribute on the record if one such exists. # * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists. # * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record. # * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}" def entry(record, options = {}) @xml.entry do @xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}") if options[:published] || (record.respond_to?(:created_at) && record.created_at) @xml.published((options[:published] || record.created_at).xmlschema) end if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at) @xml.updated((options[:updated] || record.updated_at).xmlschema) end @xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:url] || @view.polymorphic_url(record)) yield AtomBuilder.new(@xml) end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/number_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/number_helper.rb
module ActionView module Helpers #:nodoc: # Provides methods for converting numbers into formatted strings. # Methods are provided for phone numbers, currency, percentage, # precision, positional notation, and file size. module NumberHelper # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format # in the +options+ hash. # # ==== Options # * <tt>:area_code</tt> - Adds parentheses around the area code. # * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-"). # * <tt>:extension</tt> - Specifies an extension to add to the end of the # generated number. # * <tt>:country_code</tt> - Sets the country code for the phone number. # # ==== Examples # number_to_phone(5551234) # => 555-1234 # number_to_phone(1235551234) # => 123-555-1234 # number_to_phone(1235551234, :area_code => true) # => (123) 555-1234 # number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234 # number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555 # number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234 # # number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".") # => +1.123.555.1234 x 1343 def number_to_phone(number, options = {}) number = number.to_s.strip unless number.nil? options = options.symbolize_keys area_code = options[:area_code] || nil delimiter = options[:delimiter] || "-" extension = options[:extension].to_s.strip || nil country_code = options[:country_code] || nil begin str = "" str << "+#{country_code}#{delimiter}" unless country_code.blank? str << if area_code number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4}$)/,"(\\1) \\2#{delimiter}\\3") else number.gsub!(/([0-9]{0,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3") number.starts_with?('-') ? number.slice!(1..-1) : number end str << " x #{extension}" unless extension.blank? str rescue number end end # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format # in the +options+ hash. # # ==== Options # * <tt>:precision</tt> - Sets the level of precision (defaults to 2). # * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$"). # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). # * <tt>:format</tt> - Sets the format of the output string (defaults to "%u%n"). The field types are: # # %u The currency unit # %n The number # # ==== Examples # number_to_currency(1234567890.50) # => $1,234,567,890.50 # number_to_currency(1234567890.506) # => $1,234,567,890.51 # number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506 # # number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "") # # => &pound;1234567890,50 # number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "", :format => "%n %u") # # => 1234567890,50 &pound; def number_to_currency(number, options = {}) options.symbolize_keys! defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {} currency = I18n.translate(:'number.currency.format', :locale => options[:locale], :raise => true) rescue {} defaults = defaults.merge(currency) precision = options[:precision] || defaults[:precision] unit = options[:unit] || defaults[:unit] separator = options[:separator] || defaults[:separator] delimiter = options[:delimiter] || defaults[:delimiter] format = options[:format] || defaults[:format] separator = '' if precision == 0 begin format.gsub(/%n/, number_with_precision(number, :precision => precision, :delimiter => delimiter, :separator => separator) ).gsub(/%u/, unit) rescue number end end # Formats a +number+ as a percentage string (e.g., 65%). You can customize the # format in the +options+ hash. # # ==== Options # * <tt>:precision</tt> - Sets the level of precision (defaults to 3). # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). # # ==== Examples # number_to_percentage(100) # => 100.000% # number_to_percentage(100, :precision => 0) # => 100% # number_to_percentage(1000, :delimiter => '.', :separator => ',') # => 1.000,000% # number_to_percentage(302.24398923423, :precision => 5) # => 302.24399% def number_to_percentage(number, options = {}) options.symbolize_keys! defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {} percentage = I18n.translate(:'number.percentage.format', :locale => options[:locale], :raise => true) rescue {} defaults = defaults.merge(percentage) precision = options[:precision] || defaults[:precision] separator = options[:separator] || defaults[:separator] delimiter = options[:delimiter] || defaults[:delimiter] begin number_with_precision(number, :precision => precision, :separator => separator, :delimiter => delimiter) + "%" rescue number end end # Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You can # customize the format in the +options+ hash. # # ==== Options # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). # # ==== Examples # number_with_delimiter(12345678) # => 12,345,678 # number_with_delimiter(12345678.05) # => 12,345,678.05 # number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678 # number_with_delimiter(12345678, :separator => ",") # => 12,345,678 # number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",") # # => 98 765 432,98 # # You can still use <tt>number_with_delimiter</tt> with the old API that accepts the # +delimiter+ as its optional second and the +separator+ as its # optional third parameter: # number_with_delimiter(12345678, " ") # => 12 345.678 # number_with_delimiter(12345678.05, ".", ",") # => 12.345.678,05 def number_with_delimiter(number, *args) options = args.extract_options! options.symbolize_keys! defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {} unless args.empty? ActiveSupport::Deprecation.warn('number_with_delimiter takes an option hash ' + 'instead of separate delimiter and precision arguments.', caller) delimiter = args[0] || defaults[:delimiter] separator = args[1] || defaults[:separator] end delimiter ||= (options[:delimiter] || defaults[:delimiter]) separator ||= (options[:separator] || defaults[:separator]) begin parts = number.to_s.split('.') parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}") parts.join(separator) rescue number end end # Formats a +number+ with the specified level of <tt>:precision</tt> (e.g., 112.32 has a precision of 2). # You can customize the format in the +options+ hash. # # ==== Options # * <tt>:precision</tt> - Sets the level of precision (defaults to 3). # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). # # ==== Examples # number_with_precision(111.2345) # => 111.235 # number_with_precision(111.2345, :precision => 2) # => 111.23 # number_with_precision(13, :precision => 5) # => 13.00000 # number_with_precision(389.32314, :precision => 0) # => 389 # number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.') # # => 1.111,23 # # You can still use <tt>number_with_precision</tt> with the old API that accepts the # +precision+ as its optional second parameter: # number_with_precision(number_with_precision(111.2345, 2) # => 111.23 def number_with_precision(number, *args) options = args.extract_options! options.symbolize_keys! defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {} precision_defaults = I18n.translate(:'number.precision.format', :locale => options[:locale], :raise => true) rescue {} defaults = defaults.merge(precision_defaults) unless args.empty? ActiveSupport::Deprecation.warn('number_with_precision takes an option hash ' + 'instead of a separate precision argument.', caller) precision = args[0] || defaults[:precision] end precision ||= (options[:precision] || defaults[:precision]) separator ||= (options[:separator] || defaults[:separator]) delimiter ||= (options[:delimiter] || defaults[:delimiter]) begin rounded_number = (Float(number) * (10 ** precision)).round.to_f / 10 ** precision number_with_delimiter("%01.#{precision}f" % rounded_number, :separator => separator, :delimiter => delimiter) rescue number end end STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb].freeze # Formats the bytes in +size+ into a more understandable representation # (e.g., giving it 1500 yields 1.5 KB). This method is useful for # reporting file sizes to users. This method returns nil if # +size+ cannot be converted into a number. You can customize the # format in the +options+ hash. # # ==== Options # * <tt>:precision</tt> - Sets the level of precision (defaults to 1). # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). # # ==== Examples # number_to_human_size(123) # => 123 Bytes # number_to_human_size(1234) # => 1.2 KB # number_to_human_size(12345) # => 12.1 KB # number_to_human_size(1234567) # => 1.2 MB # number_to_human_size(1234567890) # => 1.1 GB # number_to_human_size(1234567890123) # => 1.1 TB # number_to_human_size(1234567, :precision => 2) # => 1.18 MB # number_to_human_size(483989, :precision => 0) # => 473 KB # number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,18 MB # # You can still use <tt>number_to_human_size</tt> with the old API that accepts the # +precision+ as its optional second parameter: # number_to_human_size(1234567, 2) # => 1.18 MB # number_to_human_size(483989, 0) # => 473 KB def number_to_human_size(number, *args) return nil if number.nil? options = args.extract_options! options.symbolize_keys! defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {} human = I18n.translate(:'number.human.format', :locale => options[:locale], :raise => true) rescue {} defaults = defaults.merge(human) unless args.empty? ActiveSupport::Deprecation.warn('number_to_human_size takes an option hash ' + 'instead of a separate precision argument.', caller) precision = args[0] || defaults[:precision] end precision ||= (options[:precision] || defaults[:precision]) separator ||= (options[:separator] || defaults[:separator]) delimiter ||= (options[:delimiter] || defaults[:delimiter]) storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true) if number.to_i < 1024 unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true) storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit) else max_exp = STORAGE_UNITS.size - 1 number = Float(number) exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024 exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit number /= 1024 ** exponent unit_key = STORAGE_UNITS[exponent] unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true) begin escaped_separator = Regexp.escape(separator) formatted_number = number_with_precision(number, :precision => precision, :separator => separator, :delimiter => delimiter ).sub(/(\d)(#{escaped_separator}[1-9]*)?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '') storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit) rescue number end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/helpers/benchmark_helper.rb
provider/vendor/rails/actionpack/lib/action_view/helpers/benchmark_helper.rb
require 'benchmark' module ActionView module Helpers # This helper offers a method to measure the execution time of a block # in a template. module BenchmarkHelper # Allows you to measure the execution time of a block # in a template and records the result to the log. Wrap this block around # expensive operations or possible bottlenecks to get a time reading # for the operation. For example, let's say you thought your file # processing method was taking too long; you could wrap it in a benchmark block. # # <% benchmark "Process data files" do %> # <%= expensive_files_operation %> # <% end %> # # That would add something like "Process data files (345.2ms)" to the log, # which you can then use to compare timings when optimizing your code. # # You may give an optional logger level as the :level option. # (:debug, :info, :warn, :error); the default value is :info. # # <% benchmark "Low-level files", :level => :debug do %> # <%= lowlevel_files_operation %> # <% end %> # # Finally, you can pass true as the third argument to silence all log activity # inside the block. This is great for boiling down a noisy block to just a single statement: # # <% benchmark "Process data files", :level => :info, :silence => true do %> # <%= expensive_and_chatty_files_operation %> # <% end %> def benchmark(message = "Benchmarking", options = {}) if controller.logger if options.is_a?(Symbol) ActiveSupport::Deprecation.warn("use benchmark('#{message}', :level => :#{options}) instead", caller) options = { :level => options, :silence => false } else options.assert_valid_keys(:level, :silence) options[:level] ||= :info end result = nil ms = Benchmark.ms { result = options[:silence] ? controller.logger.silence { yield } : yield } controller.logger.send(options[:level], '%s (%.1fms)' % [ message, ms ]) result else yield end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template_handlers/rjs.rb
provider/vendor/rails/actionpack/lib/action_view/template_handlers/rjs.rb
module ActionView module TemplateHandlers class RJS < TemplateHandler include Compilable def compile(template) "@template_format = :html;" + "controller.response.content_type ||= Mime::JS;" + "update_page do |page|;#{template.source}\nend" end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template_handlers/erb.rb
provider/vendor/rails/actionpack/lib/action_view/template_handlers/erb.rb
module ActionView module TemplateHandlers class ERB < TemplateHandler include Compilable ## # :singleton-method: # Specify trim mode for the ERB compiler. Defaults to '-'. # See ERb documentation for suitable values. cattr_accessor :erb_trim_mode self.erb_trim_mode = '-' def compile(template) src = ::ERB.new("<% __in_erb_template=true %>#{template.source}", nil, erb_trim_mode, '@output_buffer').src # Ruby 1.9 prepends an encoding to the source. However this is # useless because you can only set an encoding on the first line RUBY_VERSION >= '1.9' ? src.sub(/\A#coding:.*\n/, '') : src end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/template_handlers/builder.rb
provider/vendor/rails/actionpack/lib/action_view/template_handlers/builder.rb
require 'builder' module ActionView module TemplateHandlers class Builder < TemplateHandler include Compilable def compile(template) "_set_controller_content_type(Mime::XML);" + "xml = ::Builder::XmlMarkup.new(:indent => 2);" + "self.output_buffer = xml.target!;" + template.source + ";xml.target!;" end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/lib/action_view/erb/util.rb
provider/vendor/rails/actionpack/lib/action_view/erb/util.rb
require 'erb' class ERB module Util HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' } JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' } # A utility method for escaping HTML tag characters. # This method is also aliased as <tt>h</tt>. # # In your ERb templates, use this method to escape any unsafe content. For example: # <%=h @person.name %> # # ==== Example: # puts html_escape("is a > 0 & a < 10?") # # => is a &gt; 0 &amp; a &lt; 10? def html_escape(s) s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] } end # A utility method for escaping HTML entities in JSON strings. # This method is also aliased as <tt>j</tt>. # # In your ERb templates, use this method to escape any HTML entities: # <%=j @person.to_json %> # # ==== Example: # puts json_escape("is a > 0 & a < 10?") # # => is a \u003E 0 \u0026 a \u003C 10? def json_escape(s) s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] } end alias j json_escape module_function :j module_function :json_escape end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/init.rb
provider/vendor/plugins/oauth2_provider/init.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) # !!perform any initialization in oauth2_provider!! require 'oauth2_provider'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/controllers/oauth_user_tokens_controller.rb
provider/vendor/plugins/oauth2_provider/app/controllers/oauth_user_tokens_controller.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class OauthUserTokensController < ApplicationController include Oauth2::Provider::TransactionHelper transaction_actions :revoke, :revoke_by_admin def index @tokens = Oauth2::Provider::OauthToken.find_all_with(:user_id, current_user_id_for_oauth) end def revoke token = Oauth2::Provider::OauthToken.find_by_id(params[:token_id]) if token.nil? render_not_authorized return end if token.user_id.to_s != current_user_id_for_oauth render_not_authorized return end token.destroy redirect_after_revoke end def revoke_by_admin if params[:token_id].blank? && params[:user_id].blank? render_not_authorized return end if !params[:token_id].blank? token = Oauth2::Provider::OauthToken.find_by_id(params[:token_id]) if token.nil? render_not_authorized return end token.destroy else Oauth2::Provider::OauthToken.find_all_with(:user_id, params[:user_id]).map(&:destroy) end redirect_after_revoke end private def render_not_authorized render :text => "You are not authorized to perform this action!", :status => :bad_request end def redirect_after_revoke flash[:notice] = "OAuth access token was successfully deleted." redirect_to params[:redirect_url] || {:action => 'index'} end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/controllers/oauth_token_controller.rb
provider/vendor/plugins/oauth2_provider/app/controllers/oauth_token_controller.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class OauthTokenController < ApplicationController skip_before_filter :verify_authenticity_token include Oauth2::Provider::SslHelper include Oauth2::Provider::TransactionHelper transaction_actions :get_token def get_token authorization = Oauth2::Provider::OauthAuthorization.find_one(:code, params[:code]) authorization.destroy unless authorization.nil? original_token = Oauth2::Provider::OauthToken.find_one(:refresh_token, params[:refresh_token]) original_token.destroy unless original_token.nil? unless ['authorization-code', 'refresh-token'].include?(params[:grant_type]) render_error('unsupported-grant-type', "Grant type #{params[:grant_type]} is not supported!") return end client = Oauth2::Provider::OauthClient.find_one(:client_id, params[:client_id]) if client.nil? || client.client_secret != params[:client_secret] render_error('invalid-client-credentials', 'Invalid client credentials!') return end if client.redirect_uri != params[:redirect_uri] render_error('invalid-grant', 'Redirect uri mismatch!') return end if params[:grant_type] == 'authorization-code' if authorization.nil? || authorization.expired? || authorization.oauth_client.id != client.id render_error('invalid-grant', "Authorization expired or invalid!") return end token = authorization.generate_access_token else # refresh-token if original_token.nil? || original_token.oauth_client.id != client.id render_error('invalid-grant', 'Refresh token is invalid!') return end token = original_token.refresh end render :content_type => 'application/json', :text => token.access_token_attributes.to_json end private def render_error(error_code, description) render :status => :bad_request, :json => {:error => error_code, :error_description => description}.to_json end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/controllers/oauth_authorize_controller.rb
provider/vendor/plugins/oauth2_provider/app/controllers/oauth_authorize_controller.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class OauthAuthorizeController < ::ApplicationController include Oauth2::Provider::SslHelper include Oauth2::Provider::TransactionHelper transaction_actions :authorize def index return unless validate_params end def authorize return unless validate_params unless params[:authorize] == 'Yes' redirect_to "#{params[:redirect_uri]}?error=access-denied" return end authorization = @client.create_authorization_for_user_id(current_user_id_for_oauth) state_param = if params[:state].blank? "" else "&state=#{CGI.escape(params[:state])}" end redirect_to "#{params[:redirect_uri]}?code=#{authorization.code}&expires_in=#{authorization.expires_in}#{state_param}" end private # TODO: support 'code', 'token', 'code-and-token' VALID_RESPONSE_TYPES = ['code'] def validate_params if params[:client_id].blank? || params[:response_type].blank? redirect_to "#{params[:redirect_uri]}?error=invalid-request" return false end unless VALID_RESPONSE_TYPES.include?(params[:response_type]) redirect_to "#{params[:redirect_uri]}?error=unsupported-response-type" return end if params[:redirect_uri].blank? render :text => "You did not specify the 'redirect_uri' parameter!", :status => :bad_request return false end @client = Oauth2::Provider::OauthClient.find_one(:client_id, params[:client_id]) if @client.nil? redirect_to "#{params[:redirect_uri]}?error=invalid-client-id" return false end if @client.redirect_uri != params[:redirect_uri] redirect_to "#{params[:redirect_uri]}?error=redirect-uri-mismatch" return false end true end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/controllers/oauth_clients_controller.rb
provider/vendor/plugins/oauth2_provider/app/controllers/oauth_clients_controller.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class OauthClientsController < ApplicationController include Oauth2::Provider::SslHelper include Oauth2::Provider::TransactionHelper transaction_actions :create, :update, :destroy def index @oauth_clients = Oauth2::Provider::OauthClient.all.sort{|a, b| a.name.casecmp(b.name)} respond_to do |format| format.html format.xml { render :xml => @oauth_clients.to_xml(:root => 'oauth_clients', :dasherize => false) } end end def show @oauth_client = Oauth2::Provider::OauthClient.find(params[:id]) respond_to do |format| format.html format.xml { render :xml => @oauth_client.to_xml(:dasherize => false) } end end def new @oauth_client = Oauth2::Provider::OauthClient.new end def edit @oauth_client = Oauth2::Provider::OauthClient.find(params[:id]) end def create @oauth_client = Oauth2::Provider::OauthClient.new(params[:oauth_client]) respond_to do |format| if @oauth_client.save flash[:notice] = 'OAuth client was successfully created.' format.html { redirect_to :action => 'index' } format.xml { render :xml => @oauth_client, :status => :created, :location => @oauth_client } else flash.now[:error] = @oauth_client.errors.full_messages format.html { render :action => "new" } format.xml { render :xml => @oauth_client.errors, :status => :unprocessable_entity } end end end def update @oauth_client = Oauth2::Provider::OauthClient.find(params[:id]) respond_to do |format| if @oauth_client.update_attributes(params[:oauth_client]) flash[:notice] = 'OAuth client was successfully updated.' format.html { redirect_to :action => 'index' } format.xml { head :ok } else flash.now[:error] = @oauth_client.errors.full_messages format.html { render :action => "edit" } format.xml { render :xml => @oauth_client.errors, :status => :unprocessable_entity } end end end def destroy @oauth_client = Oauth2::Provider::OauthClient.find(params[:id]) @oauth_client.destroy respond_to do |format| flash[:notice] = 'OAuth client was successfully deleted.' format.html { redirect_to(oauth_clients_url) } format.xml { head :ok } end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/models/oauth2/provider/oauth_client.rb
provider/vendor/plugins/oauth2_provider/app/models/oauth2/provider/oauth_client.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider class OauthClient < ModelBase validates_presence_of :name, :redirect_uri validates_format_of :redirect_uri, :with => Regexp.new("^(https|http)://.+$"), :if => proc { |client| !client.redirect_uri.blank? } validates_uniqueness_of :name columns :name, :client_id, :client_secret, :redirect_uri def create_token_for_user_id(user_id) OauthToken.create!(:user_id => user_id, :oauth_client_id => id) end def create_authorization_for_user_id(user_id) oauth_authorizations.each do |authorization| authorization.destroy if authorization.user_id == user_id end OauthAuthorization.create!(:user_id => user_id, :oauth_client_id => id) end def self.model_name ActiveSupport::ModelName.new('OauthClient') end def oauth_tokens OauthToken.find_all_with(:oauth_client_id, id) end def oauth_authorizations OauthAuthorization.find_all_with(:oauth_client_id, id) end def before_create self.client_id = ActiveSupport::SecureRandom.hex(32) self.client_secret = ActiveSupport::SecureRandom.hex(32) end def before_destroy oauth_tokens.each(&:destroy) oauth_authorizations.each(&:destroy) end def before_save self.name.strip! if self.name self.redirect_uri.strip! if self.redirect_uri end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/models/oauth2/provider/oauth_authorization.rb
provider/vendor/plugins/oauth2_provider/app/models/oauth2/provider/oauth_authorization.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider class OauthAuthorization < ModelBase EXPIRY_TIME = 1.hour columns :user_id, :oauth_client_id, :code, :expires_at => :integer def oauth_client OauthClient.find_by_id(oauth_client_id) end def generate_access_token OauthToken.find_all_with(:user_id, user_id).each do |token| token.destroy if token.oauth_client_id == oauth_client_id end token = oauth_client.create_token_for_user_id(user_id) self.destroy token end def expires_in (Time.at(expires_at.to_i) - Clock.now).to_i end def expired? expires_in <= 0 end def before_create self.expires_at = (Clock.now + EXPIRY_TIME).to_i self.code = ActiveSupport::SecureRandom.hex(32) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/app/models/oauth2/provider/oauth_token.rb
provider/vendor/plugins/oauth2_provider/app/models/oauth2/provider/oauth_token.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider class OauthToken < ModelBase columns :user_id, :oauth_client_id, :access_token, :refresh_token, :expires_at => :integer EXPIRY_TIME = 90.days def oauth_client OauthClient.find_by_id(oauth_client_id) end def access_token_attributes {:access_token => access_token, :expires_in => expires_in, :refresh_token => refresh_token} end def expires_in (Time.at(expires_at.to_i) - Clock.now).to_i end def expired? expires_in <= 0 end def refresh self.destroy oauth_client.create_token_for_user_id(user_id) end def before_create self.access_token = ActiveSupport::SecureRandom.hex(32) self.expires_at = (Clock.now + EXPIRY_TIME).to_i self.refresh_token = ActiveSupport::SecureRandom.hex(32) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/oauth2_provider_generator.rb
provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/oauth2_provider_generator.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class Oauth2ProviderGenerator < Rails::Generator::Base def manifest record do |m| m.template 'config/initializers/oauth2_provider.rb', "config/initializers/oauth2_provider.rb" m.directory 'db/migrate' ['create_oauth_clients', 'create_oauth_tokens', 'create_oauth_authorizations'].each_with_index do |file_name, index| m.template "db/migrate/#{file_name}.rb", "db/migrate/#{version_with_prefix(index)}_#{file_name}.rb", :migration_file_name => file_name end end end def after_generate puts "*"*80 puts "Please edit the file 'config/initializers/oauth2_provider.rb' as per your needs!" puts "The readme file in the plugin contains more information about configuration." puts "*"*80 end private def version_with_prefix(prefix) Time.now.utc.strftime("%Y%m%d%H%M%S") + "#{prefix}" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/db/migrate/create_oauth_tokens.rb
provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/db/migrate/create_oauth_tokens.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class CreateOauthTokens < ActiveRecord::Migration def self.up create_table :oauth_tokens do |t| t.string :user_id t.integer :oauth_client_id t.string :access_token t.string :refresh_token t.integer :expires_at t.timestamps end end def self.down drop_table :oauth_tokens end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/db/migrate/create_oauth_clients.rb
provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/db/migrate/create_oauth_clients.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class CreateOauthClients < ActiveRecord::Migration def self.up create_table :oauth_clients do |t| t.string :name t.string :client_id t.string :client_secret t.string :redirect_uri t.timestamps end end def self.down drop_table :oauth_clients end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/db/migrate/create_oauth_authorizations.rb
provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/db/migrate/create_oauth_authorizations.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) class CreateOauthAuthorizations < ActiveRecord::Migration def self.up create_table :oauth_authorizations do |t| t.string :user_id t.integer :oauth_client_id t.string :code t.integer :expires_at t.timestamps end end def self.down drop_table :oauth_authorizations end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/config/initializers/oauth2_provider.rb
provider/vendor/plugins/oauth2_provider/generators/oauth2_provider/templates/config/initializers/oauth2_provider.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider raise 'OAuth2 provider not configured yet!' # please go through the readme and configure this file before you can use this plugin! # A fix for the stupid "A copy of ApplicationController has been removed from the module tree but is still active!" # error message that is caused in rails >= v2.3.3 # # This error is caused because the application controller is unloaded but, the controllers in the plugin are still # referring to the super class that is unloaded! # # Uncommenting these lines fixes the issue, but makes the ApplicationController not reloadable in dev mode. # # if RAILS_ENV == 'development' # ActiveSupport::Dependencies.load_once_paths << File.join(RAILS_ROOT, 'app/controllers/application_controller') # end # make sure no authentication for OauthTokenController OauthTokenController.skip_before_filter(:login_required) # use host app's custom authorization filter to protect OauthClientsController OauthClientsController.before_filter(:ensure_admin_user) # use host app's custom authorization filter to protect admin actions on OauthUserTokensController OauthUserTokensController.before_filter(:ensure_admin_user, :only => [:revoke_by_admin]) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2_provider.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2_provider.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) require 'oauth2/provider/a_r_datasource' require 'oauth2/provider/in_memory_datasource' require 'oauth2/provider/model_base' require 'oauth2/provider/clock' require 'oauth2/provider/url_parser' require 'oauth2/provider/configuration' require 'ext/validatable_ext' Oauth2::Provider::ModelBase.datasource = ENV["OAUTH2_PROVIDER_DATASOURCE"] Dir[File.join(File.dirname(__FILE__), "..", "app", "**", '*.rb')].each do |rb_file| require File.expand_path(rb_file) end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/clock.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/clock.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider class Clock def self.fake_now=(time_now) @fake_now = time_now end def self.now @fake_now || Time.now end def self.reset @fake_now = nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/ssl_helper.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/ssl_helper.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider module SslHelper def self.included(controller_class) controller_class.before_filter :mandatory_ssl end protected def mandatory_ssl return true if request.ssl? if ssl_enabled? redirect_to params.merge(ssl_base_url_as_url_options) else error = 'This page can only be accessed using HTTPS.' flash.now[:error] = error render(:text => '', :layout => true, :status => :forbidden) end false end private def ssl_base_url_as_url_options Oauth2::Provider::Configuration.ssl_base_url_as_url_options end def ssl_base_url Oauth2::Provider::Configuration.ssl_base_url end def ssl_enabled? !ssl_base_url.blank? && ssl_base_url_as_url_options[:protocol] == 'https' end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/in_memory_datasource.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/in_memory_datasource.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) require 'ostruct' module Oauth2 module Provider class InMemoryDatasource class MyStruct < OpenStruct attr_accessor :id def initialize(id, attrs) self.id = id super(attrs) end end @@id = 0 @@oauth_clients = [] @@oauth_tokens = [] @@oauth_authorizations = [] def reset @@id = 0 @@oauth_clients = [] @@oauth_tokens = [] @@oauth_authorizations = [] end def find_oauth_client_by_id(id) @@oauth_clients.find{|i| i.id.to_s == id.to_s} end def find_oauth_client_by_client_id(client_id) @@oauth_clients.find{|i| i.client_id.to_s == client_id.to_s} end def find_oauth_client_by_name(name) @@oauth_clients.find{|i| i.name == name} end def find_oauth_client_by_redirect_uri(redirect_uri) @@oauth_clients.find{|i| i.redirect_uri == redirect_uri} end def find_all_oauth_client @@oauth_clients end def save_oauth_client(attrs) save(@@oauth_clients, attrs) end def delete_oauth_client(id) @@oauth_clients.delete_if {|i| i.id.to_s == id.to_s} end def find_all_oauth_authorization_by_oauth_client_id(client_id) @@oauth_authorizations.select {|i| i.oauth_client_id.to_s == client_id.to_s} end def find_oauth_authorization_by_id(id) @@oauth_authorizations.find{|i| i.id.to_s == id.to_s} end def find_oauth_authorization_by_code(code) @@oauth_authorizations.find{|i| i.code.to_s == code.to_s} end def save_oauth_authorization(attrs) save(@@oauth_authorizations, attrs) end def delete_oauth_authorization(id) @@oauth_authorizations.delete_if {|i| i.id.to_s == id.to_s} end def find_oauth_token_by_id(id) @@oauth_tokens.find{|i| i.id.to_s == id.to_s} end def find_all_oauth_token_by_oauth_client_id(client_id) @@oauth_tokens.select {|i| i.oauth_client_id.to_s == client_id.to_s} end def find_all_oauth_token_by_user_id(user_id) @@oauth_tokens.select {|i| i.user_id.to_s == user_id.to_s} end def find_oauth_token_by_access_token(access_token) @@oauth_tokens.find {|i| i.access_token.to_s == access_token.to_s} end def find_oauth_token_by_refresh_token(refresh_token) @@oauth_tokens.find {|i| i.refresh_token.to_s == refresh_token.to_s} end def save_oauth_token(attrs) save(@@oauth_tokens, attrs) end def delete_oauth_token(id) @@oauth_tokens.delete_if { |i| i.id.to_s == id .to_s} end private def save(collection, attrs) dto = collection.find {|i| i.id.to_s == attrs[:id].to_s} if dto attrs.each do |k, v| dto.send("#{k}=", v) end else dto = MyStruct.new(next_id, attrs) collection << dto end dto end def next_id @@id += 1 @@id.to_s end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/url_parser.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/url_parser.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) if RUBY_PLATFORM =~ /java/ module URIParser module_function def self.parse(url) java.net.URL.new(url) end end class java::net::URL alias :scheme :protocol end else URIParser = URI end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/application_controller_methods.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/application_controller_methods.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider class HttpsRequired < StandardError end module ApplicationControllerMethods def self.included(controller_class) controller_class.extend(ClassMethods) end module ClassMethods def oauth_allowed(options = {}, &block) raise 'options cannot contain both :only and :except' if options[:only] && options[:except] [:only, :except].each do |k| if values = options[k] options[k] = Array(values).map(&:to_s).to_set end end write_inheritable_attribute(:oauth_options, options) write_inheritable_attribute(:oauth_options_proc, block) end end protected def user_id_for_oauth_access_token return nil unless oauth_allowed? if looks_like_oauth_request? raise HttpsRequired.new("HTTPS is required for OAuth Authorizations") unless request.ssl? token = OauthToken.find_one(:access_token, oauth_token_from_request_header) token.user_id if (token && !token.expired?) end end def oauth_token_from_request_header if request.headers["Authorization"] =~ /Token token="(.*)"/ return $1 end end def looks_like_oauth_request? !!oauth_token_from_request_header end def oauth_allowed? oauth_options_proc = self.class.read_inheritable_attribute(:oauth_options_proc) oauth_options = self.class.read_inheritable_attribute(:oauth_options) if oauth_options_proc && !oauth_options_proc.call(self) false else return false if oauth_options.nil? oauth_options.empty? || (oauth_options[:only] && oauth_options[:only].include?(action_name)) || (oauth_options[:except] && !oauth_options[:except].include?(action_name)) end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/transaction_helper.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/transaction_helper.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider module TransactionHelper def self.included(receiver) receiver.extend ClassMethods end class TransactionFilter def filter(controller, &block) ModelBase.transaction(&block) end end module ClassMethods def transaction_actions(*actions) self.around_filter TransactionFilter.new, :only => actions end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/model_base.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/model_base.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) require 'validatable' module Oauth2 module Provider class NotFoundException < StandardError end class RecordNotSaved < StandardError end class ModelBase include Validatable CONVERTORS = { :integer => Proc.new { |v| v ? v.to_i : nil }, :string => Proc.new { |v| v.to_s } }.with_indifferent_access class_inheritable_hash :db_columns self.db_columns = {} def self.columns(*names) options = names.extract_options! names.each do |column_name| attr_accessor column_name self.db_columns[column_name.to_s] = CONVERTORS[:string] end options.each do |column_name, converter| attr_accessor column_name self.db_columns[column_name.to_s] = CONVERTORS[converter] end end columns :id => :integer def initialize(attributes={}) assign_attributes(attributes) end cattr_accessor :datasource def self.datasource=(ds) @@datasource = case ds when NilClass default_datasource when String eval(ds).new when Class ds.new else ds end end def self.validates_uniqueness_of(*columns) options = columns.extract_options! columns.each do |column_name| self.validates_each column_name, :logic => lambda { if scope = options[:scope] dtos = self.class.find_all_with(column_name, self.send(column_name)) dtos = dtos.select{ |o| o.send(scope) == self.send(scope) } errors.add(column_name, 'is a duplicate.', options[:humanized_name]) if dtos.size == 1 && dtos.first.id != self.id else dto = datasource.send("find_#{self.class.compact_name}_by_#{column_name}", read_attribute(column_name)) errors.add(column_name, 'is a duplicate.', options[:humanized_name]) if dto && dto.id != self.id end } end end def self.datasource @@datasource ||= default_datasource end def datasource self.class.datasource end def self.default_datasource if defined?(ActiveRecord) ARDatasource.new else unless ENV['LOAD_OAUTH_SILENTLY'] puts "*"*80 puts "*** Activerecord is not defined! Using InMemoryDatasource, which will not persist across application restarts!! ***" puts "*"*80 end InMemoryDatasource.new end end def self.transaction(&block) if datasource.respond_to?(:transaction) result = nil datasource.transaction do result = yield end result else yield end end def transaction(&block) self.class.transaction(&block) end def self.find(id) find_by_id(id) || raise(NotFoundException.new("Record not found!")) end def self.find_by_id(id) find_one(:id, id) end def self.find_all_with(column_name, column_value) datasource.send("find_all_#{compact_name}_by_#{column_name}", convert(column_name, column_value)).collect do |dto| new.update_from_dto(dto) end end def self.find_one(column_name, column_value) if dto = datasource.send("find_#{compact_name}_by_#{column_name}", convert(column_name, column_value)) self.new.update_from_dto(dto) end end def self.all datasource.send("find_all_#{compact_name}").collect do |dto| new.update_from_dto(dto) end end def self.count all.size end def self.size all.size end def self.compact_name self.name.split('::').last.underscore end def self.create(attributes={}) client = self.new(attributes) client.save client end def self.create!(attributes={}) client = self.new(attributes) client.save! client end def update_attributes(attributes={}) assign_attributes(attributes) save end def save! save || raise(RecordNotSaved.new("Could not save model!")) end def save before_create if new_record? before_save attrs = db_columns.keys.inject({}) do |result, column_name| result[column_name] = read_attribute(column_name) result end if self.valid? dto = datasource.send("save_#{self.class.compact_name}", attrs.with_indifferent_access) update_from_dto(dto) return true end false end def reload update_from_dto(self.class.find(id)) end def destroy before_destroy datasource.send("delete_#{self.class.compact_name}", convert(:id, id)) end def before_create # for subclasses to override to support hooks. end def before_save # for subclasses to override to support hooks. end def before_destroy # for subclasses to override to support hooks. end def update_from_dto(dto) db_columns.keys.each do |column_name| write_attribute(column_name, dto.send(column_name)) end self end def new_record? id.nil? end def to_param id.nil? ? nil: id.to_s end def assign_attributes(attrs={}) attrs.each { |k, v| write_attribute(k, v) } end def to_xml(options = {}) acc = self.db_columns.keys.sort.inject(ActiveSupport::OrderedHash.new) do |acc, key| acc[key] = self.send(key) acc end acc.to_xml({:root => self.class.name.demodulize.underscore.downcase}.merge(options)) end private def self.convert(column_name, value) db_columns[column_name.to_s].call(value) end def convert(column_name, value) self.class.convert(column_name, value) end def read_attribute(column_name) convert(column_name, self.send(column_name)) end def write_attribute(column_name, value) self.send("#{column_name}=", convert(column_name, value)) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/configuration.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/configuration.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) module Oauth2 module Provider module Configuration def self.def_properties(*names) names.each do |name| class_eval(<<-EOS, __FILE__, __LINE__) @@__#{name} = nil def #{name} @@__#{name}.respond_to?(:call) ? @@__#{name}.call : @@__#{name} end def #{name}=(value_or_proc) @@__#{name} = value_or_proc end module_function :#{name}, :#{name}= EOS self.send(:module_function, name, "#{name}=") end end def_properties :ssl_base_url, :ssl_not_configured_message self.ssl_not_configured_message = "Customize this message using Oauth2::Provider::Configuration::ssl_not_configured_message" def self.ssl_base_url_as_url_options result = {:only_path => false} return result if ssl_base_url.blank? uri = URIParser.parse(ssl_base_url) raise "SSL base URL must be https" unless uri.scheme == 'https' result.merge!(:protocol => uri.scheme, :host => uri.host, :port => uri.port) result.delete(:port) if (uri.port == uri.default_port || uri.port == -1) result end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/a_r_datasource.rb
provider/vendor/plugins/oauth2_provider/lib/oauth2/provider/a_r_datasource.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) if defined?(ActiveRecord) module Oauth2 module Provider class ARDatasource class OauthClientDto < ActiveRecord::Base set_table_name :oauth_clients end class OauthAuthorizationDto < ActiveRecord::Base set_table_name :oauth_authorizations end class OauthTokenDto < ActiveRecord::Base set_table_name :oauth_tokens end # used in tests, use it to clear datasource def reset end def transaction(&block) ActiveRecord::Base.transaction(&block) end def find_oauth_client_by_id(id) OauthClientDto.find_by_id(id) end def find_oauth_client_by_client_id(client_id) OauthClientDto.find_by_client_id(client_id) end def find_oauth_client_by_name(name) OauthClientDto.find_by_name(name) end def find_oauth_client_by_redirect_uri(redirect_uri) OauthClientDto.find_by_redirect_uri(redirect_uri) end def find_all_oauth_client OauthClientDto.all end def save_oauth_client(attrs) save(OauthClientDto, attrs) end def delete_oauth_client(id) OauthClientDto.delete(id) end def find_all_oauth_authorization_by_oauth_client_id(client_id) OauthAuthorizationDto.find_all_by_oauth_client_id(client_id) end def find_oauth_authorization_by_id(id) OauthAuthorizationDto.find_by_id(id) end def find_oauth_authorization_by_code(code) OauthAuthorizationDto.find_by_code(code) end def save_oauth_authorization(attrs) save(OauthAuthorizationDto, attrs) end def delete_oauth_authorization(id) OauthAuthorizationDto.delete(id) end def find_oauth_token_by_id(id) OauthTokenDto.find_by_id(id) end def find_all_oauth_token_by_oauth_client_id(client_id) OauthTokenDto.find_all_by_oauth_client_id(client_id) end def find_all_oauth_token_by_user_id(user_id) OauthTokenDto.find_all_by_user_id(user_id) end def find_oauth_token_by_access_token(access_token) OauthTokenDto.find_by_access_token(access_token) end def find_oauth_token_by_refresh_token(refresh_token) OauthTokenDto.find_by_refresh_token(refresh_token) end def save_oauth_token(attrs) save(OauthTokenDto, attrs) end def delete_oauth_token(id) OauthTokenDto.delete(id) end private def save(dto_klass, attrs) dto = dto_klass.find_by_id(attrs[:id]) unless attrs[:id].blank? if dto dto.update_attributes(attrs) else dto = dto_klass.create(attrs) end dto end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/lib/ext/validatable_ext.rb
provider/vendor/plugins/oauth2_provider/lib/ext/validatable_ext.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) require 'validatable' module Validatable class Errors unless method_defined?(:add_without_humanize_options) alias :add_without_humanize_options :add def add(attribute, message, humanized_name=nil) #:nodoc: humanized_names[attribute.to_sym] = humanized_name add_without_humanize_options(attribute, message) end alias :humanize_without_humanize_options :humanize def humanize(lower_case_and_underscored_word) #:nodoc: humanized_names[lower_case_and_underscored_word.to_sym] || humanize_without_humanize_options(lower_case_and_underscored_word) end private def humanized_names @humanized_names ||= {} end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/plugins/oauth2_provider/config/routes.rb
provider/vendor/plugins/oauth2_provider/config/routes.rb
# Copyright (c) 2010 ThoughtWorks Inc. (http://thoughtworks.com) # Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php) ActionController::Routing::Routes.draw do |map| admin_prefix= ENV['ADMIN_OAUTH_URL_PREFIX'] user_prefix= ENV['USER_OAUTH_URL_PREFIX'] admin_prefix = "" if admin_prefix.blank? user_prefix = "" if user_prefix.blank? admin_prefix = admin_prefix.gsub(%r{^/}, '').gsub(%r{/$}, '') user_prefix = user_prefix.gsub(%r{^/}, '').gsub(%r{/$}, '') map.resources :oauth_clients, :controller => 'oauth_clients', :as => admin_prefix + (admin_prefix.blank? ? "" : "/") + "oauth/clients" map.connect "#{admin_prefix}/oauth/user_tokens/revoke_by_admin", :controller => 'oauth_user_tokens', :action => :revoke_by_admin, :conditions => {:method => :delete} map.connect "#{user_prefix}/oauth/authorize", :controller => 'oauth_authorize', :action => :authorize, :conditions => {:method => :post} map.connect "#{user_prefix}/oauth/authorize", :controller => 'oauth_authorize', :action => :index, :conditions => {:method => :get} map.connect "#{user_prefix}/oauth/token", :controller => 'oauth_token', :action => :get_token, :conditions => {:method => :post} map.connect "#{user_prefix}/oauth/user_tokens/revoke/:token_id", :controller => 'oauth_user_tokens', :action => :revoke, :conditions => {:method => :delete} map.connect "#{user_prefix}/oauth/user_tokens", :controller => 'oauth_user_tokens', :action => :index, :conditions => {:method => :get} end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/db/seeds.rb
provider/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Major.create(:name => 'Daley', :city => cities.first) User.create!(:email => 'admin', :password => 'p') User.create!(:email => 'mingledev01@thoughtworks.com', :password => 'p') User.create!(:email => 'mingledev02@thoughtworks.com', :password => 'p') User.create!(:email => 'admin@thoughtworks.com', :password => 'p')
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/db/schema.rb
provider/db/schema.rb
# This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 201007221918342) do create_table "oauth_authorizations", :force => true do |t| t.string "user_id" t.integer "oauth_client_id" t.string "code" t.integer "expires_at" t.datetime "created_at" t.datetime "updated_at" end create_table "oauth_clients", :force => true do |t| t.string "name" t.string "client_id" t.string "client_secret" t.string "redirect_uri" t.datetime "created_at" t.datetime "updated_at" end create_table "oauth_tokens", :force => true do |t| t.string "user_id" t.integer "oauth_client_id" t.string "access_token" t.string "refresh_token" t.integer "expires_at" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "email" t.string "password" t.datetime "created_at" t.datetime "updated_at" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/db/migrate/1_create_users.rb
provider/db/migrate/1_create_users.rb
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :email t.string :password t.timestamps end end def self.down drop_table :users end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/db/migrate/201007221918341_create_oauth_tokens.rb
provider/db/migrate/201007221918341_create_oauth_tokens.rb
class CreateOauthTokens < ActiveRecord::Migration def self.up create_table :oauth_tokens do |t| t.string :user_id t.integer :oauth_client_id t.string :access_token t.string :refresh_token t.integer :expires_at t.timestamps end end def self.down drop_table :oauth_tokens end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false