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/tools/jruby-1.5.1/lib/ruby/1.9/uri/mailto.rb
tools/jruby-1.5.1/lib/ruby/1.9/uri/mailto.rb
# # = uri/mailto.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: mailto.rb 23598 2009-05-27 17:48:54Z akr $ # require 'uri/generic' module URI # # RFC2368, The mailto URL scheme # class MailTo < Generic include REGEXP DEFAULT_PORT = nil COMPONENT = [ :scheme, :to, :headers ].freeze # :stopdoc: # "hname" and "hvalue" are encodings of an RFC 822 header name and # value, respectively. As with "to", all URL reserved characters must # be encoded. # # "#mailbox" is as specified in RFC 822 [RFC822]. This means that it # consists of zero or more comma-separated mail addresses, possibly # including "phrase" and "comment" components. Note that all URL # reserved characters in "to" must be encoded: in particular, # parentheses, commas, and the percent sign ("%"), which commonly occur # in the "mailbox" syntax. # # Within mailto URLs, the characters "?", "=", "&" are reserved. # hname = *urlc # hvalue = *urlc # header = hname "=" hvalue HEADER_PATTERN = "(?:[^?=&]*=[^?=&]*)".freeze HEADER_REGEXP = Regexp.new(HEADER_PATTERN, 'N').freeze # headers = "?" header *( "&" header ) # to = #mailbox # mailtoURL = "mailto:" [ to ] [ headers ] MAILBOX_PATTERN = "(?:#{PATTERN::ESCAPED}|[^(),%?=&])".freeze MAILTO_REGEXP = Regexp.new(" # :nodoc: \\A (#{MAILBOX_PATTERN}*?) (?# 1: to) (?: \\? (#{HEADER_PATTERN}(?:\\&#{HEADER_PATTERN})*) (?# 2: headers) )? (?: \\# (#{PATTERN::FRAGMENT}) (?# 3: fragment) )? \\z ", Regexp::EXTENDED).freeze # :startdoc: # # == Description # # Creates a new URI::MailTo object from components, with syntax checking. # # Components can be provided as an Array or Hash. If an Array is used, # the components must be supplied as [to, headers]. # # If a Hash is used, the keys are the component names preceded by colons. # # The headers can be supplied as a pre-encoded string, such as # "subject=subscribe&cc=address", or as an Array of Arrays like # [['subject', 'subscribe'], ['cc', 'address']] # # Examples: # # require 'uri' # # m1 = URI::MailTo.build(['joe@example.com', 'subject=Ruby']) # puts m1.to_s -> mailto:joe@example.com?subject=Ruby # # m2 = URI::MailTo.build(['john@example.com', [['Subject', 'Ruby'], ['Cc', 'jack@example.com']]]) # puts m2.to_s -> mailto:john@example.com?Subject=Ruby&Cc=jack@example.com # # m3 = URI::MailTo.build({:to => 'listman@example.com', :headers => [['subject', 'subscribe']]}) # puts m3.to_s -> mailto:listman@example.com?subject=subscribe # def self.build(args) tmp = Util::make_components_hash(self, args) if tmp[:to] tmp[:opaque] = tmp[:to] else tmp[:opaque] = '' end if tmp[:headers] tmp[:opaque] << '?' if tmp[:headers].kind_of?(Array) tmp[:opaque] << tmp[:headers].collect { |x| if x.kind_of?(Array) x[0] + '=' + x[1..-1].to_s else x.to_s end }.join('&') elsif tmp[:headers].kind_of?(Hash) tmp[:opaque] << tmp[:headers].collect { |h,v| h + '=' + v }.join('&') else tmp[:opaque] << tmp[:headers].to_s end end return super(tmp) end # # == Description # # Creates a new URI::MailTo object from generic URL components with # no syntax checking. # # This method is usually called from URI::parse, which checks # the validity of each component. # def initialize(*arg) super(*arg) @to = nil @headers = [] if MAILTO_REGEXP =~ @opaque if arg[-1] self.to = $1 self.headers = $2 else set_to($1) set_headers($2) end else raise InvalidComponentError, "unrecognised opaque part for mailtoURL: #{@opaque}" end end # The primary e-mail address of the URL, as a String attr_reader :to # E-mail headers set by the URL, as an Array of Arrays attr_reader :headers def check_to(v) return true unless v return true if v.size == 0 if parser.regexp[:OPAQUE] !~ v || /\A#{MAILBOX_PATTERN}*\z/o !~ v raise InvalidComponentError, "bad component(expected opaque component): #{v}" end return true end private :check_to def set_to(v) @to = v end protected :set_to def to=(v) check_to(v) set_to(v) v end def check_headers(v) return true unless v return true if v.size == 0 if parser.regexp[:OPAQUE] !~ v || /\A(#{HEADER_PATTERN}(?:\&#{HEADER_PATTERN})*)\z/o !~ v raise InvalidComponentError, "bad component(expected opaque component): #{v}" end return true end private :check_headers def set_headers(v) @headers = [] if v v.scan(HEADER_REGEXP) do |x| @headers << x.split(/=/o, 2) end end end protected :set_headers def headers=(v) check_headers(v) set_headers(v) v end def to_s @scheme + ':' + if @to @to else '' end + if @headers.size > 0 '?' + @headers.collect{|x| x.join('=')}.join('&') else '' end + if @fragment '#' + @fragment else '' end end # Returns the RFC822 e-mail text equivalent of the URL, as a String. # # Example: # # require 'uri' # # uri = URI.parse("mailto:ruby-list@ruby-lang.org?Subject=subscribe&cc=myaddr") # uri.to_mailtext # # => "To: ruby-list@ruby-lang.org\nSubject: subscribe\nCc: myaddr\n\n\n" # def to_mailtext to = parser.unescape(@to) head = '' body = '' @headers.each do |x| case x[0] when 'body' body = parser.unescape(x[1]) when 'to' to << ', ' + parser.unescape(x[1]) else head << parser.unescape(x[0]).capitalize + ': ' + parser.unescape(x[1]) + "\n" end end return "To: #{to} #{head} #{body} " end alias to_rfc822text to_mailtext end @@schemes['MAILTO'] = MailTo end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/uri/ldaps.rb
tools/jruby-1.5.1/lib/ruby/1.9/uri/ldaps.rb
require 'uri/ldap' module URI # The default port for LDAPS URIs is 636, and the scheme is 'ldaps:' rather # than 'ldap:'. Other than that, LDAPS URIs are identical to LDAP URIs; # see URI::LDAP. class LDAPS < LDAP DEFAULT_PORT = 636 end @@schemes['LDAPS'] = LDAPS end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/uri/http.rb
tools/jruby-1.5.1/lib/ruby/1.9/uri/http.rb
# # = uri/http.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: http.rb 22784 2009-03-06 03:56:38Z nobu $ # require 'uri/generic' module URI # # The syntax of HTTP URIs is defined in RFC1738 section 3.3. # # Note that the Ruby URI library allows HTTP URLs containing usernames and # passwords. This is not legal as per the RFC, but used to be # supported in Internet Explorer 5 and 6, before the MS04-004 security # update. See <URL:http://support.microsoft.com/kb/834489>. # class HTTP < Generic DEFAULT_PORT = 80 COMPONENT = [ :scheme, :userinfo, :host, :port, :path, :query, :fragment ].freeze # # == Description # # Create a new URI::HTTP object from components, with syntax checking. # # The components accepted are userinfo, host, port, path, query and # fragment. # # The components should be provided either as an Array, or as a Hash # with keys formed by preceding the component names with a colon. # # If an Array is used, the components must be passed in the order # [userinfo, host, port, path, query, fragment]. # # Example: # # newuri = URI::HTTP.build({:host => 'www.example.com', # :path> => '/foo/bar'}) # # newuri = URI::HTTP.build([nil, "www.example.com", nil, "/path", # "query", 'fragment']) # # Currently, if passed userinfo components this method generates # invalid HTTP URIs as per RFC 1738. # def self.build(args) tmp = Util::make_components_hash(self, args) return super(tmp) end # # == Description # # Create a new URI::HTTP object from generic URI components as per # RFC 2396. No HTTP-specific syntax checking (as per RFC 1738) is # performed. # # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, # +opaque+, +query+ and +fragment+, in that order. # # Example: # # uri = URI::HTTP.new(['http', nil, "www.example.com", nil, "/path", # "query", 'fragment']) # def initialize(*arg) super(*arg) end # # == Description # # Returns the full path for an HTTP request, as required by Net::HTTP::Get. # # If the URI contains a query, the full path is URI#path + '?' + URI#query. # Otherwise, the path is simply URI#path. # def request_uri r = path_query if r[0] != ?/ r = '/' + r end r end end @@schemes['HTTP'] = HTTP end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/uri/ftp.rb
tools/jruby-1.5.1/lib/ruby/1.9/uri/ftp.rb
# # = uri/ftp.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: ftp.rb 22784 2009-03-06 03:56:38Z nobu $ # require 'uri/generic' module URI # # FTP URI syntax is defined by RFC1738 section 3.2. # class FTP < Generic DEFAULT_PORT = 21 COMPONENT = [ :scheme, :userinfo, :host, :port, :path, :typecode ].freeze # # Typecode is "a", "i" or "d". # # * "a" indicates a text file (the FTP command was ASCII) # * "i" indicates a binary file (FTP command IMAGE) # * "d" indicates the contents of a directory should be displayed # TYPECODE = ['a', 'i', 'd'].freeze TYPECODE_PREFIX = ';type='.freeze def self.new2(user, password, host, port, path, typecode = nil, arg_check = true) typecode = nil if typecode.size == 0 if typecode && !TYPECODE.include?(typecode) raise ArgumentError, "bad typecode is specified: #{typecode}" end # do escape self.new('ftp', [user, password], host, port, nil, typecode ? path + TYPECODE_PREFIX + typecode : path, nil, nil, nil, arg_check) end # # == Description # # Creates a new URI::FTP object from components, with syntax checking. # # The components accepted are +userinfo+, +host+, +port+, +path+ and # +typecode+. # # The components should be provided either as an Array, or as a Hash # with keys formed by preceding the component names with a colon. # # If an Array is used, the components must be passed in the order # [userinfo, host, port, path, typecode] # # If the path supplied is absolute, it will be escaped in order to # make it absolute in the URI. Examples: # # require 'uri' # # uri = URI::FTP.build(['user:password', 'ftp.example.com', nil, # '/path/file.> zip', 'i']) # puts uri.to_s -> ftp://user:password@ftp.example.com/%2Fpath/file.zip;type=a # # uri2 = URI::FTP.build({:host => 'ftp.example.com', # :path => 'ruby/src'}) # puts uri2.to_s -> ftp://ftp.example.com/ruby/src # def self.build(args) # Fix the incoming path to be generic URL syntax # FTP path -> URL path # foo/bar /foo/bar # /foo/bar /%2Ffoo/bar # if args.kind_of?(Array) args[3] = '/' + args[3].sub(/^\//, '%2F') else args[:path] = '/' + args[:path].sub(/^\//, '%2F') end tmp = Util::make_components_hash(self, args) if tmp[:typecode] if tmp[:typecode].size == 1 tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode] end tmp[:path] << tmp[:typecode] end return super(tmp) end # # == Description # # Creates a new URI::FTP object from generic URL components with no # syntax checking. # # Unlike build(), this method does not escape the path component as # required by RFC1738; instead it is treated as per RFC2396. # # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, # +opaque+, +query+ and +fragment+, in that order. # def initialize(*arg) super(*arg) @typecode = nil tmp = @path.index(TYPECODE_PREFIX) if tmp typecode = @path[tmp + TYPECODE_PREFIX.size..-1] self.set_path(@path[0..tmp - 1]) if arg[-1] self.typecode = typecode else self.set_typecode(typecode) end end end attr_reader :typecode def check_typecode(v) if TYPECODE.include?(v) return true else raise InvalidComponentError, "bad typecode(expected #{TYPECODE.join(', ')}): #{v}" end end private :check_typecode def set_typecode(v) @typecode = v end protected :set_typecode def typecode=(typecode) check_typecode(typecode) set_typecode(typecode) typecode end def merge(oth) # :nodoc: tmp = super(oth) if self != tmp tmp.set_typecode(oth.typecode) end return tmp end # Returns the path from an FTP URI. # # RFC 1738 specifically states that the path for an FTP URI does not # include the / which separates the URI path from the URI host. Example: # # ftp://ftp.example.com/pub/ruby # # The above URI indicates that the client should connect to # ftp.example.com then cd pub/ruby from the initial login directory. # # If you want to cd to an absolute directory, you must include an # escaped / (%2F) in the path. Example: # # ftp://ftp.example.com/%2Fpub/ruby # # This method will then return "/pub/ruby" # def path return @path.sub(/^\//,'').sub(/^%2F/,'/') end def to_s save_path = nil if @typecode save_path = @path @path = @path + TYPECODE_PREFIX + @typecode end str = super if @typecode @path = save_path end return str end end @@schemes['FTP'] = FTP end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/uri/ldap.rb
tools/jruby-1.5.1/lib/ruby/1.9/uri/ldap.rb
# # = uri/ldap.rb # # Author:: # Takaaki Tateishi <ttate@jaist.ac.jp> # Akira Yamada <akira@ruby-lang.org> # License:: # URI::LDAP is copyrighted free software by Takaaki Tateishi and Akira Yamada. # You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: ldap.rb 22784 2009-03-06 03:56:38Z nobu $ # require 'uri/generic' module URI # # LDAP URI SCHEMA (described in RFC2255) # ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]] # class LDAP < Generic DEFAULT_PORT = 389 COMPONENT = [ :scheme, :host, :port, :dn, :attributes, :scope, :filter, :extensions, ].freeze SCOPE = [ SCOPE_ONE = 'one', SCOPE_SUB = 'sub', SCOPE_BASE = 'base', ].freeze def self.build(args) tmp = Util::make_components_hash(self, args) if tmp[:dn] tmp[:path] = tmp[:dn] end query = [] [:extensions, :filter, :scope, :attributes].collect do |x| next if !tmp[x] && query.size == 0 query.unshift(tmp[x]) end tmp[:query] = query.join('?') return super(tmp) end def initialize(*arg) super(*arg) if @fragment raise InvalidURIError, 'bad LDAP URL' end parse_dn parse_query end def parse_dn @dn = @path[1..-1] end private :parse_dn def parse_query @attributes = nil @scope = nil @filter = nil @extensions = nil if @query attrs, scope, filter, extensions = @query.split('?') @attributes = attrs if attrs && attrs.size > 0 @scope = scope if scope && scope.size > 0 @filter = filter if filter && filter.size > 0 @extensions = extensions if extensions && extensions.size > 0 end end private :parse_query def build_path_query @path = '/' + @dn query = [] [@extensions, @filter, @scope, @attributes].each do |x| next if !x && query.size == 0 query.unshift(x) end @query = query.join('?') end private :build_path_query def dn @dn end def set_dn(val) @dn = val build_path_query @dn end protected :set_dn def dn=(val) set_dn(val) val end def attributes @attributes end def set_attributes(val) @attributes = val build_path_query @attributes end protected :set_attributes def attributes=(val) set_attributes(val) val end def scope @scope end def set_scope(val) @scope = val build_path_query @scope end protected :set_scope def scope=(val) set_scope(val) val end def filter @filter end def set_filter(val) @filter = val build_path_query @filter end protected :set_filter def filter=(val) set_filter(val) val end def extensions @extensions end def set_extensions(val) @extensions = val build_path_query @extensions end protected :set_extensions def extensions=(val) set_extensions(val) val end def hierarchical? false end end @@schemes['LDAP'] = LDAP end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/uri/https.rb
tools/jruby-1.5.1/lib/ruby/1.9/uri/https.rb
# # = uri/https.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: https.rb 11708 2007-02-12 23:01:19Z shyouhei $ # require 'uri/http' module URI # The default port for HTTPS URIs is 443, and the scheme is 'https:' rather # than 'http:'. Other than that, HTTPS URIs are identical to HTTP URIs; # see URI::HTTP. class HTTPS < HTTP DEFAULT_PORT = 443 end @@schemes['HTTPS'] = HTTPS end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/date/delta.rb
tools/jruby-1.5.1/lib/ruby/1.9/date/delta.rb
# delta.rb: Written by Tadayoshi Funaba 2004-2009 require 'date/delta/parser' class Date class Delta include Comparable UNIT_PREFIXES = { 'yotta' => Rational(10**24), 'zetta' => Rational(10**21), 'exa' => Rational(10**18), 'peta' => Rational(10**15), 'tera' => Rational(10**12), 'giga' => Rational(10**9), 'mega' => Rational(10**6), 'kilo' => Rational(10**3), 'hecto' => Rational(10**2), 'deca' => Rational(10**1), 'deka' => Rational(10**1), 'deci' => Rational(1, 10**1), 'centi' => Rational(1, 10**2), 'milli' => Rational(1, 10**3), 'decimilli' => Rational(1, 10**4), 'centimilli' => Rational(1, 10**5), 'micro' => Rational(1, 10**6), 'nano' => Rational(1, 10**9), 'millimicro' => Rational(1, 10**9), 'pico' => Rational(1, 10**12), 'micromicro' => Rational(1, 10**12), 'femto' => Rational(1, 10**15), 'atto' => Rational(1, 10**18), 'zepto' => Rational(1, 10**21), 'yocto' => Rational(1, 10**24) } IUNITS = { 'year' => Complex(0, 12), 'month' => Complex(0, 1) } RUNITS = { 'day' => Rational(1), 'week' => Rational(7), 'sennight' => Rational(7), 'fortnight' => Rational(14), 'hour' => Rational(1, 24), 'minute' => Rational(1, 1440), 'second' => Rational(1, 86400) } UNIT_PREFIXES.each do |k, v| RUNITS[k + 'second'] = v * RUNITS['second'] end remove_const :UNIT_PREFIXES UNITS = {} IUNITS.each do |k, v| UNITS[k] = v end RUNITS.each do |k, v| UNITS[k] = v end UNITS4KEY = {} UNITS.each do |k, v| UNITS4KEY[k] = UNITS4KEY[k + 's'] = v end UNITS4KEY['y'] = UNITS4KEY['years'] UNITS4KEY['yr'] = UNITS4KEY['years'] UNITS4KEY['yrs'] = UNITS4KEY['years'] UNITS4KEY['m'] = UNITS4KEY['months'] UNITS4KEY['mo'] = UNITS4KEY['months'] UNITS4KEY['mon'] = UNITS4KEY['months'] UNITS4KEY['mnth'] = UNITS4KEY['months'] UNITS4KEY['mnths'] = UNITS4KEY['months'] UNITS4KEY['w'] = UNITS4KEY['weeks'] UNITS4KEY['wk'] = UNITS4KEY['weeks'] UNITS4KEY['d'] = UNITS4KEY['days'] UNITS4KEY['dy'] = UNITS4KEY['days'] UNITS4KEY['dys'] = UNITS4KEY['days'] UNITS4KEY['h'] = UNITS4KEY['hours'] UNITS4KEY['hr'] = UNITS4KEY['hours'] UNITS4KEY['hrs'] = UNITS4KEY['hours'] UNITS4KEY['min'] = UNITS4KEY['minutes'] UNITS4KEY['mins'] = UNITS4KEY['minutes'] UNITS4KEY['s'] = UNITS4KEY['seconds'] UNITS4KEY['sec'] = UNITS4KEY['seconds'] UNITS4KEY['secs'] = UNITS4KEY['seconds'] UNITS4KEY['ms'] = UNITS4KEY['milliseconds'] UNITS4KEY['msec'] = UNITS4KEY['milliseconds'] UNITS4KEY['msecs'] = UNITS4KEY['milliseconds'] UNITS4KEY['milli'] = UNITS4KEY['milliseconds'] UNITS4KEY['us'] = UNITS4KEY['microseconds'] UNITS4KEY['usec'] = UNITS4KEY['microseconds'] UNITS4KEY['usecs'] = UNITS4KEY['microseconds'] UNITS4KEY['micro'] = UNITS4KEY['microseconds'] UNITS4KEY['ns'] = UNITS4KEY['nanoseconds'] UNITS4KEY['nsec'] = UNITS4KEY['nanoseconds'] UNITS4KEY['nsecs'] = UNITS4KEY['nanoseconds'] UNITS4KEY['nano'] = UNITS4KEY['nanoseconds'] def self.delta_to_dhms(delta) fr = delta.imag.abs y, fr = fr.divmod(12) m, fr = fr.divmod(1) if delta.imag < 0 y = -y m = -m end fr = delta.real.abs ss, fr = fr.divmod(SECONDS_IN_DAY) # 4p d, ss = ss.divmod(86400) h, ss = ss.divmod(3600) min, s = ss.divmod(60) if delta.real < 0 d = -d h = -h min = -min s = -s end return y, m, d, h, min, s, fr end def self.dhms_to_delta(y, m, d, h, min, s, fr) fr = 0 if fr == 0 Complex(0, y.to_i * 12 + m.to_i) + Rational(d * 86400 + h * 3600 + min * 60 + (s + fr), 86400) # 4p end def initialize(delta) @delta = delta @__ca__ = {} end class << self; alias_method :new!, :new end def self.new(arg=0, h=0, min=0, s=0) if Hash === arg d = Complex(0) arg.each do |k, v| k = k.to_s.downcase unless UNITS4KEY[k] raise ArgumentError, "unknown keyword #{k}" end d += v * UNITS4KEY[k] end else d = dhms_to_delta(0, 0, arg, h, min, s, 0) end new!(d) end UNITS.each_key do |k| module_eval <<-"end;" def self.#{k}s(n=1) new(:d=>n * UNITS['#{k}']) end end; end class << self; alias_method :mins, :minutes end class << self; alias_method :secs, :seconds end def self.parse(str) d = begin (@@pa ||= Parser.new).parse(str) rescue Racc::ParseError raise ArgumentError, 'syntax error' end new!(d) end def self.diff(d1, d2) new(d1.ajd - d2.ajd) end class << self def once(*ids) # :nodoc: -- restricted for id in ids module_eval <<-"end;" alias_method :__#{id.object_id}__, :#{id.to_s} private :__#{id.object_id}__ def #{id.to_s}(*args) @__ca__[#{id.object_id}] ||= __#{id.object_id}__(*args) end end; end end private :once end def dhms() self.class.delta_to_dhms(@delta) end once :dhms def delta() @delta end protected :delta def years() dhms[0] end def months() dhms[1] end def days() dhms[2] end def hours() dhms[3] end def minutes() dhms[4] end def seconds() dhms[5] end def second_fractions() dhms[6] end alias_method :mins, :minutes alias_method :secs, :seconds alias_method :sec_fractions, :second_fractions RUNITS.each_key do |k| module_eval <<-"end;" def in_#{k}s(u=1) if @delta.imag != 0 raise ArgumentError, "#{k}: #{self} has month" end @delta.real / (u * RUNITS['#{k}']) end end; end alias_method :in_mins, :in_minutes alias_method :in_secs, :in_seconds def zero?() @delta.zero? end def nonzero?() unless zero? then self end end def integer? () @delta.imag == 0 && @delta.real.integer? end def -@ () self.class.new!(-@delta) end def +@ () self.class.new!(+@delta) end def dx_addsub(m, n) case n when Numeric; return self.class.new!(@delta.__send__(m, n)) when Delta; return self.class.new!(@delta.__send__(m, n.delta)) else l, r = n.coerce(self) return l.__send__(m, r) end end private :dx_addsub def + (n) dx_addsub(:+, n) end def - (n) dx_addsub(:-, n) end def dx_muldiv(m, n) case n when Numeric return self.class.new!(@delta.__send__(m, n)) else l, r = n.coerce(self) return l.__send__(m, r) end end private :dx_muldiv def * (n) dx_muldiv(:*, n) end def / (n) dx_muldiv(:/, n) end def dx_conv1(m, n) if @delta.imag != 0 raise ArgumentError, "#{m}: #{self} has month" end case n when Numeric return self.class.new!(Complex(@delta.real.__send__(m, n), 0)) else l, r = n.coerce(self) return l.__send__(m, r) end end private :dx_conv1 def % (n) dx_conv1(:%, n) end def div(n) dx_conv1(:div, n) end def modulo(n) dx_conv1(:modulo, n) end def divmod(n) [div(n), modulo(n)] end def quotient(n) if @delta.imag != 0 raise ArgumentError, "quotient: #{self} has month" end case n when Numeric return self.class.new!(Complex((@delta.real / n).truncate)) else l, r = n.coerce(self) return l.__send__(m, r) end end def remainder(n) dx_conv1(:remainder, n) end def quotrem(n) [quotient(n), remainder(n)] end def ** (n) dx_conv1(:**, n) end def quo(n) dx_muldiv(:quo, n) end def <=> (other) if @delta.imag != 0 raise ArgumentError, "<=>: #{self} has month" end case other when Numeric; return @delta.real <=> other when Delta; return @delta.real <=> other.delta.real else begin l, r = other.coerce(self) return l <=> r rescue NoMethodError end end nil end def == (other) case other when Numeric; return @delta == other when Delta; return @delta == other else begin l, r = other.coerce(self) return l == r rescue NoMethodError end end nil end def coerce(other) case other when Numeric; return other, @delta else super end end def eql? (other) Delta === other && self == other end def hash() @delta.hash end def dx_conv0(m) if @delta.imag != 0 raise ArgumentError, "#{m}: #{self} has month" end @delta.real.__send__(m) end private :dx_conv0 def abs() dx_conv0(:abs) end def ceil() dx_conv0(:ceil) end def floor() dx_conv0(:floor) end def round() dx_conv0(:round) end def truncate() dx_conv0(:truncate) end def to_i() dx_conv0(:to_i) end def to_f() dx_conv0(:to_f) end def to_r() dx_conv0(:to_r) end def to_c() @delta end alias_method :to_int, :to_i def inspect() format('#<%s: %s (%s)>', self.class, to_s, @delta) end def to_s format(%(%s(%dd %.02d:%02d'%02d"%03d)%s(%dy %dm)), # ' if @delta.real < 0 then '-' else '+' end, days.abs, hours.abs, mins.abs, secs.abs, sec_fractions.abs * 1000, if @delta.imag < 0 then '-' else '+' end, years.abs, months.abs) end def marshal_dump() @delta end def marshal_load(a) @delta = a @__ca__ = {} end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/date/format.rb
tools/jruby-1.5.1/lib/ruby/1.9/date/format.rb
# format.rb: Written by Tadayoshi Funaba 1999-2009 # $Id: format.rb,v 2.43 2008-01-17 20:16:31+09 tadf Exp $ class Date module Format # :nodoc: MONTHS = { 'january' => 1, 'february' => 2, 'march' => 3, 'april' => 4, 'may' => 5, 'june' => 6, 'july' => 7, 'august' => 8, 'september'=> 9, 'october' =>10, 'november' =>11, 'december' =>12 } DAYS = { 'sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday'=> 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6 } ABBR_MONTHS = { 'jan' => 1, 'feb' => 2, 'mar' => 3, 'apr' => 4, 'may' => 5, 'jun' => 6, 'jul' => 7, 'aug' => 8, 'sep' => 9, 'oct' =>10, 'nov' =>11, 'dec' =>12 } ABBR_DAYS = { 'sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6 } ZONES = { 'ut' => 0*3600, 'gmt' => 0*3600, 'est' => -5*3600, 'edt' => -4*3600, 'cst' => -6*3600, 'cdt' => -5*3600, 'mst' => -7*3600, 'mdt' => -6*3600, 'pst' => -8*3600, 'pdt' => -7*3600, 'a' => 1*3600, 'b' => 2*3600, 'c' => 3*3600, 'd' => 4*3600, 'e' => 5*3600, 'f' => 6*3600, 'g' => 7*3600, 'h' => 8*3600, 'i' => 9*3600, 'k' => 10*3600, 'l' => 11*3600, 'm' => 12*3600, 'n' => -1*3600, 'o' => -2*3600, 'p' => -3*3600, 'q' => -4*3600, 'r' => -5*3600, 's' => -6*3600, 't' => -7*3600, 'u' => -8*3600, 'v' => -9*3600, 'w' =>-10*3600, 'x' =>-11*3600, 'y' =>-12*3600, 'z' => 0*3600, 'utc' => 0*3600, 'wet' => 0*3600, 'at' => -2*3600, 'brst'=> -2*3600, 'ndt' => -(2*3600+1800), 'art' => -3*3600, 'adt' => -3*3600, 'brt' => -3*3600, 'clst'=> -3*3600, 'nst' => -(3*3600+1800), 'ast' => -4*3600, 'clt' => -4*3600, 'akdt'=> -8*3600, 'ydt' => -8*3600, 'akst'=> -9*3600, 'hadt'=> -9*3600, 'hdt' => -9*3600, 'yst' => -9*3600, 'ahst'=>-10*3600, 'cat' =>-10*3600, 'hast'=>-10*3600, 'hst' =>-10*3600, 'nt' =>-11*3600, 'idlw'=>-12*3600, 'bst' => 1*3600, 'cet' => 1*3600, 'fwt' => 1*3600, 'met' => 1*3600, 'mewt'=> 1*3600, 'mez' => 1*3600, 'swt' => 1*3600, 'wat' => 1*3600, 'west'=> 1*3600, 'cest'=> 2*3600, 'eet' => 2*3600, 'fst' => 2*3600, 'mest'=> 2*3600, 'mesz'=> 2*3600, 'sast'=> 2*3600, 'sst' => 2*3600, 'bt' => 3*3600, 'eat' => 3*3600, 'eest'=> 3*3600, 'msk' => 3*3600, 'msd' => 4*3600, 'zp4' => 4*3600, 'zp5' => 5*3600, 'ist' => (5*3600+1800), 'zp6' => 6*3600, 'wast'=> 7*3600, 'cct' => 8*3600, 'sgt' => 8*3600, 'wadt'=> 8*3600, 'jst' => 9*3600, 'kst' => 9*3600, 'east'=> 10*3600, 'gst' => 10*3600, 'eadt'=> 11*3600, 'idle'=> 12*3600, 'nzst'=> 12*3600, 'nzt' => 12*3600, 'nzdt'=> 13*3600, 'afghanistan' => 16200, 'alaskan' => -32400, 'arab' => 10800, 'arabian' => 14400, 'arabic' => 10800, 'atlantic' => -14400, 'aus central' => 34200, 'aus eastern' => 36000, 'azores' => -3600, 'canada central' => -21600, 'cape verde' => -3600, 'caucasus' => 14400, 'cen. australia' => 34200, 'central america' => -21600, 'central asia' => 21600, 'central europe' => 3600, 'central european' => 3600, 'central pacific' => 39600, 'central' => -21600, 'china' => 28800, 'dateline' => -43200, 'e. africa' => 10800, 'e. australia' => 36000, 'e. europe' => 7200, 'e. south america' => -10800, 'eastern' => -18000, 'egypt' => 7200, 'ekaterinburg' => 18000, 'fiji' => 43200, 'fle' => 7200, 'greenland' => -10800, 'greenwich' => 0, 'gtb' => 7200, 'hawaiian' => -36000, 'india' => 19800, 'iran' => 12600, 'jerusalem' => 7200, 'korea' => 32400, 'mexico' => -21600, 'mid-atlantic' => -7200, 'mountain' => -25200, 'myanmar' => 23400, 'n. central asia' => 21600, 'nepal' => 20700, 'new zealand' => 43200, 'newfoundland' => -12600, 'north asia east' => 28800, 'north asia' => 25200, 'pacific sa' => -14400, 'pacific' => -28800, 'romance' => 3600, 'russian' => 10800, 'sa eastern' => -10800, 'sa pacific' => -18000, 'sa western' => -14400, 'samoa' => -39600, 'se asia' => 25200, 'malay peninsula' => 28800, 'south africa' => 7200, 'sri lanka' => 21600, 'taipei' => 28800, 'tasmania' => 36000, 'tokyo' => 32400, 'tonga' => 46800, 'us eastern' => -18000, 'us mountain' => -25200, 'vladivostok' => 36000, 'w. australia' => 28800, 'w. central africa' => 3600, 'w. europe' => 3600, 'west asia' => 18000, 'west pacific' => 36000, 'yakutsk' => 32400 } [MONTHS, DAYS, ABBR_MONTHS, ABBR_DAYS, ZONES].each do |x| x.freeze end class Bag # :nodoc: def initialize @elem = {} end def method_missing(t, *args, &block) t = t.to_s set = t.chomp!('=') t = t.intern if set @elem[t] = args[0] else @elem[t] end end def to_hash @elem.reject{|k, v| /\A_/ =~ k.to_s || v.nil?} end end end def emit(e, f) # :nodoc: case e when Numeric sign = %w(+ + -)[e <=> 0] e = e.abs end s = e.to_s if f[:s] && f[:p] == '0' f[:w] -= 1 end if f[:s] && f[:p] == "\s" s[0,0] = sign end if f[:p] != '-' s = s.rjust(f[:w], f[:p]) end if f[:s] && f[:p] != "\s" s[0,0] = sign end s = s.upcase if f[:u] s = s.downcase if f[:d] s end def emit_w(e, w, f) # :nodoc: f[:w] = [f[:w], w].compact.max emit(e, f) end def emit_n(e, w, f) # :nodoc: f[:p] ||= '0' emit_w(e, w, f) end def emit_sn(e, w, f) # :nodoc: if e < 0 w += 1 f[:s] = true end emit_n(e, w, f) end def emit_z(e, w, f) # :nodoc: w += 1 f[:s] = true emit_n(e, w, f) end def emit_a(e, w, f) # :nodoc: f[:p] ||= "\s" emit_w(e, w, f) end def emit_ad(e, w, f) # :nodoc: if f[:x] f[:u] = true f[:d] = false end emit_a(e, w, f) end def emit_au(e, w, f) # :nodoc: if f[:x] f[:u] = false f[:d] = true end emit_a(e, w, f) end private :emit, :emit_w, :emit_n, :emit_sn, :emit_z, :emit_a, :emit_ad, :emit_au def strftime(fmt='%F') fmt.gsub(/%([-_0^#]+)?(\d+)?([EO]?(?::{1,3}z|.))/m) do f = {} m = $& s, w, c = $1, $2, $3 if s s.scan(/./) do |k| case k when '-'; f[:p] = '-' when '_'; f[:p] = "\s" when '0'; f[:p] = '0' when '^'; f[:u] = true when '#'; f[:x] = true end end end if w f[:w] = w.to_i end case c when 'A'; emit_ad(DAYNAMES[wday], 0, f) when 'a'; emit_ad(ABBR_DAYNAMES[wday], 0, f) when 'B'; emit_ad(MONTHNAMES[mon], 0, f) when 'b'; emit_ad(ABBR_MONTHNAMES[mon], 0, f) when 'C', 'EC'; emit_sn((year / 100).floor, 2, f) when 'c', 'Ec'; emit_a(strftime('%a %b %e %H:%M:%S %Y'), 0, f) when 'D'; emit_a(strftime('%m/%d/%y'), 0, f) when 'd', 'Od'; emit_n(mday, 2, f) when 'e', 'Oe'; emit_a(mday, 2, f) when 'F' if m == '%F' format('%.4d-%02d-%02d', year, mon, mday) # 4p else emit_a(strftime('%Y-%m-%d'), 0, f) end when 'G'; emit_sn(cwyear, 4, f) when 'g'; emit_n(cwyear % 100, 2, f) when 'H', 'OH'; emit_n(hour, 2, f) when 'h'; emit_ad(strftime('%b'), 0, f) when 'I', 'OI'; emit_n((hour % 12).nonzero? || 12, 2, f) when 'j'; emit_n(yday, 3, f) when 'k'; emit_a(hour, 2, f) when 'L' f[:p] = nil w = f[:w] || 3 u = 10**w emit_n((sec_fraction * u).floor, w, f) when 'l'; emit_a((hour % 12).nonzero? || 12, 2, f) when 'M', 'OM'; emit_n(min, 2, f) when 'm', 'Om'; emit_n(mon, 2, f) when 'N' f[:p] = nil w = f[:w] || 9 u = 10**w emit_n((sec_fraction * u).floor, w, f) when 'n'; emit_a("\n", 0, f) when 'P'; emit_ad(strftime('%p').downcase, 0, f) when 'p'; emit_au(if hour < 12 then 'AM' else 'PM' end, 0, f) when 'Q' s = ((ajd - UNIX_EPOCH_IN_AJD) / MILLISECONDS_IN_DAY).round emit_sn(s, 1, f) when 'R'; emit_a(strftime('%H:%M'), 0, f) when 'r'; emit_a(strftime('%I:%M:%S %p'), 0, f) when 'S', 'OS'; emit_n(sec, 2, f) when 's' s = ((ajd - UNIX_EPOCH_IN_AJD) / SECONDS_IN_DAY).round emit_sn(s, 1, f) when 'T' if m == '%T' format('%02d:%02d:%02d', hour, min, sec) # 4p else emit_a(strftime('%H:%M:%S'), 0, f) end when 't'; emit_a("\t", 0, f) when 'U', 'W', 'OU', 'OW' emit_n(if c[-1,1] == 'U' then wnum0 else wnum1 end, 2, f) when 'u', 'Ou'; emit_n(cwday, 1, f) when 'V', 'OV'; emit_n(cweek, 2, f) when 'v'; emit_a(strftime('%e-%b-%Y'), 0, f) when 'w', 'Ow'; emit_n(wday, 1, f) when 'X', 'EX'; emit_a(strftime('%H:%M:%S'), 0, f) when 'x', 'Ex'; emit_a(strftime('%m/%d/%y'), 0, f) when 'Y', 'EY'; emit_sn(year, 4, f) when 'y', 'Ey', 'Oy'; emit_n(year % 100, 2, f) when 'Z'; emit_au(strftime('%:z'), 0, f) when /\A(:{0,3})z/ t = $1.size sign = if offset < 0 then -1 else +1 end fr = offset.abs ss = fr.div(SECONDS_IN_DAY) # 4p hh, ss = ss.divmod(3600) mm, ss = ss.divmod(60) if t == 3 if ss.nonzero? then t = 2 elsif mm.nonzero? then t = 1 else t = -1 end end case t when -1 tail = [] sep = '' when 0 f[:w] -= 2 if f[:w] tail = ['%02d' % mm] sep = '' when 1 f[:w] -= 3 if f[:w] tail = ['%02d' % mm] sep = ':' when 2 f[:w] -= 6 if f[:w] tail = ['%02d' % mm, '%02d' % ss] sep = ':' end ([emit_z(sign * hh, 2, f)] + tail).join(sep) when '%'; emit_a('%', 0, f) when '+'; emit_a(strftime('%a %b %e %H:%M:%S %Z %Y'), 0, f) else m end end end # alias_method :format, :strftime def asctime() strftime('%c') end alias_method :ctime, :asctime def iso8601() strftime('%F') end def rfc3339() iso8601 end def xmlschema() iso8601 end # :nodoc: def rfc2822() strftime('%a, %-d %b %Y %T %z') end alias_method :rfc822, :rfc2822 def httpdate() new_offset(0).strftime('%a, %d %b %Y %T GMT') end # :nodoc: def jisx0301 if jd < 2405160 iso8601 else case jd when 2405160...2419614 g = 'M%02d' % (year - 1867) when 2419614...2424875 g = 'T%02d' % (year - 1911) when 2424875...2447535 g = 'S%02d' % (year - 1925) else g = 'H%02d' % (year - 1988) end g + strftime('.%m.%d') end end =begin def beat(n=0) i, f = (new_offset(HOURS_IN_DAY).day_fraction * 1000).divmod(1) ('@%03d' % i) + if n < 1 '' else '.%0*d' % [n, (f / Rational(1, 10**n)).round] end end =end def self.num_pattern? (s) # :nodoc: /\A%[EO]?[CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy\d]/ =~ s || /\A\d/ =~ s end private_class_method :num_pattern? def self._strptime_i(str, fmt, e) # :nodoc: fmt.scan(/%([EO]?(?::{1,3}z|.))|(.)/m) do |s, c| a = $& if s case s when 'A', 'a' return unless str.sub!(/\A(#{Format::DAYS.keys.join('|')})/io, '') || str.sub!(/\A(#{Format::ABBR_DAYS.keys.join('|')})/io, '') val = Format::DAYS[$1.downcase] || Format::ABBR_DAYS[$1.downcase] return unless val e.wday = val when 'B', 'b', 'h' return unless str.sub!(/\A(#{Format::MONTHS.keys.join('|')})/io, '') || str.sub!(/\A(#{Format::ABBR_MONTHS.keys.join('|')})/io, '') val = Format::MONTHS[$1.downcase] || Format::ABBR_MONTHS[$1.downcase] return unless val e.mon = val when 'C', 'EC' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,2})/ else /\A([-+]?\d{1,})/ end, '') val = $1.to_i e._cent = val when 'c', 'Ec' return unless _strptime_i(str, '%a %b %e %H:%M:%S %Y', e) when 'D' return unless _strptime_i(str, '%m/%d/%y', e) when 'd', 'e', 'Od', 'Oe' return unless str.sub!(/\A( \d|\d{1,2})/, '') val = $1.to_i return unless (1..31) === val e.mday = val when 'F' return unless _strptime_i(str, '%Y-%m-%d', e) when 'G' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,4})/ else /\A([-+]?\d{1,})/ end, '') val = $1.to_i e.cwyear = val when 'g' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..99) === val e.cwyear = val e._cent ||= if val >= 69 then 19 else 20 end when 'H', 'k', 'OH' return unless str.sub!(/\A( \d|\d{1,2})/, '') val = $1.to_i return unless (0..24) === val e.hour = val when 'I', 'l', 'OI' return unless str.sub!(/\A( \d|\d{1,2})/, '') val = $1.to_i return unless (1..12) === val e.hour = val when 'j' return unless str.sub!(/\A(\d{1,3})/, '') val = $1.to_i return unless (1..366) === val e.yday = val when 'L' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,3})/ else /\A([-+]?\d{1,})/ end, '') # val = Rational($1.to_i, 10**3) val = Rational($1.to_i, 10**$1.size) e.sec_fraction = val when 'M', 'OM' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..59) === val e.min = val when 'm', 'Om' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (1..12) === val e.mon = val when 'N' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,9})/ else /\A([-+]?\d{1,})/ end, '') # val = Rational($1.to_i, 10**9) val = Rational($1.to_i, 10**$1.size) e.sec_fraction = val when 'n', 't' return unless _strptime_i(str, "\s", e) when 'P', 'p' return unless str.sub!(/\A([ap])(?:m\b|\.m\.)/i, '') e._merid = if $1.downcase == 'a' then 0 else 12 end when 'Q' return unless str.sub!(/\A(-?\d{1,})/, '') val = Rational($1.to_i, 10**3) e.seconds = val when 'R' return unless _strptime_i(str, '%H:%M', e) when 'r' return unless _strptime_i(str, '%I:%M:%S %p', e) when 'S', 'OS' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..60) === val e.sec = val when 's' return unless str.sub!(/\A(-?\d{1,})/, '') val = $1.to_i e.seconds = val when 'T' return unless _strptime_i(str, '%H:%M:%S', e) when 'U', 'W', 'OU', 'OW' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..53) === val e.__send__(if s[-1,1] == 'U' then :wnum0= else :wnum1= end, val) when 'u', 'Ou' return unless str.sub!(/\A(\d{1})/, '') val = $1.to_i return unless (1..7) === val e.cwday = val when 'V', 'OV' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (1..53) === val e.cweek = val when 'v' return unless _strptime_i(str, '%e-%b-%Y', e) when 'w' return unless str.sub!(/\A(\d{1})/, '') val = $1.to_i return unless (0..6) === val e.wday = val when 'X', 'EX' return unless _strptime_i(str, '%H:%M:%S', e) when 'x', 'Ex' return unless _strptime_i(str, '%m/%d/%y', e) when 'Y', 'EY' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,4})/ else /\A([-+]?\d{1,})/ end, '') val = $1.to_i e.year = val when 'y', 'Ey', 'Oy' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..99) === val e.year = val e._cent ||= if val >= 69 then 19 else 20 end when 'Z', /\A:{0,3}z/ return unless str.sub!(/\A((?:gmt|utc?)?[-+]\d+(?:[,.:]\d+(?::\d+)?)? |[[:alpha:].\s]+(?:standard|daylight)\s+time\b |[[:alpha:]]+(?:\s+dst)?\b )/ix, '') val = $1 e.zone = val offset = zone_to_diff(val) e.offset = offset when '%' return unless str.sub!(/\A%/, '') when '+' return unless _strptime_i(str, '%a %b %e %H:%M:%S %Z %Y', e) else return unless str.sub!(Regexp.new('\\A' + Regexp.quote(a)), '') end else case c when /\A\s/ str.sub!(/\A\s+/, '') else return unless str.sub!(Regexp.new('\\A' + Regexp.quote(a)), '') end end end end private_class_method :_strptime_i def self._strptime(str, fmt='%F') str = str.dup e = Format::Bag.new return unless _strptime_i(str, fmt, e) if e._cent if e.cwyear e.cwyear += e._cent * 100 end if e.year e. year += e._cent * 100 end end if e._merid if e.hour e.hour %= 12 e.hour += e._merid end end unless str.empty? e.leftover = str end e.to_hash end def self.s3e(e, y, m, d, bc=false) unless String === m m = m.to_s end if y && m && !d y, m, d = d, y, m end if y == nil if d && d.size > 2 y = d d = nil end if d && d[0,1] == "'" y = d d = nil end end if y y.scan(/(\d+)(.+)?/) if $2 y, d = d, $1 end end if m if m[0,1] == "'" || m.size > 2 y, m, d = m, d, y # us -> be end end if d if d[0,1] == "'" || d.size > 2 y, d = d, y end end if y y =~ /([-+])?(\d+)/ if $1 || $2.size > 2 c = false end iy = $&.to_i if bc iy = -iy + 1 end e.year = iy end if m m =~ /\d+/ e.mon = $&.to_i end if d d =~ /\d+/ e.mday = $&.to_i end if c != nil e._comp = c end end private_class_method :s3e def self._parse_day(str, e) # :nodoc: if str.sub!(/\b(#{Format::ABBR_DAYS.keys.join('|')})[^-\d\s]*/io, ' ') e.wday = Format::ABBR_DAYS[$1.downcase] true =begin elsif str.sub!(/\b(?!\dth)(su|mo|tu|we|th|fr|sa)\b/i, ' ') e.wday = %w(su mo tu we th fr sa).index($1.downcase) true =end end end def self._parse_time(str, e) # :nodoc: if str.sub!( /( (?: \d+\s*:\s*\d+ (?: \s*:\s*\d+(?:[,.]\d*)? )? | \d+\s*h(?:\s*\d+m?(?:\s*\d+s?)?)? ) (?: \s* [ap](?:m\b|\.m\.) )? | \d+\s*[ap](?:m\b|\.m\.) ) (?: \s* ( (?:gmt|utc?)?[-+]\d+(?:[,.:]\d+(?::\d+)?)? | [[:alpha:].\s]+(?:standard|daylight)\stime\b | [[:alpha:]]+(?:\sdst)?\b ) )? /ix, ' ') t = $1 e.zone = $2 if $2 t =~ /\A(\d+)h? (?:\s*:?\s*(\d+)m? (?: \s*:?\s*(\d+)(?:[,.](\d+))?s? )? )? (?:\s*([ap])(?:m\b|\.m\.))?/ix e.hour = $1.to_i e.min = $2.to_i if $2 e.sec = $3.to_i if $3 e.sec_fraction = Rational($4.to_i, 10**$4.size) if $4 if $5 e.hour %= 12 if $5.downcase == 'p' e.hour += 12 end end true end end =begin def self._parse_beat(str, e) # :nodoc: if str.sub!(/@\s*(\d+)(?:[,.](\d*))?/, ' ') beat = Rational($1.to_i) beat += Rational($2.to_i, 10**$2.size) if $2 secs = Rational(beat, 1000) h, min, s, fr = self.day_fraction_to_time(secs) e.hour = h e.min = min e.sec = s e.sec_fraction = fr * 86400 e.zone = '+01:00' true end end =end def self._parse_eu(str, e) # :nodoc: if str.sub!( /'?(\d+)[^-\d\s]* \s* (#{Format::ABBR_MONTHS.keys.join('|')})[^-\d\s']* (?: \s* (c(?:e|\.e\.)|b(?:ce|\.c\.e\.)|a(?:d|\.d\.)|b(?:c|\.c\.))? \s* ('?-?\d+(?:(?:st|nd|rd|th)\b)?) )? /iox, ' ') # ' s3e(e, $4, Format::ABBR_MONTHS[$2.downcase], $1, $3 && $3[0,1].downcase == 'b') true end end def self._parse_us(str, e) # :nodoc: if str.sub!( /\b(#{Format::ABBR_MONTHS.keys.join('|')})[^-\d\s']* \s* ('?\d+)[^-\d\s']* (?: \s* (c(?:e|\.e\.)|b(?:ce|\.c\.e\.)|a(?:d|\.d\.)|b(?:c|\.c\.))? \s* ('?-?\d+) )? /iox, ' ') # ' s3e(e, $4, Format::ABBR_MONTHS[$1.downcase], $2, $3 && $3[0,1].downcase == 'b') true end end def self._parse_iso(str, e) # :nodoc: if str.sub!(/('?[-+]?\d+)-(\d+)-('?-?\d+)/, ' ') s3e(e, $1, $2, $3) true end end def self._parse_iso2(str, e) # :nodoc: if str.sub!(/\b(\d{2}|\d{4})?-?w(\d{2})(?:-?(\d))?\b/i, ' ') e.cwyear = $1.to_i if $1 e.cweek = $2.to_i e.cwday = $3.to_i if $3 true elsif str.sub!(/-w-(\d)\b/i, ' ') e.cwday = $1.to_i true elsif str.sub!(/--(\d{2})?-(\d{2})\b/, ' ') e.mon = $1.to_i if $1 e.mday = $2.to_i true elsif str.sub!(/--(\d{2})(\d{2})?\b/, ' ') e.mon = $1.to_i e.mday = $2.to_i if $2 true elsif /[,.](\d{2}|\d{4})-\d{3}\b/ !~ str && str.sub!(/\b(\d{2}|\d{4})-(\d{3})\b/, ' ') e.year = $1.to_i e.yday = $2.to_i true elsif /\d-\d{3}\b/ !~ str && str.sub!(/\b-(\d{3})\b/, ' ') e.yday = $1.to_i true end end def self._parse_jis(str, e) # :nodoc: if str.sub!(/\b([mtsh])(\d+)\.(\d+)\.(\d+)/i, ' ') era = { 'm'=>1867, 't'=>1911, 's'=>1925, 'h'=>1988 }[$1.downcase] e.year = $2.to_i + era e.mon = $3.to_i e.mday = $4.to_i true end end def self._parse_vms(str, e) # :nodoc: if str.sub!(/('?-?\d+)-(#{Format::ABBR_MONTHS.keys.join('|')})[^-]* -('?-?\d+)/iox, ' ') s3e(e, $3, Format::ABBR_MONTHS[$2.downcase], $1) true elsif str.sub!(/\b(#{Format::ABBR_MONTHS.keys.join('|')})[^-]* -('?-?\d+)(?:-('?-?\d+))?/iox, ' ') s3e(e, $3, Format::ABBR_MONTHS[$1.downcase], $2) true end end def self._parse_sla(str, e) # :nodoc: if str.sub!(%r|('?-?\d+)/\s*('?\d+)(?:\D\s*('?-?\d+))?|, ' ') # ' s3e(e, $1, $2, $3) true end end def self._parse_dot(str, e) # :nodoc: if str.sub!(%r|('?-?\d+)\.\s*('?\d+)\.\s*('?-?\d+)|, ' ') # ' s3e(e, $1, $2, $3) true end end def self._parse_year(str, e) # :nodoc: if str.sub!(/'(\d+)\b/, ' ') e.year = $1.to_i true end end def self._parse_mon(str, e) # :nodoc: if str.sub!(/\b(#{Format::ABBR_MONTHS.keys.join('|')})\S*/io, ' ') e.mon = Format::ABBR_MONTHS[$1.downcase] true end end def self._parse_mday(str, e) # :nodoc: if str.sub!(/(\d+)(st|nd|rd|th)\b/i, ' ') e.mday = $1.to_i true end end def self._parse_ddd(str, e) # :nodoc: if str.sub!( /([-+]?)(\d{2,14}) (?: \s* t? \s* (\d{2,6})?(?:[,.](\d*))? )? (?: \s* ( z\b | [-+]\d{1,4}\b | \[[-+]?\d[^\]]*\] ) )? /ix, ' ') case $2.size when 2 if $3.nil? && $4 e.sec = $2[-2, 2].to_i else e.mday = $2[ 0, 2].to_i end when 4 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i else e.mon = $2[ 0, 2].to_i e.mday = $2[ 2, 2].to_i end when 6 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-6, 2].to_i else e.year = ($1 + $2[ 0, 2]).to_i e.mon = $2[ 2, 2].to_i e.mday = $2[ 4, 2].to_i end when 8, 10, 12, 14 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-6, 2].to_i e.mday = $2[-8, 2].to_i if $2.size >= 10 e.mon = $2[-10, 2].to_i end if $2.size == 12 e.year = ($1 + $2[-12, 2]).to_i end if $2.size == 14 e.year = ($1 + $2[-14, 4]).to_i e._comp = false end else e.year = ($1 + $2[ 0, 4]).to_i e.mon = $2[ 4, 2].to_i e.mday = $2[ 6, 2].to_i e.hour = $2[ 8, 2].to_i if $2.size >= 10 e.min = $2[10, 2].to_i if $2.size >= 12 e.sec = $2[12, 2].to_i if $2.size >= 14 e._comp = false end when 3 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-3, 1].to_i else e.yday = $2[ 0, 3].to_i end when 5 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-5, 1].to_i else e.year = ($1 + $2[ 0, 2]).to_i e.yday = $2[ 2, 3].to_i end when 7 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-6, 2].to_i e.mday = $2[-7, 1].to_i else e.year = ($1 + $2[ 0, 4]).to_i e.yday = $2[ 4, 3].to_i end end if $3 if $4 case $3.size when 2, 4, 6 e.sec = $3[-2, 2].to_i e.min = $3[-4, 2].to_i if $3.size >= 4 e.hour = $3[-6, 2].to_i if $3.size >= 6 end else case $3.size when 2, 4, 6 e.hour = $3[ 0, 2].to_i e.min = $3[ 2, 2].to_i if $3.size >= 4 e.sec = $3[ 4, 2].to_i if $3.size >= 6 end end end if $4 e.sec_fraction = Rational($4.to_i, 10**$4.size) end if $5 e.zone = $5 if e.zone[0,1] == '[' o, n, = e.zone[1..-2].split(':') e.zone = n || o if /\A\d/ =~ o o = format('+%s', o) end e.offset = zone_to_diff(o) end end true end end private_class_method :_parse_day, :_parse_time, # :_parse_beat, :_parse_eu, :_parse_us, :_parse_iso, :_parse_iso2, :_parse_jis, :_parse_vms, :_parse_sla, :_parse_dot, :_parse_year, :_parse_mon, :_parse_mday, :_parse_ddd def self._parse(str, comp=true) str = str.dup e = Format::Bag.new e._comp = comp str.gsub!(/[^-+',.\/:@[:alnum:]\[\]]+/, ' ') _parse_time(str, e) # || _parse_beat(str, e) _parse_day(str, e) _parse_eu(str, e) || _parse_us(str, e) || _parse_iso(str, e) || _parse_jis(str, e) || _parse_vms(str, e) || _parse_sla(str, e) || _parse_dot(str, e) || _parse_iso2(str, e) || _parse_year(str, e) || _parse_mon(str, e) || _parse_mday(str, e) || _parse_ddd(str, e) if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/i, ' ') if e.year e.year = -e.year + 1 end end if str.sub!(/\A\s*(\d{1,2})\s*\z/, ' ') if e.hour && !e.mday v = $1.to_i if (1..31) === v e.mday = v end end if e.mday && !e.hour v = $1.to_i if (0..24) === v e.hour = v end end end if e._comp if e.cwyear if e.cwyear >= 0 && e.cwyear <= 99 e.cwyear += if e.cwyear >= 69 then 1900 else 2000 end end end if e.year if e.year >= 0 && e.year <= 99 e.year += if e.year >= 69 then 1900 else 2000 end end end end e.offset ||= zone_to_diff(e.zone) if e.zone e.to_hash end def self._iso8601(str) # :nodoc: if /\A\s*(([-+]?\d{2,}|-)-\d{2}-\d{2}| ([-+]?\d{2,})?-\d{3}| (\d{2}|\d{4})?-w\d{2}-\d| -w-\d) (t \d{2}:\d{2}(:\d{2}([,.]\d+)?)? (z|[-+]\d{2}(:?\d{2})?)?)?\s*\z/ix =~ str _parse(str) elsif /\A\s*(([-+]?(\d{2}|\d{4})|--)\d{2}\d{2}| ([-+]?(\d{2}|\d{4}))?\d{3}|-\d{3}| (\d{2}|\d{4})?w\d{2}\d) (t? \d{2}\d{2}(\d{2}([,.]\d+)?)? (z|[-+]\d{2}(\d{2})?)?)?\s*\z/ix =~ str _parse(str) elsif /\A\s*(\d{2}:\d{2}(:\d{2}([,.]\d+)?)? (z|[-+]\d{2}(:?\d{2})?)?)?\s*\z/ix =~ str _parse(str) elsif /\A\s*(\d{2}\d{2}(\d{2}([,.]\d+)?)? (z|[-+]\d{2}(\d{2})?)?)?\s*\z/ix =~ str _parse(str) end end def self._rfc3339(str) # :nodoc: if /\A\s*-?\d{4}-\d{2}-\d{2} # allow minus, anyway (t|\s) \d{2}:\d{2}:\d{2}(\.\d+)? (z|[-+]\d{2}:\d{2})\s*\z/ix =~ str _parse(str) end end def self._xmlschema(str) # :nodoc: if /\A\s*(-?\d{4,})(?:-(\d{2})(?:-(\d{2}))?)? (?:t (\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?)? (z|[-+]\d{2}:\d{2})?\s*\z/ix =~ str e = Format::Bag.new e.year = $1.to_i e.mon = $2.to_i if $2 e.mday = $3.to_i if $3 e.hour = $4.to_i if $4 e.min = $5.to_i if $5 e.sec = $6.to_i if $6 e.sec_fraction = Rational($7.to_i, 10**$7.size) if $7 if $8 e.zone = $8 e.offset = zone_to_diff($8) end e.to_hash elsif /\A\s*(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))? (z|[-+]\d{2}:\d{2})?\s*\z/ix =~ str e = Format::Bag.new e.hour = $1.to_i if $1 e.min = $2.to_i if $2 e.sec = $3.to_i if $3 e.sec_fraction = Rational($4.to_i, 10**$4.size) if $4 if $5 e.zone = $5 e.offset = zone_to_diff($5) end e.to_hash elsif /\A\s*(?:--(\d{2})(?:-(\d{2}))?|---(\d{2})) (z|[-+]\d{2}:\d{2})?\s*\z/ix =~ str e = Format::Bag.new e.mon = $1.to_i if $1 e.mday = $2.to_i if $2 e.mday = $3.to_i if $3 if $4 e.zone = $4 e.offset = zone_to_diff($4) end e.to_hash end end def self._rfc2822(str) # :nodoc: if /\A\s*(?:(?:#{Format::ABBR_DAYS.keys.join('|')})\s*,\s+)? \d{1,2}\s+ (?:#{Format::ABBR_MONTHS.keys.join('|')})\s+ -?(\d{2,})\s+ # allow minus, anyway \d{2}:\d{2}(:\d{2})?\s* (?:[-+]\d{4}|ut|gmt|e[sd]t|c[sd]t|m[sd]t|p[sd]t|[a-ik-z])\s*\z/iox =~ str e = _parse(str, false) if $1.size < 4 if e[:year] < 50 e[:year] += 2000 elsif e[:year] < 1000 e[:year] += 1900 end end e end end class << self; alias_method :_rfc822, :_rfc2822 end def self._httpdate(str) # :nodoc: if /\A\s*(#{Format::ABBR_DAYS.keys.join('|')})\s*,\s+ \d{2}\s+ (#{Format::ABBR_MONTHS.keys.join('|')})\s+ -?\d{4}\s+ # allow minus, anyway \d{2}:\d{2}:\d{2}\s+ gmt\s*\z/iox =~ str _rfc2822(str) elsif /\A\s*(#{Format::DAYS.keys.join('|')})\s*,\s+ \d{2}\s*-\s* (#{Format::ABBR_MONTHS.keys.join('|')})\s*-\s* \d{2}\s+ \d{2}:\d{2}:\d{2}\s+ gmt\s*\z/iox =~ str _parse(str) elsif /\A\s*(#{Format::ABBR_DAYS.keys.join('|')})\s+ (#{Format::ABBR_MONTHS.keys.join('|')})\s+ \d{1,2}\s+ \d{2}:\d{2}:\d{2}\s+ \d{4}\s*\z/iox =~ str _parse(str) end end def self._jisx0301(str) # :nodoc: if /\A\s*[mtsh]?\d{2}\.\d{2}\.\d{2} (t (\d{2}:\d{2}(:\d{2}([,.]\d*)?)? (z|[-+]\d{2}(:?\d{2})?)?)?)?\s*\z/ix =~ str if /\A\s*\d/ =~ str _parse(str.sub(/\A\s*(\d)/, 'h\1')) else _parse(str) end else _iso8601(str) end end t = Module.new do private def zone_to_diff(zone) # :nodoc: zone = zone.downcase if zone.sub!(/\s+(standard|daylight)\s+time\z/, '') dst = $1 == 'daylight' else dst = zone.sub!(/\s+dst\z/, '') end if Format::ZONES.include?(zone) offset = Format::ZONES[zone] offset += 3600 if dst elsif zone.sub!(/\A(?:gmt|utc?)?([-+])/, '') sign = $1 if zone.include?(':') hour, min, sec, = zone.split(':') elsif zone.include?(',') || zone.include?('.') hour, fr, = zone.split(/[,.]/) min = Rational(fr.to_i, 10**fr.size) * 60 else case zone.size when 3 hour = zone[0,1] min = zone[1,2] else hour = zone[0,2] min = zone[2,2] sec = zone[4,2] end end offset = hour.to_i * 3600 + min.to_i * 60 + sec.to_i offset *= -1 if sign == '-' end offset end end extend t include t end class DateTime < Date def strftime(fmt='%FT%T%:z') super(fmt) end def self._strptime(str, fmt='%FT%T%z') super(str, fmt) end def iso8601_timediv(n) # :nodoc: strftime('T%T' + if n < 1 '' else '.%0*d' % [n, (sec_fraction / Rational(1, 10**n)).round] end + '%:z') end private :iso8601_timediv def iso8601(n=0) super() + iso8601_timediv(n) end def rfc3339(n=0) iso8601(n) end def xmlschema(n=0) iso8601(n) end # :nodoc: def jisx0301(n=0) super() + iso8601_timediv(n) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/date/delta/parser.rb
tools/jruby-1.5.1/lib/ruby/1.9/date/delta/parser.rb
# # DO NOT MODIFY!!!! # This file is automatically generated by racc 1.4.5 # from racc grammer file "parser.ry". # require 'racc/parser' class Date class Delta class Parser < Racc::Parser module_eval <<'..end parser.ry modeval..id43bff5dec9', 'parser.ry', 42 def lookup(str) t = str.downcase k = UNITS4KEY[t] return [:UNIT, k] if k return [:AND, nil] if t == 'and' return [:UNKNOWNWORD, nil] end def parse(str) @q = [] until str.empty? case str when /\A\s+/ when /\AP(\d+y)?(\d+m)?(\d+d)?t?(\d+h)?(\d+m)?(\d+s)?(\d+w)?/i y, m, d, h, min, s, w = [$1, $2, $3, $4, $5, $6, $7].collect{|x| x.to_i} y *= UNITS4KEY['years'] m *= UNITS4KEY['months'] d *= UNITS4KEY['days'] h *= UNITS4KEY['hours'] min *= UNITS4KEY['minutes'] s *= UNITS4KEY['seconds'] w *= UNITS4KEY['weeks'] @q.push [:DURATION, y + m + d + h + min + s + w] when /\A\d+/ @q.push [:DIGITS, $&.to_i] when /\A[a-z]+/i @q.push lookup($&) when /\A.|\n/ @q.push [$&, $&] end str = $' end @q.push [false, false] do_parse end def next_token @q.shift end ..end parser.ry modeval..id43bff5dec9 ##### racc 1.4.5 generates ### racc_reduce_table = [ 0, 0, :racc_error, 1, 16, :_reduce_none, 1, 17, :_reduce_none, 1, 17, :_reduce_none, 3, 17, :_reduce_4, 3, 17, :_reduce_5, 3, 17, :_reduce_6, 3, 17, :_reduce_7, 3, 17, :_reduce_8, 3, 17, :_reduce_9, 3, 17, :_reduce_10, 2, 17, :_reduce_11, 2, 17, :_reduce_12, 3, 17, :_reduce_13, 2, 18, :_reduce_14, 0, 20, :_reduce_15, 1, 20, :_reduce_none, 1, 19, :_reduce_none ] racc_reduce_n = 18 racc_shift_n = 32 racc_action_table = [ 13, 14, 15, 16, 17, 18, 19, 4, 27, 23, 8, 9, 1, 4, 25, 2, 8, 9, 1, 4, 24, 2, 8, 9, 1, 4, 21, 2, 8, 9, 1, 4, 11, 2, 8, 9, 1, 4, 26, 2, 8, 9, 1, 4, nil, 2, 8, 9, 1, 4, nil, 2, 8, 9, 1, nil, nil, 2, 13, 14, 15, 16, 17, 18, 19, 13, 14, 15, 13, 14, 15, 13, 14, 15, 13, 14, 15 ] racc_action_check = [ 10, 10, 10, 10, 10, 10, 10, 17, 15, 10, 17, 17, 17, 18, 13, 17, 18, 18, 18, 4, 11, 18, 4, 4, 4, 1, 9, 4, 1, 1, 1, 8, 3, 1, 8, 8, 8, 19, 14, 8, 19, 19, 19, 0, nil, 19, 0, 0, 0, 16, nil, 0, 16, 16, 16, nil, nil, 16, 5, 5, 5, 5, 5, 5, 5, 30, 30, 30, 28, 28, 28, 29, 29, 29, 31, 31, 31 ] racc_action_pointer = [ 37, 19, nil, 32, 13, 55, nil, nil, 25, 13, -3, 20, nil, 4, 28, -2, 43, 1, 7, 31, nil, nil, nil, nil, nil, nil, nil, nil, 65, 68, 62, 71 ] racc_action_default = [ -18, -18, -17, -18, -18, -1, -2, -3, -18, -15, -18, -18, -12, -18, -18, -18, -18, -18, -18, -18, -11, -16, -14, -13, 32, -10, -8, -9, -4, -5, -6, -7 ] racc_goto_table = [ 5, 10, 3, 22, 12, nil, nil, nil, 20, nil, nil, nil, nil, nil, nil, nil, 28, 29, 30, 31 ] racc_goto_check = [ 2, 2, 1, 5, 2, nil, nil, nil, 2, nil, nil, nil, nil, nil, nil, nil, 2, 2, 2, 2 ] racc_goto_pointer = [ nil, 2, 0, nil, nil, -6 ] racc_goto_default = [ nil, nil, nil, 6, 7, nil ] racc_token_table = { false => 0, Object.new => 1, :UNARY => 2, "^" => 3, "*" => 4, "/" => 5, "+" => 6, "," => 7, :AND => 8, "-" => 9, :DIGITS => 10, "(" => 11, ")" => 12, :UNIT => 13, :DURATION => 14 } racc_use_result_var = true racc_nt_base = 15 Racc_arg = [ racc_action_table, racc_action_check, racc_action_default, racc_action_pointer, racc_goto_table, racc_goto_check, racc_goto_default, racc_goto_pointer, racc_nt_base, racc_reduce_table, racc_token_table, racc_shift_n, racc_reduce_n, racc_use_result_var ] Racc_token_to_s_table = [ '$end', 'error', 'UNARY', '"^"', '"*"', '"/"', '"+"', '","', 'AND', '"-"', 'DIGITS', '"("', '")"', 'UNIT', 'DURATION', '$start', 'stmt', 'expr', 'time', 'iso', 'unit'] Racc_debug_parser = false ##### racc system variables end ##### # reduce 0 omitted # reduce 1 omitted # reduce 2 omitted # reduce 3 omitted module_eval <<'.,.,', 'parser.ry', 18 def _reduce_4( val, _values, result ) result += val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 19 def _reduce_5( val, _values, result ) result += val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 20 def _reduce_6( val, _values, result ) result += val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 21 def _reduce_7( val, _values, result ) result -= val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 22 def _reduce_8( val, _values, result ) result *= val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 23 def _reduce_9( val, _values, result ) result /= val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 24 def _reduce_10( val, _values, result ) result **= val[2] result end .,., module_eval <<'.,.,', 'parser.ry', 25 def _reduce_11( val, _values, result ) result = -val[1] result end .,., module_eval <<'.,.,', 'parser.ry', 26 def _reduce_12( val, _values, result ) result = +val[1] result end .,., module_eval <<'.,.,', 'parser.ry', 27 def _reduce_13( val, _values, result ) result = val[1] result end .,., module_eval <<'.,.,', 'parser.ry', 30 def _reduce_14( val, _values, result ) result = val[0] * val[1] result end .,., module_eval <<'.,.,', 'parser.ry', 33 def _reduce_15( val, _values, result ) result = 1 result end .,., # reduce 16 omitted # reduce 17 omitted def _reduce_none( val, _values, result ) result end end # class Parser end # class Delta end # class Date
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rbconfig/datadir.rb
tools/jruby-1.5.1/lib/ruby/1.9/rbconfig/datadir.rb
#-- # Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others. # All rights reserved. # See LICENSE.txt for permissions. #++ module RbConfig ## # Return the path to the data directory associated with the given package # name. Normally this is just # "#{RbConfig::CONFIG['datadir']}/#{package_name}", but may be modified by # packages like RubyGems to handle versioned data directories. def self.datadir(package_name) File.join(CONFIG['datadir'], package_name) end unless RbConfig.respond_to?(:datadir) end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/optparse/version.rb
tools/jruby-1.5.1/lib/ruby/1.9/optparse/version.rb
# OptionParser internal utility class << OptionParser def show_version(*pkgs) progname = ARGV.options.program_name result = false show = proc do |klass, cname, version| str = "#{progname}" unless klass == ::Object and cname == :VERSION version = version.join(".") if Array === version str << ": #{klass}" unless klass == Object str << " version #{version}" end [:Release, :RELEASE].find do |rel| if klass.const_defined?(rel) str << " (#{klass.const_get(rel)})" end end puts str result = true end if pkgs.size == 1 and pkgs[0] == "all" self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version| unless cname[1] == ?e and klass.const_defined?(:Version) show.call(klass, cname.intern, version) end end else pkgs.each do |pkg| begin pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)} v = case when pkg.const_defined?(:Version) pkg.const_get(n = :Version) when pkg.const_defined?(:VERSION) pkg.const_get(n = :VERSION) else n = nil "unknown" end show.call(pkg, n, v) rescue NameError end end end result end def each_const(path, base = ::Object) path.split(/::|\//).inject(base) do |klass, name| raise NameError, path unless Module === klass klass.constants.grep(/#{name}/i) do |c| klass.const_defined?(c) or next c = klass.const_get(c) end end end def search_const(klass, name) klasses = [klass] while klass = klasses.shift klass.constants.each do |cname| klass.const_defined?(cname) or next const = klass.const_get(cname) yield klass, cname, const if name === cname klasses << const if Module === const and const != ::Object 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/tools/jruby-1.5.1/lib/ruby/1.9/optparse/time.rb
tools/jruby-1.5.1/lib/ruby/1.9/optparse/time.rb
require 'optparse' require 'time' OptionParser.accept(Time) do |s,| begin (Time.httpdate(s) rescue Time.parse(s)) if s rescue raise OptionParser::InvalidArgument, s end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/optparse/uri.rb
tools/jruby-1.5.1/lib/ruby/1.9/optparse/uri.rb
# -*- ruby -*- require 'optparse' require 'uri' OptionParser.accept(URI) {|s,| URI.parse(s) if s}
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/optparse/shellwords.rb
tools/jruby-1.5.1/lib/ruby/1.9/optparse/shellwords.rb
# -*- ruby -*- require 'shellwords' require 'optparse' OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/optparse/date.rb
tools/jruby-1.5.1/lib/ruby/1.9/optparse/date.rb
require 'optparse' require 'date' OptionParser.accept(DateTime) do |s,| begin DateTime.parse(s) if s rescue ArgumentError raise OptionParser::InvalidArgument, s end end OptionParser.accept(Date) do |s,| begin Date.parse(s) if s rescue ArgumentError raise OptionParser::InvalidArgument, s end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/output-method.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/output-method.rb
# # output-method.rb - optput methods used by irb # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" module IRB # OutputMethod # StdioOutputMethod class OutputMethod @RCS_ID='-$Id: output-method.rb 23985 2009-07-07 11:36:20Z keiju $-' def print(*opts) IRB.fail NotImplementError, "print" end def printn(*opts) print opts.join(" "), "\n" end # extend printf def printf(format, *opts) if /(%*)%I/ =~ format format, opts = parse_printf_format(format, opts) end print sprintf(format, *opts) end # % # <flag> [#0- +] # <minimum field width> (\*|\*[1-9][0-9]*\$|[1-9][0-9]*) # <precision>.(\*|\*[1-9][0-9]*\$|[1-9][0-9]*|)? # #<length modifier>(hh|h|l|ll|L|q|j|z|t) # <conversion specifier>[diouxXeEfgGcsb%] def parse_printf_format(format, opts) return format, opts if $1.size % 2 == 1 end def puts(*objs) for obj in objs print(*obj) print "\n" end end def pp(*objs) puts(*objs.collect{|obj| obj.inspect}) end def ppx(prefix, *objs) puts(*objs.collect{|obj| prefix+obj.inspect}) end end class StdioOutputMethod<OutputMethod def print(*opts) STDOUT.print(*opts) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/version.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/version.rb
# # irb/version.rb - irb version definition file # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # # -- # # # module IRB @RELEASE_VERSION = "0.9.6" @LAST_UPDATE_DATE = "09/06/30" end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ws-for-case-2.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ws-for-case-2.rb
# # irb/ws-for-case-2.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # while true IRB::BINDING_QUEUE.push b = binding end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/completion.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/completion.rb
# # irb/completor.rb - # $Release Version: 0.9$ # $Revision: 23129 $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # From Original Idea of shugo@ruby-lang.org # require "readline" module IRB module InputCompletor @RCS_ID='-$Id: completion.rb 23129 2009-04-03 05:04:02Z knu $-' ReservedWords = [ "BEGIN", "END", "alias", "and", "begin", "break", "case", "class", "def", "defined", "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", ] CompletionProc = proc { |input| bind = IRB.conf[:MAIN_CONTEXT].workspace.binding # puts "input: #{input}" case input when /^(\/[^\/]*\/)\.([^.]*)$/ # Regexp receiver = $1 message = Regexp.quote($2) candidates = Regexp.instance_methods.collect{|m| m.to_s} select_message(receiver, message, candidates) when /^([^\]]*\])\.([^.]*)$/ # Array receiver = $1 message = Regexp.quote($2) candidates = Array.instance_methods.collect{|m| m.to_s} select_message(receiver, message, candidates) when /^([^\}]*\})\.([^.]*)$/ # Proc or Hash receiver = $1 message = Regexp.quote($2) candidates = Proc.instance_methods.collect{|m| m.to_s} candidates |= Hash.instance_methods.collect{|m| m.to_s} select_message(receiver, message, candidates) when /^(:[^:.]*)$/ # Symbol if Symbol.respond_to?(:all_symbols) sym = $1 candidates = Symbol.all_symbols.collect{|s| ":" + s.id2name} candidates.grep(/^#{sym}/) else [] end when /^::([A-Z][^:\.\(]*)$/ # Absolute Constant or class methods receiver = $1 candidates = Object.constants.collect{|m| m.to_s} candidates.grep(/^#{receiver}/).collect{|e| "::" + e} when /^(((::)?[A-Z][^:.\(]*)+)::?([^:.]*)$/ # Constant or class methods receiver = $1 message = Regexp.quote($4) begin candidates = eval("#{receiver}.constants.collect{|m| m.to_s}", bind) candidates |= eval("#{receiver}.methods.collect{|m| m.to_s}", bind) rescue Exception candidates = [] end candidates.grep(/^#{message}/).collect{|e| receiver + "::" + e} when /^(:[^:.]+)\.([^.]*)$/ # Symbol receiver = $1 message = Regexp.quote($2) candidates = Symbol.instance_methods.collect{|m| m.to_s} select_message(receiver, message, candidates) when /^(-?(0[dbo])?[0-9_]+(\.[0-9_]+)?([eE]-?[0-9]+)?)\.([^.]*)$/ # Numeric receiver = $1 message = Regexp.quote($5) begin candidates = eval(receiver, bind).methods.collect{|m| m.to_s} rescue Exception candidates = [] end select_message(receiver, message, candidates) when /^(-?0x[0-9a-fA-F_]+)\.([^.]*)$/ # Numeric(0xFFFF) receiver = $1 message = Regexp.quote($2) begin candidates = eval(receiver, bind).methods.collect{|m| m.to_s} rescue Exception candidates = [] end select_message(receiver, message, candidates) when /^(\$[^.]*)$/ regmessage = Regexp.new(Regexp.quote($1)) candidates = global_variables.collect{|m| m.to_s}.grep(regmessage) # when /^(\$?(\.?[^.]+)+)\.([^.]*)$/ when /^((\.?[^.]+)+)\.([^.]*)$/ # variable receiver = $1 message = Regexp.quote($3) gv = eval("global_variables", bind).collect{|m| m.to_s} lv = eval("local_variables", bind).collect{|m| m.to_s} cv = eval("self.class.constants", bind).collect{|m| m.to_s} if (gv | lv | cv).include?(receiver) # foo.func and foo is local var. candidates = eval("#{receiver}.methods", bind).collect{|m| m.to_s} elsif /^[A-Z]/ =~ receiver and /\./ !~ receiver # Foo::Bar.func begin candidates = eval("#{receiver}.methods", bind).collect{|m| m.to_s} rescue Exception candidates = [] end else # func1.func2 candidates = [] ObjectSpace.each_object(Module){|m| begin name = m.name rescue Exception name = "" end next if name != "IRB::Context" and /^(IRB|SLex|RubyLex|RubyToken)/ =~ name candidates.concat m.instance_methods(false).collect{|x| x.to_s} } candidates.sort! candidates.uniq! end select_message(receiver, message, candidates) when /^\.([^.]*)$/ # unknown(maybe String) receiver = "" message = Regexp.quote($1) candidates = String.instance_methods(true).collect{|m| m.to_s} select_message(receiver, message, candidates) else candidates = eval("methods | private_methods | local_variables | self.class.constants", bind).collect{|m| m.to_s} (candidates|ReservedWords).grep(/^#{Regexp.quote(input)}/) end } Operators = ["%", "&", "*", "**", "+", "-", "/", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>", "[]", "[]=", "^", "!", "!=", "!~"] def self.select_message(receiver, message, candidates) candidates.grep(/^#{message}/).collect do |e| case e when /^[a-zA-Z_]/ receiver + "." + e when /^[0-9]/ when *Operators #receiver + " " + e end end end end end if Readline.respond_to?("basic_word_break_characters=") Readline.basic_word_break_characters= " \t\n\"\\'`><=;|&{(" end Readline.completion_append_character = nil Readline.completion_proc = IRB::InputCompletor::CompletionProc
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/xmp.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/xmp.rb
# # xmp.rb - irb version of gotoken xmp # $Release Version: 0.9$ # $Revision: 22784 $ # by Keiju ISHITSUKA(Nippon Rational Inc.) # # -- # # # require "irb" require "irb/frame" class XMP @RCS_ID='-$Id: xmp.rb 22784 2009-03-06 03:56:38Z nobu $-' def initialize(bind = nil) IRB.init_config(nil) #IRB.parse_opts #IRB.load_modules IRB.conf[:PROMPT_MODE] = :XMP bind = IRB::Frame.top(1) unless bind ws = IRB::WorkSpace.new(bind) @io = StringInputMethod.new @irb = IRB::Irb.new(ws, @io) @irb.context.ignore_sigint = false # IRB.conf[:IRB_RC].call(@irb.context) if IRB.conf[:IRB_RC] IRB.conf[:MAIN_CONTEXT] = @irb.context end def puts(exps) @io.puts exps if @irb.context.ignore_sigint begin trap_proc_b = trap("SIGINT"){@irb.signal_handle} catch(:IRB_EXIT) do @irb.eval_input end ensure trap("SIGINT", trap_proc_b) end else catch(:IRB_EXIT) do @irb.eval_input end end end class StringInputMethod < IRB::InputMethod def initialize super @exps = [] end def eof? @exps.empty? end def gets while l = @exps.shift next if /^\s+$/ =~ l l.concat "\n" print @prompt, l break end l end def puts(exps) if @encoding and exps.encoding != @encoding enc = Encoding.compatible?(@exps.join("\n"), exps) if enc.nil? raise Encoding::CompatibilityError, "Encoding in which the passed exression is encoded is not compatible to the preceding's one" else @encoding = enc end else @encoding = exps.encoding end @exps.concat exps.split(/\n/) end attr_reader :encoding end end def xmp(exps, bind = nil) bind = IRB::Frame.top(1) unless bind xmp = XMP.new(bind) xmp.puts exps xmp end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ruby-token.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ruby-token.rb
# # irb/ruby-token.rb - ruby tokens # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module RubyToken EXPR_BEG = :EXPR_BEG EXPR_MID = :EXPR_MID EXPR_END = :EXPR_END EXPR_ARG = :EXPR_ARG EXPR_FNAME = :EXPR_FNAME EXPR_DOT = :EXPR_DOT EXPR_CLASS = :EXPR_CLASS # for ruby 1.4X if !defined?(Symbol) Symbol = Integer end class Token def initialize(seek, line_no, char_no) @seek = seek @line_no = line_no @char_no = char_no end attr :seek, :line_no, :char_no end class TkNode < Token def initialize(seek, line_no, char_no) super end attr :node end class TkId < Token def initialize(seek, line_no, char_no, name) super(seek, line_no, char_no) @name = name end attr :name end class TkVal < Token def initialize(seek, line_no, char_no, value = nil) super(seek, line_no, char_no) @value = value end attr :value end class TkOp < Token attr_accessor :name end class TkOPASGN < TkOp def initialize(seek, line_no, char_no, op) super(seek, line_no, char_no) op = TkReading2Token[op][0] unless op.kind_of?(Symbol) @op = op end attr :op end class TkUnknownChar < Token def initialize(seek, line_no, char_no, id) super(seek, line_no, char_no) @name = name end attr :name end class TkError < Token end def Token(token, value = nil) case token when String if (tk = TkReading2Token[token]).nil? IRB.fail TkReading2TokenNoKey, token end tk = Token(tk[0], value) if tk.kind_of?(TkOp) tk.name = token end return tk when Symbol if (tk = TkSymbol2Token[token]).nil? IRB.fail TkSymbol2TokenNoKey, token end return Token(tk[0], value) else if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty? token.new(@prev_seek, @prev_line_no, @prev_char_no) else token.new(@prev_seek, @prev_line_no, @prev_char_no, value) end end end TokenDefinitions = [ [:TkCLASS, TkId, "class", EXPR_CLASS], [:TkMODULE, TkId, "module", EXPR_BEG], [:TkDEF, TkId, "def", EXPR_FNAME], [:TkUNDEF, TkId, "undef", EXPR_FNAME], [:TkBEGIN, TkId, "begin", EXPR_BEG], [:TkRESCUE, TkId, "rescue", EXPR_MID], [:TkENSURE, TkId, "ensure", EXPR_BEG], [:TkEND, TkId, "end", EXPR_END], [:TkIF, TkId, "if", EXPR_BEG, :TkIF_MOD], [:TkUNLESS, TkId, "unless", EXPR_BEG, :TkUNLESS_MOD], [:TkTHEN, TkId, "then", EXPR_BEG], [:TkELSIF, TkId, "elsif", EXPR_BEG], [:TkELSE, TkId, "else", EXPR_BEG], [:TkCASE, TkId, "case", EXPR_BEG], [:TkWHEN, TkId, "when", EXPR_BEG], [:TkWHILE, TkId, "while", EXPR_BEG, :TkWHILE_MOD], [:TkUNTIL, TkId, "until", EXPR_BEG, :TkUNTIL_MOD], [:TkFOR, TkId, "for", EXPR_BEG], [:TkBREAK, TkId, "break", EXPR_END], [:TkNEXT, TkId, "next", EXPR_END], [:TkREDO, TkId, "redo", EXPR_END], [:TkRETRY, TkId, "retry", EXPR_END], [:TkIN, TkId, "in", EXPR_BEG], [:TkDO, TkId, "do", EXPR_BEG], [:TkRETURN, TkId, "return", EXPR_MID], [:TkYIELD, TkId, "yield", EXPR_END], [:TkSUPER, TkId, "super", EXPR_END], [:TkSELF, TkId, "self", EXPR_END], [:TkNIL, TkId, "nil", EXPR_END], [:TkTRUE, TkId, "true", EXPR_END], [:TkFALSE, TkId, "false", EXPR_END], [:TkAND, TkId, "and", EXPR_BEG], [:TkOR, TkId, "or", EXPR_BEG], [:TkNOT, TkId, "not", EXPR_BEG], [:TkIF_MOD, TkId], [:TkUNLESS_MOD, TkId], [:TkWHILE_MOD, TkId], [:TkUNTIL_MOD, TkId], [:TkALIAS, TkId, "alias", EXPR_FNAME], [:TkDEFINED, TkId, "defined?", EXPR_END], [:TklBEGIN, TkId, "BEGIN", EXPR_END], [:TklEND, TkId, "END", EXPR_END], [:Tk__LINE__, TkId, "__LINE__", EXPR_END], [:Tk__FILE__, TkId, "__FILE__", EXPR_END], [:TkIDENTIFIER, TkId], [:TkFID, TkId], [:TkGVAR, TkId], [:TkCVAR, TkId], [:TkIVAR, TkId], [:TkCONSTANT, TkId], [:TkINTEGER, TkVal], [:TkFLOAT, TkVal], [:TkSTRING, TkVal], [:TkXSTRING, TkVal], [:TkREGEXP, TkVal], [:TkSYMBOL, TkVal], [:TkDSTRING, TkNode], [:TkDXSTRING, TkNode], [:TkDREGEXP, TkNode], [:TkNTH_REF, TkNode], [:TkBACK_REF, TkNode], [:TkUPLUS, TkOp, "+@"], [:TkUMINUS, TkOp, "-@"], [:TkPOW, TkOp, "**"], [:TkCMP, TkOp, "<=>"], [:TkEQ, TkOp, "=="], [:TkEQQ, TkOp, "==="], [:TkNEQ, TkOp, "!="], [:TkGEQ, TkOp, ">="], [:TkLEQ, TkOp, "<="], [:TkANDOP, TkOp, "&&"], [:TkOROP, TkOp, "||"], [:TkMATCH, TkOp, "=~"], [:TkNMATCH, TkOp, "!~"], [:TkDOT2, TkOp, ".."], [:TkDOT3, TkOp, "..."], [:TkAREF, TkOp, "[]"], [:TkASET, TkOp, "[]="], [:TkLSHFT, TkOp, "<<"], [:TkRSHFT, TkOp, ">>"], [:TkCOLON2, TkOp], [:TkCOLON3, TkOp], # [:OPASGN, TkOp], # +=, -= etc. # [:TkASSOC, TkOp, "=>"], [:TkQUESTION, TkOp, "?"], #? [:TkCOLON, TkOp, ":"], #: [:TkfLPAREN], # func( # [:TkfLBRACK], # func[ # [:TkfLBRACE], # func{ # [:TkSTAR], # *arg [:TkAMPER], # &arg # [:TkSYMBEG], # :SYMBOL [:TkGT, TkOp, ">"], [:TkLT, TkOp, "<"], [:TkPLUS, TkOp, "+"], [:TkMINUS, TkOp, "-"], [:TkMULT, TkOp, "*"], [:TkDIV, TkOp, "/"], [:TkMOD, TkOp, "%"], [:TkBITOR, TkOp, "|"], [:TkBITXOR, TkOp, "^"], [:TkBITAND, TkOp, "&"], [:TkBITNOT, TkOp, "~"], [:TkNOTOP, TkOp, "!"], [:TkBACKQUOTE, TkOp, "`"], [:TkASSIGN, Token, "="], [:TkDOT, Token, "."], [:TkLPAREN, Token, "("], #(exp) [:TkLBRACK, Token, "["], #[arry] [:TkLBRACE, Token, "{"], #{hash} [:TkRPAREN, Token, ")"], [:TkRBRACK, Token, "]"], [:TkRBRACE, Token, "}"], [:TkCOMMA, Token, ","], [:TkSEMICOLON, Token, ";"], [:TkCOMMENT], [:TkRD_COMMENT], [:TkSPACE], [:TkNL], [:TkEND_OF_SCRIPT], [:TkBACKSLASH, TkUnknownChar, "\\"], [:TkAT, TkUnknownChar, "@"], [:TkDOLLAR, TkUnknownChar, "$"], ] # {reading => token_class} # {reading => [token_class, *opt]} TkReading2Token = {} TkSymbol2Token = {} def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts) token_n = token_n.id2name if token_n.kind_of?(Symbol) if RubyToken.const_defined?(token_n) IRB.fail AlreadyDefinedToken, token_n end token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}") if reading if TkReading2Token[reading] IRB.fail TkReading2TokenDuplicateError, token_n, reading end if opts.empty? TkReading2Token[reading] = [token_c] else TkReading2Token[reading] = [token_c].concat(opts) end end TkSymbol2Token[token_n.intern] = token_c end for defs in TokenDefinitions def_token(*defs) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/frame.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/frame.rb
# # frame.rb - # $Release Version: 0.9$ # $Revision: 22784 $ # by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd) # # -- # # # require "e2mmap" module IRB class Frame extend Exception2MessageMapper def_exception :FrameOverflow, "frame overflow" def_exception :FrameUnderflow, "frame underflow" INIT_STACK_TIMES = 3 CALL_STACK_OFFSET = 3 def initialize @frames = [TOPLEVEL_BINDING] * INIT_STACK_TIMES end def trace_func(event, file, line, id, binding) case event when 'call', 'class' @frames.push binding when 'return', 'end' @frames.pop end end def top(n = 0) bind = @frames[-(n + CALL_STACK_OFFSET)] Fail FrameUnderflow unless bind bind end def bottom(n = 0) bind = @frames[n] Fail FrameOverflow unless bind bind end # singleton functions def Frame.bottom(n = 0) @backtrace.bottom(n) end def Frame.top(n = 0) @backtrace.top(n) end def Frame.sender eval "self", @backtrace.top end @backtrace = Frame.new set_trace_func proc{|event, file, line, id, binding, klass| @backtrace.trace_func(event, file, line, id, binding) } end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/input-method.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/input-method.rb
# # irb/input-method.rb - input methods used irb # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require 'irb/src_encoding' require 'irb/magic-file' module IRB # # InputMethod # StdioInputMethod # FileInputMethod # (ReadlineInputMethod) # STDIN_FILE_NAME = "(line)" class InputMethod @RCS_ID='-$Id: input-method.rb 23985 2009-07-07 11:36:20Z keiju $-' def initialize(file = STDIN_FILE_NAME) @file_name = file end attr_reader :file_name attr_accessor :prompt def gets IRB.fail NotImplementedError, "gets" end public :gets def readable_atfer_eof? false end end class StdioInputMethod < InputMethod def initialize super @line_no = 0 @line = [] @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-") @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-") end def gets print @prompt line = @stdin.gets @line[@line_no += 1] = line end def eof? @stdin.eof? end def readable_atfer_eof? true end def line(line_no) @line[line_no] end def encoding @stdin.external_encoding end end class FileInputMethod < InputMethod def initialize(file) super @io = IRB::MagicFile.open(file) end attr_reader :file_name def eof? @io.eof? end def gets print @prompt l = @io.gets # print @prompt, l l end def encoding @io.external_encoding end end begin require "readline" class ReadlineInputMethod < InputMethod include Readline def initialize super @line_no = 0 @line = [] @eof = false @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-") @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-") end def gets Readline.input = @stdin Readline.output = @stdout if l = readline(@prompt, false) HISTORY.push(l) if !l.empty? @line[@line_no += 1] = l + "\n" else @eof = true l end end def eof? @eof end def readable_atfer_eof? true end def line(line_no) @line[line_no] end def encoding @stdin.external_encoding end end rescue LoadError end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/src_encoding.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/src_encoding.rb
# DO NOT WRITE ANY MAGIC COMMENT HERE. def default_src_encoding return __ENCODING__ end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/inspector.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/inspector.rb
# # irb/inspector.rb - inspect methods # $Release Version: 0.9.6$ # $Revision: 1.19 $ # $Date: 2002/06/11 07:51:31 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB def IRB::Inspector(inspect, init = nil) Inspector.new(inspect, init) end class Inspector def initialize(inspect_proc, init_proc = nil) @init = init_proc @inspect = inspect_proc end def init @init.call if @init end def inspect_value(v) @inspect.call(v) end end INSPECTORS = {} def INSPECTORS.keys_with_inspector(inspector) select{|k,v| v == inspector}.collect{|k, v| k} end # ex) # INSPECTORS.def_inspector(key, init_p=nil){|v| v.inspect} # INSPECTORS.def_inspector([key1,..], init_p=nil){|v| v.inspect} # INSPECTORS.def_inspector(key, inspector) # INSPECTORS.def_inspector([key1,...], inspector) def INSPECTORS.def_inspector(key, arg=nil, &block) # if !block_given? # case arg # when nil, Proc # inspector = IRB::Inspector(init_p) # when Inspector # inspector = init_p # else # IRB.Raise IllegalParameter, init_p # end # init_p = nil # else # inspector = IRB::Inspector(block, init_p) # end if block_given? inspector = IRB::Inspector(block, arg) else inspector = arg end case key when Array for k in key def_inspector(k, inspector) end when Symbol self[key] = inspector self[key.to_s] = inspector when String self[key] = inspector self[key.intern] = inspector else self[key] = inspector end end INSPECTORS.def_inspector([false, :to_s, :raw]){|v| v.to_s} INSPECTORS.def_inspector([true, :p, :inspect]){|v| begin v.inspect rescue NoMethodError puts "(Object doesn't support #inspect)" end } INSPECTORS.def_inspector([:pp, :pretty_inspect], proc{require "pp"}){|v| v.pretty_inspect.chomp} INSPECTORS.def_inspector([:yaml, :YAML], proc{require "yaml"}){|v| begin YAML.dump(v) rescue puts "(can't dump yaml. use inspect)" v.inspect end } INSPECTORS.def_inspector([:marshal, :Marshal, :MARSHAL, Marshal]){|v| Marshal.dump(v) } end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/help.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/help.rb
# # irb/help.rb - print usage module # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # # -- # # # require 'irb/magic-file' module IRB def IRB.print_usage lc = IRB.conf[:LC_MESSAGES] path = lc.find("irb/help-message") space_line = false IRB::MagicFile.open(path){|f| f.each_line do |l| if /^\s*$/ =~ l lc.puts l unless space_line space_line = true next end space_line = false l.sub!(/#.*$/, "") next if /^\s*$/ =~ l lc.puts l end } end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/locale.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/locale.rb
# # irb/locale.rb - internationalization module # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Locale @RCS_ID='-$Id: locale.rb 23985 2009-07-07 11:36:20Z keiju $-' LOCALE_NAME_RE = %r[ (?<language>[[:alpha:]]{2}) (?:_ (?<territory>[[:alpha:]]{2,3}) (?:\. (?<codeset>[^@]+) )? )? (?:@ (?<modifier>.*) )? ]x LOCALE_DIR = "/lc/" @@legacy_encoding_alias_map = {}.freeze def initialize(locale = nil) @lang = @territory = @encoding_name = @modifier = nil @locale = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C" if m = LOCALE_NAME_RE.match(@locale) @lang, @territory, @encoding_name, @modifier = m[:language], m[:territory], m[:codeset], m[:modifier] if @encoding_name begin load 'irb/encoding_aliases.rb'; rescue LoadError; end if @encoding = @@legacy_encoding_alias_map[@encoding_name] warn "%s is obsolete. use %s" % ["#{@lang}_#{@territory}.#{@encoding_name}", "#{@lang}_#{@territory}.#{@encoding.name}"] end @encoding = Encoding.find(@encoding_name) rescue nil end end @encoding ||= (Encoding.find('locale') rescue Encoding::ASCII_8BIT) end attr_reader :lang, :territory, :encoding, :modifieer def String(mes) mes = super(mes) if @encoding mes.encode(@encoding) else mes end end def format(*opts) String(super(*opts)) end def gets(*rs) String(super(*rs)) end def readline(*rs) String(super(*rs)) end def print(*opts) ary = opts.collect{|opt| String(opt)} super(*ary) end def printf(*opts) s = format(*opts) print s end def puts(*opts) ary = opts.collect{|opt| String(opt)} super(*ary) end def require(file, priv = nil) rex = Regexp.new("lc/#{Regexp.quote(file)}\.(so|o|sl|rb)?") return false if $".find{|f| f =~ rex} case file when /\.rb$/ begin load(file, priv) $".push file return true rescue LoadError end when /\.(so|o|sl)$/ return super end begin load(f = file + ".rb") $".push f #" return true rescue LoadError return ruby_require(file) end end alias toplevel_load load def load(file, priv=nil) dir = File.dirname(file) dir = "" if dir == "." base = File.basename(file) if dir[0] == ?/ #/ lc_path = search_file(dir, base) return real_load(lc_path, priv) if lc_path end for path in $: lc_path = search_file(path + "/" + dir, base) return real_load(lc_path, priv) if lc_path end raise LoadError, "No such file to load -- #{file}" end def real_load(path, priv) src = MagicFile.open(path){|f| f.read} if priv eval("self", TOPLEVEL_BINDING).extend(Module.new {eval(src, nil, path)}) else eval(src, TOPLEVEL_BINDING, path) end end private :real_load def find(file , paths = $:) dir = File.dirname(file) dir = "" if dir == "." base = File.basename(file) if dir =~ /^\// return lc_path = search_file(dir, base) else for path in $: if lc_path = search_file(path + "/" + dir, base) return lc_path end end end nil end def search_file(path, file) each_sublocale do |lc| full_path = path + lc_path(file, lc) return full_path if File.exist?(full_path) end nil end private :search_file def lc_path(file = "", lc = @locale) if lc.nil? LOCALE_DIR + file else LOCALE_DIR + @lang + "/" + file end end private :lc_path def each_sublocale if @lang if @territory if @encoding_name yield "#{@lang}_#{@territory}.#{@encoding_name}@#{@modifier}" if @modifier yield "#{@lang}_#{@territory}.#{@encoding_name}" end yield "#{@lang}_#{@territory}@#{@modifier}" if @modifier yield "#{@lang}_#{@territory}" end yield "#{@lang}@#{@modifier}" if @modifier yield "#{@lang}" end yield nil end private :each_sublocale end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/extend-command.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/extend-command.rb
# # irb/extend-command.rb - irb extend command # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB # # IRB extended command # module ExtendCommandBundle EXCB = ExtendCommandBundle NO_OVERRIDE = 0 OVERRIDE_PRIVATE_ONLY = 0x01 OVERRIDE_ALL = 0x02 def irb_exit(ret = 0) irb_context.exit(ret) end def irb_context IRB.CurrentContext end @ALIASES = [ [:context, :irb_context, NO_OVERRIDE], [:conf, :irb_context, NO_OVERRIDE], [:irb_quit, :irb_exit, OVERRIDE_PRIVATE_ONLY], [:exit, :irb_exit, OVERRIDE_PRIVATE_ONLY], [:quit, :irb_exit, OVERRIDE_PRIVATE_ONLY], ] @EXTEND_COMMANDS = [ [:irb_current_working_workspace, :CurrentWorkingWorkspace, "irb/cmd/chws", [:irb_print_working_workspace, OVERRIDE_ALL], [:irb_cwws, OVERRIDE_ALL], [:irb_pwws, OVERRIDE_ALL], # [:irb_cww, OVERRIDE_ALL], # [:irb_pww, OVERRIDE_ALL], [:cwws, NO_OVERRIDE], [:pwws, NO_OVERRIDE], # [:cww, NO_OVERRIDE], # [:pww, NO_OVERRIDE], [:irb_current_working_binding, OVERRIDE_ALL], [:irb_print_working_binding, OVERRIDE_ALL], [:irb_cwb, OVERRIDE_ALL], [:irb_pwb, OVERRIDE_ALL], # [:cwb, NO_OVERRIDE], # [:pwb, NO_OVERRIDE] ], [:irb_change_workspace, :ChangeWorkspace, "irb/cmd/chws", [:irb_chws, OVERRIDE_ALL], # [:irb_chw, OVERRIDE_ALL], [:irb_cws, OVERRIDE_ALL], # [:irb_cw, OVERRIDE_ALL], [:chws, NO_OVERRIDE], # [:chw, NO_OVERRIDE], [:cws, NO_OVERRIDE], # [:cw, NO_OVERRIDE], [:irb_change_binding, OVERRIDE_ALL], [:irb_cb, OVERRIDE_ALL], [:cb, NO_OVERRIDE]], [:irb_workspaces, :Workspaces, "irb/cmd/pushws", [:workspaces, NO_OVERRIDE], [:irb_bindings, OVERRIDE_ALL], [:bindings, NO_OVERRIDE]], [:irb_push_workspace, :PushWorkspace, "irb/cmd/pushws", [:irb_pushws, OVERRIDE_ALL], # [:irb_pushw, OVERRIDE_ALL], [:pushws, NO_OVERRIDE], # [:pushw, NO_OVERRIDE], [:irb_push_binding, OVERRIDE_ALL], [:irb_pushb, OVERRIDE_ALL], [:pushb, NO_OVERRIDE]], [:irb_pop_workspace, :PopWorkspace, "irb/cmd/pushws", [:irb_popws, OVERRIDE_ALL], # [:irb_popw, OVERRIDE_ALL], [:popws, NO_OVERRIDE], # [:popw, NO_OVERRIDE], [:irb_pop_binding, OVERRIDE_ALL], [:irb_popb, OVERRIDE_ALL], [:popb, NO_OVERRIDE]], [:irb_load, :Load, "irb/cmd/load"], [:irb_require, :Require, "irb/cmd/load"], [:irb_source, :Source, "irb/cmd/load", [:source, NO_OVERRIDE]], [:irb, :IrbCommand, "irb/cmd/subirb"], [:irb_jobs, :Jobs, "irb/cmd/subirb", [:jobs, NO_OVERRIDE]], [:irb_fg, :Foreground, "irb/cmd/subirb", [:fg, NO_OVERRIDE]], [:irb_kill, :Kill, "irb/cmd/subirb", [:kill, OVERRIDE_PRIVATE_ONLY]], [:irb_help, :Help, "irb/cmd/help", [:help, NO_OVERRIDE]], ] def self.install_extend_commands for args in @EXTEND_COMMANDS def_extend_command(*args) end end # aliases = [commands_alias, flag], ... def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases) case cmd_class when Symbol cmd_class = cmd_class.id2name when String when Class cmd_class = cmd_class.name end if load_file eval %[ def #{cmd_name}(*opts, &b) require "#{load_file}" arity = ExtendCommand::#{cmd_class}.instance_method(:execute).arity args = (1..arity.abs).map {|i| "arg" + i.to_s } args << "*opts" if arity < 0 args << "&block" args = args.join(", ") eval %[ def #{cmd_name}(\#{args}) ExtendCommand::#{cmd_class}.execute(irb_context, \#{args}) end ] send :#{cmd_name}, *opts, &b end ] else eval %[ def #{cmd_name}(*opts, &b) ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b) end ] end for ali, flag in aliases @ALIASES.push [ali, cmd_name, flag] end end # override = {NO_OVERRIDE, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL} def install_alias_method(to, from, override = NO_OVERRIDE) to = to.id2name unless to.kind_of?(String) from = from.id2name unless from.kind_of?(String) if override == OVERRIDE_ALL or (override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or (override == NO_OVERRIDE) && !respond_to?(to, true) target = self (class<<self;self;end).instance_eval{ if target.respond_to?(to, true) && !target.respond_to?(EXCB.irb_original_method_name(to), true) alias_method(EXCB.irb_original_method_name(to), to) end alias_method to, from } else print "irb: warn: can't alias #{to} from #{from}.\n" end end def self.irb_original_method_name(method_name) "irb_" + method_name + "_org" end def self.extend_object(obj) unless (class<<obj;ancestors;end).include?(EXCB) super for ali, com, flg in @ALIASES obj.install_alias_method(ali, com, flg) end end end install_extend_commands end # extension support for Context module ContextExtender CE = ContextExtender @EXTEND_COMMANDS = [ [:eval_history=, "irb/ext/history.rb"], [:use_tracer=, "irb/ext/tracer.rb"], [:math_mode=, "irb/ext/math-mode.rb"], [:use_loader=, "irb/ext/use-loader.rb"], [:save_history=, "irb/ext/save-history.rb"], ] def self.install_extend_commands for args in @EXTEND_COMMANDS def_extend_command(*args) end end def self.def_extend_command(cmd_name, load_file, *aliases) Context.module_eval %[ def #{cmd_name}(*opts, &b) Context.module_eval {remove_method(:#{cmd_name})} require "#{load_file}" send :#{cmd_name}, *opts, &b end for ali in aliases alias_method ali, cmd_name end ] end CE.install_extend_commands end module MethodExtender def def_pre_proc(base_method, extend_method) base_method = base_method.to_s extend_method = extend_method.to_s alias_name = new_alias_name(base_method) module_eval %[ alias_method alias_name, base_method def #{base_method}(*opts) send :#{extend_method}, *opts send :#{alias_name}, *opts end ] end def def_post_proc(base_method, extend_method) base_method = base_method.to_s extend_method = extend_method.to_s alias_name = new_alias_name(base_method) module_eval %[ alias_method alias_name, base_method def #{base_method}(*opts) send :#{alias_name}, *opts send :#{extend_method}, *opts end ] end # return #{prefix}#{name}#{postfix}<num> def new_alias_name(name, prefix = "__alias_of__", postfix = "__") base_name = "#{prefix}#{name}#{postfix}" all_methods = instance_methods(true) + private_instance_methods(true) same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/) return base_name if same_methods.empty? no = same_methods.size while !same_methods.include?(alias_name = base_name + no) no += 1 end alias_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/tools/jruby-1.5.1/lib/ruby/1.9/irb/ruby-lex.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ruby-lex.rb
# # irb/ruby-lex.rb - ruby lexcal analyzer # $Release Version: 0.9.6$ # $Revision: 24555 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/slex" require "irb/ruby-token" class RubyLex @RCS_ID='-$Id: ruby-lex.rb 24555 2009-08-16 12:32:35Z naruse $-' extend Exception2MessageMapper def_exception(:AlreadyDefinedToken, "Already defined token(%s)") def_exception(:TkReading2TokenNoKey, "key nothing(key='%s')") def_exception(:TkSymbol2TokenNoKey, "key nothing(key='%s')") def_exception(:TkReading2TokenDuplicateError, "key duplicate(token_n='%s', key='%s')") def_exception(:SyntaxError, "%s") def_exception(:TerminateLineInput, "Terminate Line Input") include RubyToken class << self attr_accessor :debug_level def debug? @debug_level > 0 end end @debug_level = 0 def initialize lex_init set_input(STDIN) @seek = 0 @exp_line_no = @line_no = 1 @base_char_no = 0 @char_no = 0 @rests = [] @readed = [] @here_readed = [] @indent = 0 @indent_stack = [] @lex_state = EXPR_BEG @space_seen = false @here_header = false @continue = false @line = "" @skip_space = false @readed_auto_clean_up = false @exception_on_syntax_error = true @prompt = nil end attr_accessor :skip_space attr_accessor :readed_auto_clean_up attr_accessor :exception_on_syntax_error attr_reader :seek attr_reader :char_no attr_reader :line_no attr_reader :indent # io functions def set_input(io, p = nil, &block) @io = io if p.respond_to?(:call) @input = p elsif block_given? @input = block else @input = Proc.new{@io.gets} end end def get_readed if idx = @readed.reverse.index("\n") @base_char_no = idx else @base_char_no += @readed.size end readed = @readed.join("") @readed = [] readed end def getc while @rests.empty? # return nil unless buf_input @rests.push nil unless buf_input end c = @rests.shift return if c == nil if @here_header @here_readed.push c else @readed.push c end @seek += 1 if c == "\n" @line_no += 1 @char_no = 0 else @char_no += 1 end c end def gets l = "" while c = getc l.concat(c) break if c == "\n" end return nil if l == "" and c.nil? l end def eof? @io.eof? end def getc_of_rests if @rests.empty? nil else getc end end def ungetc(c = nil) if @here_readed.empty? c2 = @readed.pop else c2 = @here_readed.pop end c = c2 unless c @rests.unshift c #c = @seek -= 1 if c == "\n" @line_no -= 1 if idx = @readed.reverse.index("\n") @char_no = @readed.size - idx else @char_no = @base_char_no + @readed.size end else @char_no -= 1 end end def peek_equal?(str) chrs = str.split(//) until @rests.size >= chrs.size return false unless buf_input end @rests[0, chrs.size] == chrs end def peek_match?(regexp) while @rests.empty? return false unless buf_input end regexp =~ @rests.join("") end def peek(i = 0) while @rests.size <= i return nil unless buf_input end @rests[i] end def buf_input prompt line = @input.call return nil unless line @rests.concat line.chars.to_a true end private :buf_input def set_prompt(p = nil, &block) p = block if block_given? if p.respond_to?(:call) @prompt = p else @prompt = Proc.new{print p} end end def prompt if @prompt @prompt.call(@ltype, @indent, @continue, @line_no) end end def initialize_input @ltype = nil @quoted = nil @indent = 0 @indent_stack = [] @lex_state = EXPR_BEG @space_seen = false @here_header = false @continue = false prompt @line = "" @exp_line_no = @line_no end def each_top_level_statement initialize_input catch(:TERM_INPUT) do loop do begin @continue = false prompt unless l = lex throw :TERM_INPUT if @line == '' else @line.concat l if @ltype or @continue or @indent > 0 next end end if @line != "\n" @line.force_encoding(@io.encoding) yield @line, @exp_line_no end break unless l @line = '' @exp_line_no = @line_no @indent = 0 @indent_stack = [] prompt rescue TerminateLineInput initialize_input prompt get_readed end end end end def lex until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) && !@continue or tk.nil?) #p tk #p @lex_state #p self end line = get_readed # print self.inspect if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil? nil else line end end def token # require "tracer" # Tracer.on @prev_seek = @seek @prev_line_no = @line_no @prev_char_no = @char_no begin begin tk = @OP.match(self) @space_seen = tk.kind_of?(TkSPACE) rescue SyntaxError raise if @exception_on_syntax_error tk = TkError.new(@seek, @line_no, @char_no) end end while @skip_space and tk.kind_of?(TkSPACE) if @readed_auto_clean_up get_readed end # Tracer.off tk end ENINDENT_CLAUSE = [ "case", "class", "def", "do", "for", "if", "module", "unless", "until", "while", "begin" #, "when" ] DEINDENT_CLAUSE = ["end" #, "when" ] PERCENT_LTYPE = { "q" => "\'", "Q" => "\"", "x" => "\`", "r" => "/", "w" => "]", "W" => "]", "s" => ":" } PERCENT_PAREN = { "{" => "}", "[" => "]", "<" => ">", "(" => ")" } Ltype2Token = { "\'" => TkSTRING, "\"" => TkSTRING, "\`" => TkXSTRING, "/" => TkREGEXP, "]" => TkDSTRING, ":" => TkSYMBOL } DLtype2Token = { "\"" => TkDSTRING, "\`" => TkDXSTRING, "/" => TkDREGEXP, } def lex_init() @OP = IRB::SLex.new @OP.def_rules("\0", "\004", "\032") do |op, io| Token(TkEND_OF_SCRIPT) end @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io| @space_seen = true while getc =~ /[ \t\f\r\13]/; end ungetc Token(TkSPACE) end @OP.def_rule("#") do |op, io| identify_comment end @OP.def_rule("=begin", proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do |op, io| @ltype = "=" until getc == "\n"; end until peek_equal?("=end") && peek(4) =~ /\s/ until getc == "\n"; end end gets @ltype = nil Token(TkRD_COMMENT) end @OP.def_rule("\n") do |op, io| print "\\n\n" if RubyLex.debug? case @lex_state when EXPR_BEG, EXPR_FNAME, EXPR_DOT @continue = true else @continue = false @lex_state = EXPR_BEG until (@indent_stack.empty? || [TkLPAREN, TkLBRACK, TkLBRACE, TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) @indent_stack.pop end end @here_header = false @here_readed = [] Token(TkNL) end @OP.def_rules("*", "**", "=", "==", "===", "=~", "<=>", "<", "<=", ">", ">=", ">>", "!", "!=", "!~") do |op, io| case @lex_state when EXPR_FNAME, EXPR_DOT @lex_state = EXPR_ARG else @lex_state = EXPR_BEG end Token(op) end @OP.def_rules("<<") do |op, io| tk = nil if @lex_state != EXPR_END && @lex_state != EXPR_CLASS && (@lex_state != EXPR_ARG || @space_seen) c = peek(0) if /\S/ =~ c && (/["'`]/ =~ c || /\w/ =~ c || c == "-") tk = identify_here_document end end unless tk tk = Token(op) case @lex_state when EXPR_FNAME, EXPR_DOT @lex_state = EXPR_ARG else @lex_state = EXPR_BEG end end tk end @OP.def_rules("'", '"') do |op, io| identify_string(op) end @OP.def_rules("`") do |op, io| if @lex_state == EXPR_FNAME @lex_state = EXPR_END Token(op) else identify_string(op) end end @OP.def_rules('?') do |op, io| if @lex_state == EXPR_END @lex_state = EXPR_BEG Token(TkQUESTION) else ch = getc if @lex_state == EXPR_ARG && ch =~ /\s/ ungetc @lex_state = EXPR_BEG; Token(TkQUESTION) else if (ch == '\\') read_escape end @lex_state = EXPR_END Token(TkINTEGER) end end end @OP.def_rules("&", "&&", "|", "||") do |op, io| @lex_state = EXPR_BEG Token(op) end @OP.def_rules("+=", "-=", "*=", "**=", "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do |op, io| @lex_state = EXPR_BEG op =~ /^(.*)=$/ Token(TkOPASGN, $1) end @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token(op) end @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token(op) end @OP.def_rules("+", "-") do |op, io| catch(:RET) do if @lex_state == EXPR_ARG if @space_seen and peek(0) =~ /[0-9]/ throw :RET, identify_number else @lex_state = EXPR_BEG end elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/ throw :RET, identify_number else @lex_state = EXPR_BEG end Token(op) end end @OP.def_rule(".") do |op, io| @lex_state = EXPR_BEG if peek(0) =~ /[0-9]/ ungetc identify_number else # for "obj.if" etc. @lex_state = EXPR_DOT Token(TkDOT) end end @OP.def_rules("..", "...") do |op, io| @lex_state = EXPR_BEG Token(op) end lex_int2 end def lex_int2 @OP.def_rules("]", "}", ")") do |op, io| @lex_state = EXPR_END @indent -= 1 @indent_stack.pop Token(op) end @OP.def_rule(":") do |op, io| if @lex_state == EXPR_END || peek(0) =~ /\s/ @lex_state = EXPR_BEG Token(TkCOLON) else @lex_state = EXPR_FNAME; Token(TkSYMBEG) end end @OP.def_rule("::") do |op, io| # p @lex_state.id2name, @space_seen if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen @lex_state = EXPR_BEG Token(TkCOLON3) else @lex_state = EXPR_DOT Token(TkCOLON2) end end @OP.def_rule("/") do |op, io| if @lex_state == EXPR_BEG || @lex_state == EXPR_MID identify_string(op) elsif peek(0) == '=' getc @lex_state = EXPR_BEG Token(TkOPASGN, "/") #/) elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ identify_string(op) else @lex_state = EXPR_BEG Token("/") #/) end end @OP.def_rules("^") do |op, io| @lex_state = EXPR_BEG Token("^") end # @OP.def_rules("^=") do # @lex_state = EXPR_BEG # Token(OP_ASGN, :^) # end @OP.def_rules(",") do |op, io| @lex_state = EXPR_BEG Token(op) end @OP.def_rules(";") do |op, io| @lex_state = EXPR_BEG until (@indent_stack.empty? || [TkLPAREN, TkLBRACK, TkLBRACE, TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) @indent_stack.pop end Token(op) end @OP.def_rule("~") do |op, io| @lex_state = EXPR_BEG Token("~") end @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_BEG Token("~") end @OP.def_rule("(") do |op, io| @indent += 1 if @lex_state == EXPR_BEG || @lex_state == EXPR_MID @lex_state = EXPR_BEG tk_c = TkfLPAREN else @lex_state = EXPR_BEG tk_c = TkLPAREN end @indent_stack.push tk_c tk = Token(tk_c) end @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token("[]") end @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token("[]=") end @OP.def_rule("[") do |op, io| @indent += 1 if @lex_state == EXPR_FNAME tk_c = TkfLBRACK else if @lex_state == EXPR_BEG || @lex_state == EXPR_MID tk_c = TkLBRACK elsif @lex_state == EXPR_ARG && @space_seen tk_c = TkLBRACK else tk_c = TkfLBRACK end @lex_state = EXPR_BEG end @indent_stack.push tk_c Token(tk_c) end @OP.def_rule("{") do |op, io| @indent += 1 if @lex_state != EXPR_END && @lex_state != EXPR_ARG tk_c = TkLBRACE else tk_c = TkfLBRACE end @lex_state = EXPR_BEG @indent_stack.push tk_c Token(tk_c) end @OP.def_rule('\\') do |op, io| if getc == "\n" @space_seen = true @continue = true Token(TkSPACE) else ungetc Token("\\") end end @OP.def_rule('%') do |op, io| if @lex_state == EXPR_BEG || @lex_state == EXPR_MID identify_quotation elsif peek(0) == '=' getc Token(TkOPASGN, :%) elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ identify_quotation else @lex_state = EXPR_BEG Token("%") #)) end end @OP.def_rule('$') do |op, io| identify_gvar end @OP.def_rule('@') do |op, io| if peek(0) =~ /[\w_@]/ ungetc identify_identifier else Token("@") end end # @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do # |op, io| # @indent += 1 # @lex_state = EXPR_FNAME # # @lex_state = EXPR_END # # until @rests[0] == "\n" or @rests[0] == ";" # # rests.shift # # end # end @OP.def_rule("") do |op, io| printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug? if peek(0) =~ /[0-9]/ t = identify_number elsif peek(0) =~ /\w/ t = identify_identifier end printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug? t end p @OP if RubyLex.debug? end def identify_gvar @lex_state = EXPR_END case ch = getc when /[~_*$?!@\/\\;,=:<>".]/ #" Token(TkGVAR, "$" + ch) when "-" Token(TkGVAR, "$-" + getc) when "&", "`", "'", "+" Token(TkBACK_REF, "$"+ch) when /[1-9]/ while getc =~ /[0-9]/; end ungetc Token(TkNTH_REF) when /\w/ ungetc ungetc identify_identifier else ungetc Token("$") end end def identify_identifier token = "" if peek(0) =~ /[$@]/ token.concat(c = getc) if c == "@" and peek(0) == "@" token.concat getc end end while (ch = getc) =~ /\w|_/ print ":", ch, ":" if RubyLex.debug? token.concat ch end ungetc if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "=" token.concat getc end # almost fix token case token when /^\$/ return Token(TkGVAR, token) when /^\@\@/ @lex_state = EXPR_END # p Token(TkCVAR, token) return Token(TkCVAR, token) when /^\@/ @lex_state = EXPR_END return Token(TkIVAR, token) end if @lex_state != EXPR_DOT print token, "\n" if RubyLex.debug? token_c, *trans = TkReading2Token[token] if token_c # reserved word? if (@lex_state != EXPR_BEG && @lex_state != EXPR_FNAME && trans[1]) # modifiers token_c = TkSymbol2Token[trans[1]] @lex_state = trans[0] else if @lex_state != EXPR_FNAME if ENINDENT_CLAUSE.include?(token) # check for ``class = val'' etc. valid = true case token when "class" valid = false unless peek_match?(/^\s*(<<|\w|::)/) when "def" valid = false if peek_match?(/^\s*(([+\-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/) when "do" valid = false if peek_match?(/^\s*([+\-\/*]?=|\*|<|>|\&)/) when *ENINDENT_CLAUSE valid = false if peek_match?(/^\s*([+\-\/*]?=|\*|<|>|\&|\|)/) else # no nothing end if valid if token == "do" if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last) @indent += 1 @indent_stack.push token_c end else @indent += 1 @indent_stack.push token_c end # p @indent_stack end elsif DEINDENT_CLAUSE.include?(token) @indent -= 1 @indent_stack.pop end @lex_state = trans[0] else @lex_state = EXPR_END end end return Token(token_c, token) end end if @lex_state == EXPR_FNAME @lex_state = EXPR_END if peek(0) == '=' token.concat getc end elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT @lex_state = EXPR_ARG else @lex_state = EXPR_END end if token[0, 1] =~ /[A-Z]/ return Token(TkCONSTANT, token) elsif token[token.size - 1, 1] =~ /[!?]/ return Token(TkFID, token) else return Token(TkIDENTIFIER, token) end end def identify_here_document ch = getc # if lt = PERCENT_LTYPE[ch] if ch == "-" ch = getc indent = true end if /['"`]/ =~ ch lt = ch quoted = "" while (c = getc) && c != lt quoted.concat c end else lt = '"' quoted = ch.dup while (c = getc) && c =~ /\w/ quoted.concat c end ungetc end ltback, @ltype = @ltype, lt reserve = [] while ch = getc reserve.push ch if ch == "\\" reserve.push ch = getc elsif ch == "\n" break end end @here_header = false while l = gets l = l.sub(/(:?\r)?\n\z/, '') if (indent ? l.strip : l) == quoted break end end @here_header = true @here_readed.concat reserve while ch = reserve.pop ungetc ch end @ltype = ltback @lex_state = EXPR_END Token(Ltype2Token[lt]) end def identify_quotation ch = getc if lt = PERCENT_LTYPE[ch] ch = getc elsif ch =~ /\W/ lt = "\"" else RubyLex.fail SyntaxError, "unknown type of %string" end # if ch !~ /\W/ # ungetc # next # end #@ltype = lt @quoted = ch unless @quoted = PERCENT_PAREN[ch] identify_string(lt, @quoted) end def identify_number @lex_state = EXPR_END if peek(0) == "0" && peek(1) !~ /[.eE]/ getc case peek(0) when /[xX]/ ch = getc match = /[0-9a-fA-F_]/ when /[bB]/ ch = getc match = /[01_]/ when /[oO]/ ch = getc match = /[0-7_]/ when /[dD]/ ch = getc match = /[0-9_]/ when /[0-7]/ match = /[0-7_]/ when /[89]/ RubyLex.fail SyntaxError, "Invalid octal digit" else return Token(TkINTEGER) end len0 = true non_digit = false while ch = getc if match =~ ch if ch == "_" if non_digit RubyLex.fail SyntaxError, "trailing `#{ch}' in number" else non_digit = ch end else non_digit = false len0 = false end else ungetc if len0 RubyLex.fail SyntaxError, "numeric literal without digits" end if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end break end end return Token(TkINTEGER) end type = TkINTEGER allow_point = true allow_e = true non_digit = false while ch = getc case ch when /[0-9]/ non_digit = false when "_" non_digit = ch when allow_point && "." if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end type = TkFLOAT if peek(0) !~ /[0-9]/ type = TkINTEGER ungetc break end allow_point = false when allow_e && "e", allow_e && "E" if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end type = TkFLOAT if peek(0) =~ /[+-]/ getc end allow_e = false allow_point = false non_digit = ch else if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end ungetc break end end Token(type) end def identify_string(ltype, quoted = ltype) @ltype = ltype @quoted = quoted subtype = nil begin nest = 0 while ch = getc if @quoted == ch and nest == 0 break elsif ch == "#" and peek(0) == "{" identify_string_dvar elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#" subtype = true elsif ch == '\\' and @ltype == "'" #' case ch = getc when "\\", "\n", "'" else ungetc end elsif ch == '\\' #' read_escape end if PERCENT_PAREN.values.include?(@quoted) if PERCENT_PAREN[ch] == @quoted nest += 1 elsif ch == @quoted nest -= 1 end end end if @ltype == "/" if peek(0) =~ /i|m|x|o|e|s|u|n/ getc end end if subtype Token(DLtype2Token[ltype]) else Token(Ltype2Token[ltype]) end ensure @ltype = nil @quoted = nil @lex_state = EXPR_END end end def identify_string_dvar begin getc reserve_continue = @continue reserve_ltype = @ltype reserve_indent = @indent reserve_indent_stack = @indent_stack reserve_state = @lex_state reserve_quoted = @quoted @ltype = nil @quoted = nil @indent = 0 @indent_stack = [] @lex_state = EXPR_BEG loop do @continue = false prompt tk = token if @ltype or @continue or @indent > 0 next end break if tk.kind_of?(TkRBRACE) end ensure @continue = reserve_continue @ltype = reserve_ltype @indent = reserve_indent @indent_stack = reserve_indent_stack @lex_state = reserve_state @quoted = reserve_quoted end end def identify_comment @ltype = "#" while ch = getc # if ch == "\\" #" # read_escape # end if ch == "\n" @ltype = nil ungetc break end end return Token(TkCOMMENT) end def read_escape case ch = getc when "\n", "\r", "\f" when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #" when /[0-7]/ ungetc ch 3.times do case ch = getc when /[0-7]/ when nil break else ungetc break end end when "x" 2.times do case ch = getc when /[0-9a-fA-F]/ when nil break else ungetc break end end when "M" if (ch = getc) != '-' ungetc else if (ch = getc) == "\\" #" read_escape end end when "C", "c" #, "^" if ch == "C" and (ch = getc) != "-" ungetc elsif (ch = getc) == "\\" #" read_escape end else # other characters end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/notifier.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/notifier.rb
# # notifier.rb - output methods used by irb # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/output-method" module IRB module Notifier extend Exception2MessageMapper def_exception :ErrUndefinedNotifier, "undefined notifier level: %d is specified" def_exception :ErrUnrecognizedLevel, "unrecognized notifier level: %s is specified" def def_notifier(prefix = "", output_method = StdioOutputMethod.new) CompositeNotifier.new(prefix, output_method) end module_function :def_notifier class AbstructNotifier def initialize(prefix, base_notifier) @prefix = prefix @base_notifier = base_notifier end attr_reader :prefix def notify? true end def print(*opts) @base_notifier.print prefix, *opts if notify? end def printn(*opts) @base_notifier.printn prefix, *opts if notify? end def printf(format, *opts) @base_notifier.printf(prefix + format, *opts) if notify? end def puts(*objs) if notify? @base_notifier.puts(*objs.collect{|obj| prefix + obj.to_s}) end end def pp(*objs) if notify? @base_notifier.ppx @prefix, *objs end end def ppx(prefix, *objs) if notify? @base_notifier.ppx @prefix+prefix, *objs end end def exec_if yield(@base_notifier) if notify? end end class CompositeNotifier<AbstructNotifier def initialize(prefix, base_notifier) super @notifiers = [D_NOMSG] @level_notifier = D_NOMSG end attr_reader :notifiers def def_notifier(level, prefix = "") notifier = LeveledNotifier.new(self, level, prefix) @notifiers[level] = notifier notifier end attr_reader :level_notifier alias level level_notifier def level_notifier=(value) case value when AbstructNotifier @level_notifier = value when Integer l = @notifiers[value] Notifier.Raise ErrUndefinedNotifer, value unless l @level_notifier = l else Notifier.Raise ErrUnrecognizedLevel, value unless l end end alias level= level_notifier= end class LeveledNotifier<AbstructNotifier include Comparable def initialize(base, level, prefix) super(prefix, base) @level = level end attr_reader :level def <=>(other) @level <=> other.level end def notify? @base_notifier.level >= self end end class NoMsgNotifier<LeveledNotifier def initialize @base_notifier = nil @level = 0 @prefix = "" end def notify? false end end D_NOMSG = NoMsgNotifier.new end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/slex.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/slex.rb
# # irb/slex.rb - simple lex analyzer # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/notifier" module IRB class SLex @RCS_ID='-$Id: slex.rb 23985 2009-07-07 11:36:20Z keiju $-' extend Exception2MessageMapper def_exception :ErrNodeNothing, "node nothing" def_exception :ErrNodeAlreadyExists, "node already exists" DOUT = Notifier::def_notifier("SLex::") D_WARN = DOUT::def_notifier(1, "Warn: ") D_DEBUG = DOUT::def_notifier(2, "Debug: ") D_DETAIL = DOUT::def_notifier(4, "Detail: ") DOUT.level = Notifier::D_NOMSG def initialize @head = Node.new("") end def def_rule(token, preproc = nil, postproc = nil, &block) D_DETAIL.pp token postproc = block if block_given? node = create(token, preproc, postproc) end def def_rules(*tokens, &block) if block_given? p = block end for token in tokens def_rule(token, nil, p) end end def preproc(token, proc) node = search(token) node.preproc=proc end #$BMW%A%'%C%/(B? def postproc(token) node = search(token, proc) node.postproc=proc end def search(token) @head.search(token.split(//)) end def create(token, preproc = nil, postproc = nil) @head.create_subnode(token.split(//), preproc, postproc) end def match(token) case token when Array when String return match(token.split(//)) else return @head.match_io(token) end ret = @head.match(token) D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect} ret end def inspect format("<SLex: @head = %s>", @head.inspect) end #---------------------------------------------------------------------- # # class Node - # #---------------------------------------------------------------------- class Node # if postproc is nil, this node is an abstract node. # if postproc is non-nil, this node is a real node. def initialize(preproc = nil, postproc = nil) @Tree = {} @preproc = preproc @postproc = postproc end attr_accessor :preproc attr_accessor :postproc def search(chrs, opt = nil) return self if chrs.empty? ch = chrs.shift if node = @Tree[ch] node.search(chrs, opt) else if opt chrs.unshift ch self.create_subnode(chrs) else SLex.fail ErrNodeNothing end end end def create_subnode(chrs, preproc = nil, postproc = nil) if chrs.empty? if @postproc D_DETAIL.pp node SLex.fail ErrNodeAlreadyExists else D_DEBUG.puts "change abstract node to real node." @preproc = preproc @postproc = postproc end return self end ch = chrs.shift if node = @Tree[ch] if chrs.empty? if node.postproc DebugLogger.pp node DebugLogger.pp self DebugLogger.pp ch DebugLogger.pp chrs SLex.fail ErrNodeAlreadyExists else D_WARN.puts "change abstract node to real node" node.preproc = preproc node.postproc = postproc end else node.create_subnode(chrs, preproc, postproc) end else if chrs.empty? node = Node.new(preproc, postproc) else node = Node.new node.create_subnode(chrs, preproc, postproc) end @Tree[ch] = node end node end # # chrs: String # character array # io must have getc()/ungetc(); and ungetc() must be # able to be called arbitrary number of times. # def match(chrs, op = "") D_DETAIL.print "match>: ", chrs, "op:", op, "\n" if chrs.empty? if @preproc.nil? || @preproc.call(op, chrs) DOUT.printf(D_DETAIL, "op1: %s\n", op) @postproc.call(op, chrs) else nil end else ch = chrs.shift if node = @Tree[ch] if ret = node.match(chrs, op+ch) return ret else chrs.unshift ch if @postproc and @preproc.nil? || @preproc.call(op, chrs) DOUT.printf(D_DETAIL, "op2: %s\n", op.inspect) ret = @postproc.call(op, chrs) return ret else return nil end end else chrs.unshift ch if @postproc and @preproc.nil? || @preproc.call(op, chrs) DOUT.printf(D_DETAIL, "op3: %s\n", op) @postproc.call(op, chrs) return "" else return nil end end end end def match_io(io, op = "") if op == "" ch = io.getc if ch == nil return nil end else ch = io.getc_of_rests end if ch.nil? if @preproc.nil? || @preproc.call(op, io) D_DETAIL.printf("op1: %s\n", op) @postproc.call(op, io) else nil end else if node = @Tree[ch] if ret = node.match_io(io, op+ch) ret else io.ungetc ch if @postproc and @preproc.nil? || @preproc.call(op, io) DOUT.exec_if{D_DETAIL.printf "op2: %s\n", op.inspect} @postproc.call(op, io) else nil end end else io.ungetc ch if @postproc and @preproc.nil? || @preproc.call(op, io) D_DETAIL.printf("op3: %s\n", op) @postproc.call(op, io) else nil end end end end end end end if $0 == __FILE__ # Tracer.on case $1 when "1" tr = SLex.new print "0: ", tr.inspect, "\n" tr.def_rule("=") {print "=\n"} print "1: ", tr.inspect, "\n" tr.def_rule("==") {print "==\n"} print "2: ", tr.inspect, "\n" print "case 1:\n" print tr.match("="), "\n" print "case 2:\n" print tr.match("=="), "\n" print "case 3:\n" print tr.match("=>"), "\n" when "2" tr = SLex.new print "0: ", tr.inspect, "\n" tr.def_rule("=") {print "=\n"} print "1: ", tr.inspect, "\n" tr.def_rule("==", proc{false}) {print "==\n"} print "2: ", tr.inspect, "\n" print "case 1:\n" print tr.match("="), "\n" print "case 2:\n" print tr.match("=="), "\n" print "case 3:\n" print tr.match("=>"), "\n" end exit end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/context.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/context.rb
# # irb/context.rb - irb context # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/workspace" require "irb/inspector" module IRB class Context # # Arguments: # input_method: nil -- stdin or readline # String -- File # other -- using this as InputMethod # def initialize(irb, workspace = nil, input_method = nil, output_method = nil) @irb = irb if workspace @workspace = workspace else @workspace = WorkSpace.new end @thread = Thread.current if defined? Thread # @irb_level = 0 # copy of default configuration @ap_name = IRB.conf[:AP_NAME] @rc = IRB.conf[:RC] @load_modules = IRB.conf[:LOAD_MODULES] @use_readline = IRB.conf[:USE_READLINE] self.inspect_mode = IRB.conf[:INSPECT_MODE] self.math_mode = IRB.conf[:MATH_MODE] if IRB.conf[:MATH_MODE] self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRACER] self.use_loader = IRB.conf[:USE_LOADER] if IRB.conf[:USE_LOADER] self.eval_history = IRB.conf[:EVAL_HISTORY] if IRB.conf[:EVAL_HISTORY] @ignore_sigint = IRB.conf[:IGNORE_SIGINT] @ignore_eof = IRB.conf[:IGNORE_EOF] @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT] self.prompt_mode = IRB.conf[:PROMPT_MODE] if IRB.conf[:SINGLE_IRB] or !defined?(JobManager) @irb_name = IRB.conf[:IRB_NAME] else @irb_name = "irb#"+IRB.JobManager.n_jobs.to_s end @irb_path = "(" + @irb_name + ")" case input_method when nil case use_readline? when nil if (defined?(ReadlineInputMethod) && STDIN.tty? && IRB.conf[:PROMPT_MODE] != :INF_RUBY) @io = ReadlineInputMethod.new else @io = StdioInputMethod.new end when false @io = StdioInputMethod.new when true if defined?(ReadlineInputMethod) @io = ReadlineInputMethod.new else @io = StdioInputMethod.new end end when String @io = FileInputMethod.new(input_method) @irb_name = File.basename(input_method) @irb_path = input_method else @io = input_method end self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY] if output_method @output_method = output_method else @output_method = StdioOutputMethod.new end @verbose = IRB.conf[:VERBOSE] @echo = IRB.conf[:ECHO] if @echo.nil? @echo = true end @debug_level = IRB.conf[:DEBUG_LEVEL] end def main @workspace.main end attr_reader :workspace_home attr_accessor :workspace attr_reader :thread attr_accessor :io attr_accessor :irb attr_accessor :ap_name attr_accessor :rc attr_accessor :load_modules attr_accessor :irb_name attr_accessor :irb_path attr_reader :use_readline attr_reader :inspect_mode attr_reader :prompt_mode attr_accessor :prompt_i attr_accessor :prompt_s attr_accessor :prompt_c attr_accessor :prompt_n attr_accessor :auto_indent_mode attr_accessor :return_format attr_accessor :ignore_sigint attr_accessor :ignore_eof attr_accessor :echo attr_accessor :verbose attr_reader :debug_level attr_accessor :back_trace_limit alias use_readline? use_readline alias rc? rc alias ignore_sigint? ignore_sigint alias ignore_eof? ignore_eof alias echo? echo def verbose? if @verbose.nil? if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod) false elsif !STDIN.tty? or @io.kind_of?(FileInputMethod) true else false end end end def prompting? verbose? || (STDIN.tty? && @io.kind_of?(StdioInputMethod) || (defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod))) end attr_reader :last_value def set_last_value(value) @last_value = value @workspace.evaluate self, "_ = IRB.CurrentContext.last_value" end attr_reader :irb_name def prompt_mode=(mode) @prompt_mode = mode pconf = IRB.conf[:PROMPT][mode] @prompt_i = pconf[:PROMPT_I] @prompt_s = pconf[:PROMPT_S] @prompt_c = pconf[:PROMPT_C] @prompt_n = pconf[:PROMPT_N] @return_format = pconf[:RETURN] if ai = pconf.include?(:AUTO_INDENT) @auto_indent_mode = ai else @auto_indent_mode = IRB.conf[:AUTO_INDENT] end end def inspect? @inspect_mode.nil? or @inspect_mode end def file_input? @io.class == FileInputMethod end def inspect_mode=(opt) if i = INSPECTORS[opt] @inspect_mode = opt @inspect_method = i i.init else case opt when nil if INSPECTORS.keys_with_inspector(INSPECTORS[true]).include?(@inspect_mode) self.inspect_mode = false elsif INSPECTORS.keys_with_inspector(INSPECTORS[false]).include?(@inspect_mode) self.inspect_mode = true else puts "Can't switch inspect mode." return end when /^\s*\{.*\}\s*$/ begin inspector = eval "proc#{opt}" rescue Exception puts "Can't switch inspect mode(#{opt})." return end self.inspect_mode = inspector when Proc self.inspect_mode = IRB::Inspector(opt) when Inspector prefix = "usr%d" i = 1 while INSPECTORS[format(prefix, i)]; i += 1; end @inspect_mode = format(prefix, i) @inspect_method = opt INSPECTORS.def_inspector(format(prefix, i), @inspect_method) else puts "Can't switch inspect mode(#{opt})." return end end print "Switch to#{unless @inspect_mode; ' non';end} inspect mode.\n" if verbose? @inspect_mode end def use_readline=(opt) @use_readline = opt print "use readline module\n" if @use_readline end def debug_level=(value) @debug_level = value RubyLex.debug_level = value SLex.debug_level = value end def debug? @debug_level > 0 end def evaluate(line, line_no) @line_no = line_no set_last_value(@workspace.evaluate(self, line, irb_path, line_no)) # @workspace.evaluate("_ = IRB.conf[:MAIN_CONTEXT]._") # @_ = @workspace.evaluate(line, irb_path, line_no) end def inspect_last_value @inspect_method.inspect_value(@last_value) end alias __exit__ exit def exit(ret = 0) IRB.irb_exit(@irb, ret) end NOPRINTING_IVARS = ["@last_value"] NO_INSPECTING_IVARS = ["@irb", "@io"] IDNAME_IVARS = ["@prompt_mode"] alias __inspect__ inspect def inspect array = [] for ivar in instance_variables.sort{|e1, e2| e1 <=> e2} ivar = ivar.to_s name = ivar.sub(/^@(.*)$/, '\1') val = instance_eval(ivar) case ivar when *NOPRINTING_IVARS array.push format("conf.%s=%s", name, "...") when *NO_INSPECTING_IVARS array.push format("conf.%s=%s", name, val.to_s) when *IDNAME_IVARS array.push format("conf.%s=:%s", name, val.id2name) else array.push format("conf.%s=%s", name, val.inspect) end end array.join("\n") end alias __to_s__ to_s alias to_s inspect end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/workspace.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/workspace.rb
# # irb/workspace-binding.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class WorkSpace # create new workspace. set self to main if specified, otherwise # inherit main from TOPLEVEL_BINDING. def initialize(*main) if main[0].kind_of?(Binding) @binding = main.shift elsif IRB.conf[:SINGLE_IRB] @binding = TOPLEVEL_BINDING else case IRB.conf[:CONTEXT_MODE] when 0 # binding in proc on TOPLEVEL_BINDING @binding = eval("proc{binding}.call", TOPLEVEL_BINDING, __FILE__, __LINE__) when 1 # binding in loaded file require "tempfile" f = Tempfile.open("irb-binding") f.print <<EOF $binding = binding EOF f.close load f.path @binding = $binding when 2 # binding in loaded file(thread use) unless defined? BINDING_QUEUE require "thread" IRB.const_set("BINDING_QUEUE", SizedQueue.new(1)) Thread.abort_on_exception = true Thread.start do eval "require \"irb/ws-for-case-2\"", TOPLEVEL_BINDING, __FILE__, __LINE__ end Thread.pass end @binding = BINDING_QUEUE.pop when 3 # binging in function on TOPLEVEL_BINDING(default) @binding = eval("def irb_binding; binding; end; irb_binding", TOPLEVEL_BINDING, __FILE__, __LINE__ - 3) end end if main.empty? @main = eval("self", @binding) else @main = main[0] IRB.conf[:__MAIN__] = @main case @main when Module @binding = eval("IRB.conf[:__MAIN__].module_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__) else begin @binding = eval("IRB.conf[:__MAIN__].instance_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__) rescue TypeError IRB.fail CantChangeBinding, @main.inspect end end end eval("_=nil", @binding) end attr_reader :binding attr_reader :main def evaluate(context, statements, file = __FILE__, line = __LINE__) eval(statements, @binding, file, line) end # error message manipulator def filter_backtrace(bt) case IRB.conf[:CONTEXT_MODE] when 0 return nil if bt =~ /\(irb_local_binding\)/ when 1 if(bt =~ %r!/tmp/irb-binding! or bt =~ %r!irb/.*\.rb! or bt =~ /irb\.rb/) return nil end when 2 return nil if bt =~ /irb\/.*\.rb/ return nil if bt =~ /irb\.rb/ when 3 return nil if bt =~ /irb\/.*\.rb/ return nil if bt =~ /irb\.rb/ bt.sub!(/:\s*in `irb_binding'/, '') end bt end def IRB.delete_caller end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/init.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/init.rb
# # irb/init.rb - irb initialize module # $Release Version: 0.9.6$ # $Revision: 24229 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB # initialize config def IRB.setup(ap_path) IRB.init_config(ap_path) IRB.init_error IRB.parse_opts IRB.run_config IRB.load_modules unless @CONF[:PROMPT][@CONF[:PROMPT_MODE]] IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE]) end end # @CONF default setting def IRB.init_config(ap_path) # class instance variables @TRACER_INITIALIZED = false # default configurations unless ap_path and @CONF[:AP_NAME] ap_path = File.join(File.dirname(File.dirname(__FILE__)), "irb.rb") end @CONF[:AP_NAME] = File::basename(ap_path, ".rb") @CONF[:IRB_NAME] = "irb" @CONF[:IRB_LIB_PATH] = File.dirname(__FILE__) @CONF[:RC] = true @CONF[:LOAD_MODULES] = [] @CONF[:IRB_RC] = nil @CONF[:MATH_MODE] = false @CONF[:USE_READLINE] = false unless defined?(ReadlineInputMethod) @CONF[:INSPECT_MODE] = true @CONF[:USE_TRACER] = false @CONF[:USE_LOADER] = false @CONF[:IGNORE_SIGINT] = true @CONF[:IGNORE_EOF] = false @CONF[:ECHO] = nil @CONF[:VERBOSE] = nil @CONF[:EVAL_HISTORY] = nil @CONF[:SAVE_HISTORY] = nil @CONF[:BACK_TRACE_LIMIT] = 16 @CONF[:PROMPT] = { :NULL => { :PROMPT_I => nil, :PROMPT_N => nil, :PROMPT_S => nil, :PROMPT_C => nil, :RETURN => "%s\n" }, :DEFAULT => { :PROMPT_I => "%N(%m):%03n:%i> ", :PROMPT_N => "%N(%m):%03n:%i> ", :PROMPT_S => "%N(%m):%03n:%i%l ", :PROMPT_C => "%N(%m):%03n:%i* ", :RETURN => "=> %s\n" }, :CLASSIC => { :PROMPT_I => "%N(%m):%03n:%i> ", :PROMPT_N => "%N(%m):%03n:%i> ", :PROMPT_S => "%N(%m):%03n:%i%l ", :PROMPT_C => "%N(%m):%03n:%i* ", :RETURN => "%s\n" }, :SIMPLE => { :PROMPT_I => ">> ", :PROMPT_N => ">> ", :PROMPT_S => nil, :PROMPT_C => "?> ", :RETURN => "=> %s\n" }, :INF_RUBY => { :PROMPT_I => "%N(%m):%03n:%i> ", # :PROMPT_N => "%N(%m):%03n:%i> ", :PROMPT_N => nil, :PROMPT_S => nil, :PROMPT_C => nil, :RETURN => "%s\n", :AUTO_INDENT => true }, :XMP => { :PROMPT_I => nil, :PROMPT_N => nil, :PROMPT_S => nil, :PROMPT_C => nil, :RETURN => " ==>%s\n" } } @CONF[:PROMPT_MODE] = (STDIN.tty? ? :DEFAULT : :NULL) @CONF[:AUTO_INDENT] = false @CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING @CONF[:SINGLE_IRB] = false # @CONF[:LC_MESSAGES] = "en" @CONF[:LC_MESSAGES] = Locale.new @CONF[:AT_EXIT] = [] @CONF[:DEBUG_LEVEL] = 1 end def IRB.init_error @CONF[:LC_MESSAGES].load("irb/error.rb") end FEATURE_IOPT_CHANGE_VERSION = "1.9.0" # option analyzing def IRB.parse_opts load_path = [] while opt = ARGV.shift case opt when "-f" @CONF[:RC] = false when "-m" @CONF[:MATH_MODE] = true when "-d" $DEBUG = true when /^-r(.+)?/ opt = $1 || ARGV.shift @CONF[:LOAD_MODULES].push opt if opt when /^-I(.+)?/ opt = $1 || ARGV.shift load_path.concat(opt.split(File::PATH_SEPARATOR)) if opt when '-U' set_encoding("UTF-8", "UTF-8") when /^-E(.+)?/, /^--encoding(?:=(.+))?/ opt = $1 || ARGV.shift set_encoding(*opt.split(':', 2)) when "--inspect" if /^-/ !~ ARGV.first @CONF[:INSPECT_MODE] = ARGV.shift else @CONF[:INSPECT_MODE] = true end when "--noinspect" @CONF[:INSPECT_MODE] = false when "--readline" @CONF[:USE_READLINE] = true when "--noreadline" @CONF[:USE_READLINE] = false when "--echo" @CONF[:ECHO] = true when "--noecho" @CONF[:ECHO] = false when "--verbose" @CONF[:VERBOSE] = true when "--noverbose" @CONF[:VERBOSE] = false when /^--prompt-mode(?:=(.+))?/, /^--prompt(?:=(.+))?/ opt = $1 || ARGV.shift prompt_mode = opt.upcase.tr("-", "_").intern @CONF[:PROMPT_MODE] = prompt_mode when "--noprompt" @CONF[:PROMPT_MODE] = :NULL when "--inf-ruby-mode" @CONF[:PROMPT_MODE] = :INF_RUBY when "--sample-book-mode", "--simple-prompt" @CONF[:PROMPT_MODE] = :SIMPLE when "--tracer" @CONF[:USE_TRACER] = true when /^--back-trace-limit(?:=(.+))?/ @CONF[:BACK_TRACE_LIMIT] = ($1 || ARGV.shift).to_i when /^--context-mode(?:=(.+))?/ @CONF[:CONTEXT_MODE] = ($1 || ARGV.shift).to_i when "--single-irb" @CONF[:SINGLE_IRB] = true when /^--irb_debug=(?:=(.+))?/ @CONF[:DEBUG_LEVEL] = ($1 || ARGV.shift).to_i when "-v", "--version" print IRB.version, "\n" exit 0 when "-h", "--help" require "irb/help" IRB.print_usage exit 0 when "--" if opt = ARGV.shfit @CONF[:SCRIPT] = opt $0 = opt end break when /^-/ IRB.fail UnrecognizedSwitch, opt else @CONF[:SCRIPT] = opt $0 = opt break end end if RUBY_VERSION >= FEATURE_IOPT_CHANGE_VERSION load_path.collect! do |path| /\A\.\// =~ path ? path : File.expand_path(path) end end $LOAD_PATH.unshift(*load_path) end # running config def IRB.run_config if @CONF[:RC] begin load rc_file rescue LoadError, Errno::ENOENT rescue # StandardError, ScriptError print "load error: #{rc_file}\n" print $!.class, ": ", $!, "\n" for err in $@[0, $@.size - 2] print "\t", err, "\n" end end end end IRBRC_EXT = "rc" def IRB.rc_file(ext = IRBRC_EXT) if !@CONF[:RC_NAME_GENERATOR] rc_file_generators do |rcgen| @CONF[:RC_NAME_GENERATOR] ||= rcgen if File.exist?(rcgen.call(IRBRC_EXT)) @CONF[:RC_NAME_GENERATOR] = rcgen break end end end @CONF[:RC_NAME_GENERATOR].call ext end # enumerate possible rc-file base name generators def IRB.rc_file_generators if irbrc = ENV["IRBRC"] yield proc{|rc| rc == "rc" ? irbrc : irbrc+rc} end if home = ENV["HOME"] yield proc{|rc| home+"/.irb#{rc}"} end home = Dir.pwd yield proc{|rc| home+"/.irb#{rc}"} yield proc{|rc| home+"/irb#{rc.sub(/\A_?/, '.')}"} yield proc{|rc| home+"/_irb#{rc}"} yield proc{|rc| home+"/$irb#{rc}"} end # loading modules def IRB.load_modules for m in @CONF[:LOAD_MODULES] begin require m rescue LoadError => err warn err.backtrace[0] << ":#{err.class}: #{err}" end end end DefaultEncodings = Struct.new(:external, :internal) class << IRB private def set_encoding(extern, intern = nil) verbose, $VERBOSE = $VERBOSE, nil Encoding.default_external = extern unless extern.nil? || extern.empty? Encoding.default_internal = intern unless intern.nil? || intern.empty? @CONF[:ENCODINGS] = IRB::DefaultEncodings.new(extern, intern) [$stdin, $stdout, $stderr].each do |io| io.set_encoding(extern, intern) end @CONF[:LC_MESSAGES].instance_variable_set(:@encoding, extern) ensure $VERBOSE = verbose end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/magic-file.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/magic-file.rb
module IRB class << (MagicFile = Object.new) # see parser_magic_comment in parse.y ENCODING_SPEC_RE = %r"coding\s*[=:]\s*([[:alnum:]\-_]+)" def open(path) io = File.open(path, 'rb') line = io.gets line = io.gets if line[0,2] == "#!" encoding = detect_encoding(line) encoding ||= default_src_encoding io.rewind io.set_encoding(encoding, nil) if block_given? begin return (yield io) ensure io.close end else return io end end private def detect_encoding(line) return unless line[0] == ?# line = line[1..-1] line = $1 if line[/-\*-\s*(.*?)\s*-*-$/] return nil unless ENCODING_SPEC_RE =~ line encoding = $1 return encoding.sub(/-(?:mac|dos|unix)/i, '') end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/nop.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/nop.rb
# # nop.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB module ExtendCommand class Nop @RCS_ID='-$Id: nop.rb 23985 2009-07-07 11:36:20Z keiju $-' def self.execute(conf, *opts) command = new(conf) command.execute(*opts) end def initialize(conf) @irb_context = conf end attr_reader :irb_context def irb @irb_context.irb end def execute(*opts) #nop 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/load.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/load.rb
# # load.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/loader" module IRB module ExtendCommand class Load<Nop include IrbLoader def execute(file_name, priv = nil) # return ruby_load(file_name) unless IRB.conf[:USE_LOADER] return irb_load(file_name, priv) end end class Require<Nop include IrbLoader def execute(file_name) # return ruby_require(file_name) unless IRB.conf[:USE_LOADER] rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?") return false if $".find{|f| f =~ rex} case file_name when /\.rb$/ begin if irb_load(file_name) $".push file_name return true end rescue LoadError end when /\.(so|o|sl)$/ return ruby_require(file_name) end begin irb_load(f = file_name + ".rb") $".push f return true rescue LoadError return ruby_require(file_name) end end end class Source<Nop include IrbLoader def execute(file_name) source_file(file_name) 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/chws.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/chws.rb
# # change-ws.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/change-ws.rb" module IRB module ExtendCommand class CurrentWorkingWorkspace<Nop def execute(*obj) irb_context.main end end class ChangeWorkspace<Nop def execute(*obj) irb_context.change_workspace(*obj) irb_context.main 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/help.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/help.rb
# # help.rb - helper using ri # $Release Version: 0.9.6$ # $Revision: 24227 $ # # -- # # # require 'rdoc/ri/driver' require 'rdoc/ri/util' require "irb/cmd/nop.rb" module IRB module ExtendCommand class Help<Nop begin Ri = RDoc::RI::Driver.new rescue SystemExit else def execute(*names) names.each do |name| begin Ri.get_info_for(name.to_s) rescue RDoc::RI::Error puts $!.message end end nil 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/pushws.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/pushws.rb
# # change-ws.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/workspaces.rb" module IRB module ExtendCommand class Workspaces<Nop def execute(*obj) irb_context.workspaces.collect{|ws| ws.main} end end class PushWorkspace<Workspaces def execute(*obj) irb_context.push_workspace(*obj) super end end class PopWorkspace<Workspaces def execute(*obj) irb_context.pop_workspace(*obj) super 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/fork.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/fork.rb
# # fork.rb - # $Release Version: 0.9.6 $ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # @RCS_ID='-$Id: fork.rb 23985 2009-07-07 11:36:20Z keiju $-' module IRB module ExtendCommand class Fork<Nop def execute(&block) pid = send ExtendCommand.irb_original_method_name("fork") unless pid class<<self alias_method :exit, ExtendCommand.irb_original_method_name('exit') end if iterator? begin yield ensure exit end end end pid 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/subirb.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/cmd/subirb.rb
# multi.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/multi-irb" module IRB module ExtendCommand class IrbCommand<Nop def execute(*obj) IRB.irb(nil, *obj) end end class Jobs<Nop def execute IRB.JobManager end end class Foreground<Nop def execute(key) IRB.JobManager.switch(key) end end class Kill<Nop def execute(*keys) IRB.JobManager.kill(*keys) 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/math-mode.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/math-mode.rb
# # math-mode.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "mathn" module IRB class Context attr_reader :math_mode alias math? math_mode def math_mode=(opt) if @math_mode == true && opt == false IRB.fail CantReturnToNormalMode return end @math_mode = opt if math_mode main.extend Math print "start math mode\n" if verbose? end end def inspect? @inspect_mode.nil? && !@math_mode or @inspect_mode end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/change-ws.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/change-ws.rb
# # irb/ext/cb.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Context def home_workspace if defined? @home_workspace @home_workspace else @home_workspace = @workspace end end def change_workspace(*_main) if _main.empty? @workspace = home_workspace return main end @workspace = WorkSpace.new(_main[0]) if !(class<<main;ancestors;end).include?(ExtendCommandBundle) main.extend ExtendCommandBundle end end # def change_binding(*_main) # back = @workspace # @workspace = WorkSpace.new(*_main) # unless _main.empty? # begin # main.extend ExtendCommandBundle # rescue # print "can't change binding to: ", main.inspect, "\n" # @workspace = back # return nil # end # end # @irb_level += 1 # begin # catch(:SU_EXIT) do # @irb.eval_input # end # ensure # @irb_level -= 1 # @workspace = back # end # end # alias change_workspace change_binding end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/save-history.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/save-history.rb
# save-history.rb - # $Release Version: 0.9.6$ # $Revision: 24229 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "readline" module IRB module HistorySavingAbility @RCS_ID='-$Id: save-history.rb 24229 2009-07-21 15:39:51Z keiju $-' end class Context def init_save_history unless (class<<@io;self;end).include?(HistorySavingAbility) @io.extend(HistorySavingAbility) end end def save_history IRB.conf[:SAVE_HISTORY] end def save_history=(val) IRB.conf[:SAVE_HISTORY] = val if val main_context = IRB.conf[:MAIN_CONTEXT] main_context = self unless main_context main_context.init_save_history end end def history_file IRB.conf[:HISTORY_FILE] end def history_file=(hist) IRB.conf[:HISTORY_FILE] = hist end end module HistorySavingAbility include Readline # def HistorySavingAbility.create_finalizer # proc do # if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0 # if hf = IRB.conf[:HISTORY_FILE] # file = File.expand_path(hf) # end # file = IRB.rc_file("_history") unless file # open(file, 'w' ) do |f| # hist = HISTORY.to_a # f.puts(hist[-num..-1] || hist) # end # end # end # end def HistorySavingAbility.extended(obj) # ObjectSpace.define_finalizer(obj, HistorySavingAbility.create_finalizer) IRB.conf[:AT_EXIT].push proc{obj.save_history} obj.load_history obj end def load_history if history_file = IRB.conf[:HISTORY_FILE] history_file = File.expand_path(history_file) end history_file = IRB.rc_file("_history") unless history_file if File.exist?(history_file) open(history_file) do |f| f.each {|l| HISTORY << l.chomp} end end end def save_history if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0 if history_file = IRB.conf[:HISTORY_FILE] history_file = File.expand_path(history_file) end history_file = IRB.rc_file("_history") unless history_file open(history_file, 'w' ) do |f| hist = HISTORY.to_a f.puts(hist[-num..-1] || hist) 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/tracer.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/tracer.rb
# # irb/lib/tracer.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "tracer" module IRB # initialize tracing function def IRB.initialize_tracer Tracer.verbose = false Tracer.add_filter { |event, file, line, id, binding, *rests| /^#{Regexp.quote(@CONF[:IRB_LIB_PATH])}/ !~ file and File::basename(file) != "irb.rb" } end class Context attr_reader :use_tracer alias use_tracer? use_tracer def use_tracer=(opt) if opt Tracer.set_get_line_procs(@irb_path) { |line_no, *rests| @io.line(line_no) } elsif !opt && @use_tracer Tracer.off end @use_tracer=opt end end class WorkSpace alias __evaluate__ evaluate def evaluate(context, statements, file = nil, line = nil) if context.use_tracer? && file != nil && line != nil Tracer.on begin __evaluate__(context, statements, file, line) ensure Tracer.off end else __evaluate__(context, statements, file || __FILE__, line || __LINE__) end end end IRB.initialize_tracer end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/loader.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/loader.rb
# # loader.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class LoadAbort < Exception;end module IrbLoader @RCS_ID='-$Id: loader.rb 23985 2009-07-07 11:36:20Z keiju $-' alias ruby_load load alias ruby_require require def irb_load(fn, priv = nil) path = search_file_from_ruby_path(fn) raise LoadError, "No such file to load -- #{fn}" unless path load_file(path, priv) end def search_file_from_ruby_path(fn) if /^#{Regexp.quote(File::Separator)}/ =~ fn return fn if File.exist?(fn) return nil end for path in $: if File.exist?(f = File.join(path, fn)) return f end end return nil end def source_file(path) irb.suspend_name(path, File.basename(path)) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) irb.eval_input else begin irb.eval_input rescue LoadAbort print "load abort!!\n" end end end end end end def load_file(path, priv = nil) irb.suspend_name(path, File.basename(path)) do if priv ws = WorkSpace.new(Module.new) else ws = WorkSpace.new end irb.suspend_workspace(ws) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| irb.signal_status(:IN_LOAD) do # p irb.conf if back_io.kind_of?(FileInputMethod) irb.eval_input else begin irb.eval_input rescue LoadAbort print "load abort!!\n" end end end end end end end def old back_io = @io back_path = @irb_path back_name = @irb_name back_scanner = @irb.scanner begin @io = FileInputMethod.new(path) @irb_name = File.basename(path) @irb_path = path @irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) @irb.eval_input else begin @irb.eval_input rescue LoadAbort print "load abort!!\n" end end end ensure @io = back_io @irb_name = back_name @irb_path = back_path @irb.scanner = back_scanner 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/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/use-loader.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/use-loader.rb
# # use-loader.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/load" require "irb/ext/loader" class Object alias __original__load__IRB_use_loader__ load alias __original__require__IRB_use_loader__ require end module IRB module ExtendCommandBundle def irb_load(*opts, &b) ExtendCommand::Load.execute(irb_context, *opts, &b) end def irb_require(*opts, &b) ExtendCommand::Require.execute(irb_context, *opts, &b) end end class Context IRB.conf[:USE_LOADER] = false def use_loader IRB.conf[:USE_LOADER] end alias use_loader? use_loader def use_loader=(opt) if IRB.conf[:USE_LOADER] != opt IRB.conf[:USE_LOADER] = opt if opt if !$".include?("irb/cmd/load") end (class<<@workspace.main;self;end).instance_eval { alias_method :load, :irb_load alias_method :require, :irb_require } else (class<<@workspace.main;self;end).instance_eval { alias_method :load, :__original__load__IRB_use_loader__ alias_method :require, :__original__require__IRB_use_loader__ } end end print "Switch to load/require#{unless use_loader; ' non';end} trace mode.\n" if verbose? opt end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/history.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/history.rb
# # history.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Context NOPRINTING_IVARS.push "@eval_history_values" alias _set_last_value set_last_value def set_last_value(value) _set_last_value(value) # @workspace.evaluate self, "_ = IRB.CurrentContext.last_value" if @eval_history #and !@eval_history_values.equal?(llv) @eval_history_values.push @line_no, @last_value @workspace.evaluate self, "__ = IRB.CurrentContext.instance_eval{@eval_history_values}" end @last_value end attr_reader :eval_history def eval_history=(no) if no if defined?(@eval_history) && @eval_history @eval_history_values.size(no) else @eval_history_values = History.new(no) IRB.conf[:__TMP__EHV__] = @eval_history_values @workspace.evaluate(self, "__ = IRB.conf[:__TMP__EHV__]") IRB.conf.delete(:__TMP_EHV__) end else @eval_history_values = nil end @eval_history = no end end class History @RCS_ID='-$Id: history.rb 23985 2009-07-07 11:36:20Z keiju $-' def initialize(size = 16) @size = size @contents = [] end def size(size) if size != 0 && size < @size @contents = @contents[@size - size .. @size] end @size = size end def [](idx) begin if idx >= 0 @contents.find{|no, val| no == idx}[1] else @contents[idx][1] end rescue NameError nil end end def push(no, val) @contents.push [no, val] @contents.shift if @size != 0 && @contents.size > @size end alias real_inspect inspect def inspect if @contents.empty? return real_inspect end unless (last = @contents.pop)[1].equal?(self) @contents.push last last = nil end str = @contents.collect{|no, val| if val.equal?(self) "#{no} ...self-history..." else "#{no} #{val.inspect}" end }.join("\n") if str == "" str = "Empty." end @contents.push last if last str end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/multi-irb.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/multi-irb.rb
# # irb/multi-irb.rb - multiple irb module # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # IRB.fail CantShiftToMultiIrbMode unless defined?(Thread) require "thread" module IRB # job management class class JobManager @RCS_ID='-$Id: multi-irb.rb 23985 2009-07-07 11:36:20Z keiju $-' def initialize # @jobs = [[thread, irb],...] @jobs = [] @current_job = nil end attr_accessor :current_job def n_jobs @jobs.size end def thread(key) th, irb = search(key) th end def irb(key) th, irb = search(key) irb end def main_thread @jobs[0][0] end def main_irb @jobs[0][1] end def insert(irb) @jobs.push [Thread.current, irb] end def switch(key) th, irb = search(key) IRB.fail IrbAlreadyDead unless th.alive? IRB.fail IrbSwitchedToCurrentThread if th == Thread.current @current_job = irb th.run Thread.stop @current_job = irb(Thread.current) end def kill(*keys) for key in keys th, irb = search(key) IRB.fail IrbAlreadyDead unless th.alive? th.exit end end def search(key) job = case key when Integer @jobs[key] when Irb @jobs.find{|k, v| v.equal?(key)} when Thread @jobs.assoc(key) else @jobs.find{|k, v| v.context.main.equal?(key)} end IRB.fail NoSuchJob, key if job.nil? job end def delete(key) case key when Integer IRB.fail NoSuchJob, key unless @jobs[key] @jobs[key] = nil else catch(:EXISTS) do @jobs.each_index do |i| if @jobs[i] and (@jobs[i][0] == key || @jobs[i][1] == key || @jobs[i][1].context.main.equal?(key)) @jobs[i] = nil throw :EXISTS end end IRB.fail NoSuchJob, key end end until assoc = @jobs.pop; end unless @jobs.empty? @jobs.push assoc end def inspect ary = [] @jobs.each_index do |i| th, irb = @jobs[i] next if th.nil? if th.alive? if th.stop? t_status = "stop" else t_status = "running" end else t_status = "exited" end ary.push format("#%d->%s on %s (%s: %s)", i, irb.context.irb_name, irb.context.main, th, t_status) end ary.join("\n") end end @JobManager = JobManager.new def IRB.JobManager @JobManager end def IRB.CurrentContext IRB.JobManager.irb(Thread.current).context end # invoke multi-irb def IRB.irb(file = nil, *main) workspace = WorkSpace.new(*main) parent_thread = Thread.current Thread.start do begin irb = Irb.new(workspace, file) rescue print "Subirb can't start with context(self): ", workspace.main.inspect, "\n" print "return to main irb\n" Thread.pass Thread.main.wakeup Thread.exit end @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @JobManager.insert(irb) @JobManager.current_job = irb begin system_exit = false catch(:IRB_EXIT) do irb.eval_input end rescue SystemExit system_exit = true raise #fail ensure unless system_exit @JobManager.delete(irb) if parent_thread.alive? @JobManager.current_job = @JobManager.irb(parent_thread) parent_thread.run else @JobManager.current_job = @JobManager.main_irb @JobManager.main_thread.run end end end end Thread.stop @JobManager.current_job = @JobManager.irb(Thread.current) end # class Context # def set_last_value(value) # @last_value = value # @workspace.evaluate "_ = IRB.JobManager.irb(Thread.current).context.last_value" # if @eval_history #and !@__.equal?(@last_value) # @eval_history_values.push @line_no, @last_value # @workspace.evaluate "__ = IRB.JobManager.irb(Thread.current).context.instance_eval{@eval_history_values}" # end # @last_value # end # end # module ExtendCommand # def irb_context # IRB.JobManager.irb(Thread.current).context # end # # alias conf irb_context # end @CONF[:SINGLE_IRB_MODE] = false @JobManager.insert(@CONF[:MAIN_CONTEXT].irb) @JobManager.current_job = @CONF[:MAIN_CONTEXT].irb class Irb def signal_handle unless @context.ignore_sigint? print "\nabort!!\n" if @context.verbose? exit end case @signal_status when :IN_INPUT print "^C\n" IRB.JobManager.thread(self).raise RubyLex::TerminateLineInput when :IN_EVAL IRB.irb_abort(self) when :IN_LOAD IRB.irb_abort(self, LoadAbort) when :IN_IRB # ignore else # ignore other cases as well end end end trap("SIGINT") do @JobManager.current_job.signal_handle Thread.stop end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/workspaces.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/ext/workspaces.rb
# # push-ws.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Context def irb_level workspace_stack.size end def workspaces if defined? @workspaces @workspaces else @workspaces = [] end end def push_workspace(*_main) if _main.empty? if workspaces.empty? print "No other workspace\n" return nil end ws = workspaces.pop workspaces.push @workspace @workspace = ws return workspaces end workspaces.push @workspace @workspace = WorkSpace.new(@workspace.binding, _main[0]) if !(class<<main;ancestors;end).include?(ExtendCommandBundle) main.extend ExtendCommandBundle end end def pop_workspace if workspaces.empty? print "workspace stack empty\n" return end @workspace = workspaces.pop end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/lc/error.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/lc/error.rb
# # irb/lc/error.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" module IRB # exceptions extend Exception2MessageMapper def_exception :UnrecognizedSwitch, "Unrecognized switch: %s" def_exception :NotImplementedError, "Need to define `%s'" def_exception :CantReturnToNormalMode, "Can't return to normal mode." def_exception :IllegalParameter, "Invalid parameter(%s)." def_exception :IrbAlreadyDead, "Irb is already dead." def_exception :IrbSwitchedToCurrentThread, "Switched to current thread." def_exception :NoSuchJob, "No such job(%s)." def_exception :CantShiftToMultiIrbMode, "Can't shift to multi irb mode." def_exception :CantChangeBinding, "Can't change binding to (%s)." def_exception :UndefinedPromptMode, "Undefined prompt mode(%s)." end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/lc/ja/encoding_aliases.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/lc/ja/encoding_aliases.rb
module IRB class Locale @@legacy_encoding_alias_map = { 'ujis' => Encoding::EUC_JP, 'euc' => Encoding::EUC_JP }.freeze end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/irb/lc/ja/error.rb
tools/jruby-1.5.1/lib/ruby/1.9/irb/lc/ja/error.rb
# -*- coding: utf-8 -*- # irb/lc/ja/error.rb - # $Release Version: 0.9.6$ # $Revision: 23985 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" module IRB # exceptions extend Exception2MessageMapper def_exception :UnrecognizedSwitch, 'スイッチ(%s)が分りません' def_exception :NotImplementedError, '`%s\'の定義が必要です' def_exception :CantReturnToNormalMode, 'Normalモードに戻れません.' def_exception :IllegalParameter, 'パラメータ(%s)が間違っています.' def_exception :IrbAlreadyDead, 'Irbは既に死んでいます.' def_exception :IrbSwitchedToCurrentThread, 'カレントスレッドに切り替わりました.' def_exception :NoSuchJob, 'そのようなジョブ(%s)はありません.' def_exception :CantShiftToMultiIrbMode, 'multi-irb modeに移れません.' def_exception :CantChangeBinding, 'バインディング(%s)に変更できません.' def_exception :UndefinedPromptMode, 'プロンプトモード(%s)は定義されていません.' end # vim:fileencoding=utf-8
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/content.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/content.rb
require "rss/rss" module RSS CONTENT_PREFIX = 'content' CONTENT_URI = "http://purl.org/rss/1.0/modules/content/" module ContentModel extend BaseModel ELEMENTS = ["#{CONTENT_PREFIX}_encoded"] def self.append_features(klass) super klass.install_must_call_validator(CONTENT_PREFIX, CONTENT_URI) ELEMENTS.each do |full_name| name = full_name[(CONTENT_PREFIX.size + 1)..-1] klass.install_text_element(name, CONTENT_URI, "?", full_name) end end end prefix_size = CONTENT_PREFIX.size + 1 ContentModel::ELEMENTS.each do |full_name| name = full_name[prefix_size..-1] BaseListener.install_get_text_element(CONTENT_URI, name, full_name) end end require 'rss/content/1.0' require 'rss/content/2.0'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/syndication.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/syndication.rb
require "rss/1.0" module RSS SY_PREFIX = 'sy' SY_URI = "http://purl.org/rss/1.0/modules/syndication/" RDF.install_ns(SY_PREFIX, SY_URI) module SyndicationModel extend BaseModel ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator(SY_PREFIX, SY_URI) klass.module_eval do [ ["updatePeriod"], ["updateFrequency", :positive_integer] ].each do |name, type| install_text_element(name, SY_URI, "?", "#{SY_PREFIX}_#{name}", type, "#{SY_PREFIX}:#{name}") end %w(updateBase).each do |name| install_date_element(name, SY_URI, "?", "#{SY_PREFIX}_#{name}", 'w3cdtf', "#{SY_PREFIX}:#{name}") end end klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) alias_method(:_sy_updatePeriod=, :sy_updatePeriod=) def sy_updatePeriod=(new_value) new_value = new_value.strip validate_sy_updatePeriod(new_value) if @do_validate self._sy_updatePeriod = new_value end EOC end private SY_UPDATEPERIOD_AVAILABLE_VALUES = %w(hourly daily weekly monthly yearly) def validate_sy_updatePeriod(value) unless SY_UPDATEPERIOD_AVAILABLE_VALUES.include?(value) raise NotAvailableValueError.new("updatePeriod", value) end end end class RDF class Channel; include SyndicationModel; end end prefix_size = SY_PREFIX.size + 1 SyndicationModel::ELEMENTS.uniq! SyndicationModel::ELEMENTS.each do |full_name| name = full_name[prefix_size..-1] BaseListener.install_get_text_element(SY_URI, name, full_name) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/converter.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/converter.rb
require "rss/utils" module RSS class Converter include Utils def initialize(to_enc, from_enc=nil) if "".respond_to?(:encode) @to_encoding = to_enc return end normalized_to_enc = to_enc.downcase.gsub(/-/, '_') from_enc ||= 'utf-8' normalized_from_enc = from_enc.downcase.gsub(/-/, '_') if normalized_to_enc == normalized_from_enc def_same_enc() else def_diff_enc = "def_to_#{normalized_to_enc}_from_#{normalized_from_enc}" if respond_to?(def_diff_enc) __send__(def_diff_enc) else def_else_enc(to_enc, from_enc) end end end def convert(value) if value.is_a?(String) and value.respond_to?(:encode) value.encode(@to_encoding) else value end end def def_convert(depth=0) instance_eval(<<-EOC, *get_file_and_line_from_caller(depth)) def convert(value) if value.kind_of?(String) #{yield('value')} else value end end EOC end def def_iconv_convert(to_enc, from_enc, depth=0) begin require "iconv" @iconv = Iconv.new(to_enc, from_enc) def_convert(depth+1) do |value| <<-EOC begin @iconv.iconv(#{value}) rescue Iconv::Failure raise ConversionError.new(#{value}, "#{to_enc}", "#{from_enc}") end EOC end rescue LoadError, ArgumentError, SystemCallError raise UnknownConversionMethodError.new(to_enc, from_enc) end end def def_else_enc(to_enc, from_enc) def_iconv_convert(to_enc, from_enc, 0) end def def_same_enc() def_convert do |value| value end end def def_uconv_convert_if_can(meth, to_enc, from_enc, nkf_arg) begin require "uconv" def_convert(1) do |value| <<-EOC begin Uconv.#{meth}(#{value}) rescue Uconv::Error raise ConversionError.new(#{value}, "#{to_enc}", "#{from_enc}") end EOC end rescue LoadError require 'nkf' if NKF.const_defined?(:UTF8) def_convert(1) do |value| "NKF.nkf(#{nkf_arg.dump}, #{value})" end else def_iconv_convert(to_enc, from_enc, 1) end end end def def_to_euc_jp_from_utf_8 def_uconv_convert_if_can('u8toeuc', 'EUC-JP', 'UTF-8', '-We') end def def_to_utf_8_from_euc_jp def_uconv_convert_if_can('euctou8', 'UTF-8', 'EUC-JP', '-Ew') end def def_to_shift_jis_from_utf_8 def_uconv_convert_if_can('u8tosjis', 'Shift_JIS', 'UTF-8', '-Ws') end def def_to_utf_8_from_shift_jis def_uconv_convert_if_can('sjistou8', 'UTF-8', 'Shift_JIS', '-Sw') end def def_to_euc_jp_from_shift_jis require "nkf" def_convert do |value| "NKF.nkf('-Se', #{value})" end end def def_to_shift_jis_from_euc_jp require "nkf" def_convert do |value| "NKF.nkf('-Es', #{value})" end end def def_to_euc_jp_from_iso_2022_jp require "nkf" def_convert do |value| "NKF.nkf('-Je', #{value})" end end def def_to_iso_2022_jp_from_euc_jp require "nkf" def_convert do |value| "NKF.nkf('-Ej', #{value})" end end def def_to_utf_8_from_iso_8859_1 def_convert do |value| "#{value}.unpack('C*').pack('U*')" end end def def_to_iso_8859_1_from_utf_8 def_convert do |value| <<-EOC array_utf8 = #{value}.unpack('U*') array_enc = [] array_utf8.each do |num| if num <= 0xFF array_enc << num else array_enc.concat "&\#\#{num};".unpack('C*') end end array_enc.pack('C*') EOC 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/taxonomy.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/taxonomy.rb
require "rss/1.0" require "rss/dublincore" module RSS TAXO_PREFIX = "taxo" TAXO_URI = "http://purl.org/rss/1.0/modules/taxonomy/" RDF.install_ns(TAXO_PREFIX, TAXO_URI) TAXO_ELEMENTS = [] %w(link).each do |name| full_name = "#{TAXO_PREFIX}_#{name}" BaseListener.install_get_text_element(TAXO_URI, name, full_name) TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}" end %w(topic topics).each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(TAXO_URI, name, "Taxonomy#{class_name}") TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}" end module TaxonomyTopicsModel extend BaseModel def self.append_features(klass) super klass.install_must_call_validator(TAXO_PREFIX, TAXO_URI) %w(topics).each do |name| klass.install_have_child_element(name, TAXO_URI, "?", "#{TAXO_PREFIX}_#{name}") end end class TaxonomyTopics < Element include RSS10 Bag = ::RSS::RDF::Bag class << self def required_prefix TAXO_PREFIX end def required_uri TAXO_URI end end @tag_name = "topics" install_have_child_element("Bag", RDF::URI, nil) install_must_call_validator('rdf', RDF::URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.Bag = args[0] end self.Bag ||= Bag.new end def full_name tag_name_with_prefix(TAXO_PREFIX) end def maker_target(target) target.taxo_topics end def resources if @Bag @Bag.lis.collect do |li| li.resource end else [] end end end end module TaxonomyTopicModel extend BaseModel def self.append_features(klass) super var_name = "#{TAXO_PREFIX}_topic" klass.install_have_children_element("topic", TAXO_URI, "*", var_name) end class TaxonomyTopic < Element include RSS10 include DublinCoreModel include TaxonomyTopicsModel class << self def required_prefix TAXO_PREFIX end def required_uri TAXO_URI end end @tag_name = "topic" install_get_attribute("about", ::RSS::RDF::URI, true, nil, nil, "#{RDF::PREFIX}:about") install_text_element("link", TAXO_URI, "?", "#{TAXO_PREFIX}_link") def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end def full_name tag_name_with_prefix(TAXO_PREFIX) end def maker_target(target) target.new_taxo_topic end end end class RDF include TaxonomyTopicModel class Channel include TaxonomyTopicsModel end class Item; include TaxonomyTopicsModel; end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker.rb
require "rss/rss" module RSS module Maker MAKERS = {} class << self def make(version, &block) self[version].make(&block) end def [](version) maker_info = maker(version) raise UnsupportedMakerVersionError.new(version) if maker_info.nil? maker_info[:maker] end def add_maker(version, normalized_version, maker) MAKERS[version] = {:maker => maker, :version => normalized_version} end def versions MAKERS.keys.uniq.sort end def makers MAKERS.values.collect {|info| info[:maker]}.uniq end def supported?(version) versions.include?(version) end private # Can I remove this method? def maker(version) MAKERS[version] end end end end require "rss/maker/1.0" require "rss/maker/2.0" require "rss/maker/feed" require "rss/maker/entry" require "rss/maker/content" require "rss/maker/dublincore" require "rss/maker/slash" require "rss/maker/syndication" require "rss/maker/taxonomy" require "rss/maker/trackback" require "rss/maker/image" require "rss/maker/itunes"
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/rexmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/rexmlparser.rb
require "rexml/document" require "rexml/streamlistener" /\A(\d+)\.(\d+)(?:\.\d+)+\z/ =~ REXML::Version if ([$1.to_i, $2.to_i] <=> [2, 5]) < 0 raise LoadError, "needs REXML 2.5 or later (#{REXML::Version})" end module RSS class REXMLParser < BaseParser class << self def listener REXMLListener end end private def _parse begin REXML::Document.parse_stream(@rss, @listener) rescue RuntimeError => e raise NotWellFormedError.new{e.message} rescue REXML::ParseException => e context = e.context line = context[0] if context raise NotWellFormedError.new(line){e.message} end end end class REXMLListener < BaseListener include REXML::StreamListener include ListenerMixin class << self def raise_for_undefined_entity? false end end def xmldecl(version, encoding, standalone) super(version, encoding, standalone == "yes") # Encoding is converted to UTF-8 when REXML parse XML. @encoding = 'UTF-8' end alias_method(:cdata, :text) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/utils.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/utils.rb
module RSS module Utils module_function # Convert a name_with_underscores to CamelCase. def to_class_name(name) name.split(/[_\-]/).collect do |part| "#{part[0, 1].upcase}#{part[1..-1]}" end.join("") end def get_file_and_line_from_caller(i=0) file, line, = caller[i].split(':') line = line.to_i line += 1 if i.zero? [file, line] end # escape '&', '"', '<' and '>' for use in HTML. def html_escape(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end alias h html_escape # If +value+ is an instance of class +klass+, return it, else # create a new instance of +klass+ with value +value+. def new_with_value_if_need(klass, value) if value.is_a?(klass) value else klass.new(value) end end def element_initialize_arguments?(args) [true, false].include?(args[0]) and args[1].is_a?(Hash) end module YesCleanOther module_function def parse(value) if [true, false, nil].include?(value) value else case value.to_s when /\Ayes\z/i true when /\Aclean\z/i false else nil end end end end module YesOther module_function def parse(value) if [true, false].include?(value) value else /\Ayes\z/i.match(value.to_s) ? true : false end end end module CSV module_function def parse(value, &block) if value.is_a?(String) value = value.strip.split(/\s*,\s*/) value = value.collect(&block) if block_given? value else value end end end module InheritedReader def inherited_reader(constant_name) base_class = inherited_base result = base_class.const_get(constant_name) found_base_class = false ancestors.reverse_each do |klass| if found_base_class if klass.const_defined?(constant_name) result = yield(result, klass.const_get(constant_name)) end else found_base_class = klass == base_class end end result end def inherited_array_reader(constant_name) inherited_reader(constant_name) do |result, current| current + result end end def inherited_hash_reader(constant_name) inherited_reader(constant_name) do |result, current| result.merge(current) 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/xml.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/xml.rb
require "rss/utils" module RSS module XML class Element include Enumerable attr_reader :name, :prefix, :uri, :attributes, :children def initialize(name, prefix=nil, uri=nil, attributes={}, children=[]) @name = name @prefix = prefix @uri = uri @attributes = attributes if children.is_a?(String) or !children.respond_to?(:each) @children = [children] else @children = children end end def [](name) @attributes[name] end def []=(name, value) @attributes[name] = value end def <<(child) @children << child end def each(&block) @children.each(&block) end def ==(other) other.kind_of?(self.class) and @name == other.name and @uri == other.uri and @attributes == other.attributes and @children == other.children end def to_s rv = "<#{full_name}" attributes.each do |key, value| rv << " #{Utils.html_escape(key)}=\"#{Utils.html_escape(value)}\"" end if children.empty? rv << "/>" else rv << ">" children.each do |child| rv << child.to_s end rv << "</#{full_name}>" end rv end def full_name if @prefix "#{@prefix}:#{@name}" else @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/tools/jruby-1.5.1/lib/ruby/1.9/rss/parser.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/parser.rb
require "forwardable" require "open-uri" require "rss/rss" require "rss/xml" module RSS class NotWellFormedError < Error attr_reader :line, :element # Create a new NotWellFormedError for an error at +line+ # in +element+. If a block is given the return value of # the block ends up in the error message. def initialize(line=nil, element=nil) message = "This is not well formed XML" if element or line message << "\nerror occurred" message << " in #{element}" if element message << " at about #{line} line" if line end message << "\n#{yield}" if block_given? super(message) end end class XMLParserNotFound < Error def initialize super("available XML parser was not found in " << "#{AVAILABLE_PARSER_LIBRARIES.inspect}.") end end class NotValidXMLParser < Error def initialize(parser) super("#{parser} is not an available XML parser. " << "Available XML parser" << (AVAILABLE_PARSERS.size > 1 ? "s are " : " is ") << "#{AVAILABLE_PARSERS.inspect}.") end end class NSError < InvalidRSSError attr_reader :tag, :prefix, :uri def initialize(tag, prefix, require_uri) @tag, @prefix, @uri = tag, prefix, require_uri super("prefix <#{prefix}> doesn't associate uri " << "<#{require_uri}> in tag <#{tag}>") end end class Parser extend Forwardable class << self @@default_parser = nil def default_parser @@default_parser || AVAILABLE_PARSERS.first end # Set @@default_parser to new_value if it is one of the # available parsers. Else raise NotValidXMLParser error. def default_parser=(new_value) if AVAILABLE_PARSERS.include?(new_value) @@default_parser = new_value else raise NotValidXMLParser.new(new_value) end end def parse(rss, do_validate=true, ignore_unknown_element=true, parser_class=default_parser) parser = new(rss, parser_class) parser.do_validate = do_validate parser.ignore_unknown_element = ignore_unknown_element parser.parse end end def_delegators(:@parser, :parse, :rss, :ignore_unknown_element, :ignore_unknown_element=, :do_validate, :do_validate=) def initialize(rss, parser_class=self.class.default_parser) @parser = parser_class.new(normalize_rss(rss)) end private # Try to get the XML associated with +rss+. # Return +rss+ if it already looks like XML, or treat it as a URI, # or a file to get the XML, def normalize_rss(rss) return rss if maybe_xml?(rss) uri = to_uri(rss) if uri.respond_to?(:read) uri.read elsif !rss.tainted? and File.readable?(rss) File.open(rss) {|f| f.read} else rss end end # maybe_xml? tests if source is a string that looks like XML. def maybe_xml?(source) source.is_a?(String) and /</ =~ source end # Attempt to convert rss to a URI, but just return it if # there's a ::URI::Error def to_uri(rss) return rss if rss.is_a?(::URI::Generic) begin ::URI.parse(rss) rescue ::URI::Error rss end end end class BaseParser class << self def raise_for_undefined_entity? listener.raise_for_undefined_entity? end end def initialize(rss) @listener = self.class.listener.new @rss = rss end def rss @listener.rss end def ignore_unknown_element @listener.ignore_unknown_element end def ignore_unknown_element=(new_value) @listener.ignore_unknown_element = new_value end def do_validate @listener.do_validate end def do_validate=(new_value) @listener.do_validate = new_value end def parse if @listener.rss.nil? _parse end @listener.rss end end class BaseListener extend Utils class << self @@accessor_bases = {} @@registered_uris = {} @@class_names = {} # return the setter for the uri, tag_name pair, or nil. def setter(uri, tag_name) _getter = getter(uri, tag_name) if _getter "#{_getter}=" else nil end end def getter(uri, tag_name) (@@accessor_bases[uri] || {})[tag_name] end # return the tag_names for setters associated with uri def available_tags(uri) (@@accessor_bases[uri] || {}).keys end # register uri against this name. def register_uri(uri, name) @@registered_uris[name] ||= {} @@registered_uris[name][uri] = nil end # test if this uri is registered against this name def uri_registered?(uri, name) @@registered_uris[name].has_key?(uri) end # record class_name for the supplied uri and tag_name def install_class_name(uri, tag_name, class_name) @@class_names[uri] ||= {} @@class_names[uri][tag_name] = class_name end # retrieve class_name for the supplied uri and tag_name # If it doesn't exist, capitalize the tag_name def class_name(uri, tag_name) name = (@@class_names[uri] || {})[tag_name] return name if name tag_name = tag_name.gsub(/[_\-]([a-z]?)/) {$1.upcase} tag_name[0, 1].upcase + tag_name[1..-1] end def install_get_text_element(uri, name, accessor_base) install_accessor_base(uri, name, accessor_base) def_get_text_element(uri, name, *get_file_and_line_from_caller(1)) end def raise_for_undefined_entity? true end private # set the accessor for the uri, tag_name pair def install_accessor_base(uri, tag_name, accessor_base) @@accessor_bases[uri] ||= {} @@accessor_bases[uri][tag_name] = accessor_base.chomp("=") end def def_get_text_element(uri, element_name, file, line) register_uri(uri, element_name) method_name = "start_#{element_name}" unless private_method_defined?(method_name) define_method(method_name) do |name, prefix, attrs, ns| uri = _ns(ns, prefix) if self.class.uri_registered?(uri, element_name) start_get_text_element(name, prefix, ns, uri) else start_else_element(name, prefix, attrs, ns) end end private(method_name) end end end end module ListenerMixin attr_reader :rss attr_accessor :ignore_unknown_element attr_accessor :do_validate def initialize @rss = nil @ignore_unknown_element = true @do_validate = true @ns_stack = [{"xml" => :xml}] @tag_stack = [[]] @text_stack = [''] @proc_stack = [] @last_element = nil @version = @encoding = @standalone = nil @xml_stylesheets = [] @xml_child_mode = false @xml_element = nil @last_xml_element = nil end # set instance vars for version, encoding, standalone def xmldecl(version, encoding, standalone) @version, @encoding, @standalone = version, encoding, standalone end def instruction(name, content) if name == "xml-stylesheet" params = parse_pi_content(content) if params.has_key?("href") @xml_stylesheets << XMLStyleSheet.new(params) end end end def tag_start(name, attributes) @text_stack.push('') ns = @ns_stack.last.dup attrs = {} attributes.each do |n, v| if /\Axmlns(?:\z|:)/ =~ n ns[$POSTMATCH] = v else attrs[n] = v end end @ns_stack.push(ns) prefix, local = split_name(name) @tag_stack.last.push([_ns(ns, prefix), local]) @tag_stack.push([]) if @xml_child_mode previous = @last_xml_element element_attrs = attributes.dup unless previous ns.each do |ns_prefix, value| next if ns_prefix == "xml" key = ns_prefix.empty? ? "xmlns" : "xmlns:#{ns_prefix}" element_attrs[key] ||= value end end next_element = XML::Element.new(local, prefix.empty? ? nil : prefix, _ns(ns, prefix), element_attrs) previous << next_element if previous @last_xml_element = next_element pr = Proc.new do |text, tags| if previous @last_xml_element = previous else @xml_element = @last_xml_element @last_xml_element = nil end end @proc_stack.push(pr) else if @rss.nil? and respond_to?("initial_start_#{local}", true) __send__("initial_start_#{local}", local, prefix, attrs, ns.dup) elsif respond_to?("start_#{local}", true) __send__("start_#{local}", local, prefix, attrs, ns.dup) else start_else_element(local, prefix, attrs, ns.dup) end end end def tag_end(name) if DEBUG p "end tag #{name}" p @tag_stack end text = @text_stack.pop tags = @tag_stack.pop pr = @proc_stack.pop pr.call(text, tags) unless pr.nil? @ns_stack.pop end def text(data) if @xml_child_mode @last_xml_element << data if @last_xml_element else @text_stack.last << data end end private def _ns(ns, prefix) ns.fetch(prefix, "") end CONTENT_PATTERN = /\s*([^=]+)=(["'])([^\2]+?)\2/ # Extract the first name="value" pair from content. # Works with single quotes according to the constant # CONTENT_PATTERN. Return a Hash. def parse_pi_content(content) params = {} content.scan(CONTENT_PATTERN) do |name, quote, value| params[name] = value end params end def start_else_element(local, prefix, attrs, ns) class_name = self.class.class_name(_ns(ns, prefix), local) current_class = @last_element.class if known_class?(current_class, class_name) next_class = current_class.const_get(class_name) start_have_something_element(local, prefix, attrs, ns, next_class) else if !@do_validate or @ignore_unknown_element @proc_stack.push(setup_next_element_in_unknown_element) else parent = "ROOT ELEMENT???" if current_class.tag_name parent = current_class.tag_name end raise NotExpectedTagError.new(local, _ns(ns, prefix), parent) end end end if Module.method(:const_defined?).arity == -1 def known_class?(target_class, class_name) class_name and (target_class.const_defined?(class_name, false) or target_class.constants.include?(class_name.to_sym)) end else def known_class?(target_class, class_name) class_name and (target_class.const_defined?(class_name) or target_class.constants.include?(class_name)) end end NAMESPLIT = /^(?:([\w:][-\w\d.]*):)?([\w:][-\w\d.]*)/ def split_name(name) name =~ NAMESPLIT [$1 || '', $2] end def check_ns(tag_name, prefix, ns, require_uri, ignore_unknown_element=nil) if _ns(ns, prefix) == require_uri true else if ignore_unknown_element.nil? ignore_unknown_element = @ignore_unknown_element end if ignore_unknown_element false elsif @do_validate raise NSError.new(tag_name, prefix, require_uri) else # Force bind required URI with prefix @ns_stack.last[prefix] = require_uri true end end end def start_get_text_element(tag_name, prefix, ns, required_uri) pr = Proc.new do |text, tags| setter = self.class.setter(required_uri, tag_name) if setter and @last_element.respond_to?(setter) if @do_validate getter = self.class.getter(required_uri, tag_name) if @last_element.__send__(getter) raise TooMuchTagError.new(tag_name, @last_element.tag_name) end end @last_element.__send__(setter, text.to_s) else if @do_validate and !@ignore_unknown_element raise NotExpectedTagError.new(tag_name, _ns(ns, prefix), @last_element.tag_name) end end end @proc_stack.push(pr) end def start_have_something_element(tag_name, prefix, attrs, ns, klass) if check_ns(tag_name, prefix, ns, klass.required_uri) attributes = collect_attributes(tag_name, prefix, attrs, ns, klass) @proc_stack.push(setup_next_element(tag_name, klass, attributes)) else @proc_stack.push(setup_next_element_in_unknown_element) end end def collect_attributes(tag_name, prefix, attrs, ns, klass) attributes = {} klass.get_attributes.each do |a_name, a_uri, required, element_name| if a_uri.is_a?(String) or !a_uri.respond_to?(:include?) a_uri = [a_uri] end unless a_uri == [""] for prefix, uri in ns if a_uri.include?(uri) val = attrs["#{prefix}:#{a_name}"] break if val end end end if val.nil? and a_uri.include?("") val = attrs[a_name] end if @do_validate and required and val.nil? unless a_uri.include?("") for prefix, uri in ns if a_uri.include?(uri) a_name = "#{prefix}:#{a_name}" end end end raise MissingAttributeError.new(tag_name, a_name) end attributes[a_name] = val end attributes end def setup_next_element(tag_name, klass, attributes) previous = @last_element next_element = klass.new(@do_validate, attributes) previous.set_next_element(tag_name, next_element) @last_element = next_element @last_element.parent = previous if klass.need_parent? @xml_child_mode = @last_element.have_xml_content? Proc.new do |text, tags| p(@last_element.class) if DEBUG if @xml_child_mode @last_element.content = @xml_element.to_s xml_setter = @last_element.class.xml_setter @last_element.__send__(xml_setter, @xml_element) @xml_element = nil @xml_child_mode = false else if klass.have_content? if @last_element.need_base64_encode? text = text.lstrip.unpack("m").first end @last_element.content = text end end if @do_validate @last_element.validate_for_stream(tags, @ignore_unknown_element) end @last_element = previous end end def setup_next_element_in_unknown_element current_element, @last_element = @last_element, nil Proc.new {@last_element = current_element} end end unless const_defined? :AVAILABLE_PARSER_LIBRARIES AVAILABLE_PARSER_LIBRARIES = [ ["rss/xmlparser", :XMLParserParser], ["rss/xmlscanner", :XMLScanParser], ["rss/rexmlparser", :REXMLParser], ] end AVAILABLE_PARSERS = [] AVAILABLE_PARSER_LIBRARIES.each do |lib, parser| begin require lib AVAILABLE_PARSERS.push(const_get(parser)) rescue LoadError end end if AVAILABLE_PARSERS.empty? raise XMLParserNotFound end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/1.0.rb
require "rss/parser" module RSS module RSS10 NSPOOL = {} ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator('', ::RSS::URI) end end class RDF < Element include RSS10 include RootElementMixin class << self def required_uri URI end end @tag_name = 'RDF' PREFIX = 'rdf' URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" install_ns('', ::RSS::URI) install_ns(PREFIX, URI) [ ["channel", nil], ["image", "?"], ["item", "+", :children], ["textinput", "?"], ].each do |tag, occurs, type| type ||= :child __send__("install_have_#{type}_element", tag, ::RSS::URI, occurs) end alias_method(:rss_version, :feed_version) def initialize(version=nil, encoding=nil, standalone=nil) super('1.0', version, encoding, standalone) @feed_type = "rss" end def full_name tag_name_with_prefix(PREFIX) end class Li < Element include RSS10 class << self def required_uri URI end end [ ["resource", [URI, ""], true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end def full_name tag_name_with_prefix(PREFIX) end end class Seq < Element include RSS10 Li = ::RSS::RDF::Li class << self def required_uri URI end end @tag_name = 'Seq' install_have_children_element("li", URI, "*") install_must_call_validator('rdf', ::RSS::RDF::URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() @li = args[0] if args[0] end end def full_name tag_name_with_prefix(PREFIX) end def setup_maker(target) lis.each do |li| target << li.resource end end end class Bag < Element include RSS10 Li = ::RSS::RDF::Li class << self def required_uri URI end end @tag_name = 'Bag' install_have_children_element("li", URI, "*") install_must_call_validator('rdf', URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() @li = args[0] if args[0] end end def full_name tag_name_with_prefix(PREFIX) end def setup_maker(target) lis.each do |li| target << li.resource end end end class Channel < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end [ ['title', nil, :text], ['link', nil, :text], ['description', nil, :text], ['image', '?', :have_child], ['items', nil, :have_child], ['textinput', '?', :have_child], ].each do |tag, occurs, type| __send__("install_#{type}_element", tag, ::RSS::URI, occurs) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(maker) maker.channel end def setup_maker_attributes(channel) channel.about = about end class Image < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["resource", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end end class Textinput < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["resource", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end end class Items < Element include RSS10 Seq = ::RSS::RDF::Seq class << self def required_uri ::RSS::URI end end install_have_child_element("Seq", URI, nil) install_must_call_validator('rdf', URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.Seq = args[0] end self.Seq ||= Seq.new end def resources if @Seq @Seq.lis.collect do |li| li.resource end else [] end end end end class Image < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end %w(title url link).each do |name| install_text_element(name, ::RSS::URI, nil) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(maker) maker.image end end class Item < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end [ ["title", nil], ["link", nil], ["description", "?"], ].each do |tag, occurs| install_text_element(tag, ::RSS::URI, occurs) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(items) if items.respond_to?("items") # For backward compatibility items = items.items end items.new_item end end class Textinput < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end %w(title description name link).each do |name| install_text_element(name, ::RSS::URI, nil) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(maker) maker.textinput end end end RSS10::ELEMENTS.each do |name| BaseListener.install_get_text_element(URI, name, name) end module ListenerMixin private def initial_start_RDF(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, RDF::URI, false) @rss = RDF.new(@version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags, @ignore_unknown_element) if @do_validate end @proc_stack.push(pr) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/2.0.rb
require "rss/0.9" module RSS class Rss class Channel [ ["generator"], ["ttl", :integer], ].each do |name, type| install_text_element(name, "", "?", name, type) end [ %w(category categories), ].each do |name, plural_name| install_have_children_element(name, "", "*", name, plural_name) end [ ["image", "?"], ["language", "?"], ].each do |name, occurs| install_model(name, "", occurs) end Category = Item::Category class Item [ ["comments", "?"], ["author", "?"], ].each do |name, occurs| install_text_element(name, "", occurs) end [ ["pubDate", '?'], ].each do |name, occurs| install_date_element(name, "", occurs, name, 'rfc822') end alias date pubDate alias date= pubDate= [ ["guid", '?'], ].each do |name, occurs| install_have_child_element(name, "", occurs) end private alias _setup_maker_element setup_maker_element def setup_maker_element(item) _setup_maker_element(item) @guid.setup_maker(item) if @guid end class Guid < Element include RSS09 [ ["isPermaLink", "", false, :boolean] ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.isPermaLink = args[0] self.content = args[1] end end alias_method :_PermaLink?, :PermaLink? private :_PermaLink? def PermaLink? perma = _PermaLink? perma or perma.nil? end private def maker_target(item) item.guid end def setup_maker_attributes(guid) guid.isPermaLink = isPermaLink guid.content = content end end end end end RSS09::ELEMENTS.each do |name| BaseListener.install_get_text_element("", name, name) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/0.9.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/0.9.rb
require "rss/parser" module RSS module RSS09 NSPOOL = {} ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator('', "") end end class Rss < Element include RSS09 include RootElementMixin %w(channel).each do |name| install_have_child_element(name, "", nil) end attr_writer :feed_version alias_method(:rss_version, :feed_version) alias_method(:rss_version=, :feed_version=) def initialize(feed_version, version=nil, encoding=nil, standalone=nil) super @feed_type = "rss" end def items if @channel @channel.items else [] end end def image if @channel @channel.image else nil end end def textinput if @channel @channel.textInput else nil end end def setup_maker_elements(maker) super items.each do |item| item.setup_maker(maker.items) end image.setup_maker(maker) if image textinput.setup_maker(maker) if textinput end private def _attrs [ ["version", true, "feed_version"], ] end class Channel < Element include RSS09 [ ["title", nil, :text], ["link", nil, :text], ["description", nil, :text], ["language", nil, :text], ["copyright", "?", :text], ["managingEditor", "?", :text], ["webMaster", "?", :text], ["rating", "?", :text], ["pubDate", "?", :date, :rfc822], ["lastBuildDate", "?", :date, :rfc822], ["docs", "?", :text], ["cloud", "?", :have_attribute], ["skipDays", "?", :have_child], ["skipHours", "?", :have_child], ["image", nil, :have_child], ["item", "*", :have_children], ["textInput", "?", :have_child], ].each do |name, occurs, type, *args| __send__("install_#{type}_element", name, "", occurs, name, *args) end alias date pubDate alias date= pubDate= private def maker_target(maker) maker.channel end def setup_maker_elements(channel) super [ [skipDays, "day"], [skipHours, "hour"], ].each do |skip, key| if skip skip.__send__("#{key}s").each do |val| target_skips = channel.__send__("skip#{key.capitalize}s") new_target = target_skips.__send__("new_#{key}") new_target.content = val.content end end end end def not_need_to_call_setup_maker_variables %w(image textInput) end class SkipDays < Element include RSS09 [ ["day", "*"] ].each do |name, occurs| install_have_children_element(name, "", occurs) end class Day < Element include RSS09 content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end end end class SkipHours < Element include RSS09 [ ["hour", "*"] ].each do |name, occurs| install_have_children_element(name, "", occurs) end class Hour < Element include RSS09 content_setup(:integer) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end end end class Image < Element include RSS09 %w(url title link).each do |name| install_text_element(name, "", nil) end [ ["width", :integer], ["height", :integer], ["description"], ].each do |name, type| install_text_element(name, "", "?", name, type) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.url = args[0] self.title = args[1] self.link = args[2] self.width = args[3] self.height = args[4] self.description = args[5] end end private def maker_target(maker) maker.image end end class Cloud < Element include RSS09 [ ["domain", "", true], ["port", "", true, :integer], ["path", "", true], ["registerProcedure", "", true], ["protocol", "", true], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.domain = args[0] self.port = args[1] self.path = args[2] self.registerProcedure = args[3] self.protocol = args[4] end end end class Item < Element include RSS09 [ ["title", '?', :text], ["link", '?', :text], ["description", '?', :text], ["category", '*', :have_children, "categories"], ["source", '?', :have_child], ["enclosure", '?', :have_child], ].each do |tag, occurs, type, *args| __send__("install_#{type}_element", tag, "", occurs, tag, *args) end private def maker_target(items) if items.respond_to?("items") # For backward compatibility items = items.items end items.new_item end def setup_maker_element(item) super @enclosure.setup_maker(item) if @enclosure @source.setup_maker(item) if @source end class Source < Element include RSS09 [ ["url", "", true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.url = args[0] self.content = args[1] end end private def maker_target(item) item.source end def setup_maker_attributes(source) source.url = url source.content = content end end class Enclosure < Element include RSS09 [ ["url", "", true], ["length", "", true, :integer], ["type", "", true], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.url = args[0] self.length = args[1] self.type = args[2] end end private def maker_target(item) item.enclosure end def setup_maker_attributes(enclosure) enclosure.url = url enclosure.length = length enclosure.type = type end end class Category < Element include RSS09 [ ["domain", "", false] ].each do |name, uri, required| install_get_attribute(name, uri, required) end content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.domain = args[0] self.content = args[1] end end private def maker_target(item) item.new_category end def setup_maker_attributes(category) category.domain = domain category.content = content end end end class TextInput < Element include RSS09 %w(title description name link).each do |name| install_text_element(name, "", nil) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.title = args[0] self.description = args[1] self.name = args[2] self.link = args[3] end end private def maker_target(maker) maker.textinput end end end end RSS09::ELEMENTS.each do |name| BaseListener.install_get_text_element("", name, name) end module ListenerMixin private def initial_start_rss(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, "", false) @rss = Rss.new(attrs['version'], @version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags, @ignore_unknown_element) if @do_validate end @proc_stack.push(pr) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/atom.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/atom.rb
require 'rss/parser' module RSS module Atom URI = "http://www.w3.org/2005/Atom" XHTML_URI = "http://www.w3.org/1999/xhtml" module CommonModel NSPOOL = {} ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator("atom", URI) [ ["lang", :xml], ["base", :xml], ].each do |name, uri, required| klass.install_get_attribute(name, uri, required, [nil, :inherit]) end klass.class_eval do class << self def required_uri URI end def need_parent? true end end end end end module ContentModel module ClassMethods def content_type @content_type ||= nil end end class << self def append_features(klass) super klass.extend(ClassMethods) klass.content_setup(klass.content_type, klass.tag_name) end end def maker_target(target) target end private def setup_maker_element_writer "#{self.class.name.split(/::/).last.downcase}=" end def setup_maker_element(target) target.__send__(setup_maker_element_writer, content) super end end module URIContentModel class << self def append_features(klass) super klass.class_eval do @content_type = [nil, :uri] include(ContentModel) end end end end module TextConstruct def self.append_features(klass) super klass.class_eval do [ ["type", ""], ].each do |name, uri, required| install_get_attribute(name, uri, required, :text_type) end content_setup add_need_initialize_variable("xhtml") class << self def xml_getter "xhtml" end def xml_setter "xhtml=" end end end end attr_writer :xhtml def xhtml return @xhtml if @xhtml.nil? if @xhtml.is_a?(XML::Element) and [@xhtml.name, @xhtml.uri] == ["div", XHTML_URI] return @xhtml end children = @xhtml children = [children] unless children.is_a?(Array) XML::Element.new("div", nil, XHTML_URI, {"xmlns" => XHTML_URI}, children) end def have_xml_content? @type == "xhtml" end def atom_validate(ignore_unknown_element, tags, uri) if have_xml_content? if @xhtml.nil? raise MissingTagError.new("div", tag_name) end unless [@xhtml.name, @xhtml.uri] == ["div", XHTML_URI] raise NotExpectedTagError.new(@xhtml.name, @xhtml.uri, tag_name) end end end private def maker_target(target) target.__send__(self.class.name.split(/::/).last.downcase) {|x| x} end def setup_maker_attributes(target) target.type = type target.content = content target.xml_content = @xhtml end end module PersonConstruct def self.append_features(klass) super klass.class_eval do [ ["name", nil], ["uri", "?"], ["email", "?"], ].each do |tag, occurs| install_have_attribute_element(tag, URI, occurs, nil, :content) end end end def maker_target(target) target.__send__("new_#{self.class.name.split(/::/).last.downcase}") end class Name < RSS::Element include CommonModel include ContentModel end class Uri < RSS::Element include CommonModel include URIContentModel end class Email < RSS::Element include CommonModel include ContentModel end end module DateConstruct def self.append_features(klass) super klass.class_eval do @content_type = :w3cdtf include(ContentModel) end end def atom_validate(ignore_unknown_element, tags, uri) raise NotAvailableValueError.new(tag_name, "") if content.nil? end end module DuplicateLinkChecker def validate_duplicate_links(links) link_infos = {} links.each do |link| rel = link.rel || "alternate" next unless rel == "alternate" key = [link.hreflang, link.type] if link_infos.has_key?(key) raise TooMuchTagError.new("link", tag_name) end link_infos[key] = true end end end class Feed < RSS::Element include RootElementMixin include CommonModel include DuplicateLinkChecker install_ns('', URI) [ ["author", "*", :children], ["category", "*", :children, "categories"], ["contributor", "*", :children], ["generator", "?"], ["icon", "?", nil, :content], ["id", nil, nil, :content], ["link", "*", :children], ["logo", "?"], ["rights", "?"], ["subtitle", "?", nil, :content], ["title", nil, nil, :content], ["updated", nil, nil, :content], ["entry", "*", :children, "entries"], ].each do |tag, occurs, type, *args| type ||= :child __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def initialize(version=nil, encoding=nil, standalone=nil) super("1.0", version, encoding, standalone) @feed_type = "atom" @feed_subtype = "feed" end alias_method :items, :entries def have_author? authors.any? {|author| !author.to_s.empty?} or entries.any? {|entry| entry.have_author?(false)} end private def atom_validate(ignore_unknown_element, tags, uri) unless have_author? raise MissingTagError.new("author", tag_name) end validate_duplicate_links(links) end def have_required_elements? super and have_author? end def maker_target(maker) maker.channel end def setup_maker_element(channel) prev_dc_dates = channel.dc_dates.to_a.dup super channel.about = id.content if id channel.dc_dates.replace(prev_dc_dates) end def setup_maker_elements(channel) super items = channel.maker.items entries.each do |entry| entry.setup_maker(items) end end class Author < RSS::Element include CommonModel include PersonConstruct end class Category < RSS::Element include CommonModel [ ["term", "", true], ["scheme", "", false, [nil, :uri]], ["label", ""], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end private def maker_target(target) target.new_category end end class Contributor < RSS::Element include CommonModel include PersonConstruct end class Generator < RSS::Element include CommonModel include ContentModel [ ["uri", "", false, [nil, :uri]], ["version", ""], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end private def setup_maker_attributes(target) target.generator do |generator| generator.uri = uri if uri generator.version = version if version end end end class Icon < RSS::Element include CommonModel include URIContentModel end class Id < RSS::Element include CommonModel include URIContentModel end class Link < RSS::Element include CommonModel [ ["href", "", true, [nil, :uri]], ["rel", ""], ["type", ""], ["hreflang", ""], ["title", ""], ["length", ""], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end private def maker_target(target) target.new_link end end class Logo < RSS::Element include CommonModel include URIContentModel def maker_target(target) target.maker.image end private def setup_maker_element_writer "url=" end end class Rights < RSS::Element include CommonModel include TextConstruct end class Subtitle < RSS::Element include CommonModel include TextConstruct end class Title < RSS::Element include CommonModel include TextConstruct end class Updated < RSS::Element include CommonModel include DateConstruct end class Entry < RSS::Element include CommonModel include DuplicateLinkChecker [ ["author", "*", :children], ["category", "*", :children, "categories"], ["content", "?", :child], ["contributor", "*", :children], ["id", nil, nil, :content], ["link", "*", :children], ["published", "?", :child, :content], ["rights", "?", :child], ["source", "?"], ["summary", "?", :child], ["title", nil], ["updated", nil, :child, :content], ].each do |tag, occurs, type, *args| type ||= :attribute __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def have_author?(check_parent=true) authors.any? {|author| !author.to_s.empty?} or (check_parent and @parent and @parent.have_author?) or (source and source.have_author?) end private def atom_validate(ignore_unknown_element, tags, uri) unless have_author? raise MissingTagError.new("author", tag_name) end validate_duplicate_links(links) end def have_required_elements? super and have_author? end def maker_target(items) if items.respond_to?("items") # For backward compatibility items = items.items end items.new_item end Author = Feed::Author Category = Feed::Category class Content < RSS::Element include CommonModel class << self def xml_setter "xml=" end def xml_getter "xml" end end [ ["type", ""], ["src", "", false, [nil, :uri]], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end content_setup add_need_initialize_variable("xml") attr_writer :xml def have_xml_content? inline_xhtml? or inline_other_xml? end def xml return @xml unless inline_xhtml? return @xml if @xml.nil? if @xml.is_a?(XML::Element) and [@xml.name, @xml.uri] == ["div", XHTML_URI] return @xml end children = @xml children = [children] unless children.is_a?(Array) XML::Element.new("div", nil, XHTML_URI, {"xmlns" => XHTML_URI}, children) end def xhtml if inline_xhtml? xml else nil end end def atom_validate(ignore_unknown_element, tags, uri) if out_of_line? raise MissingAttributeError.new(tag_name, "type") if @type.nil? unless (content.nil? or content.empty?) raise NotAvailableValueError.new(tag_name, content) end elsif inline_xhtml? if @xml.nil? raise MissingTagError.new("div", tag_name) end unless @xml.name == "div" and @xml.uri == XHTML_URI raise NotExpectedTagError.new(@xml.name, @xml.uri, tag_name) end end end def inline_text? !out_of_line? and [nil, "text", "html"].include?(@type) end def inline_html? return false if out_of_line? @type == "html" or mime_split == ["text", "html"] end def inline_xhtml? !out_of_line? and @type == "xhtml" end def inline_other? return false if out_of_line? media_type, subtype = mime_split return false if media_type.nil? or subtype.nil? true end def inline_other_text? return false unless inline_other? return false if inline_other_xml? media_type, subtype = mime_split return true if "text" == media_type.downcase false end def inline_other_xml? return false unless inline_other? media_type, subtype = mime_split normalized_mime_type = "#{media_type}/#{subtype}".downcase if /(?:\+xml|^xml)$/ =~ subtype or %w(text/xml-external-parsed-entity application/xml-external-parsed-entity application/xml-dtd).find {|x| x == normalized_mime_type} return true end false end def inline_other_base64? inline_other? and !inline_other_text? and !inline_other_xml? end def out_of_line? not @src.nil? end def mime_split media_type = subtype = nil if /\A\s*([a-z]+)\/([a-z\+]+)\s*(?:;.*)?\z/i =~ @type.to_s media_type = $1.downcase subtype = $2.downcase end [media_type, subtype] end def need_base64_encode? inline_other_base64? end private def empty_content? out_of_line? or super end end Contributor = Feed::Contributor Id = Feed::Id Link = Feed::Link class Published < RSS::Element include CommonModel include DateConstruct end Rights = Feed::Rights class Source < RSS::Element include CommonModel [ ["author", "*", :children], ["category", "*", :children, "categories"], ["contributor", "*", :children], ["generator", "?"], ["icon", "?"], ["id", "?", nil, :content], ["link", "*", :children], ["logo", "?"], ["rights", "?"], ["subtitle", "?"], ["title", "?"], ["updated", "?", nil, :content], ].each do |tag, occurs, type, *args| type ||= :attribute __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def have_author? !author.to_s.empty? end Author = Feed::Author Category = Feed::Category Contributor = Feed::Contributor Generator = Feed::Generator Icon = Feed::Icon Id = Feed::Id Link = Feed::Link Logo = Feed::Logo Rights = Feed::Rights Subtitle = Feed::Subtitle Title = Feed::Title Updated = Feed::Updated end class Summary < RSS::Element include CommonModel include TextConstruct end Title = Feed::Title Updated = Feed::Updated end end class Entry < RSS::Element include RootElementMixin include CommonModel include DuplicateLinkChecker [ ["author", "*", :children], ["category", "*", :children, "categories"], ["content", "?"], ["contributor", "*", :children], ["id", nil, nil, :content], ["link", "*", :children], ["published", "?", :child, :content], ["rights", "?"], ["source", "?"], ["summary", "?"], ["title", nil], ["updated", nil, nil, :content], ].each do |tag, occurs, type, *args| type ||= :attribute __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def initialize(version=nil, encoding=nil, standalone=nil) super("1.0", version, encoding, standalone) @feed_type = "atom" @feed_subtype = "entry" end def items [self] end def setup_maker(maker) maker = maker.maker if maker.respond_to?("maker") super(maker) end def have_author? authors.any? {|author| !author.to_s.empty?} or (source and source.have_author?) end private def atom_validate(ignore_unknown_element, tags, uri) unless have_author? raise MissingTagError.new("author", tag_name) end validate_duplicate_links(links) end def have_required_elements? super and have_author? end def maker_target(maker) maker.items.new_item end Author = Feed::Entry::Author Category = Feed::Entry::Category Content = Feed::Entry::Content Contributor = Feed::Entry::Contributor Id = Feed::Entry::Id Link = Feed::Entry::Link Published = Feed::Entry::Published Rights = Feed::Entry::Rights Source = Feed::Entry::Source Summary = Feed::Entry::Summary Title = Feed::Entry::Title Updated = Feed::Entry::Updated end end Atom::CommonModel::ELEMENTS.each do |name| BaseListener.install_get_text_element(Atom::URI, name, "#{name}=") end module ListenerMixin private def initial_start_feed(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, Atom::URI, false) @rss = Atom::Feed.new(@version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @rss.lang = attrs["xml:lang"] @rss.base = attrs["xml:base"] @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags) if @do_validate end @proc_stack.push(pr) end def initial_start_entry(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, Atom::URI, false) @rss = Atom::Entry.new(@version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @rss.lang = attrs["xml:lang"] @rss.base = attrs["xml:base"] @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags) if @do_validate end @proc_stack.push(pr) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/xmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/xmlparser.rb
begin require "xml/parser" rescue LoadError require "xmlparser" end begin require "xml/encoding-ja" rescue LoadError require "xmlencoding-ja" if defined?(Kconv) module XMLEncoding_ja class SJISHandler include Kconv end end end end module XML class Parser unless defined?(Error) Error = ::XMLParserError end end end module RSS class REXMLLikeXMLParser < ::XML::Parser include ::XML::Encoding_ja def listener=(listener) @listener = listener end def startElement(name, attrs) @listener.tag_start(name, attrs) end def endElement(name) @listener.tag_end(name) end def character(data) @listener.text(data) end def xmlDecl(version, encoding, standalone) @listener.xmldecl(version, encoding, standalone == 1) end def processingInstruction(target, content) @listener.instruction(target, content) end end class XMLParserParser < BaseParser class << self def listener XMLParserListener end end private def _parse begin parser = REXMLLikeXMLParser.new parser.listener = @listener parser.parse(@rss) rescue ::XML::Parser::Error => e raise NotWellFormedError.new(parser.line){e.message} end end end class XMLParserListener < BaseListener include ListenerMixin def xmldecl(version, encoding, standalone) super # Encoding is converted to UTF-8 when XMLParser parses XML. @encoding = 'UTF-8' end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/rss.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/rss.rb
require "time" class Time class << self unless respond_to?(:w3cdtf) def w3cdtf(date) if /\A\s* (-?\d+)-(\d\d)-(\d\d) (?:T (\d\d):(\d\d)(?::(\d\d))? (\.\d+)? (Z|[+-]\d\d:\d\d)?)? \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8)) datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i] usec = 0 usec = $7.to_f * 1000000 if $7 zone = $8 if zone off = zone_offset(zone, datetime[0]) datetime = apply_offset(*(datetime + [off])) datetime << usec time = Time.utc(*datetime) time.localtime unless zone_utc?(zone) time else datetime << usec Time.local(*datetime) end else raise ArgumentError.new("invalid date: #{date.inspect}") end end end end unless method_defined?(:w3cdtf) def w3cdtf if usec.zero? fraction_digits = 0 else fraction_digits = Math.log10(usec.to_s.sub(/0*$/, '').to_i).floor + 1 end xmlschema(fraction_digits) end end end require "English" require "rss/utils" require "rss/converter" require "rss/xml-stylesheet" module RSS VERSION = "0.2.7" URI = "http://purl.org/rss/1.0/" DEBUG = false class Error < StandardError; end class OverlappedPrefixError < Error attr_reader :prefix def initialize(prefix) @prefix = prefix end end class InvalidRSSError < Error; end class MissingTagError < InvalidRSSError attr_reader :tag, :parent def initialize(tag, parent) @tag, @parent = tag, parent super("tag <#{tag}> is missing in tag <#{parent}>") end end class TooMuchTagError < InvalidRSSError attr_reader :tag, :parent def initialize(tag, parent) @tag, @parent = tag, parent super("tag <#{tag}> is too much in tag <#{parent}>") end end class MissingAttributeError < InvalidRSSError attr_reader :tag, :attribute def initialize(tag, attribute) @tag, @attribute = tag, attribute super("attribute <#{attribute}> is missing in tag <#{tag}>") end end class UnknownTagError < InvalidRSSError attr_reader :tag, :uri def initialize(tag, uri) @tag, @uri = tag, uri super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>") end end class NotExpectedTagError < InvalidRSSError attr_reader :tag, :uri, :parent def initialize(tag, uri, parent) @tag, @uri, @parent = tag, uri, parent super("tag <{#{uri}}#{tag}> is not expected in tag <#{parent}>") end end # For backward compatibility :X NotExceptedTagError = NotExpectedTagError class NotAvailableValueError < InvalidRSSError attr_reader :tag, :value, :attribute def initialize(tag, value, attribute=nil) @tag, @value, @attribute = tag, value, attribute message = "value <#{value}> of " message << "attribute <#{attribute}> of " if attribute message << "tag <#{tag}> is not available." super(message) end end class UnknownConversionMethodError < Error attr_reader :to, :from def initialize(to, from) @to = to @from = from super("can't convert to #{to} from #{from}.") end end # for backward compatibility UnknownConvertMethod = UnknownConversionMethodError class ConversionError < Error attr_reader :string, :to, :from def initialize(string, to, from) @string = string @to = to @from = from super("can't convert #{@string} to #{to} from #{from}.") end end class NotSetError < Error attr_reader :name, :variables def initialize(name, variables) @name = name @variables = variables super("required variables of #{@name} are not set: #{@variables.join(', ')}") end end class UnsupportedMakerVersionError < Error attr_reader :version def initialize(version) @version = version super("Maker doesn't support version: #{@version}") end end module BaseModel include Utils def install_have_child_element(tag_name, uri, occurs, name=nil, type=nil) name ||= tag_name add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) writer_type, reader_type = type def_corresponded_attr_writer name, writer_type def_corresponded_attr_reader name, reader_type install_element(name) do |n, elem_name| <<-EOC if @#{n} "\#{@#{n}.to_s(need_convert, indent)}" else '' end EOC end end alias_method(:install_have_attribute_element, :install_have_child_element) def install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil) name ||= tag_name plural_name ||= "#{name}s" add_have_children_element(name, plural_name) add_plural_form(name, plural_name) install_model(tag_name, uri, occurs, plural_name, true) def_children_accessor(name, plural_name) install_element(name, "s") do |n, elem_name| <<-EOC rv = [] @#{n}.each do |x| value = "\#{x.to_s(need_convert, indent)}" rv << value if /\\A\\s*\\z/ !~ value end rv.join("\n") EOC end end def install_text_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil) name ||= tag_name disp_name ||= name self::ELEMENTS << name unless self::ELEMENTS.include?(name) add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) def_corresponded_attr_writer(name, type, disp_name) def_corresponded_attr_reader(name, type || :convert) install_element(name) do |n, elem_name| <<-EOC if respond_to?(:#{n}_content) content = #{n}_content else content = @#{n} end if content rv = "\#{indent}<#{elem_name}>" value = html_escape(content) if need_convert rv << convert(value) else rv << value end rv << "</#{elem_name}>" rv else '' end EOC end end def install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil) name ||= tag_name type ||= :w3cdtf disp_name ||= name self::ELEMENTS << name add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) # accessor convert_attr_reader name date_writer(name, type, disp_name) install_element(name) do |n, elem_name| <<-EOC if @#{n} rv = "\#{indent}<#{elem_name}>" value = html_escape(@#{n}.#{type}) if need_convert rv << convert(value) else rv << value end rv << "</#{elem_name}>" rv else '' end EOC end end private def install_element(name, postfix="") elem_name = name.sub('_', ':') method_name = "#{name}_element#{postfix}" add_to_element_method(method_name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{method_name}(need_convert=true, indent='') #{yield(name, elem_name)} end private :#{method_name} EOC end def inherit_convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr}_without_inherit convert(@#{attr}) end def #{attr} if @#{attr} #{attr}_without_inherit elsif @parent @parent.#{attr} else nil end end EOC end end def uri_convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr}_without_base convert(@#{attr}) end def #{attr} value = #{attr}_without_base return nil if value.nil? if /\\A[a-z][a-z0-9+.\\-]*:/i =~ value value else "\#{base}\#{value}" end end EOC end end def convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr} convert(@#{attr}) end EOC end end def yes_clean_other_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}? YesCleanOther.parse(@#{attr}) end EOC end end def yes_other_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}? Utils::YesOther.parse(@#{attr}) end EOC end end def csv_attr_reader(*attrs) separator = nil if attrs.last.is_a?(Hash) options = attrs.pop separator = options[:separator] end separator ||= ", " attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}_content if @#{attr}.nil? @#{attr} else @#{attr}.join(#{separator.dump}) end end EOC end end def date_writer(name, type, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value elsif new_value.kind_of?(Time) @#{name} = new_value.dup else if @do_validate begin @#{name} = Time.__send__('#{type}', new_value) rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = nil if /\\A\\s*\\z/ !~ new_value.to_s begin unless Date._parse(new_value, false).empty? @#{name} = Time.parse(new_value) end rescue ArgumentError end end end end # Is it need? if @#{name} class << @#{name} undef_method(:to_s) alias_method(:to_s, :#{type}) end end end EOC end def integer_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate begin @#{name} = Integer(new_value) rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = new_value.to_i end end end EOC end def positive_integer_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate begin tmp = Integer(new_value) raise ArgumentError if tmp <= 0 @#{name} = tmp rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = new_value.to_i end end end EOC end def boolean_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate and ![true, false, "true", "false"].include?(new_value) raise NotAvailableValueError.new('#{disp_name}', new_value) end if [true, false].include?(new_value) @#{name} = new_value else @#{name} = new_value == "true" end end end EOC end def text_type_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if @do_validate and !["text", "html", "xhtml", nil].include?(new_value) raise NotAvailableValueError.new('#{disp_name}', new_value) end @#{name} = new_value end EOC end def content_writer(name, disp_name=name) klass_name = "self.class::#{Utils.to_class_name(name)}" module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.is_a?(#{klass_name}) @#{name} = new_value else @#{name} = #{klass_name}.new @#{name}.content = new_value end end EOC end def yes_clean_other_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(value) value = (value ? "yes" : "no") if [true, false].include?(value) @#{name} = value end EOC end def yes_other_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) if [true, false].include?(new_value) new_value = new_value ? "yes" : "no" end @#{name} = new_value end EOC end def csv_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) @#{name} = Utils::CSV.parse(new_value) end EOC end def csv_integer_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) @#{name} = Utils::CSV.parse(new_value) {|v| Integer(v)} end EOC end def def_children_accessor(accessor_name, plural_name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{plural_name} @#{accessor_name} end def #{accessor_name}(*args) if args.empty? @#{accessor_name}.first else @#{accessor_name}[*args] end end def #{accessor_name}=(*args) receiver = self.class.name warn("Warning:\#{caller.first.sub(/:in `.*'\z/, '')}: " \ "Don't use `\#{receiver}\##{accessor_name} = XXX'/" \ "`\#{receiver}\#set_#{accessor_name}(XXX)'. " \ "Those APIs are not sense of Ruby. " \ "Use `\#{receiver}\##{plural_name} << XXX' instead of them.") if args.size == 1 @#{accessor_name}.push(args[0]) else @#{accessor_name}.__send__("[]=", *args) end end alias_method(:set_#{accessor_name}, :#{accessor_name}=) EOC end end module SetupMaker def setup_maker(maker) target = maker_target(maker) unless target.nil? setup_maker_attributes(target) setup_maker_element(target) setup_maker_elements(target) end end private def maker_target(maker) nil end def setup_maker_attributes(target) end def setup_maker_element(target) self.class.need_initialize_variables.each do |var| value = __send__(var) next if value.nil? if value.respond_to?("setup_maker") and !not_need_to_call_setup_maker_variables.include?(var) value.setup_maker(target) else setter = "#{var}=" if target.respond_to?(setter) target.__send__(setter, value) end end end end def not_need_to_call_setup_maker_variables [] end def setup_maker_elements(parent) self.class.have_children_elements.each do |name, plural_name| if parent.respond_to?(plural_name) target = parent.__send__(plural_name) __send__(plural_name).each do |elem| elem.setup_maker(target) end end end end end class Element extend BaseModel include Utils extend Utils::InheritedReader include SetupMaker INDENT = " " MUST_CALL_VALIDATORS = {} MODELS = [] GET_ATTRIBUTES = [] HAVE_CHILDREN_ELEMENTS = [] TO_ELEMENT_METHODS = [] NEED_INITIALIZE_VARIABLES = [] PLURAL_FORMS = {} class << self def must_call_validators inherited_hash_reader("MUST_CALL_VALIDATORS") end def models inherited_array_reader("MODELS") end def get_attributes inherited_array_reader("GET_ATTRIBUTES") end def have_children_elements inherited_array_reader("HAVE_CHILDREN_ELEMENTS") end def to_element_methods inherited_array_reader("TO_ELEMENT_METHODS") end def need_initialize_variables inherited_array_reader("NEED_INITIALIZE_VARIABLES") end def plural_forms inherited_hash_reader("PLURAL_FORMS") end def inherited_base ::RSS::Element end def inherited(klass) klass.const_set("MUST_CALL_VALIDATORS", {}) klass.const_set("MODELS", []) klass.const_set("GET_ATTRIBUTES", []) klass.const_set("HAVE_CHILDREN_ELEMENTS", []) klass.const_set("TO_ELEMENT_METHODS", []) klass.const_set("NEED_INITIALIZE_VARIABLES", []) klass.const_set("PLURAL_FORMS", {}) tag_name = klass.name.split(/::/).last tag_name[0, 1] = tag_name[0, 1].downcase klass.instance_variable_set("@tag_name", tag_name) klass.instance_variable_set("@have_content", false) end def install_must_call_validator(prefix, uri) self::MUST_CALL_VALIDATORS[uri] = prefix end def install_model(tag, uri, occurs=nil, getter=nil, plural=false) getter ||= tag if m = self::MODELS.find {|t, u, o, g, p| t == tag and u == uri} m[2] = occurs else self::MODELS << [tag, uri, occurs, getter, plural] end end def install_get_attribute(name, uri, required=true, type=nil, disp_name=nil, element_name=nil) disp_name ||= name element_name ||= name writer_type, reader_type = type def_corresponded_attr_writer name, writer_type, disp_name def_corresponded_attr_reader name, reader_type if type == :boolean and /^is/ =~ name alias_method "#{$POSTMATCH}?", name end self::GET_ATTRIBUTES << [name, uri, required, element_name] add_need_initialize_variable(disp_name) end def def_corresponded_attr_writer(name, type=nil, disp_name=nil) disp_name ||= name case type when :integer integer_writer name, disp_name when :positive_integer positive_integer_writer name, disp_name when :boolean boolean_writer name, disp_name when :w3cdtf, :rfc822, :rfc2822 date_writer name, type, disp_name when :text_type text_type_writer name, disp_name when :content content_writer name, disp_name when :yes_clean_other yes_clean_other_writer name, disp_name when :yes_other yes_other_writer name, disp_name when :csv csv_writer name when :csv_integer csv_integer_writer name else attr_writer name end end def def_corresponded_attr_reader(name, type=nil) case type when :inherit inherit_convert_attr_reader name when :uri uri_convert_attr_reader name when :yes_clean_other yes_clean_other_attr_reader name when :yes_other yes_other_attr_reader name when :csv csv_attr_reader name when :csv_integer csv_attr_reader name, :separator => "," else convert_attr_reader name end end def content_setup(type=nil, disp_name=nil) writer_type, reader_type = type def_corresponded_attr_writer :content, writer_type, disp_name def_corresponded_attr_reader :content, reader_type @have_content = true end def have_content? @have_content end def add_have_children_element(variable_name, plural_name) self::HAVE_CHILDREN_ELEMENTS << [variable_name, plural_name] end def add_to_element_method(method_name) self::TO_ELEMENT_METHODS << method_name end def add_need_initialize_variable(variable_name) self::NEED_INITIALIZE_VARIABLES << variable_name end def add_plural_form(singular, plural) self::PLURAL_FORMS[singular] = plural end def required_prefix nil end def required_uri "" end def need_parent? false end def install_ns(prefix, uri) if self::NSPOOL.has_key?(prefix) raise OverlappedPrefixError.new(prefix) end self::NSPOOL[prefix] = uri end def tag_name @tag_name end end attr_accessor :parent, :do_validate def initialize(do_validate=true, attrs=nil) @parent = nil @converter = nil if attrs.nil? and (do_validate.is_a?(Hash) or do_validate.is_a?(Array)) do_validate, attrs = true, do_validate end @do_validate = do_validate initialize_variables(attrs || {}) end def tag_name self.class.tag_name end def full_name tag_name end def converter=(converter) @converter = converter targets = children.dup self.class.have_children_elements.each do |variable_name, plural_name| targets.concat(__send__(plural_name)) end targets.each do |target| target.converter = converter unless target.nil? end end def convert(value) if @converter @converter.convert(value) else value end end def valid?(ignore_unknown_element=true) validate(ignore_unknown_element) true rescue RSS::Error false end def validate(ignore_unknown_element=true) do_validate = @do_validate @do_validate = true validate_attribute __validate(ignore_unknown_element) ensure @do_validate = do_validate end def validate_for_stream(tags, ignore_unknown_element=true) validate_attribute __validate(ignore_unknown_element, tags, false) end def to_s(need_convert=true, indent='') if self.class.have_content? return "" if !empty_content? and !content_is_set? rv = tag(indent) do |next_indent| if empty_content? "" else xmled_content end end else rv = tag(indent) do |next_indent| self.class.to_element_methods.collect do |method_name| __send__(method_name, false, next_indent) end end end rv = convert(rv) if need_convert rv end def have_xml_content? false end def need_base64_encode? false end def set_next_element(tag_name, next_element) klass = next_element.class prefix = "" prefix << "#{klass.required_prefix}_" if klass.required_prefix key = "#{prefix}#{tag_name.gsub(/-/, '_')}" if self.class.plural_forms.has_key?(key) ary = __send__("#{self.class.plural_forms[key]}") ary << next_element else __send__("#{key}=", next_element) end end protected def have_required_elements? self.class::MODELS.all? do |tag, uri, occurs, getter| if occurs.nil? or occurs == "+" child = __send__(getter) if child.is_a?(Array) children = child children.any? {|c| c.have_required_elements?} else !child.to_s.empty? end else true end end end private def initialize_variables(attrs) normalized_attrs = {} attrs.each do |key, value| normalized_attrs[key.to_s] = value end self.class.need_initialize_variables.each do |variable_name| value = normalized_attrs[variable_name.to_s] if value __send__("#{variable_name}=", value) else instance_variable_set("@#{variable_name}", nil) end end initialize_have_children_elements @content = normalized_attrs["content"] if self.class.have_content? end def initialize_have_children_elements self.class.have_children_elements.each do |variable_name, plural_name| instance_variable_set("@#{variable_name}", []) end end def tag(indent, additional_attrs={}, &block) next_indent = indent + INDENT attrs = collect_attrs return "" if attrs.nil? return "" unless have_required_elements? attrs.update(additional_attrs) start_tag = make_start_tag(indent, next_indent, attrs.dup) if block content = block.call(next_indent) else content = [] end if content.is_a?(String) content = [content] start_tag << ">" end_tag = "</#{full_name}>" else content = content.reject{|x| x.empty?} if content.empty? return "" if attrs.empty? end_tag = "/>" else start_tag << ">\n" end_tag = "\n#{indent}</#{full_name}>" end end start_tag + content.join("\n") + end_tag end def make_start_tag(indent, next_indent, attrs) start_tag = ["#{indent}<#{full_name}"] unless attrs.empty? start_tag << attrs.collect do |key, value| %Q[#{h key}="#{h value}"] end.join("\n#{next_indent}") end start_tag.join(" ") end def collect_attrs attrs = {} _attrs.each do |name, required, alias_name| value = __send__(alias_name || name) return nil if required and value.nil? next if value.nil? return nil if attrs.has_key?(name) attrs[name] = value end attrs end def tag_name_with_prefix(prefix) "#{prefix}:#{tag_name}" end # For backward compatibility def calc_indent '' end def children rv = [] self.class.models.each do |name, uri, occurs, getter| value = __send__(getter) next if value.nil? value = [value] unless value.is_a?(Array) value.each do |v| rv << v if v.is_a?(Element) end end rv end def _tags rv = [] self.class.models.each do |name, uri, occurs, getter, plural| value = __send__(getter) next if value.nil? if plural and value.is_a?(Array) rv.concat([[uri, name]] * value.size) else rv << [uri, name] end end rv end def _attrs self.class.get_attributes.collect do |name, uri, required, element_name| [element_name, required, name] end end def __validate(ignore_unknown_element, tags=_tags, recursive=true) if recursive children.compact.each do |child| child.validate end end must_call_validators = self.class.must_call_validators tags = tag_filter(tags.dup) p tags if DEBUG must_call_validators.each do |uri, prefix| _validate(ignore_unknown_element, tags[uri], uri) meth = "#{prefix}_validate" if !prefix.empty? and respond_to?(meth, true) __send__(meth, ignore_unknown_element, tags[uri], uri) end end end def validate_attribute _attrs.each do |a_name, required, alias_name| value = instance_variable_get("@#{alias_name || a_name}") if required and value.nil? raise MissingAttributeError.new(tag_name, a_name) end __send__("#{alias_name || a_name}=", value) end end def _validate(ignore_unknown_element, tags, uri, models=self.class.models) count = 1 do_redo = false not_shift = false tag = nil models = models.find_all {|model| model[1] == uri} element_names = models.collect {|model| model[0]} if tags tags_size = tags.size tags = tags.sort_by {|x| element_names.index(x) || tags_size} end _tags = tags.dup if tags models.each_with_index do |model, i| name, model_uri, occurs, getter = model if DEBUG p "before" p tags p model end if not_shift not_shift = false elsif tags tag = tags.shift end if DEBUG p "mid" p count end case occurs when '?' if count > 2 raise TooMuchTagError.new(name, tag_name) else if name == tag do_redo = true else not_shift = true end end when '*' if name == tag do_redo = true else not_shift = true end when '+' if name == tag do_redo = true else if count > 1 not_shift = true else raise MissingTagError.new(name, tag_name) end end else if name == tag if models[i+1] and models[i+1][0] != name and tags and tags.first == name raise TooMuchTagError.new(name, tag_name) end else raise MissingTagError.new(name, tag_name) end end if DEBUG p "after" p not_shift p do_redo p tag end if do_redo do_redo = false count += 1 redo else count = 1 end end if !ignore_unknown_element and !tags.nil? and !tags.empty? raise NotExpectedTagError.new(tags.first, uri, tag_name) end end def tag_filter(tags) rv = {} tags.each do |tag| rv[tag[0]] = [] unless rv.has_key?(tag[0]) rv[tag[0]].push(tag[1]) end rv end def empty_content? false end def content_is_set? if have_xml_content? __send__(self.class.xml_getter) else content end end def xmled_content if have_xml_content? __send__(self.class.xml_getter).to_s else _content = content _content = [_content].pack("m").delete("\n") if need_base64_encode? h(_content) end end end module RootElementMixin include XMLStyleSheetMixin attr_reader :output_encoding attr_reader :feed_type, :feed_subtype, :feed_version attr_accessor :version, :encoding, :standalone def initialize(feed_version, version=nil, encoding=nil, standalone=nil) super() @feed_type = nil @feed_subtype = nil @feed_version = feed_version @version = version || '1.0' @encoding = encoding @standalone = standalone @output_encoding = nil end def feed_info [@feed_type, @feed_version, @feed_subtype] end def output_encoding=(enc) @output_encoding = enc self.converter = Converter.new(@output_encoding, @encoding) end def setup_maker(maker) maker.version = version maker.encoding = encoding maker.standalone = standalone xml_stylesheets.each do |xss| xss.setup_maker(maker) end super end def to_feed(type, &block) Maker.make(type) do |maker| setup_maker(maker) block.call(maker) if block end end def to_rss(type, &block) to_feed("rss#{type}", &block) end def to_atom(type, &block) to_feed("atom:#{type}", &block) end def to_xml(type=nil, &block) if type.nil? or same_feed_type?(type) to_s else to_feed(type, &block).to_s
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/xml-stylesheet.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/xml-stylesheet.rb
require "rss/utils" module RSS module XMLStyleSheetMixin attr_accessor :xml_stylesheets def initialize(*args) super @xml_stylesheets = [] end private def xml_stylesheet_pi xsss = @xml_stylesheets.collect do |xss| pi = xss.to_s pi = nil if /\A\s*\z/ =~ pi pi end.compact xsss.push("") unless xsss.empty? xsss.join("\n") end end class XMLStyleSheet include Utils ATTRIBUTES = %w(href type title media charset alternate) GUESS_TABLE = { "xsl" => "text/xsl", "css" => "text/css", } attr_accessor(*ATTRIBUTES) attr_accessor(:do_validate) def initialize(*attrs) if attrs.size == 1 and (attrs.first.is_a?(Hash) or attrs.first.is_a?(Array)) attrs = attrs.first end @do_validate = true ATTRIBUTES.each do |attr| __send__("#{attr}=", nil) end vars = ATTRIBUTES.dup vars.unshift(:do_validate) attrs.each do |name, value| if vars.include?(name.to_s) __send__("#{name}=", value) end end end def to_s rv = "" if @href rv << %Q[<?xml-stylesheet] ATTRIBUTES.each do |name| if __send__(name) rv << %Q[ #{name}="#{h __send__(name)}"] end end rv << %Q[?>] end rv end remove_method(:href=) def href=(value) @href = value if @href and @type.nil? @type = guess_type(@href) end @href end remove_method(:alternate=) def alternate=(value) if value.nil? or /\A(?:yes|no)\z/ =~ value @alternate = value else if @do_validate args = ["?xml-stylesheet?", %Q[alternate="#{value}"]] raise NotAvailableValueError.new(*args) end end @alternate end def setup_maker(maker) xss = maker.xml_stylesheets.new_xml_stylesheet ATTRIBUTES.each do |attr| xss.__send__("#{attr}=", __send__(attr)) end end private def guess_type(filename) /\.([^.]+)$/ =~ filename GUESS_TABLE[$1] end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/slash.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/slash.rb
require 'rss/1.0' module RSS SLASH_PREFIX = 'slash' SLASH_URI = "http://purl.org/rss/1.0/modules/slash/" RDF.install_ns(SLASH_PREFIX, SLASH_URI) module SlashModel extend BaseModel ELEMENT_INFOS = \ [ ["section"], ["department"], ["comments", :positive_integer], ["hit_parade", :csv_integer], ] class << self def append_features(klass) super return if klass.instance_of?(Module) klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI) ELEMENT_INFOS.each do |name, type, *additional_infos| full_name = "#{SLASH_PREFIX}_#{name}" klass.install_text_element(full_name, SLASH_URI, "?", full_name, type, name) end klass.module_eval do alias_method(:slash_hit_parades, :slash_hit_parade) undef_method(:slash_hit_parade) alias_method(:slash_hit_parade, :slash_hit_parade_content) end end end end class RDF class Item; include SlashModel; end end SlashModel::ELEMENT_INFOS.each do |name, type| accessor_base = "#{SLASH_PREFIX}_#{name}" BaseListener.install_get_text_element(SLASH_URI, name, accessor_base) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore.rb
require "rss/rss" module RSS DC_PREFIX = 'dc' DC_URI = "http://purl.org/dc/elements/1.1/" module BaseDublinCoreModel def append_features(klass) super return if klass.instance_of?(Module) DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name| plural = plural_name || "#{name}s" full_name = "#{DC_PREFIX}_#{name}" full_plural_name = "#{DC_PREFIX}_#{plural}" klass_name = "DublinCore#{Utils.to_class_name(name)}" klass.install_must_call_validator(DC_PREFIX, DC_URI) klass.install_have_children_element(name, DC_URI, "*", full_name, full_plural_name) klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0)) remove_method :#{full_name} remove_method :#{full_name}= remove_method :set_#{full_name} def #{full_name} @#{full_name}.first and @#{full_name}.first.value end def #{full_name}=(new_value) @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value) end alias set_#{full_name} #{full_name}= EOC end klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0)) if method_defined?(:date) alias date_without_#{DC_PREFIX}_date= date= def date=(value) self.date_without_#{DC_PREFIX}_date = value self.#{DC_PREFIX}_date = value end else alias date #{DC_PREFIX}_date alias date= #{DC_PREFIX}_date= end # For backward compatibility alias #{DC_PREFIX}_rightses #{DC_PREFIX}_rights_list EOC end end module DublinCoreModel extend BaseModel extend BaseDublinCoreModel TEXT_ELEMENTS = { "title" => nil, "description" => nil, "creator" => nil, "subject" => nil, "publisher" => nil, "contributor" => nil, "type" => nil, "format" => nil, "identifier" => nil, "source" => nil, "language" => nil, "relation" => nil, "coverage" => nil, "rights" => "rights_list" } DATE_ELEMENTS = { "date" => "w3cdtf", } ELEMENT_NAME_INFOS = DublinCoreModel::TEXT_ELEMENTS.to_a DublinCoreModel::DATE_ELEMENTS.each do |name, | ELEMENT_NAME_INFOS << [name, nil] end ELEMENTS = TEXT_ELEMENTS.keys + DATE_ELEMENTS.keys ELEMENTS.each do |name, plural_name| module_eval(<<-EOC, *get_file_and_line_from_caller(0)) class DublinCore#{Utils.to_class_name(name)} < Element include RSS10 content_setup class << self def required_prefix DC_PREFIX end def required_uri DC_URI end end @tag_name = #{name.dump} alias_method(:value, :content) alias_method(:value=, :content=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end def full_name tag_name_with_prefix(DC_PREFIX) end def maker_target(target) target.new_#{name} end def setup_maker_attributes(#{name}) #{name}.content = content end end EOC end DATE_ELEMENTS.each do |name, type| tag_name = "#{DC_PREFIX}:#{name}" module_eval(<<-EOC, *get_file_and_line_from_caller(0)) class DublinCore#{Utils.to_class_name(name)} < Element remove_method(:content=) remove_method(:value=) date_writer("content", #{type.dump}, #{tag_name.dump}) alias_method(:value=, :content=) end EOC end end # For backward compatibility DublincoreModel = DublinCoreModel DublinCoreModel::ELEMENTS.each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(DC_URI, name, "DublinCore#{class_name}") end DublinCoreModel::ELEMENTS.collect! {|name| "#{DC_PREFIX}_#{name}"} end require 'rss/dublincore/1.0' require 'rss/dublincore/2.0' require 'rss/dublincore/atom'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/itunes.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/itunes.rb
require 'rss/2.0' module RSS ITUNES_PREFIX = 'itunes' ITUNES_URI = 'http://www.itunes.com/dtds/podcast-1.0.dtd' Rss.install_ns(ITUNES_PREFIX, ITUNES_URI) module ITunesModelUtils include Utils def def_class_accessor(klass, name, type, *args) normalized_name = name.gsub(/-/, "_") full_name = "#{ITUNES_PREFIX}_#{normalized_name}" klass_name = "ITunes#{Utils.to_class_name(normalized_name)}" case type when :element, :attribute klass::ELEMENTS << full_name def_element_class_accessor(klass, name, full_name, klass_name, *args) when :elements klass::ELEMENTS << full_name def_elements_class_accessor(klass, name, full_name, klass_name, *args) else klass.install_must_call_validator(ITUNES_PREFIX, ITUNES_URI) klass.install_text_element(normalized_name, ITUNES_URI, "?", full_name, type, name) end end def def_element_class_accessor(klass, name, full_name, klass_name, recommended_attribute_name=nil) klass.install_have_child_element(name, ITUNES_PREFIX, "?", full_name) end def def_elements_class_accessor(klass, name, full_name, klass_name, plural_name, recommended_attribute_name=nil) full_plural_name = "#{ITUNES_PREFIX}_#{plural_name}" klass.install_have_children_element(name, ITUNES_PREFIX, "*", full_name, full_plural_name) end end module ITunesBaseModel extend ITunesModelUtils ELEMENTS = [] ELEMENT_INFOS = [["author"], ["block", :yes_other], ["explicit", :yes_clean_other], ["keywords", :csv], ["subtitle"], ["summary"]] end module ITunesChannelModel extend BaseModel extend ITunesModelUtils include ITunesBaseModel ELEMENTS = [] class << self def append_features(klass) super return if klass.instance_of?(Module) ELEMENT_INFOS.each do |name, type, *additional_infos| def_class_accessor(klass, name, type, *additional_infos) end end end ELEMENT_INFOS = [ ["category", :elements, "categories", "text"], ["image", :attribute, "href"], ["owner", :element], ["new-feed-url"], ] + ITunesBaseModel::ELEMENT_INFOS class ITunesCategory < Element include RSS09 @tag_name = "category" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end end [ ["text", "", true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end ITunesCategory = self install_have_children_element("category", ITUNES_URI, "*", "#{ITUNES_PREFIX}_category", "#{ITUNES_PREFIX}_categories") def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.text = args[0] end end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def maker_target(categories) if text or !itunes_categories.empty? categories.new_category else nil end end def setup_maker_attributes(category) category.text = text if text end def setup_maker_elements(category) super(category) itunes_categories.each do |sub_category| sub_category.setup_maker(category) end end end class ITunesImage < Element include RSS09 @tag_name = "image" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end end [ ["href", "", true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.href = args[0] end end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def maker_target(target) if href target.itunes_image {|image| image} else nil end end def setup_maker_attributes(image) image.href = href end end class ITunesOwner < Element include RSS09 @tag_name = "owner" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end end install_must_call_validator(ITUNES_PREFIX, ITUNES_URI) [ ["name"], ["email"], ].each do |name,| ITunesBaseModel::ELEMENT_INFOS << name install_text_element(name, ITUNES_URI, nil, "#{ITUNES_PREFIX}_#{name}") end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.itunes_name = args[0] self.itunes_email = args[1] end end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def maker_target(target) target.itunes_owner end def setup_maker_element(owner) super(owner) owner.itunes_name = itunes_name owner.itunes_email = itunes_email end end end module ITunesItemModel extend BaseModel extend ITunesModelUtils include ITunesBaseModel class << self def append_features(klass) super return if klass.instance_of?(Module) ELEMENT_INFOS.each do |name, type| def_class_accessor(klass, name, type) end end end ELEMENT_INFOS = ITunesBaseModel::ELEMENT_INFOS + [["duration", :element, "content"]] class ITunesDuration < Element include RSS09 @tag_name = "duration" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end def parse(duration, do_validate=true) if do_validate and /\A(?: \d?\d:[0-5]\d:[0-5]\d| [0-5]?\d:[0-5]\d )\z/x !~ duration raise ArgumentError, "must be one of HH:MM:SS, H:MM:SS, MM::SS, M:SS: " + duration.inspect end components = duration.split(':') components[3..-1] = nil if components.size > 3 components.unshift("00") until components.size == 3 components.collect do |component| component.to_i end end def construct(hour, minute, second) components = [minute, second] if components.include?(nil) nil else components.unshift(hour) if hour and hour > 0 components.collect do |component| "%02d" % component end.join(":") end end end content_setup alias_method(:value, :content) remove_method(:content=) attr_reader :hour, :minute, :second def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() args = args[0] if args.size == 1 and args[0].is_a?(Array) if args.size == 1 self.content = args[0] elsif args.size > 3 raise ArgumentError, "must be (do_validate, params), (content), " + "(minute, second), ([minute, second]), " + "(hour, minute, second) or ([hour, minute, second]): " + args.inspect else @second, @minute, @hour = args.reverse update_content end end end def content=(value) if value.nil? @content = nil elsif value.is_a?(self.class) self.content = value.content else begin @hour, @minute, @second = self.class.parse(value, @do_validate) rescue ArgumentError raise NotAvailableValueError.new(tag_name, value) end @content = value end end alias_method(:value=, :content=) def hour=(hour) @hour = @do_validate ? Integer(hour) : hour.to_i update_content hour end def minute=(minute) @minute = @do_validate ? Integer(minute) : minute.to_i update_content minute end def second=(second) @second = @do_validate ? Integer(second) : second.to_i update_content second end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def update_content @content = self.class.construct(hour, minute, second) end def maker_target(target) if @content target.itunes_duration {|duration| duration} else nil end end def setup_maker_element(duration) super(duration) duration.content = @content end end end class Rss class Channel include ITunesChannelModel class Item; include ITunesItemModel; end end end element_infos = ITunesChannelModel::ELEMENT_INFOS + ITunesItemModel::ELEMENT_INFOS element_infos.each do |name, type| case type when :element, :elements, :attribute class_name = Utils.to_class_name(name) BaseListener.install_class_name(ITUNES_URI, name, "ITunes#{class_name}") else accessor_base = "#{ITUNES_PREFIX}_#{name.gsub(/-/, '_')}" BaseListener.install_get_text_element(ITUNES_URI, name, accessor_base) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/image.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/image.rb
require 'rss/1.0' require 'rss/dublincore' module RSS IMAGE_PREFIX = 'image' IMAGE_URI = 'http://purl.org/rss/1.0/modules/image/' RDF.install_ns(IMAGE_PREFIX, IMAGE_URI) IMAGE_ELEMENTS = [] %w(item favicon).each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(IMAGE_URI, name, "Image#{class_name}") IMAGE_ELEMENTS << "#{IMAGE_PREFIX}_#{name}" end module ImageModelUtils def validate_one_tag_name(ignore_unknown_element, name, tags) if !ignore_unknown_element invalid = tags.find {|tag| tag != name} raise UnknownTagError.new(invalid, IMAGE_URI) if invalid end raise TooMuchTagError.new(name, tag_name) if tags.size > 1 end end module ImageItemModel include ImageModelUtils extend BaseModel def self.append_features(klass) super klass.install_have_child_element("item", IMAGE_URI, "?", "#{IMAGE_PREFIX}_item") klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI) end class ImageItem < Element include RSS10 include DublinCoreModel @tag_name = "item" class << self def required_prefix IMAGE_PREFIX end def required_uri IMAGE_URI end end install_must_call_validator(IMAGE_PREFIX, IMAGE_URI) [ ["about", ::RSS::RDF::URI, true], ["resource", ::RSS::RDF::URI, false], ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{::RSS::RDF::PREFIX}:#{name}") end %w(width height).each do |tag| full_name = "#{IMAGE_PREFIX}_#{tag}" disp_name = "#{IMAGE_PREFIX}:#{tag}" install_text_element(tag, IMAGE_URI, "?", full_name, :integer, disp_name) BaseListener.install_get_text_element(IMAGE_URI, tag, full_name) end alias width= image_width= alias width image_width alias height= image_height= alias height image_height def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] self.resource = args[1] end end def full_name tag_name_with_prefix(IMAGE_PREFIX) end private def maker_target(target) target.image_item end def setup_maker_attributes(item) item.about = self.about item.resource = self.resource end end end module ImageFaviconModel include ImageModelUtils extend BaseModel def self.append_features(klass) super unless klass.class == Module klass.install_have_child_element("favicon", IMAGE_URI, "?", "#{IMAGE_PREFIX}_favicon") klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI) end end class ImageFavicon < Element include RSS10 include DublinCoreModel @tag_name = "favicon" class << self def required_prefix IMAGE_PREFIX end def required_uri IMAGE_URI end end [ ["about", ::RSS::RDF::URI, true, ::RSS::RDF::PREFIX], ["size", IMAGE_URI, true, IMAGE_PREFIX], ].each do |name, uri, required, prefix| install_get_attribute(name, uri, required, nil, nil, "#{prefix}:#{name}") end AVAILABLE_SIZES = %w(small medium large) alias_method :set_size, :size= private :set_size def size=(new_value) if @do_validate and !new_value.nil? new_value = new_value.strip unless AVAILABLE_SIZES.include?(new_value) attr_name = "#{IMAGE_PREFIX}:size" raise NotAvailableValueError.new(full_name, new_value, attr_name) end end set_size(new_value) end alias image_size= size= alias image_size size def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] self.size = args[1] end end def full_name tag_name_with_prefix(IMAGE_PREFIX) end private def maker_target(target) target.image_favicon end def setup_maker_attributes(favicon) favicon.about = self.about favicon.size = self.size end end end class RDF class Channel; include ImageFaviconModel; end class Item; include ImageItemModel; end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/xmlscanner.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/xmlscanner.rb
require 'xmlscan/scanner' require 'stringio' module RSS class XMLScanParser < BaseParser class << self def listener XMLScanListener end end private def _parse begin if @rss.is_a?(String) input = StringIO.new(@rss) else input = @rss end scanner = XMLScan::XMLScanner.new(@listener) scanner.parse(input) rescue XMLScan::Error => e lineno = e.lineno || scanner.lineno || input.lineno raise NotWellFormedError.new(lineno){e.message} end end end class XMLScanListener < BaseListener include XMLScan::Visitor include ListenerMixin ENTITIES = { 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '"', 'apos' => '\'' } def on_xmldecl_version(str) @version = str end def on_xmldecl_encoding(str) @encoding = str end def on_xmldecl_standalone(str) @standalone = str end def on_xmldecl_end xmldecl(@version, @encoding, @standalone == "yes") end alias_method(:on_pi, :instruction) alias_method(:on_chardata, :text) alias_method(:on_cdata, :text) def on_etag(name) tag_end(name) end def on_entityref(ref) text(entity(ref)) end def on_charref(code) text([code].pack('U')) end alias_method(:on_charref_hex, :on_charref) def on_stag(name) @attrs = {} end def on_attribute(name) @attrs[name] = @current_attr = '' end def on_attr_value(str) @current_attr << str end def on_attr_entityref(ref) @current_attr << entity(ref) end def on_attr_charref(code) @current_attr << [code].pack('U') end alias_method(:on_attr_charref_hex, :on_attr_charref) def on_stag_end(name) tag_start(name, @attrs) end def on_stag_end_empty(name) tag_start(name, @attrs) tag_end(name) end private def entity(ref) ent = ENTITIES[ref] if ent ent else wellformed_error("undefined entity: #{ref}") 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/trackback.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/trackback.rb
require 'rss/1.0' require 'rss/2.0' module RSS TRACKBACK_PREFIX = 'trackback' TRACKBACK_URI = 'http://madskills.com/public/xml/rss/module/trackback/' RDF.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI) Rss.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI) module TrackBackUtils private def trackback_validate(ignore_unknown_element, tags, uri) return if tags.nil? if tags.find {|tag| tag == "about"} and !tags.find {|tag| tag == "ping"} raise MissingTagError.new("#{TRACKBACK_PREFIX}:ping", tag_name) end end end module BaseTrackBackModel ELEMENTS = %w(ping about) def append_features(klass) super unless klass.class == Module klass.module_eval {include TrackBackUtils} klass.install_must_call_validator(TRACKBACK_PREFIX, TRACKBACK_URI) %w(ping).each do |name| var_name = "#{TRACKBACK_PREFIX}_#{name}" klass_name = "TrackBack#{Utils.to_class_name(name)}" klass.install_have_child_element(name, TRACKBACK_URI, "?", var_name) klass.module_eval(<<-EOC, __FILE__, __LINE__) remove_method :#{var_name} def #{var_name} @#{var_name} and @#{var_name}.value end remove_method :#{var_name}= def #{var_name}=(value) @#{var_name} = Utils.new_with_value_if_need(#{klass_name}, value) end EOC end [%w(about s)].each do |name, postfix| var_name = "#{TRACKBACK_PREFIX}_#{name}" klass_name = "TrackBack#{Utils.to_class_name(name)}" klass.install_have_children_element(name, TRACKBACK_URI, "*", var_name) klass.module_eval(<<-EOC, __FILE__, __LINE__) remove_method :#{var_name} def #{var_name}(*args) if args.empty? @#{var_name}.first and @#{var_name}.first.value else ret = @#{var_name}.__send__("[]", *args) if ret.is_a?(Array) ret.collect {|x| x.value} else ret.value end end end remove_method :#{var_name}= remove_method :set_#{var_name} def #{var_name}=(*args) if args.size == 1 item = Utils.new_with_value_if_need(#{klass_name}, args[0]) @#{var_name}.push(item) else new_val = args.last if new_val.is_a?(Array) new_val = new_value.collect do |val| Utils.new_with_value_if_need(#{klass_name}, val) end else new_val = Utils.new_with_value_if_need(#{klass_name}, new_val) end @#{var_name}.__send__("[]=", *(args[0..-2] + [new_val])) end end alias set_#{var_name} #{var_name}= EOC end end end end module TrackBackModel10 extend BaseModel extend BaseTrackBackModel class TrackBackPing < Element include RSS10 class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end @tag_name = "ping" [ ["resource", ::RSS::RDF::URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{::RSS::RDF::PREFIX}:#{name}") end alias_method(:value, :resource) alias_method(:value=, :resource=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end end class TrackBackAbout < Element include RSS10 class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end @tag_name = "about" [ ["resource", ::RSS::RDF::URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{::RSS::RDF::PREFIX}:#{name}") end alias_method(:value, :resource) alias_method(:value=, :resource=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end private def maker_target(abouts) abouts.new_about end def setup_maker_attributes(about) about.resource = self.resource end end end module TrackBackModel20 extend BaseModel extend BaseTrackBackModel class TrackBackPing < Element include RSS09 @tag_name = "ping" content_setup class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end alias_method(:value, :content) alias_method(:value=, :content=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end end class TrackBackAbout < Element include RSS09 @tag_name = "about" content_setup class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end alias_method(:value, :content) alias_method(:value=, :content=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end end end class RDF class Item; include TrackBackModel10; end end class Rss class Channel class Item; include TrackBackModel20; end end end BaseTrackBackModel::ELEMENTS.each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(TRACKBACK_URI, name, "TrackBack#{class_name}") end BaseTrackBackModel::ELEMENTS.collect! {|name| "#{TRACKBACK_PREFIX}_#{name}"} end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/content/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/content/1.0.rb
require 'rss/1.0' module RSS RDF.install_ns(CONTENT_PREFIX, CONTENT_URI) class RDF class Item; include ContentModel; end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/content/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/content/2.0.rb
require "rss/2.0" module RSS Rss.install_ns(CONTENT_PREFIX, CONTENT_URI) class Rss class Channel class Item; include ContentModel; 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore/1.0.rb
require "rss/1.0" module RSS RDF.install_ns(DC_PREFIX, DC_URI) class RDF class Channel; include DublinCoreModel; end class Image; include DublinCoreModel; end class Item; include DublinCoreModel; end class Textinput; include DublinCoreModel; end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore/2.0.rb
require "rss/2.0" module RSS Rss.install_ns(DC_PREFIX, DC_URI) class Rss class Channel include DublinCoreModel class Item; include DublinCoreModel; 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore/atom.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/dublincore/atom.rb
require "rss/atom" module RSS module Atom Feed.install_ns(DC_PREFIX, DC_URI) class Feed include DublinCoreModel class Entry; include DublinCoreModel; end end class Entry include DublinCoreModel end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/feed.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/feed.rb
require "rss/maker/atom" module RSS module Maker module Atom class Feed < RSSBase def initialize(feed_version="1.0") super @feed_type = "atom" @feed_subtype = "feed" end private def make_feed ::RSS::Atom::Feed.new(@version, @encoding, @standalone) end def setup_elements(feed) setup_channel(feed) setup_image(feed) setup_items(feed) end class Channel < ChannelBase include SetupDefaultLanguage def to_feed(feed) set_default_values do setup_values(feed) feed.dc_dates.clear setup_other_elements(feed) if image_favicon.about icon = feed.class::Icon.new icon.content = image_favicon.about feed.icon = icon end unless have_required_values? raise NotSetError.new("maker.channel", not_set_required_variables) end end end def have_required_values? super and (!authors.empty? or @maker.items.any? {|item| !item.authors.empty?}) end private def required_variable_names %w(id updated) end def variables super + %w(id updated) end def variable_is_set? super or !authors.empty? end def not_set_required_variables vars = super if authors.empty? and @maker.items.all? {|item| item.author.to_s.empty?} vars << "author" end vars << "title" unless title {|t| t.have_required_values?} vars end def _set_default_values(&block) keep = { :id => id, } self.id ||= about super(&block) ensure self.id = keep[:id] end class SkipDays < SkipDaysBase def to_feed(*args) end class Day < DayBase end end class SkipHours < SkipHoursBase def to_feed(*args) end class Hour < HourBase end end class Cloud < CloudBase def to_feed(*args) end end class Categories < CategoriesBase class Category < CategoryBase include AtomCategory def self.not_set_name "maker.channel.category" end end end class Links < LinksBase class Link < LinkBase include AtomLink def self.not_set_name "maker.channel.link" end end end AtomPersons.def_atom_persons(self, "author", "maker.channel.author") AtomPersons.def_atom_persons(self, "contributor", "maker.channel.contributor") class Generator < GeneratorBase include AtomGenerator def self.not_set_name "maker.channel.generator" end end AtomTextConstruct.def_atom_text_construct(self, "rights", "maker.channel.copyright", "Copyright") AtomTextConstruct.def_atom_text_construct(self, "subtitle", "maker.channel.description", "Description") AtomTextConstruct.def_atom_text_construct(self, "title", "maker.channel.title") end class Image < ImageBase def to_feed(feed) logo = feed.class::Logo.new class << logo alias_method(:url=, :content=) end set = setup_values(logo) class << logo remove_method(:url=) end if set feed.logo = logo set_parent(logo, feed) setup_other_elements(feed, logo) elsif variable_is_set? raise NotSetError.new("maker.image", not_set_required_variables) end end private def required_variable_names %w(url) end end class Items < ItemsBase def to_feed(feed) normalize.each do |item| item.to_feed(feed) end setup_other_elements(feed, feed.entries) end class Item < ItemBase def to_feed(feed) set_default_values do entry = feed.class::Entry.new set = setup_values(entry) entry.dc_dates.clear setup_other_elements(feed, entry) if set feed.entries << entry set_parent(entry, feed) elsif variable_is_set? raise NotSetError.new("maker.item", not_set_required_variables) end end end def have_required_values? set_default_values do super and title {|t| t.have_required_values?} end end private def required_variable_names %w(id updated) end def variables super + ["updated"] end def not_set_required_variables vars = super vars << "title" unless title {|t| t.have_required_values?} vars end def _set_default_values(&block) keep = { :id => id, } self.id ||= link super(&block) ensure self.id = keep[:id] end class Guid < GuidBase def to_feed(feed, current) end end class Enclosure < EnclosureBase def to_feed(feed, current) end end class Source < SourceBase def to_feed(feed, current) source = current.class::Source.new setup_values(source) current.source = source set_parent(source, current) setup_other_elements(feed, source) current.source = nil if source.to_s == "<source/>" end private def required_variable_names [] end def variables super + ["updated"] end AtomPersons.def_atom_persons(self, "author", "maker.item.source.author") AtomPersons.def_atom_persons(self, "contributor", "maker.item.source.contributor") class Categories < CategoriesBase class Category < CategoryBase include AtomCategory def self.not_set_name "maker.item.source.category" end end end class Generator < GeneratorBase include AtomGenerator def self.not_set_name "maker.item.source.generator" end end class Icon < IconBase def to_feed(feed, current) icon = current.class::Icon.new class << icon alias_method(:url=, :content=) end set = setup_values(icon) class << icon remove_method(:url=) end if set current.icon = icon set_parent(icon, current) setup_other_elements(feed, icon) elsif variable_is_set? raise NotSetError.new("maker.item.source.icon", not_set_required_variables) end end private def required_variable_names %w(url) end end class Links < LinksBase class Link < LinkBase include AtomLink def self.not_set_name "maker.item.source.link" end end end class Logo < LogoBase include AtomLogo def self.not_set_name "maker.item.source.logo" end end maker_name_base = "maker.item.source." maker_name = "#{maker_name_base}rights" AtomTextConstruct.def_atom_text_construct(self, "rights", maker_name) maker_name = "#{maker_name_base}subtitle" AtomTextConstruct.def_atom_text_construct(self, "subtitle", maker_name) maker_name = "#{maker_name_base}title" AtomTextConstruct.def_atom_text_construct(self, "title", maker_name) end class Categories < CategoriesBase class Category < CategoryBase include AtomCategory def self.not_set_name "maker.item.category" end end end AtomPersons.def_atom_persons(self, "author", "maker.item.author") AtomPersons.def_atom_persons(self, "contributor", "maker.item.contributor") class Links < LinksBase class Link < LinkBase include AtomLink def self.not_set_name "maker.item.link" end end end AtomTextConstruct.def_atom_text_construct(self, "rights", "maker.item.rights") AtomTextConstruct.def_atom_text_construct(self, "summary", "maker.item.description", "Description") AtomTextConstruct.def_atom_text_construct(self, "title", "maker.item.title") class Content < ContentBase def to_feed(feed, current) content = current.class::Content.new if setup_values(content) content.src = nil if content.src and content.content current.content = content set_parent(content, current) setup_other_elements(feed, content) elsif variable_is_set? raise NotSetError.new("maker.item.content", not_set_required_variables) end end alias_method(:xml, :xml_content) private def required_variable_names if out_of_line? %w(type) elsif xml_type? %w(xml_content) else %w(content) end end def variables if out_of_line? super elsif xml_type? super + %w(xml) else super end end def xml_type? _type = type return false if _type.nil? _type == "xhtml" or /(?:\+xml|\/xml)$/i =~ _type or %w(text/xml-external-parsed-entity application/xml-external-parsed-entity application/xml-dtd).include?(_type.downcase) end end end end class Textinput < TextinputBase end end end add_maker("atom", "1.0", Atom::Feed) add_maker("atom:feed", "1.0", Atom::Feed) add_maker("atom1.0", "1.0", Atom::Feed) add_maker("atom1.0:feed", "1.0", Atom::Feed) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/entry.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/entry.rb
require "rss/maker/atom" require "rss/maker/feed" module RSS module Maker module Atom class Entry < RSSBase def initialize(feed_version="1.0") super @feed_type = "atom" @feed_subtype = "entry" end private def make_feed ::RSS::Atom::Entry.new(@version, @encoding, @standalone) end def setup_elements(entry) setup_items(entry) end class Channel < ChannelBase class SkipDays < SkipDaysBase class Day < DayBase end end class SkipHours < SkipHoursBase class Hour < HourBase end end class Cloud < CloudBase end Categories = Feed::Channel::Categories Links = Feed::Channel::Links Authors = Feed::Channel::Authors Contributors = Feed::Channel::Contributors class Generator < GeneratorBase include AtomGenerator def self.not_set_name "maker.channel.generator" end end Copyright = Feed::Channel::Copyright class Description < DescriptionBase end Title = Feed::Channel::Title end class Image < ImageBase end class Items < ItemsBase def to_feed(entry) (normalize.first || Item.new(@maker)).to_feed(entry) end class Item < ItemBase def to_feed(entry) set_default_values do setup_values(entry) entry.dc_dates.clear setup_other_elements(entry) unless have_required_values? raise NotSetError.new("maker.item", not_set_required_variables) end end end private def required_variable_names %w(id updated) end def variables super + ["updated"] end def variable_is_set? super or !authors.empty? end def not_set_required_variables set_default_values do vars = super if authors.all? {|author| !author.have_required_values?} vars << "author" end vars << "title" unless title {|t| t.have_required_values?} vars end end def _set_default_values(&block) keep = { :authors => authors.to_a.dup, :contributors => contributors.to_a.dup, :categories => categories.to_a.dup, :id => id, :links => links.to_a.dup, :rights => @rights, :title => @title, :updated => updated, } authors.replace(@maker.channel.authors) if keep[:authors].empty? if keep[:contributors].empty? contributors.replace(@maker.channel.contributors) end if keep[:categories].empty? categories.replace(@maker.channel.categories) end self.id ||= link || @maker.channel.id links.replace(@maker.channel.links) if keep[:links].empty? unless keep[:rights].variable_is_set? @maker.channel.rights {|r| @rights = r} end unless keep[:title].variable_is_set? @maker.channel.title {|t| @title = t} end self.updated ||= @maker.channel.updated super(&block) ensure authors.replace(keep[:authors]) contributors.replace(keep[:contributors]) categories.replace(keep[:categories]) links.replace(keep[:links]) self.id = keep[:id] @rights = keep[:rights] @title = keep[:title] self.updated = keep[:updated] end Guid = Feed::Items::Item::Guid Enclosure = Feed::Items::Item::Enclosure Source = Feed::Items::Item::Source Categories = Feed::Items::Item::Categories Authors = Feed::Items::Item::Authors Contributors = Feed::Items::Item::Contributors Links = Feed::Items::Item::Links Rights = Feed::Items::Item::Rights Description = Feed::Items::Item::Description Title = Feed::Items::Item::Title Content = Feed::Items::Item::Content end end class Textinput < TextinputBase end end end add_maker("atom:entry", "1.0", Atom::Entry) add_maker("atom1.0:entry", "1.0", Atom::Entry) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/content.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/content.rb
require 'rss/content' require 'rss/maker/1.0' require 'rss/maker/2.0' module RSS module Maker module ContentModel def self.append_features(klass) super ::RSS::ContentModel::ELEMENTS.each do |name| klass.def_other_element(name) end end end class ItemsBase class ItemBase; include ContentModel; 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/syndication.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/syndication.rb
require 'rss/syndication' require 'rss/maker/1.0' module RSS module Maker module SyndicationModel def self.append_features(klass) super ::RSS::SyndicationModel::ELEMENTS.each do |name| klass.def_other_element(name) end end end class ChannelBase; include SyndicationModel; end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/taxonomy.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/taxonomy.rb
require 'rss/taxonomy' require 'rss/maker/1.0' require 'rss/maker/dublincore' module RSS module Maker module TaxonomyTopicsModel def self.append_features(klass) super klass.def_classed_element("#{RSS::TAXO_PREFIX}_topics", "TaxonomyTopics") end def self.install_taxo_topics(klass) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class TaxonomyTopics < TaxonomyTopicsBase def to_feed(feed, current) if current.respond_to?(:taxo_topics) topics = current.class::TaxonomyTopics.new bag = topics.Bag @resources.each do |resource| bag.lis << RDF::Bag::Li.new(resource) end current.taxo_topics = topics end end end EOC end class TaxonomyTopicsBase < Base attr_reader :resources def_array_element("resource") remove_method :new_resource end end module TaxonomyTopicModel def self.append_features(klass) super class_name = "TaxonomyTopics" klass.def_classed_elements("#{TAXO_PREFIX}_topic", "value", class_name) end def self.install_taxo_topic(klass) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class TaxonomyTopics < TaxonomyTopicsBase class TaxonomyTopic < TaxonomyTopicBase DublinCoreModel.install_dublin_core(self) TaxonomyTopicsModel.install_taxo_topics(self) def to_feed(feed, current) if current.respond_to?(:taxo_topics) topic = current.class::TaxonomyTopic.new(value) topic.taxo_link = value taxo_topics.to_feed(feed, topic) if taxo_topics current.taxo_topics << topic setup_other_elements(feed, topic) end end end end EOC end class TaxonomyTopicsBase < Base def_array_element("topic", nil, "TaxonomyTopic") alias_method(:new_taxo_topic, :new_topic) # For backward compatibility class TaxonomyTopicBase < Base include DublinCoreModel include TaxonomyTopicsModel attr_accessor :value add_need_initialize_variable("value") alias_method(:taxo_link, :value) alias_method(:taxo_link=, :value=) def have_required_values? @value end end end end class RSSBase include TaxonomyTopicModel end class ChannelBase include TaxonomyTopicsModel end class ItemsBase class ItemBase include TaxonomyTopicsModel end end makers.each do |maker| maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1) TaxonomyTopicModel.install_taxo_topic(self) class Channel TaxonomyTopicsModel.install_taxo_topics(self) end class Items class Item TaxonomyTopicsModel.install_taxo_topics(self) end end EOC end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/1.0.rb
require "rss/1.0" require "rss/maker/base" module RSS module Maker class RSS10 < RSSBase def initialize(feed_version="1.0") super @feed_type = "rss" end private def make_feed RDF.new(@version, @encoding, @standalone) end def setup_elements(rss) setup_channel(rss) setup_image(rss) setup_items(rss) setup_textinput(rss) end class Channel < ChannelBase include SetupDefaultLanguage def to_feed(rss) set_default_values do _not_set_required_variables = not_set_required_variables if _not_set_required_variables.empty? channel = RDF::Channel.new(@about) set = setup_values(channel) channel.dc_dates.clear rss.channel = channel set_parent(channel, rss) setup_items(rss) setup_image(rss) setup_textinput(rss) setup_other_elements(rss, channel) else raise NotSetError.new("maker.channel", _not_set_required_variables) end end end private def setup_items(rss) items = RDF::Channel::Items.new seq = items.Seq set_parent(items, seq) target_items = @maker.items.normalize raise NotSetError.new("maker", ["items"]) if target_items.empty? target_items.each do |item| li = RDF::Channel::Items::Seq::Li.new(item.link) seq.lis << li set_parent(li, seq) end rss.channel.items = items set_parent(rss.channel, items) end def setup_image(rss) if @maker.image.have_required_values? image = RDF::Channel::Image.new(@maker.image.url) rss.channel.image = image set_parent(image, rss.channel) end end def setup_textinput(rss) if @maker.textinput.have_required_values? textinput = RDF::Channel::Textinput.new(@maker.textinput.link) rss.channel.textinput = textinput set_parent(textinput, rss.channel) end end def required_variable_names %w(about link) end def not_set_required_variables vars = super vars << "description" unless description {|d| d.have_required_values?} vars << "title" unless title {|t| t.have_required_values?} vars end class SkipDays < SkipDaysBase def to_feed(*args) end class Day < DayBase end end class SkipHours < SkipHoursBase def to_feed(*args) end class Hour < HourBase end end class Cloud < CloudBase def to_feed(*args) end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Links < LinksBase def to_feed(rss, channel) return if @links.empty? @links.first.to_feed(rss, channel) end class Link < LinkBase def to_feed(rss, channel) if have_required_values? channel.link = href else raise NotSetError.new("maker.channel.link", not_set_required_variables) end end private def required_variable_names %w(href) end end end class Authors < AuthorsBase def to_feed(rss, channel) end class Author < AuthorBase def to_feed(rss, channel) end end end class Contributors < ContributorsBase def to_feed(rss, channel) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(rss, channel) end end class Copyright < CopyrightBase def to_feed(rss, channel) end end class Description < DescriptionBase def to_feed(rss, channel) channel.description = content if have_required_values? end private def required_variable_names %w(content) end end class Title < TitleBase def to_feed(rss, channel) channel.title = content if have_required_values? end private def required_variable_names %w(content) end end end class Image < ImageBase def to_feed(rss) if @url image = RDF::Image.new(@url) set = setup_values(image) if set rss.image = image set_parent(image, rss) setup_other_elements(rss, image) end end end def have_required_values? super and @maker.channel.have_required_values? end private def variables super + ["link"] end def required_variable_names %w(url title link) end end class Items < ItemsBase def to_feed(rss) if rss.channel normalize.each do |item| item.to_feed(rss) end setup_other_elements(rss, rss.items) end end class Item < ItemBase def to_feed(rss) set_default_values do item = RDF::Item.new(link) set = setup_values(item) if set item.dc_dates.clear rss.items << item set_parent(item, rss) setup_other_elements(rss, item) elsif !have_required_values? raise NotSetError.new("maker.item", not_set_required_variables) end end end private def required_variable_names %w(link) end def variables super + %w(link) end def not_set_required_variables set_default_values do vars = super vars << "title" unless title {|t| t.have_required_values?} vars end end class Guid < GuidBase def to_feed(*args) end end class Enclosure < EnclosureBase def to_feed(*args) end end class Source < SourceBase def to_feed(*args) end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Contributors < ContributorsBase def to_feed(*args) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(*args) end end class Icon < IconBase def to_feed(*args) end end class Links < LinksBase def to_feed(*args) end class Link < LinkBase end end class Logo < LogoBase def to_feed(*args) end end class Rights < RightsBase def to_feed(*args) end end class Subtitle < SubtitleBase def to_feed(*args) end end class Title < TitleBase def to_feed(*args) end end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Links < LinksBase def to_feed(*args) end class Link < LinkBase end end class Contributors < ContributorsBase def to_feed(rss, item) end class Contributor < ContributorBase end end class Rights < RightsBase def to_feed(rss, item) end end class Description < DescriptionBase def to_feed(rss, item) item.description = content if have_required_values? end private def required_variable_names %w(content) end end class Content < ContentBase def to_feed(rss, item) end end class Title < TitleBase def to_feed(rss, item) item.title = content if have_required_values? end private def required_variable_names %w(content) end end end end class Textinput < TextinputBase def to_feed(rss) if @link textinput = RDF::Textinput.new(@link) set = setup_values(textinput) if set rss.textinput = textinput set_parent(textinput, rss) setup_other_elements(rss, textinput) end end end def have_required_values? super and @maker.channel.have_required_values? end private def required_variable_names %w(title description name link) end end end add_maker("1.0", "1.0", RSS10) add_maker("rss1.0", "1.0", RSS10) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/2.0.rb
require "rss/2.0" require "rss/maker/0.9" module RSS module Maker class RSS20 < RSS09 def initialize(feed_version="2.0") super end class Channel < RSS09::Channel private def required_variable_names %w(link) end class SkipDays < RSS09::Channel::SkipDays class Day < RSS09::Channel::SkipDays::Day end end class SkipHours < RSS09::Channel::SkipHours class Hour < RSS09::Channel::SkipHours::Hour end end class Cloud < RSS09::Channel::Cloud def to_feed(rss, channel) cloud = Rss::Channel::Cloud.new set = setup_values(cloud) if set channel.cloud = cloud set_parent(cloud, channel) setup_other_elements(rss, cloud) end end private def required_variable_names %w(domain port path registerProcedure protocol) end end class Categories < RSS09::Channel::Categories def to_feed(rss, channel) @categories.each do |category| category.to_feed(rss, channel) end end class Category < RSS09::Channel::Categories::Category def to_feed(rss, channel) category = Rss::Channel::Category.new set = setup_values(category) if set channel.categories << category set_parent(category, channel) setup_other_elements(rss, category) end end private def required_variable_names %w(content) end end end class Generator < GeneratorBase def to_feed(rss, channel) channel.generator = content end private def required_variable_names %w(content) end end end class Image < RSS09::Image private def required_element? false end end class Items < RSS09::Items class Item < RSS09::Items::Item private def required_variable_names [] end def not_set_required_variables vars = super if !title {|t| t.have_required_values?} and !description {|d| d.have_required_values?} vars << "title or description" end vars end def variables super + ["pubDate"] end class Guid < RSS09::Items::Item::Guid def to_feed(rss, item) guid = Rss::Channel::Item::Guid.new set = setup_values(guid) if set item.guid = guid set_parent(guid, item) setup_other_elements(rss, guid) end end private def required_variable_names %w(content) end end class Enclosure < RSS09::Items::Item::Enclosure def to_feed(rss, item) enclosure = Rss::Channel::Item::Enclosure.new set = setup_values(enclosure) if set item.enclosure = enclosure set_parent(enclosure, item) setup_other_elements(rss, enclosure) end end private def required_variable_names %w(url length type) end end class Source < RSS09::Items::Item::Source def to_feed(rss, item) source = Rss::Channel::Item::Source.new set = setup_values(source) if set item.source = source set_parent(source, item) setup_other_elements(rss, source) end end private def required_variable_names %w(url content) end class Links < RSS09::Items::Item::Source::Links def to_feed(rss, source) return if @links.empty? @links.first.to_feed(rss, source) end class Link < RSS09::Items::Item::Source::Links::Link def to_feed(rss, source) source.url = href end end end end class Categories < RSS09::Items::Item::Categories def to_feed(rss, item) @categories.each do |category| category.to_feed(rss, item) end end class Category < RSS09::Items::Item::Categories::Category def to_feed(rss, item) category = Rss::Channel::Item::Category.new set = setup_values(category) if set item.categories << category set_parent(category, item) setup_other_elements(rss) end end private def required_variable_names %w(content) end end end class Authors < RSS09::Items::Item::Authors def to_feed(rss, item) return if @authors.empty? @authors.first.to_feed(rss, item) end class Author < RSS09::Items::Item::Authors::Author def to_feed(rss, item) item.author = name end end end end end class Textinput < RSS09::Textinput end end add_maker("2.0", "2.0", RSS20) add_maker("rss2.0", "2.0", RSS20) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/base.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/base.rb
require 'forwardable' require 'rss/rss' module RSS module Maker class Base extend Utils::InheritedReader OTHER_ELEMENTS = [] NEED_INITIALIZE_VARIABLES = [] class << self def other_elements inherited_array_reader("OTHER_ELEMENTS") end def need_initialize_variables inherited_array_reader("NEED_INITIALIZE_VARIABLES") end def inherited_base ::RSS::Maker::Base end def inherited(subclass) subclass.const_set("OTHER_ELEMENTS", []) subclass.const_set("NEED_INITIALIZE_VARIABLES", []) end def add_other_element(variable_name) self::OTHER_ELEMENTS << variable_name end def add_need_initialize_variable(variable_name, init_value=nil, &init_block) init_value ||= init_block self::NEED_INITIALIZE_VARIABLES << [variable_name, init_value] end def def_array_element(name, plural=nil, klass_name=nil) include Enumerable extend Forwardable plural ||= "#{name}s" klass_name ||= Utils.to_class_name(name) def_delegators("@#{plural}", :<<, :[], :[]=, :first, :last) def_delegators("@#{plural}", :push, :pop, :shift, :unshift) def_delegators("@#{plural}", :each, :size, :empty?, :clear) add_need_initialize_variable(plural) {[]} module_eval(<<-EOC, __FILE__, __LINE__ + 1) def new_#{name} #{name} = self.class::#{klass_name}.new(@maker) @#{plural} << #{name} if block_given? yield #{name} else #{name} end end alias new_child new_#{name} def to_feed(*args) @#{plural}.each do |#{name}| #{name}.to_feed(*args) end end def replace(elements) @#{plural}.replace(elements.to_a) end EOC end def def_classed_element_without_accessor(name, class_name=nil) class_name ||= Utils.to_class_name(name) add_other_element(name) add_need_initialize_variable(name) do |object| object.send("make_#{name}") end module_eval(<<-EOC, __FILE__, __LINE__ + 1) private def setup_#{name}(feed, current) @#{name}.to_feed(feed, current) end def make_#{name} self.class::#{class_name}.new(@maker) end EOC end def def_classed_element(name, class_name=nil, attribute_name=nil) def_classed_element_without_accessor(name, class_name) if attribute_name module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name} if block_given? yield(@#{name}) else @#{name}.#{attribute_name} end end def #{name}=(new_value) @#{name}.#{attribute_name} = new_value end EOC else attr_reader name end end def def_classed_elements(name, attribute, plural_class_name=nil, plural_name=nil, new_name=nil) plural_name ||= "#{name}s" new_name ||= name def_classed_element(plural_name, plural_class_name) local_variable_name = "_#{name}" new_value_variable_name = "new_value" additional_setup_code = nil if block_given? additional_setup_code = yield(local_variable_name, new_value_variable_name) end module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name} #{local_variable_name} = #{plural_name}.first #{local_variable_name} ? #{local_variable_name}.#{attribute} : nil end def #{name}=(#{new_value_variable_name}) #{local_variable_name} = #{plural_name}.first || #{plural_name}.new_#{new_name} #{additional_setup_code} #{local_variable_name}.#{attribute} = #{new_value_variable_name} end EOC end def def_other_element(name) attr_accessor name def_other_element_without_accessor(name) end def def_other_element_without_accessor(name) add_need_initialize_variable(name) add_other_element(name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def setup_#{name}(feed, current) if !@#{name}.nil? and current.respond_to?(:#{name}=) current.#{name} = @#{name} end end EOC end def def_csv_element(name, type=nil) def_other_element_without_accessor(name) attr_reader(name) converter = "" if type == :integer converter = "{|v| Integer(v)}" end module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(value) @#{name} = Utils::CSV.parse(value)#{converter} end EOC end end attr_reader :maker def initialize(maker) @maker = maker @default_values_are_set = false initialize_variables end def have_required_values? not_set_required_variables.empty? end def variable_is_set? variables.any? {|var| not __send__(var).nil?} end private def initialize_variables self.class.need_initialize_variables.each do |variable_name, init_value| if init_value.nil? value = nil else if init_value.respond_to?(:call) value = init_value.call(self) elsif init_value.is_a?(String) # just for backward compatibility value = instance_eval(init_value, __FILE__, __LINE__) else value = init_value end end instance_variable_set("@#{variable_name}", value) end end def setup_other_elements(feed, current=nil) current ||= current_element(feed) self.class.other_elements.each do |element| __send__("setup_#{element}", feed, current) end end def current_element(feed) feed end def set_default_values(&block) return yield if @default_values_are_set begin @default_values_are_set = true _set_default_values(&block) ensure @default_values_are_set = false end end def _set_default_values(&block) yield end def setup_values(target) set = false if have_required_values? variables.each do |var| setter = "#{var}=" if target.respond_to?(setter) value = __send__(var) unless value.nil? target.__send__(setter, value) set = true end end end end set end def set_parent(target, parent) target.parent = parent if target.class.need_parent? end def variables self.class.need_initialize_variables.find_all do |name, init| # init == "nil" is just for backward compatibility init.nil? or init == "nil" end.collect do |name, init| name end end def not_set_required_variables required_variable_names.find_all do |var| __send__(var).nil? end end def required_variables_are_set? required_variable_names.each do |var| return false if __send__(var).nil? end true end end module AtomPersonConstructBase def self.append_features(klass) super klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) %w(name uri email).each do |element| attr_accessor element add_need_initialize_variable(element) end EOC end end module AtomTextConstructBase module EnsureXMLContent class << self def included(base) super base.class_eval do %w(type content xml_content).each do |element| attr_reader element attr_writer element if element != "xml_content" add_need_initialize_variable(element) end alias_method(:xhtml, :xml_content) end end end def ensure_xml_content(content) xhtml_uri = ::RSS::Atom::XHTML_URI unless content.is_a?(RSS::XML::Element) and ["div", xhtml_uri] == [content.name, content.uri] children = content children = [children] unless content.is_a?(Array) children = set_xhtml_uri_as_default_uri(children) content = RSS::XML::Element.new("div", nil, xhtml_uri, {"xmlns" => xhtml_uri}, children) end content end def xml_content=(content) @xml_content = ensure_xml_content(content) end def xhtml=(content) self.xml_content = content end private def set_xhtml_uri_as_default_uri(children) children.collect do |child| if child.is_a?(RSS::XML::Element) and child.prefix.nil? and child.uri.nil? RSS::XML::Element.new(child.name, nil, ::RSS::Atom::XHTML_URI, child.attributes.dup, set_xhtml_uri_as_default_uri(child.children)) else child end end end end def self.append_features(klass) super klass.class_eval do include EnsureXMLContent end end end module SetupDefaultDate private def _set_default_values(&block) keep = { :date => date, :dc_dates => dc_dates.to_a.dup, } _date = date if _date and !dc_dates.any? {|dc_date| dc_date.value == _date} dc_date = self.class::DublinCoreDates::DublinCoreDate.new(self) dc_date.value = _date.dup dc_dates.unshift(dc_date) end self.date ||= self.dc_date super(&block) ensure date = keep[:date] dc_dates.replace(keep[:dc_dates]) end end module SetupDefaultLanguage private def _set_default_values(&block) keep = { :dc_languages => dc_languages.to_a.dup, } _language = language if _language and !dc_languages.any? {|dc_language| dc_language.value == _language} dc_language = self.class::DublinCoreLanguages::DublinCoreLanguage.new(self) dc_language.value = _language.dup dc_languages.unshift(dc_language) end super(&block) ensure dc_languages.replace(keep[:dc_languages]) end end class RSSBase < Base class << self def make(*args, &block) new(*args).make(&block) end end %w(xml_stylesheets channel image items textinput).each do |element| attr_reader element add_need_initialize_variable(element) do |object| object.send("make_#{element}") end module_eval(<<-EOC, __FILE__, __LINE__ + 1) private def setup_#{element}(feed) @#{element}.to_feed(feed) end def make_#{element} self.class::#{Utils.to_class_name(element)}.new(self) end EOC end attr_reader :feed_version alias_method(:rss_version, :feed_version) attr_accessor :version, :encoding, :standalone def initialize(feed_version) super(self) @feed_type = nil @feed_subtype = nil @feed_version = feed_version @version = "1.0" @encoding = "UTF-8" @standalone = nil end def make yield(self) to_feed end def to_feed feed = make_feed setup_xml_stylesheets(feed) setup_elements(feed) setup_other_elements(feed) feed.validate feed end private remove_method :make_xml_stylesheets def make_xml_stylesheets XMLStyleSheets.new(self) end end class XMLStyleSheets < Base def_array_element("xml_stylesheet", nil, "XMLStyleSheet") class XMLStyleSheet < Base ::RSS::XMLStyleSheet::ATTRIBUTES.each do |attribute| attr_accessor attribute add_need_initialize_variable(attribute) end def to_feed(feed) xss = ::RSS::XMLStyleSheet.new guess_type_if_need(xss) set = setup_values(xss) if set feed.xml_stylesheets << xss end end private def guess_type_if_need(xss) if @type.nil? xss.href = @href @type = xss.type end end def required_variable_names %w(href type) end end end class ChannelBase < Base include SetupDefaultDate %w(cloud categories skipDays skipHours).each do |name| def_classed_element(name) end %w(generator copyright description title).each do |name| def_classed_element(name, nil, "content") end [ ["link", "href", Proc.new {|target,| "#{target}.href = 'self'"}], ["author", "name"], ["contributor", "name"], ].each do |name, attribute, additional_setup_maker| def_classed_elements(name, attribute, &additional_setup_maker) end %w(id about language managingEditor webMaster rating docs date lastBuildDate ttl).each do |element| attr_accessor element add_need_initialize_variable(element) end def pubDate date end def pubDate=(date) self.date = date end def updated date end def updated=(date) self.date = date end alias_method(:rights, :copyright) alias_method(:rights=, :copyright=) alias_method(:subtitle, :description) alias_method(:subtitle=, :description=) def icon image_favicon.about end def icon=(url) image_favicon.about = url end def logo maker.image.url end def logo=(url) maker.image.url = url end class SkipDaysBase < Base def_array_element("day") class DayBase < Base %w(content).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class SkipHoursBase < Base def_array_element("hour") class HourBase < Base %w(content).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class CloudBase < Base %w(domain port path registerProcedure protocol).each do |element| attr_accessor element add_need_initialize_variable(element) end end class CategoriesBase < Base def_array_element("category", "categories") class CategoryBase < Base %w(domain content label).each do |element| attr_accessor element add_need_initialize_variable(element) end alias_method(:term, :domain) alias_method(:term=, :domain=) alias_method(:scheme, :content) alias_method(:scheme=, :content=) end end class LinksBase < Base def_array_element("link") class LinkBase < Base %w(href rel type hreflang title length).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class AuthorsBase < Base def_array_element("author") class AuthorBase < Base include AtomPersonConstructBase end end class ContributorsBase < Base def_array_element("contributor") class ContributorBase < Base include AtomPersonConstructBase end end class GeneratorBase < Base %w(uri version content).each do |element| attr_accessor element add_need_initialize_variable(element) end end class CopyrightBase < Base include AtomTextConstructBase end class DescriptionBase < Base include AtomTextConstructBase end class TitleBase < Base include AtomTextConstructBase end end class ImageBase < Base %w(title url width height description).each do |element| attr_accessor element add_need_initialize_variable(element) end def link @maker.channel.link end end class ItemsBase < Base def_array_element("item") attr_accessor :do_sort, :max_size def initialize(maker) super @do_sort = false @max_size = -1 end def normalize if @max_size >= 0 sort_if_need[0...@max_size] else sort_if_need[0..@max_size] end end private def sort_if_need if @do_sort.respond_to?(:call) @items.sort do |x, y| @do_sort.call(x, y) end elsif @do_sort @items.sort do |x, y| y <=> x end else @items end end class ItemBase < Base include SetupDefaultDate %w(guid enclosure source categories content).each do |name| def_classed_element(name) end %w(rights description title).each do |name| def_classed_element(name, nil, "content") end [ ["author", "name"], ["link", "href", Proc.new {|target,| "#{target}.href = 'alternate'"}], ["contributor", "name"], ].each do |name, attribute| def_classed_elements(name, attribute) end %w(date comments id published).each do |element| attr_accessor element add_need_initialize_variable(element) end def pubDate date end def pubDate=(date) self.date = date end def updated date end def updated=(date) self.date = date end alias_method(:summary, :description) alias_method(:summary=, :description=) def <=>(other) _date = date || dc_date _other_date = other.date || other.dc_date if _date and _other_date _date <=> _other_date elsif _date 1 elsif _other_date -1 else 0 end end class GuidBase < Base %w(isPermaLink content).each do |element| attr_accessor element add_need_initialize_variable(element) end def permanent_link? isPermaLink end def permanent_link=(bool) self.isPermaLink = bool end end class EnclosureBase < Base %w(url length type).each do |element| attr_accessor element add_need_initialize_variable(element) end end class SourceBase < Base %w(authors categories contributors generator icon logo rights subtitle title).each do |name| def_classed_element(name) end [ ["link", "href"], ].each do |name, attribute| def_classed_elements(name, attribute) end %w(id content date).each do |element| attr_accessor element add_need_initialize_variable(element) end alias_method(:url, :link) alias_method(:url=, :link=) def updated date end def updated=(date) self.date = date end private AuthorsBase = ChannelBase::AuthorsBase CategoriesBase = ChannelBase::CategoriesBase ContributorsBase = ChannelBase::ContributorsBase GeneratorBase = ChannelBase::GeneratorBase class IconBase < Base %w(url).each do |element| attr_accessor element add_need_initialize_variable(element) end end LinksBase = ChannelBase::LinksBase class LogoBase < Base %w(uri).each do |element| attr_accessor element add_need_initialize_variable(element) end end class RightsBase < Base include AtomTextConstructBase end class SubtitleBase < Base include AtomTextConstructBase end class TitleBase < Base include AtomTextConstructBase end end CategoriesBase = ChannelBase::CategoriesBase AuthorsBase = ChannelBase::AuthorsBase LinksBase = ChannelBase::LinksBase ContributorsBase = ChannelBase::ContributorsBase class RightsBase < Base include AtomTextConstructBase end class DescriptionBase < Base include AtomTextConstructBase end class ContentBase < Base include AtomTextConstructBase::EnsureXMLContent %w(src).each do |element| attr_accessor(element) add_need_initialize_variable(element) end def xml_content=(content) content = ensure_xml_content(content) if inline_xhtml? @xml_content = content end alias_method(:xml, :xml_content) alias_method(:xml=, :xml_content=) def inline_text? [nil, "text", "html"].include?(@type) end def inline_html? @type == "html" end def inline_xhtml? @type == "xhtml" end def inline_other? !out_of_line? and ![nil, "text", "html", "xhtml"].include?(@type) end def inline_other_text? return false if @type.nil? or out_of_line? /\Atext\//i.match(@type) ? true : false end def inline_other_xml? return false if @type.nil? or out_of_line? /[\+\/]xml\z/i.match(@type) ? true : false end def inline_other_base64? return false if @type.nil? or out_of_line? @type.include?("/") and !inline_other_text? and !inline_other_xml? end def out_of_line? not @src.nil? and @content.nil? end end class TitleBase < Base include AtomTextConstructBase end end end class TextinputBase < Base %w(title description name link).each do |element| attr_accessor element add_need_initialize_variable(element) 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/0.9.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/0.9.rb
require "rss/0.9" require "rss/maker/base" module RSS module Maker class RSS09 < RSSBase def initialize(feed_version) super @feed_type = "rss" end private def make_feed Rss.new(@feed_version, @version, @encoding, @standalone) end def setup_elements(rss) setup_channel(rss) end class Channel < ChannelBase def to_feed(rss) channel = Rss::Channel.new set = setup_values(channel) _not_set_required_variables = not_set_required_variables if _not_set_required_variables.empty? rss.channel = channel set_parent(channel, rss) setup_items(rss) setup_image(rss) setup_textinput(rss) setup_other_elements(rss, channel) rss else raise NotSetError.new("maker.channel", _not_set_required_variables) end end private def setup_items(rss) @maker.items.to_feed(rss) end def setup_image(rss) @maker.image.to_feed(rss) end def setup_textinput(rss) @maker.textinput.to_feed(rss) end def variables super + ["pubDate"] end def required_variable_names %w(link language) end def not_set_required_variables vars = super vars << "description" unless description {|d| d.have_required_values?} vars << "title" unless title {|t| t.have_required_values?} vars end class SkipDays < SkipDaysBase def to_feed(rss, channel) unless @days.empty? skipDays = Rss::Channel::SkipDays.new channel.skipDays = skipDays set_parent(skipDays, channel) @days.each do |day| day.to_feed(rss, skipDays.days) end end end class Day < DayBase def to_feed(rss, days) day = Rss::Channel::SkipDays::Day.new set = setup_values(day) if set days << day set_parent(day, days) setup_other_elements(rss, day) end end private def required_variable_names %w(content) end end end class SkipHours < SkipHoursBase def to_feed(rss, channel) unless @hours.empty? skipHours = Rss::Channel::SkipHours.new channel.skipHours = skipHours set_parent(skipHours, channel) @hours.each do |hour| hour.to_feed(rss, skipHours.hours) end end end class Hour < HourBase def to_feed(rss, hours) hour = Rss::Channel::SkipHours::Hour.new set = setup_values(hour) if set hours << hour set_parent(hour, hours) setup_other_elements(rss, hour) end end private def required_variable_names %w(content) end end end class Cloud < CloudBase def to_feed(*args) end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Links < LinksBase def to_feed(rss, channel) return if @links.empty? @links.first.to_feed(rss, channel) end class Link < LinkBase def to_feed(rss, channel) if have_required_values? channel.link = href else raise NotSetError.new("maker.channel.link", not_set_required_variables) end end private def required_variable_names %w(href) end end end class Authors < AuthorsBase def to_feed(rss, channel) end class Author < AuthorBase def to_feed(rss, channel) end end end class Contributors < ContributorsBase def to_feed(rss, channel) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(rss, channel) end end class Copyright < CopyrightBase def to_feed(rss, channel) channel.copyright = content if have_required_values? end private def required_variable_names %w(content) end end class Description < DescriptionBase def to_feed(rss, channel) channel.description = content if have_required_values? end private def required_variable_names %w(content) end end class Title < TitleBase def to_feed(rss, channel) channel.title = content if have_required_values? end private def required_variable_names %w(content) end end end class Image < ImageBase def to_feed(rss) image = Rss::Channel::Image.new set = setup_values(image) if set image.link = link rss.channel.image = image set_parent(image, rss.channel) setup_other_elements(rss, image) elsif required_element? raise NotSetError.new("maker.image", not_set_required_variables) end end private def required_variable_names %w(url title link) end def required_element? true end end class Items < ItemsBase def to_feed(rss) if rss.channel normalize.each do |item| item.to_feed(rss) end setup_other_elements(rss, rss.items) end end class Item < ItemBase def to_feed(rss) item = Rss::Channel::Item.new set = setup_values(item) _not_set_required_variables = not_set_required_variables if _not_set_required_variables.empty? rss.items << item set_parent(item, rss.channel) setup_other_elements(rss, item) elsif variable_is_set? raise NotSetError.new("maker.items", _not_set_required_variables) end end private def required_variable_names [] end def not_set_required_variables vars = super if @maker.feed_version == "0.91" vars << "title" unless title {|t| t.have_required_values?} vars << "link" unless link {|l| l.have_required_values?} end vars end class Guid < GuidBase def to_feed(*args) end end class Enclosure < EnclosureBase def to_feed(*args) end end class Source < SourceBase def to_feed(*args) end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Contributors < ContributorsBase def to_feed(*args) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(*args) end end class Icon < IconBase def to_feed(*args) end end class Links < LinksBase def to_feed(*args) end class Link < LinkBase end end class Logo < LogoBase def to_feed(*args) end end class Rights < RightsBase def to_feed(*args) end end class Subtitle < SubtitleBase def to_feed(*args) end end class Title < TitleBase def to_feed(*args) end end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Links < LinksBase def to_feed(rss, item) return if @links.empty? @links.first.to_feed(rss, item) end class Link < LinkBase def to_feed(rss, item) if have_required_values? item.link = href else raise NotSetError.new("maker.link", not_set_required_variables) end end private def required_variable_names %w(href) end end end class Contributors < ContributorsBase def to_feed(rss, item) end class Contributor < ContributorBase end end class Rights < RightsBase def to_feed(rss, item) end end class Description < DescriptionBase def to_feed(rss, item) item.description = content if have_required_values? end private def required_variable_names %w(content) end end class Content < ContentBase def to_feed(rss, item) end end class Title < TitleBase def to_feed(rss, item) item.title = content if have_required_values? end private def required_variable_names %w(content) end end end end class Textinput < TextinputBase def to_feed(rss) textInput = Rss::Channel::TextInput.new set = setup_values(textInput) if set rss.channel.textInput = textInput set_parent(textInput, rss.channel) setup_other_elements(rss, textInput) end end private def required_variable_names %w(title description name link) end end end class RSS091 < RSS09 def initialize(feed_version="0.91") super end class Channel < RSS09::Channel end class Items < RSS09::Items class Item < RSS09::Items::Item end end class Image < RSS09::Image end class Textinput < RSS09::Textinput end end class RSS092 < RSS09 def initialize(feed_version="0.92") super end class Channel < RSS09::Channel end class Items < RSS09::Items class Item < RSS09::Items::Item end end class Image < RSS09::Image end class Textinput < RSS09::Textinput end end add_maker("0.9", "0.92", RSS092) add_maker("0.91", "0.91", RSS091) add_maker("0.92", "0.92", RSS092) add_maker("rss0.9", "0.92", RSS092) add_maker("rss0.91", "0.91", RSS091) add_maker("rss0.92", "0.92", RSS092) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/atom.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/atom.rb
require "rss/atom" require "rss/maker/base" module RSS module Maker module AtomPersons module_function def def_atom_persons(klass, name, maker_name, plural=nil) plural ||= "#{name}s" klass_name = Utils.to_class_name(name) plural_klass_name = Utils.to_class_name(plural) klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) class #{plural_klass_name} < #{plural_klass_name}Base class #{klass_name} < #{klass_name}Base def to_feed(feed, current) #{name} = feed.class::#{klass_name}.new set = setup_values(#{name}) unless set raise NotSetError.new(#{maker_name.dump}, not_set_required_variables) end current.#{plural} << #{name} set_parent(#{name}, current) setup_other_elements(#{name}) end private def required_variable_names %w(name) end end end EOC end end module AtomTextConstruct class << self def def_atom_text_construct(klass, name, maker_name, klass_name=nil, atom_klass_name=nil) klass_name ||= Utils.to_class_name(name) atom_klass_name ||= Utils.to_class_name(name) klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) class #{klass_name} < #{klass_name}Base include #{self.name} def to_feed(feed, current) #{name} = current.class::#{atom_klass_name}.new if setup_values(#{name}) current.#{name} = #{name} set_parent(#{name}, current) setup_other_elements(feed) elsif variable_is_set? raise NotSetError.new(#{maker_name.dump}, not_set_required_variables) end end end EOC end end private def required_variable_names if type == "xhtml" %w(xml_content) else %w(content) end end def variables if type == "xhtml" super + %w(xhtml) else super end end end module AtomCategory def to_feed(feed, current) category = feed.class::Category.new set = setup_values(category) if set current.categories << category set_parent(category, current) setup_other_elements(feed) else raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(term) end def variables super + ["term", "scheme"] end end module AtomLink def to_feed(feed, current) link = feed.class::Link.new set = setup_values(link) if set current.links << link set_parent(link, current) setup_other_elements(feed) else raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(href) end end module AtomGenerator def to_feed(feed, current) generator = current.class::Generator.new if setup_values(generator) current.generator = generator set_parent(generator, current) setup_other_elements(feed) elsif variable_is_set? raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(content) end end module AtomLogo def to_feed(feed, current) logo = current.class::Logo.new class << logo alias_method(:uri=, :content=) end set = setup_values(logo) class << logo remove_method(:uri=) end if set current.logo = logo set_parent(logo, current) setup_other_elements(feed) elsif variable_is_set? raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(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/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/slash.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/slash.rb
require 'rss/slash' require 'rss/maker/1.0' module RSS module Maker module SlashModel def self.append_features(klass) super ::RSS::SlashModel::ELEMENT_INFOS.each do |name, type| full_name = "#{RSS::SLASH_PREFIX}_#{name}" case type when :csv_integer klass.def_csv_element(full_name, :integer) else klass.def_other_element(full_name) end end klass.module_eval do alias_method(:slash_hit_parades, :slash_hit_parade) alias_method(:slash_hit_parades=, :slash_hit_parade=) end end end class ItemsBase class ItemBase include SlashModel 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/dublincore.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/dublincore.rb
require 'rss/dublincore' require 'rss/maker/1.0' module RSS module Maker module DublinCoreModel def self.append_features(klass) super ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name| plural_name ||= "#{name}s" full_name = "#{RSS::DC_PREFIX}_#{name}" full_plural_name = "#{RSS::DC_PREFIX}_#{plural_name}" klass_name = Utils.to_class_name(name) plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}" full_plural_klass_name = "self.class::#{plural_klass_name}" full_klass_name = "#{full_plural_klass_name}::#{klass_name}" klass.def_classed_elements(full_name, "value", plural_klass_name, full_plural_name, name) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) def new_#{full_name}(value=nil) _#{full_name} = #{full_plural_name}.new_#{name} _#{full_name}.value = value if block_given? yield _#{full_name} else _#{full_name} end end EOC end klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) # For backward compatibility alias #{DC_PREFIX}_rightses #{DC_PREFIX}_rights_list EOC end ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name| plural_name ||= "#{name}s" full_name ||= "#{DC_PREFIX}_#{name}" full_plural_name ||= "#{DC_PREFIX}_#{plural_name}" klass_name = Utils.to_class_name(name) full_klass_name = "DublinCore#{klass_name}" plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}" module_eval(<<-EOC, __FILE__, __LINE__ + 1) class #{plural_klass_name}Base < Base def_array_element(#{name.dump}, #{full_plural_name.dump}, #{full_klass_name.dump}) class #{full_klass_name}Base < Base attr_accessor :value add_need_initialize_variable("value") alias_method(:content, :value) alias_method(:content=, :value=) def have_required_values? @value end def to_feed(feed, current) if value and current.respond_to?(:#{full_name}) new_item = current.class::#{full_klass_name}.new(value) current.#{full_plural_name} << new_item end end end #{klass_name}Base = #{full_klass_name}Base end EOC end def self.install_dublin_core(klass) ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name| plural_name ||= "#{name}s" klass_name = Utils.to_class_name(name) full_klass_name = "DublinCore#{klass_name}" plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}" klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class #{plural_klass_name} < #{plural_klass_name}Base class #{full_klass_name} < #{full_klass_name}Base end #{klass_name} = #{full_klass_name} end EOC end end end class ChannelBase include DublinCoreModel end class ImageBase; include DublinCoreModel; end class ItemsBase class ItemBase include DublinCoreModel end end class TextinputBase; include DublinCoreModel; end makers.each do |maker| maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class Channel DublinCoreModel.install_dublin_core(self) end class Image DublinCoreModel.install_dublin_core(self) end class Items class Item DublinCoreModel.install_dublin_core(self) end end class Textinput DublinCoreModel.install_dublin_core(self) end EOC end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/itunes.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/itunes.rb
require 'rss/itunes' require 'rss/maker/2.0' module RSS module Maker module ITunesBaseModel def def_class_accessor(klass, name, type, *args) name = name.gsub(/-/, "_").gsub(/^itunes_/, '') full_name = "#{RSS::ITUNES_PREFIX}_#{name}" case type when nil klass.def_other_element(full_name) when :yes_other def_yes_other_accessor(klass, full_name) when :yes_clean_other def_yes_clean_other_accessor(klass, full_name) when :csv def_csv_accessor(klass, full_name) when :element, :attribute recommended_attribute_name, = *args klass_name = "ITunes#{Utils.to_class_name(name)}" klass.def_classed_element(full_name, klass_name, recommended_attribute_name) when :elements plural_name, recommended_attribute_name = args plural_name ||= "#{name}s" full_plural_name = "#{RSS::ITUNES_PREFIX}_#{plural_name}" klass_name = "ITunes#{Utils.to_class_name(name)}" plural_klass_name = "ITunes#{Utils.to_class_name(plural_name)}" def_elements_class_accessor(klass, name, full_name, full_plural_name, klass_name, plural_klass_name, recommended_attribute_name) end end def def_yes_other_accessor(klass, full_name) klass.def_other_element(full_name) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{full_name}? Utils::YesOther.parse(@#{full_name}) end EOC end def def_yes_clean_other_accessor(klass, full_name) klass.def_other_element(full_name) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{full_name}? Utils::YesCleanOther.parse(#{full_name}) end EOC end def def_csv_accessor(klass, full_name) klass.def_csv_element(full_name) end def def_elements_class_accessor(klass, name, full_name, full_plural_name, klass_name, plural_klass_name, recommended_attribute_name=nil) if recommended_attribute_name klass.def_classed_elements(full_name, recommended_attribute_name, plural_klass_name, full_plural_name) else klass.def_classed_element(full_plural_name, plural_klass_name) end klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) def new_#{full_name}(text=nil) #{full_name} = @#{full_plural_name}.new_#{name} #{full_name}.text = text if block_given? yield #{full_name} else #{full_name} end end EOC end end module ITunesChannelModel extend ITunesBaseModel class << self def append_features(klass) super ::RSS::ITunesChannelModel::ELEMENT_INFOS.each do |name, type, *args| def_class_accessor(klass, name, type, *args) end end end class ITunesCategoriesBase < Base def_array_element("category", "itunes_categories", "ITunesCategory") class ITunesCategoryBase < Base attr_accessor :text add_need_initialize_variable("text") def_array_element("category", "itunes_categories", "ITunesCategory") def have_required_values? text end alias_method :to_feed_for_categories, :to_feed def to_feed(feed, current) if text and current.respond_to?(:itunes_category) new_item = current.class::ITunesCategory.new(text) to_feed_for_categories(feed, new_item) current.itunes_categories << new_item end end end end class ITunesImageBase < Base add_need_initialize_variable("href") attr_accessor("href") def to_feed(feed, current) if @href and current.respond_to?(:itunes_image) current.itunes_image ||= current.class::ITunesImage.new current.itunes_image.href = @href end end end class ITunesOwnerBase < Base %w(itunes_name itunes_email).each do |name| add_need_initialize_variable(name) attr_accessor(name) end def to_feed(feed, current) if current.respond_to?(:itunes_owner=) _not_set_required_variables = not_set_required_variables if (required_variable_names - _not_set_required_variables).empty? return end unless have_required_values? raise NotSetError.new("maker.channel.itunes_owner", _not_set_required_variables) end current.itunes_owner ||= current.class::ITunesOwner.new current.itunes_owner.itunes_name = @itunes_name current.itunes_owner.itunes_email = @itunes_email end end private def required_variable_names %w(itunes_name itunes_email) end end end module ITunesItemModel extend ITunesBaseModel class << self def append_features(klass) super ::RSS::ITunesItemModel::ELEMENT_INFOS.each do |name, type, *args| def_class_accessor(klass, name, type, *args) end end end class ITunesDurationBase < Base attr_reader :content add_need_initialize_variable("content") %w(hour minute second).each do |name| attr_reader(name) add_need_initialize_variable(name, 0) end def content=(content) if content.nil? @hour, @minute, @second, @content = nil else @hour, @minute, @second = ::RSS::ITunesItemModel::ITunesDuration.parse(content) @content = content end end def hour=(hour) @hour = Integer(hour) update_content end def minute=(minute) @minute = Integer(minute) update_content end def second=(second) @second = Integer(second) update_content end def to_feed(feed, current) if @content and current.respond_to?(:itunes_duration=) current.itunes_duration ||= current.class::ITunesDuration.new current.itunes_duration.content = @content end end private def update_content components = [@hour, @minute, @second] @content = ::RSS::ITunesItemModel::ITunesDuration.construct(*components) end end end class ChannelBase include Maker::ITunesChannelModel class ITunesCategories < ITunesCategoriesBase class ITunesCategory < ITunesCategoryBase ITunesCategory = self end end class ITunesImage < ITunesImageBase; end class ITunesOwner < ITunesOwnerBase; end end class ItemsBase class ItemBase include Maker::ITunesItemModel class ITunesDuration < ITunesDurationBase; 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/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/image.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/image.rb
require 'rss/image' require 'rss/maker/1.0' require 'rss/maker/dublincore' module RSS module Maker module ImageItemModel def self.append_features(klass) super name = "#{RSS::IMAGE_PREFIX}_item" klass.def_classed_element(name) end def self.install_image_item(klass) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class ImageItem < ImageItemBase DublinCoreModel.install_dublin_core(self) end EOC end class ImageItemBase < Base include Maker::DublinCoreModel attr_accessor :about, :resource, :image_width, :image_height add_need_initialize_variable("about") add_need_initialize_variable("resource") add_need_initialize_variable("image_width") add_need_initialize_variable("image_height") alias width= image_width= alias width image_width alias height= image_height= alias height image_height def have_required_values? @about end def to_feed(feed, current) if current.respond_to?(:image_item=) and have_required_values? item = current.class::ImageItem.new setup_values(item) setup_other_elements(item) current.image_item = item end end end end module ImageFaviconModel def self.append_features(klass) super name = "#{RSS::IMAGE_PREFIX}_favicon" klass.def_classed_element(name) end def self.install_image_favicon(klass) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class ImageFavicon < ImageFaviconBase DublinCoreModel.install_dublin_core(self) end EOC end class ImageFaviconBase < Base include Maker::DublinCoreModel attr_accessor :about, :image_size add_need_initialize_variable("about") add_need_initialize_variable("image_size") alias size image_size alias size= image_size= def have_required_values? @about and @image_size end def to_feed(feed, current) if current.respond_to?(:image_favicon=) and have_required_values? favicon = current.class::ImageFavicon.new setup_values(favicon) setup_other_elements(favicon) current.image_favicon = favicon end end end end class ChannelBase; include Maker::ImageFaviconModel; end class ItemsBase class ItemBase; include Maker::ImageItemModel; end end makers.each do |maker| maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class Channel ImageFaviconModel.install_image_favicon(self) end class Items class Item ImageItemModel.install_image_item(self) end end EOC end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/trackback.rb
tools/jruby-1.5.1/lib/ruby/1.9/rss/maker/trackback.rb
require 'rss/trackback' require 'rss/maker/1.0' require 'rss/maker/2.0' module RSS module Maker module TrackBackModel def self.append_features(klass) super klass.def_other_element("#{RSS::TRACKBACK_PREFIX}_ping") klass.def_classed_elements("#{RSS::TRACKBACK_PREFIX}_about", "value", "TrackBackAbouts") end class TrackBackAboutsBase < Base def_array_element("about", nil, "TrackBackAbout") class TrackBackAboutBase < Base attr_accessor :value add_need_initialize_variable("value") alias_method(:resource, :value) alias_method(:resource=, :value=) alias_method(:content, :value) alias_method(:content=, :value=) def have_required_values? @value end def to_feed(feed, current) if current.respond_to?(:trackback_abouts) and have_required_values? about = current.class::TrackBackAbout.new setup_values(about) setup_other_elements(about) current.trackback_abouts << about end end end end end class ItemsBase class ItemBase; include TrackBackModel; end end makers.each do |maker| maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class Items class Item class TrackBackAbouts < TrackBackAboutsBase class TrackBackAbout < TrackBackAboutBase end end end end EOC end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/test/unit.rb
tools/jruby-1.5.1/lib/ruby/1.9/test/unit.rb
# test/unit compatibility layer using minitest. require 'minitest/unit' require 'test/unit/assertions' require 'test/unit/testcase' module Test module Unit TEST_UNIT_IMPLEMENTATION = 'test/unit compatibility layer using minitest' def self.setup_argv(original_argv=ARGV) minitest_argv = [] files = [] reject = [] original_argv = original_argv.dup while arg = original_argv.shift case arg when '-v' minitest_argv << arg when /\A(-n)(.+)?/, /\A(--name)=?\b(.+)?/ minitest_argv << $1 minitest_argv << ($2 || original_argv.shift) when /\A-x(.+)?/ reject << ($1 || original_argv.shift) else files << arg end end if block_given? files = yield files end files.map! {|f| f = f.tr(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR if File.directory? f Dir["#{f}/**/test_*.rb"] elsif File.file? f f else raise ArgumentError, "file not found: #{f}" end } files.flatten! reject_pat = Regexp.union(reject.map {|r| /#{r}/ }) files.reject! {|f| reject_pat =~ f } files.each {|f| d = File.dirname(path = File.expand_path(f)) unless $:.include? d $: << d end begin require path rescue LoadError puts "#{f}: #{$!}" end } ARGV.replace minitest_argv end end end MiniTest::Unit.autorun
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.9/test/unit/assertions.rb
tools/jruby-1.5.1/lib/ruby/1.9/test/unit/assertions.rb
require 'minitest/unit' require 'pp' module Test module Unit module Assertions include MiniTest::Assertions def mu_pp(obj) obj.pretty_inspect.chomp end def assert_raise(*args, &b) assert_raises(*args, &b) end def assert_nothing_raised(*args) self._assertions += 1 if Module === args.last msg = nil else msg = args.pop end begin line = __LINE__; yield rescue Exception => e bt = e.backtrace as = e.instance_of?(MiniTest::Assertion) if as ans = /\A#{Regexp.quote(__FILE__)}:#{line}:in /o bt.reject! {|ln| ans =~ ln} end if ((args.empty? && !as) || args.any? {|a| a.instance_of?(Module) ? e.is_a?(a) : e.class == a }) msg = message(msg) { "Exception raised:\n<#{mu_pp(e)}>" } raise MiniTest::Assertion, msg.call, bt else raise end end nil end def assert_nothing_thrown(msg=nil) begin yield rescue ArgumentError => error raise error if /\Auncaught throw (.+)\z/m !~ error.message msg = message(msg) { "<#{$1}> was thrown when nothing was expected" } flunk(msg) end assert(true, "Expected nothing to be thrown") end def assert_equal(exp, act, msg = nil) msg = message(msg) { exp_str = mu_pp(exp) act_str = mu_pp(act) exp_comment = '' act_comment = '' if exp_str == act_str if (exp.is_a?(String) && act.is_a?(String)) || (exp.is_a?(Regexp) && act.is_a?(Regexp)) exp_comment = " (#{exp.encoding})" act_comment = " (#{act.encoding})" elsif exp.is_a?(Float) && act.is_a?(Float) exp_str = "%\#.#{Float::DIG+2}g" % exp act_str = "%\#.#{Float::DIG+2}g" % act elsif exp.is_a?(Time) && act.is_a?(Time) exp_comment = " (nsec=#{exp.nsec})" act_comment = " (nsec=#{act.nsec})" elsif exp.class != act.class # a subclass of Range, for example. exp_comment = " (#{exp.class})" act_comment = " (#{act.class})" end elsif !Encoding.compatible?(exp_str, act_str) if exp.is_a?(String) && act.is_a?(String) exp_str = exp.dump act_str = act.dump exp_comment = " (#{exp.encoding})" act_comment = " (#{act.encoding})" else exp_str = exp_str.dump act_str = act_str.dump end end "<#{exp_str}>#{exp_comment} expected but was\n<#{act_str}>#{act_comment}" } assert(exp == act, msg) end def assert_not_nil(exp, msg=nil) msg = message(msg) { "<#{mu_pp(exp)}> expected to not be nil" } assert(!exp.nil?, msg) end def assert_not_equal(exp, act, msg=nil) msg = message(msg) { "<#{mu_pp(exp)}> expected to be != to\n<#{mu_pp(act)}>" } assert(exp != act, msg) end def assert_no_match(regexp, string, msg=nil) assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.") self._assertions -= 1 msg = message(msg) { "<#{mu_pp(regexp)}> expected to not match\n<#{mu_pp(string)}>" } assert(regexp !~ string, msg) end def assert_not_same(expected, actual, message="") msg = message(msg) { build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__) } <?> with id <?> expected to not be equal\\? to <?> with id <?>. EOT assert(!actual.equal?(expected), msg) end # get rid of overcounting def assert_respond_to obj, meth, msg = nil super if !caller[0].rindex(MiniTest::MINI_DIR, 0) || !obj.respond_to?(meth) end ms = instance_methods(true).map {|sym| sym.to_s } ms.grep(/\Arefute_/) do |m| mname = ('assert_not_' << m.to_s[/.*?_(.*)/, 1]) alias_method(mname, m) unless ms.include? mname end def build_message(head, template=nil, *arguments) template &&= template.chomp template.gsub(/\?/) { mu_pp(arguments.shift) } 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/tools/jruby-1.5.1/lib/ruby/1.9/test/unit/testcase.rb
tools/jruby-1.5.1/lib/ruby/1.9/test/unit/testcase.rb
require 'test/unit/assertions' module Test module Unit # remove silly TestCase class remove_const(:TestCase) if defined?(self::TestCase) class TestCase < MiniTest::Unit::TestCase include Assertions def self.test_order :sorted 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/tools/jruby-1.5.1/lib/ruby/1.9/net/http.rb
tools/jruby-1.5.1/lib/ruby/1.9/net/http.rb
# # = net/http.rb # # Copyright (c) 1999-2007 Yukihiro Matsumoto # Copyright (c) 1999-2007 Minero Aoki # Copyright (c) 2001 GOTOU Yuuzou # # Written and maintained by Minero Aoki <aamine@loveruby.net>. # HTTPS support added by GOTOU Yuuzou <gotoyuzo@notwork.org>. # # This file is derived from "http-access.rb". # # Documented by Minero Aoki; converted to RDoc by William Webber. # # This program is free software. You can re-distribute and/or # modify this program under the same terms of ruby itself --- # Ruby Distribution License or GNU General Public License. # # See Net::HTTP for an overview and examples. # # NOTE: You can find Japanese version of this document here: # http://www.ruby-lang.org/ja/man/html/net_http.html # #-- # $Id: http.rb 23311 2009-04-30 09:19:42Z matz $ #++ require 'net/protocol' require 'uri' module Net #:nodoc: # :stopdoc: class HTTPBadResponse < StandardError; end class HTTPHeaderSyntaxError < StandardError; end # :startdoc: # == What Is This Library? # # This library provides your program functions to access WWW # documents via HTTP, Hyper Text Transfer Protocol version 1.1. # For details of HTTP, refer to [RFC2616] # (http://www.ietf.org/rfc/rfc2616.txt). # # == Examples # # === Getting Document From WWW Server # # Example #1: Simple GET+print # # require 'net/http' # Net::HTTP.get_print 'www.example.com', '/index.html' # # Example #2: Simple GET+print by URL # # require 'net/http' # require 'uri' # Net::HTTP.get_print URI.parse('http://www.example.com/index.html') # # Example #3: More generic GET+print # # require 'net/http' # require 'uri' # # url = URI.parse('http://www.example.com/index.html') # res = Net::HTTP.start(url.host, url.port) {|http| # http.get('/index.html') # } # puts res.body # # Example #4: More generic GET+print # # require 'net/http' # # url = URI.parse('http://www.example.com/index.html') # req = Net::HTTP::Get.new(url.path) # res = Net::HTTP.start(url.host, url.port) {|http| # http.request(req) # } # puts res.body # # === Posting Form Data # # require 'net/http' # require 'uri' # # #1: Simple POST # res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'), # {'q' => 'ruby', 'max' => '50'}) # puts res.body # # #2: POST with basic authentication # res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'), # {'from' => '2005-01-01', # 'to' => '2005-03-31'}) # puts res.body # # #3: Detailed control # url = URI.parse('http://www.example.com/todo.cgi') # req = Net::HTTP::Post.new(url.path) # req.basic_auth 'jack', 'pass' # req.set_form_data({'from' => '2005-01-01', 'to' => '2005-03-31'}, ';') # res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) } # case res # when Net::HTTPSuccess, Net::HTTPRedirection # # OK # else # res.error! # end # # #4: Multiple values # res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'), # {'q' => ['ruby', 'perl'], 'max' => '50'}) # puts res.body # # === Accessing via Proxy # # Net::HTTP.Proxy creates http proxy class. It has same # methods of Net::HTTP but its instances always connect to # proxy, instead of given host. # # require 'net/http' # # proxy_addr = 'your.proxy.host' # proxy_port = 8080 # : # Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http| # # always connect to your.proxy.addr:8080 # : # } # # Since Net::HTTP.Proxy returns Net::HTTP itself when proxy_addr is nil, # there's no need to change code if there's proxy or not. # # There are two additional parameters in Net::HTTP.Proxy which allow to # specify proxy user name and password: # # Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user = nil, proxy_pass = nil) # # You may use them to work with authorization-enabled proxies: # # require 'net/http' # require 'uri' # # proxy_host = 'your.proxy.host' # proxy_port = 8080 # uri = URI.parse(ENV['http_proxy']) # proxy_user, proxy_pass = uri.userinfo.split(/:/) if uri.userinfo # Net::HTTP::Proxy(proxy_host, proxy_port, # proxy_user, proxy_pass).start('www.example.com') {|http| # # always connect to your.proxy.addr:8080 using specified username and password # : # } # # Note that net/http never rely on HTTP_PROXY environment variable. # If you want to use proxy, set it explicitly. # # === Following Redirection # # require 'net/http' # require 'uri' # # def fetch(uri_str, limit = 10) # # You should choose better exception. # raise ArgumentError, 'HTTP redirect too deep' if limit == 0 # # response = Net::HTTP.get_response(URI.parse(uri_str)) # case response # when Net::HTTPSuccess then response # when Net::HTTPRedirection then fetch(response['location'], limit - 1) # else # response.error! # end # end # # print fetch('http://www.ruby-lang.org') # # Net::HTTPSuccess and Net::HTTPRedirection is a HTTPResponse class. # All HTTPResponse objects belong to its own response class which # indicate HTTP result status. For details of response classes, # see section "HTTP Response Classes". # # === Basic Authentication # # require 'net/http' # # Net::HTTP.start('www.example.com') {|http| # req = Net::HTTP::Get.new('/secret-page.html') # req.basic_auth 'account', 'password' # response = http.request(req) # print response.body # } # # === HTTP Request Classes # # Here is HTTP request class hierarchy. # # Net::HTTPRequest # Net::HTTP::Get # Net::HTTP::Head # Net::HTTP::Post # Net::HTTP::Put # Net::HTTP::Proppatch # Net::HTTP::Lock # Net::HTTP::Unlock # Net::HTTP::Options # Net::HTTP::Propfind # Net::HTTP::Delete # Net::HTTP::Move # Net::HTTP::Copy # Net::HTTP::Mkcol # Net::HTTP::Trace # # === HTTP Response Classes # # Here is HTTP response class hierarchy. # All classes are defined in Net module. # # HTTPResponse # HTTPUnknownResponse # HTTPInformation # 1xx # HTTPContinue # 100 # HTTPSwitchProtocol # 101 # HTTPSuccess # 2xx # HTTPOK # 200 # HTTPCreated # 201 # HTTPAccepted # 202 # HTTPNonAuthoritativeInformation # 203 # HTTPNoContent # 204 # HTTPResetContent # 205 # HTTPPartialContent # 206 # HTTPRedirection # 3xx # HTTPMultipleChoice # 300 # HTTPMovedPermanently # 301 # HTTPFound # 302 # HTTPSeeOther # 303 # HTTPNotModified # 304 # HTTPUseProxy # 305 # HTTPTemporaryRedirect # 307 # HTTPClientError # 4xx # HTTPBadRequest # 400 # HTTPUnauthorized # 401 # HTTPPaymentRequired # 402 # HTTPForbidden # 403 # HTTPNotFound # 404 # HTTPMethodNotAllowed # 405 # HTTPNotAcceptable # 406 # HTTPProxyAuthenticationRequired # 407 # HTTPRequestTimeOut # 408 # HTTPConflict # 409 # HTTPGone # 410 # HTTPLengthRequired # 411 # HTTPPreconditionFailed # 412 # HTTPRequestEntityTooLarge # 413 # HTTPRequestURITooLong # 414 # HTTPUnsupportedMediaType # 415 # HTTPRequestedRangeNotSatisfiable # 416 # HTTPExpectationFailed # 417 # HTTPServerError # 5xx # HTTPInternalServerError # 500 # HTTPNotImplemented # 501 # HTTPBadGateway # 502 # HTTPServiceUnavailable # 503 # HTTPGatewayTimeOut # 504 # HTTPVersionNotSupported # 505 # # == Switching Net::HTTP versions # # You can use net/http.rb 1.1 features (bundled with Ruby 1.6) # by calling HTTP.version_1_1. Calling Net::HTTP.version_1_2 # allows you to use 1.2 features again. # # # example # Net::HTTP.start {|http1| ...(http1 has 1.2 features)... } # # Net::HTTP.version_1_1 # Net::HTTP.start {|http2| ...(http2 has 1.1 features)... } # # Net::HTTP.version_1_2 # Net::HTTP.start {|http3| ...(http3 has 1.2 features)... } # # This function is NOT thread-safe. # class HTTP < Protocol # :stopdoc: Revision = %q$Revision: 23311 $.split[1] HTTPVersion = '1.1' @newimpl = true begin require 'zlib' require 'stringio' #for our purposes (unpacking gzip) lump these together HAVE_ZLIB=true rescue LoadError HAVE_ZLIB=false end # :startdoc: # Turns on net/http 1.2 (ruby 1.8) features. # Defaults to ON in ruby 1.8. # # I strongly recommend to call this method always. # # require 'net/http' # Net::HTTP.version_1_2 # def HTTP.version_1_2 @newimpl = true end # Turns on net/http 1.1 (ruby 1.6) features. # Defaults to OFF in ruby 1.8. def HTTP.version_1_1 @newimpl = false end # true if net/http is in version 1.2 mode. # Defaults to true. def HTTP.version_1_2? @newimpl end # true if net/http is in version 1.1 compatible mode. # Defaults to true. def HTTP.version_1_1? not @newimpl end class << HTTP alias is_version_1_1? version_1_1? #:nodoc: alias is_version_1_2? version_1_2? #:nodoc: end # # short cut methods # # # Get body from target and output it to +$stdout+. The # target can either be specified as (+uri+), or as # (+host+, +path+, +port+ = 80); so: # # Net::HTTP.get_print URI.parse('http://www.example.com/index.html') # # or: # # Net::HTTP.get_print 'www.example.com', '/index.html' # def HTTP.get_print(uri_or_host, path = nil, port = nil) get_response(uri_or_host, path, port) {|res| res.read_body do |chunk| $stdout.print chunk end } nil end # Send a GET request to the target and return the response # as a string. The target can either be specified as # (+uri+), or as (+host+, +path+, +port+ = 80); so: # # print Net::HTTP.get(URI.parse('http://www.example.com/index.html')) # # or: # # print Net::HTTP.get('www.example.com', '/index.html') # def HTTP.get(uri_or_host, path = nil, port = nil) get_response(uri_or_host, path, port).body end # Send a GET request to the target and return the response # as a Net::HTTPResponse object. The target can either be specified as # (+uri+), or as (+host+, +path+, +port+ = 80); so: # # res = Net::HTTP.get_response(URI.parse('http://www.example.com/index.html')) # print res.body # # or: # # res = Net::HTTP.get_response('www.example.com', '/index.html') # print res.body # def HTTP.get_response(uri_or_host, path = nil, port = nil, &block) if path host = uri_or_host new(host, port || HTTP.default_port).start {|http| return http.request_get(path, &block) } else uri = uri_or_host new(uri.host, uri.port).start {|http| return http.request_get(uri.request_uri, &block) } end end # Posts HTML form data to the +URL+. # Form data must be represented as a Hash of String to String, e.g: # # { "cmd" => "search", "q" => "ruby", "max" => "50" } # # This method also does Basic Authentication iff +URL+.user exists. # # Example: # # require 'net/http' # require 'uri' # # HTTP.post_form URI.parse('http://www.example.com/search.cgi'), # { "q" => "ruby", "max" => "50" } # def HTTP.post_form(url, params) req = Post.new(url.path) req.form_data = params req.basic_auth url.user, url.password if url.user new(url.host, url.port).start {|http| http.request(req) } end # # HTTP session management # # The default port to use for HTTP requests; defaults to 80. def HTTP.default_port http_default_port() end # The default port to use for HTTP requests; defaults to 80. def HTTP.http_default_port 80 end # The default port to use for HTTPS requests; defaults to 443. def HTTP.https_default_port 443 end def HTTP.socket_type #:nodoc: obsolete BufferedIO end # creates a new Net::HTTP object and opens its TCP connection and # HTTP session. If the optional block is given, the newly # created Net::HTTP object is passed to it and closed when the # block finishes. In this case, the return value of this method # is the return value of the block. If no block is given, the # return value of this method is the newly created Net::HTTP object # itself, and the caller is responsible for closing it upon completion. def HTTP.start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+ new(address, port, p_addr, p_port, p_user, p_pass).start(&block) end class << HTTP alias newobj new end # Creates a new Net::HTTP object. # If +proxy_addr+ is given, creates an Net::HTTP object with proxy support. # This method does not open the TCP connection. def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil) h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port) h.instance_eval { @newimpl = ::Net::HTTP.version_1_2? } h end # Creates a new Net::HTTP object for the specified +address+. # This method does not open the TCP connection. def initialize(address, port = nil) @address = address @port = (port || HTTP.default_port) @curr_http_version = HTTPVersion @no_keepalive_server = false @close_on_empty_response = false @socket = nil @started = false @open_timeout = nil @read_timeout = 60 @debug_output = nil @use_ssl = false @ssl_context = nil @enable_post_connection_check = true @compression = nil @sspi_enabled = false if defined?(SSL_ATTRIBUTES) SSL_ATTRIBUTES.each do |name| instance_variable_set "@#{name}", nil end end end def inspect "#<#{self.class} #{@address}:#{@port} open=#{started?}>" end # *WARNING* This method causes serious security hole. # Never use this method in production code. # # Set an output stream for debugging. # # http = Net::HTTP.new # http.set_debug_output $stderr # http.start { .... } # def set_debug_output(output) warn 'Net::HTTP#set_debug_output called after HTTP started' if started? @debug_output = output end # The host name to connect to. attr_reader :address # The port number to connect to. attr_reader :port # Seconds to wait until connection is opened. # If the HTTP object cannot open a connection in this many seconds, # it raises a TimeoutError exception. attr_accessor :open_timeout # Seconds to wait until reading one block (by one read(2) call). # If the HTTP object cannot open a connection in this many seconds, # it raises a TimeoutError exception. attr_reader :read_timeout # Setter for the read_timeout attribute. def read_timeout=(sec) @socket.read_timeout = sec if @socket @read_timeout = sec end # returns true if the HTTP session is started. def started? @started end alias active? started? #:nodoc: obsolete attr_accessor :close_on_empty_response # returns true if use SSL/TLS with HTTP. def use_ssl? false # redefined in net/https end # Opens TCP connection and HTTP session. # # When this method is called with block, gives a HTTP object # to the block and closes the TCP connection / HTTP session # after the block executed. # # When called with a block, returns the return value of the # block; otherwise, returns self. # def start # :yield: http raise IOError, 'HTTP session already opened' if @started if block_given? begin do_start return yield(self) ensure do_finish end end do_start self end def do_start connect @started = true end private :do_start def connect D "opening connection to #{conn_address()}..." s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) } D "opened" if use_ssl? ssl_parameters = Hash.new iv_list = instance_variables SSL_ATTRIBUTES.each do |name| ivname = "@#{name}".intern if iv_list.include?(ivname) and value = instance_variable_get(ivname) ssl_parameters[name] = value end end @ssl_context = OpenSSL::SSL::SSLContext.new @ssl_context.set_params(ssl_parameters) s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context) s.sync_close = true end @socket = BufferedIO.new(s) @socket.read_timeout = @read_timeout @socket.debug_output = @debug_output if use_ssl? if proxy? @socket.writeline sprintf('CONNECT %s:%s HTTP/%s', @address, @port, HTTPVersion) @socket.writeline "Host: #{@address}:#{@port}" if proxy_user credential = ["#{proxy_user}:#{proxy_pass}"].pack('m') credential.delete!("\r\n") @socket.writeline "Proxy-Authorization: Basic #{credential}" end @socket.writeline '' HTTPResponse.read_new(@socket).value end s.connect if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE s.post_connection_check(@address) end end on_connect end private :connect def on_connect end private :on_connect # Finishes HTTP session and closes TCP connection. # Raises IOError if not started. def finish raise IOError, 'HTTP session not yet started' unless started? do_finish end def do_finish @started = false @socket.close if @socket and not @socket.closed? @socket = nil end private :do_finish # # proxy # public # no proxy @is_proxy_class = false @proxy_addr = nil @proxy_port = nil @proxy_user = nil @proxy_pass = nil # Creates an HTTP proxy class. # Arguments are address/port of proxy host and username/password # if authorization on proxy server is required. # You can replace the HTTP class with created proxy class. # # If ADDRESS is nil, this method returns self (Net::HTTP). # # # Example # proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080) # : # proxy_class.start('www.ruby-lang.org') {|http| # # connecting proxy.foo.org:8080 # : # } # def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil) return self unless p_addr delta = ProxyDelta proxyclass = Class.new(self) proxyclass.module_eval { include delta # with proxy @is_proxy_class = true @proxy_address = p_addr @proxy_port = p_port || default_port() @proxy_user = p_user @proxy_pass = p_pass } proxyclass end class << HTTP # returns true if self is a class which was created by HTTP::Proxy. def proxy_class? @is_proxy_class end attr_reader :proxy_address attr_reader :proxy_port attr_reader :proxy_user attr_reader :proxy_pass end # True if self is a HTTP proxy class. def proxy? self.class.proxy_class? end # Address of proxy host. If self does not use a proxy, nil. def proxy_address self.class.proxy_address end # Port number of proxy host. If self does not use a proxy, nil. def proxy_port self.class.proxy_port end # User name for accessing proxy. If self does not use a proxy, nil. def proxy_user self.class.proxy_user end # User password for accessing proxy. If self does not use a proxy, nil. def proxy_pass self.class.proxy_pass end alias proxyaddr proxy_address #:nodoc: obsolete alias proxyport proxy_port #:nodoc: obsolete private # without proxy def conn_address address() end def conn_port port() end def edit_path(path) path end module ProxyDelta #:nodoc: internal use only private def conn_address proxy_address() end def conn_port proxy_port() end def edit_path(path) use_ssl? ? path : "http://#{addr_port()}#{path}" end end # # HTTP operations # public # Gets data from +path+ on the connected-to host. # +initheader+ must be a Hash like { 'Accept' => '*/*', ... }, # and it defaults to an empty hash. # If +initheader+ doesn't have the key 'accept-encoding', then # a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used, # so that gzip compression is used in preference to deflate # compression, which is used in preference to no compression. # Ruby doesn't have libraries to support the compress (Lempel-Ziv) # compression, so that is not supported. The intent of this is # to reduce bandwidth by default. If this routine sets up # compression, then it does the decompression also, removing # the header as well to prevent confusion. Otherwise # it leaves the body as it found it. # # In version 1.1 (ruby 1.6), this method returns a pair of objects, # a Net::HTTPResponse object and the entity body string. # In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse # object. # # If called with a block, yields each fragment of the # entity body in turn as a string as it is read from # the socket. Note that in this case, the returned response # object will *not* contain a (meaningful) body. # # +dest+ argument is obsolete. # It still works but you must not use it. # # In version 1.1, this method might raise an exception for # 3xx (redirect). In this case you can get a HTTPResponse object # by "anException.response". # # In version 1.2, this method never raises exception. # # # version 1.1 (bundled with Ruby 1.6) # response, body = http.get('/index.html') # # # version 1.2 (bundled with Ruby 1.8 or later) # response = http.get('/index.html') # # # using block # File.open('result.txt', 'w') {|f| # http.get('/~foo/') do |str| # f.write str # end # } # def get(path, initheader = {}, dest = nil, &block) # :yield: +body_segment+ res = nil if HAVE_ZLIB unless initheader.keys.any?{|k| k.downcase == "accept-encoding"} initheader["accept-encoding"] = "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" @compression = true end end request(Get.new(path, initheader)) {|r| if r.key?("content-encoding") and @compression @compression = nil # Clear it till next set. the_body = r.read_body dest, &block case r["content-encoding"] when "gzip" r.body= Zlib::GzipReader.new(StringIO.new(the_body)).read r.delete("content-encoding") when "deflate" r.body= Zlib::Inflate.inflate(the_body); r.delete("content-encoding") when "identity" ; # nothing needed else ; # Don't do anything dramatic, unless we need to later end else r.read_body dest, &block end res = r } unless @newimpl res.value return res, res.body end res end # Gets only the header from +path+ on the connected-to host. # +header+ is a Hash like { 'Accept' => '*/*', ... }. # # This method returns a Net::HTTPResponse object. # # In version 1.1, this method might raise an exception for # 3xx (redirect). On the case you can get a HTTPResponse object # by "anException.response". # In version 1.2, this method never raises an exception. # # response = nil # Net::HTTP.start('some.www.server', 80) {|http| # response = http.head('/index.html') # } # p response['content-type'] # def head(path, initheader = nil) res = request(Head.new(path, initheader)) res.value unless @newimpl res end # Posts +data+ (must be a String) to +path+. +header+ must be a Hash # like { 'Accept' => '*/*', ... }. # # In version 1.1 (ruby 1.6), this method returns a pair of objects, a # Net::HTTPResponse object and an entity body string. # In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object. # # If called with a block, yields each fragment of the # entity body in turn as a string as it are read from # the socket. Note that in this case, the returned response # object will *not* contain a (meaningful) body. # # +dest+ argument is obsolete. # It still works but you must not use it. # # In version 1.1, this method might raise an exception for # 3xx (redirect). In this case you can get an HTTPResponse object # by "anException.response". # In version 1.2, this method never raises exception. # # # version 1.1 # response, body = http.post('/cgi-bin/search.rb', 'query=foo') # # # version 1.2 # response = http.post('/cgi-bin/search.rb', 'query=foo') # # # using block # File.open('result.txt', 'w') {|f| # http.post('/cgi-bin/search.rb', 'query=foo') do |str| # f.write str # end # } # # You should set Content-Type: header field for POST. # If no Content-Type: field given, this method uses # "application/x-www-form-urlencoded" by default. # def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+ res = nil request(Post.new(path, initheader), data) {|r| r.read_body dest, &block res = r } unless @newimpl res.value return res, res.body end res end def put(path, data, initheader = nil) #:nodoc: res = request(Put.new(path, initheader), data) res.value unless @newimpl res end # Sends a PROPPATCH request to the +path+ and gets a response, # as an HTTPResponse object. def proppatch(path, body, initheader = nil) request(Proppatch.new(path, initheader), body) end # Sends a LOCK request to the +path+ and gets a response, # as an HTTPResponse object. def lock(path, body, initheader = nil) request(Lock.new(path, initheader), body) end # Sends a UNLOCK request to the +path+ and gets a response, # as an HTTPResponse object. def unlock(path, body, initheader = nil) request(Unlock.new(path, initheader), body) end # Sends a OPTIONS request to the +path+ and gets a response, # as an HTTPResponse object. def options(path, initheader = nil) request(Options.new(path, initheader)) end # Sends a PROPFIND request to the +path+ and gets a response, # as an HTTPResponse object. def propfind(path, body = nil, initheader = {'Depth' => '0'}) request(Propfind.new(path, initheader), body) end # Sends a DELETE request to the +path+ and gets a response, # as an HTTPResponse object. def delete(path, initheader = {'Depth' => 'Infinity'}) request(Delete.new(path, initheader)) end # Sends a MOVE request to the +path+ and gets a response, # as an HTTPResponse object. def move(path, initheader = nil) request(Move.new(path, initheader)) end # Sends a COPY request to the +path+ and gets a response, # as an HTTPResponse object. def copy(path, initheader = nil) request(Copy.new(path, initheader)) end # Sends a MKCOL request to the +path+ and gets a response, # as an HTTPResponse object. def mkcol(path, body = nil, initheader = nil) request(Mkcol.new(path, initheader), body) end # Sends a TRACE request to the +path+ and gets a response, # as an HTTPResponse object. def trace(path, initheader = nil) request(Trace.new(path, initheader)) end # Sends a GET request to the +path+ and gets a response, # as an HTTPResponse object. # # When called with a block, yields an HTTPResponse object. # The body of this response will not have been read yet; # the caller can process it using HTTPResponse#read_body, # if desired. # # Returns the response. # # This method never raises Net::* exceptions. # # response = http.request_get('/index.html') # # The entity body is already read here. # p response['content-type'] # puts response.body # # # using block # http.request_get('/index.html') {|response| # p response['content-type'] # response.read_body do |str| # read body now # print str # end # } # def request_get(path, initheader = nil, &block) # :yield: +response+ request(Get.new(path, initheader), &block) end # Sends a HEAD request to the +path+ and gets a response, # as an HTTPResponse object. # # Returns the response. # # This method never raises Net::* exceptions. # # response = http.request_head('/index.html') # p response['content-type'] # def request_head(path, initheader = nil, &block) request(Head.new(path, initheader), &block) end # Sends a POST request to the +path+ and gets a response, # as an HTTPResponse object. # # When called with a block, yields an HTTPResponse object. # The body of this response will not have been read yet; # the caller can process it using HTTPResponse#read_body, # if desired. # # Returns the response. # # This method never raises Net::* exceptions. # # # example # response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...') # p response.status # puts response.body # body is already read # # # using block # http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response| # p response.status # p response['content-type'] # response.read_body do |str| # read body now # print str # end # } # def request_post(path, data, initheader = nil, &block) # :yield: +response+ request Post.new(path, initheader), data, &block end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true