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 |
|---|---|---|---|---|---|---|---|---|
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/printenabled-example.rb | gems/gems/erubis-2.6.0/test/data/users-guide/printenabled-example.rb | require 'erubis'
class PrintEnabledEruby < Erubis::Eruby
include Erubis::PrintEnabledEnhancer
end
input = File.read('printenabled-example.eruby')
eruby = PrintEnabledEruby.new(input)
list = ['aaa', 'bbb', 'ccc']
print eruby.evaluate(:list=>list)
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/main_program2.rb | gems/gems/erubis-2.6.0/test/data/users-guide/main_program2.rb | require 'erubis'
eruby = Erubis::Eruby.new(File.read('template2.rhtml'))
items = ['foo', 'bar', 'baz']
x = 1
## only 'items' are passed to template
print eruby.evaluate(:items=>items)
## local variable 'x' is not changed!
puts "** debug: x=#{x.inspect}" #=> 1
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/main_program1.rb | gems/gems/erubis-2.6.0/test/data/users-guide/main_program1.rb | require 'erubis'
eruby = Erubis::Eruby.new(File.read('template1.rhtml'))
items = ['foo', 'bar', 'baz']
x = 1
## local variable 'x' and 'eruby' are passed to template as well as 'items'!
print eruby.result(binding())
## local variable 'x' is changed unintendedly because it is changed in template!
puts "** debug: x=#{x.inspect}" #=> "baz"
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/example2.rb | gems/gems/erubis-2.6.0/test/data/users-guide/example2.rb | require 'erubis'
input = File.read('example2.eruby')
eruby = Erubis::Eruby.new(input, :trim=>false)
puts "----- script source ---"
puts eruby.src # print script source
puts "----- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding()) # get result
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/def_method.rb | gems/gems/erubis-2.6.0/test/data/users-guide/def_method.rb | require 'erubis'
s = "hello <%= name %>"
eruby = Erubis::Eruby.new(s)
filename = 'hello.rhtml'
## define instance method to Dummy class (or module)
class Dummy; end
eruby.def_method(Dummy, 'render(name)', filename) # filename is optional
p Dummy.new.render('world') #=> "hello world"
## define singleton method to dummy object
obj = Object.new
eruby.def_method(obj, 'render(name)', filename) # filename is optional
p obj.render('world') #=> "hello world"
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/context.rb | gems/gems/erubis-2.6.0/test/data/users-guide/context.rb | @title = 'Users List'
@users = [
{ 'name'=>'foo', 'mail'=>'foo@mail.com' },
{ 'name'=>'bar', 'mail'=>'bar@mail.net' },
{ 'name'=>'baz', 'mail'=>'baz@mail.org' },
]
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/test/data/users-guide/example6.rb | gems/gems/erubis-2.6.0/test/data/users-guide/example6.rb | class MyData
attr_accessor :val, :list
end
## any object can be a context object
mydata = MyData.new
mydata.val = 'Erubis Example'
mydata.list = ['aaa', 'bbb', 'ccc']
require 'erubis'
eruby = Erubis::Eruby.new(File.read('example5.eruby'))
puts eruby.evaluate(mydata)
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis.rb | gems/gems/erubis-2.6.0/lib/erubis.rb | ##
## $Rev: 99 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
##
## an implementation of eRuby
##
## ex.
## input = <<'END'
## <ul>
## <% for item in @list %>
## <li><%= item %>
## <%== item %></li>
## <% end %>
## </ul>
## END
## list = ['<aaa>', 'b&b', '"ccc"']
## eruby = Erubis::Eruby.new(input)
## puts "--- code ---"
## puts eruby.src
## puts "--- result ---"
## context = Erubis::Context.new() # or new(:list=>list)
## context[:list] = list
## puts eruby.evaluate(context)
##
## result:
## --- source ---
## _buf = ''; _buf << '<ul>
## '; for item in @list
## _buf << ' <li>'; _buf << ( item ).to_s; _buf << '
## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
## '; end
## _buf << '</ul>
## ';
## _buf.to_s
## --- result ---
## <ul>
## <li><aaa>
## <aaa></li>
## <li>b&b
## b&b</li>
## <li>"ccc"
## "ccc"</li>
## </ul>
##
module Erubis
VERSION = ('$Release: 2.6.0 $' =~ /([.\d]+)/) && $1
end
require 'erubis/engine'
#require 'erubis/generator'
#require 'erubis/converter'
#require 'erubis/evaluator'
#require 'erubis/error'
#require 'erubis/context'
require 'erubis/helper'
require 'erubis/enhancer'
#require 'erubis/tiny'
require 'erubis/engine/eruby'
#require 'erubis/engine/enhanced' # enhanced eruby engines
#require 'erubis/engine/optimized' # generates optimized ruby code
#require 'erubis/engine/ephp'
#require 'erubis/engine/ec'
#require 'erubis/engine/ejava'
#require 'erubis/engine/escheme'
#require 'erubis/engine/eperl'
#require 'erubis/engine/ejavascript'
require 'erubis/local-setting'
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/main.rb | gems/gems/erubis-2.6.0/lib/erubis/main.rb | ###
### $Rev: 91 $
### $Release: 2.6.0 $
### copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
###
require 'yaml'
require 'erubis'
require 'erubis/tiny'
require 'erubis/engine/enhanced'
require 'erubis/engine/optimized'
require 'erubis/engine/eruby'
require 'erubis/engine/ephp'
require 'erubis/engine/ec'
require 'erubis/engine/ejava'
require 'erubis/engine/escheme'
require 'erubis/engine/eperl'
require 'erubis/engine/ejavascript'
module Erubis
Ejs = Ejavascript
EscapedEjs = EscapedEjavascript
class CommandOptionError < ErubisError
end
##
## main class of command
##
## ex.
## Main.main(ARGV)
##
class Main
def self.main(argv=ARGV)
status = 0
begin
Main.new.execute(ARGV)
rescue CommandOptionError => ex
$stderr.puts ex.message
status = 1
end
exit(status)
end
def initialize
@single_options = "hvxztTSbeBXNUC"
@arg_options = "pcrfKIlaE" #C
@option_names = {
?h => :help,
?v => :version,
?x => :source,
?z => :syntax,
?T => :unexpand,
?t => :untabify, # obsolete
?S => :intern,
?b => :bodyonly,
?B => :binding,
?p => :pattern,
?c => :context,
#?C => :class,
?e => :escape,
?r => :requires,
?f => :datafiles,
?K => :kanji,
?I => :includes,
?l => :lang,
?a => :action,
?E => :enhancers,
?X => :notext,
?N => :linenum,
?U => :unique,
?C => :compact,
}
assert unless @single_options.length + @arg_options.length == @option_names.length
(@single_options + @arg_options).each_byte do |ch|
assert unless @option_names.key?(ch)
end
end
def execute(argv=ARGV)
## parse command-line options
options, properties = parse_argv(argv, @single_options, @arg_options)
filenames = argv
options[?h] = true if properties[:help]
opts = Object.new
arr = @option_names.collect { |ch, name| "def #{name}; @#{name}; end\n" }
opts.instance_eval arr.join
options.each do |ch, val|
name = @option_names[ch]
opts.instance_variable_set("@#{name}", val)
end
## help, version, enhancer list
if opts.help || opts.version
puts version() if opts.version
puts usage() if opts.help
puts show_properties() if opts.help
puts show_enhancers() if opts.help
return
end
## include path
opts.includes.split(/,/).each do |path|
$: << path
end if opts.includes
## require library
opts.requires.split(/,/).each do |library|
require library
end if opts.requires
## action
action = opts.action
action ||= 'syntax' if opts.syntax
action ||= 'convert' if opts.source || opts.notext
## lang
lang = opts.lang || 'ruby'
action ||= 'convert' if opts.lang
## class name of Eruby
#classname = opts.class
classname = nil
klass = get_classobj(classname, lang, properties[:pi])
## kanji code
$KCODE = opts.kanji if opts.kanji
## read context values from yaml file
datafiles = opts.datafiles
context = load_datafiles(datafiles, opts)
## parse context data
if opts.context
context = parse_context_data(opts.context, opts)
end
## properties for engine
properties[:escape] = true if opts.escape && !properties.key?(:escape)
properties[:pattern] = opts.pattern if opts.pattern
#properties[:trim] = false if opts.notrim
properties[:preamble] = properties[:postamble] = false if opts.bodyonly
properties[:pi] = nil if properties[:pi] == true
## create engine and extend enhancers
engine = klass.new(nil, properties)
enhancers = get_enhancers(opts.enhancers)
#enhancers.push(Erubis::EscapeEnhancer) if opts.escape
enhancers.each do |enhancer|
engine.extend(enhancer)
engine.bipattern = properties[:bipattern] if enhancer == Erubis::BiPatternEnhancer
end
## no-text
engine.extend(Erubis::NoTextEnhancer) if opts.notext
## convert and execute
val = nil
msg = "Syntax OK\n"
if filenames && !filenames.empty?
filenames.each do |filename|
test(?f, filename) or raise CommandOptionError.new("#{filename}: file not found.")
engine.filename = filename
engine.convert!(File.read(filename))
val = do_action(action, engine, context, filename, opts)
msg = nil if val
end
else
engine.filename = filename = '(stdin)'
engine.convert!($stdin.read())
val = do_action(action, engine, context, filename, opts)
msg = nil if val
end
print msg if action == 'syntax' && msg
end
private
def do_action(action, engine, context, filename, opts)
case action
when 'convert'
s = manipulate_src(engine.src, opts)
when nil, 'exec', 'execute'
s = opts.binding ? engine.result(context.to_hash) : engine.evaluate(context)
when 'syntax'
s = check_syntax(filename, engine.src)
else
raise "*** internal error"
end
print s if s
return s
end
def manipulate_src(source, opts)
flag_linenum = opts.linenum
flag_unique = opts.unique
flag_compact = opts.compact
if flag_linenum
n = 0
source.gsub!(/^/) { n += 1; "%5d: " % n }
source.gsub!(/^ *\d+:\s+?\n/, '') if flag_compact
source.gsub!(/(^ *\d+:\s+?\n)+/, "\n") if flag_unique
else
source.gsub!(/^\s*?\n/, '') if flag_compact
source.gsub!(/(^\s*?\n)+/, "\n") if flag_unique
end
return source
end
def usage(command=nil)
command ||= File.basename($0)
buf = []
buf << "erubis - embedded program converter for multi-language"
buf << "Usage: #{command} [..options..] [file ...]"
buf << " -h, --help : help"
buf << " -v : version"
buf << " -x : show converted code"
buf << " -X : show converted code, only ruby code and no text part"
buf << " -N : numbering: add line numbers (for '-x/-X')"
buf << " -U : unique: compress empty lines to a line (for '-x/-X')"
buf << " -C : compact: remove empty lines (for '-x/-X')"
buf << " -b : body only: no preamble nor postamble (for '-x/-X')"
buf << " -z : syntax checking"
buf << " -e : escape (equal to '--E Escape')"
buf << " -p pattern : embedded pattern (default '<% %>')"
buf << " -l lang : convert but no execute (ruby/php/c/java/scheme/perl/js)"
buf << " -E e1,e2,... : enhancer names (Escape, PercentLine, BiPattern, ...)"
buf << " -I path : library include path"
buf << " -K kanji : kanji code (euc/sjis/utf8) (default none)"
buf << " -c context : context data string (yaml inline style or ruby code)"
buf << " -f datafile : context data file ('*.yaml', '*.yml', or '*.rb')"
#buf << " -t : expand tab characters in YAML file"
buf << " -T : don't expand tab characters in YAML file"
buf << " -S : convert mapping key from string to symbol in YAML file"
buf << " -B : invoke 'result(binding)' instead of 'evaluate(context)'"
buf << " --pi=name : parse '<?name ... ?>' instead of '<% ... %>'"
#'
# -T : don't trim spaces around '<% %>'
# -c class : class name (XmlEruby/PercentLineEruby/...) (default Eruby)
# -r library : require library
# -a : action (convert/execute)
return buf.join("\n")
end
def collect_supported_properties(erubis_klass)
list = []
erubis_klass.ancestors.each do |klass|
if klass.respond_to?(:supported_properties)
list.concat(klass.supported_properties)
end
end
return list
end
def show_properties
s = "supported properties:\n"
basic_props = collect_supported_properties(Erubis::Basic::Engine)
pi_props = collect_supported_properties(Erubis::PI::Engine)
list = []
common_props = basic_props & pi_props
list << ['(common)', common_props]
list << ['(basic)', basic_props - common_props]
list << ['(pi)', pi_props - common_props]
%w[ruby php c java scheme perl javascript].each do |lang|
klass = Erubis.const_get("E#{lang}")
list << [lang, collect_supported_properties(klass) - basic_props]
end
list.each do |lang, props|
s << " * #{lang}\n"
props.each do |name, default_val, desc|
s << (" --%-23s : %s\n" % ["#{name}=#{default_val.inspect}", desc])
end
end
s << "\n"
return s
end
def show_enhancers
s = "enhancers:\n"
list = []
ObjectSpace.each_object(Module) do |m| list << m end
list.sort_by { |m| m.name }.each do |m|
next unless m.name =~ /\AErubis::(.*)Enhancer\z/
name = $1
desc = m.desc
s << (" %-13s : %s\n" % [name, desc])
end
return s
end
def version
return Erubis::VERSION
end
def parse_argv(argv, arg_none='', arg_required='', arg_optional='')
options = {}
context = {}
while argv[0] && argv[0][0] == ?-
optstr = argv.shift
optstr = optstr[1, optstr.length-1]
#
if optstr[0] == ?- # context
unless optstr =~ /\A\-([-\w]+)(?:=(.*))?/
raise CommandOptionError.new("-#{optstr}: invalid context value.")
end
name = $1; value = $2
name = name.gsub(/-/, '_').intern
#value = value.nil? ? true : YAML.load(value) # error, why?
value = value.nil? ? true : YAML.load("---\n#{value}\n")
context[name] = value
#
else # options
while optstr && !optstr.empty?
optchar = optstr[0]
optstr[0,1] = ""
if arg_none.include?(optchar)
options[optchar] = true
elsif arg_required.include?(optchar)
arg = optstr.empty? ? argv.shift : optstr
unless arg
mesg = "-#{optchar.chr}: #{@option_args[optchar]} required."
raise CommandOptionError.new(mesg)
end
options[optchar] = arg
optstr = nil
elsif arg_optional.include?(optchar)
arg = optstr.empty? ? true : optstr
options[optchar] = arg
optstr = nil
else
raise CommandOptionError.new("-#{optchar.chr}: unknown option.")
end
end
end
#
end # end of while
return options, context
end
def untabify(str, width=8)
list = str.split(/\t/)
last = list.pop
sb = ''
list.each do |s|
column = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length
n = width - (column % width)
sb << s << (' ' * n)
end
sb << last
return sb
end
#--
#def untabify(str, width=8)
# sb = ''
# str.scan(/(.*?)\t/m) do |s, |
# len = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length
# sb << s << (" " * (width - len % width))
# end
# return $' ? (sb << $') : str
#end
#++
def get_classobj(classname, lang, pi)
classname ||= "E#{lang}"
base_module = pi ? Erubis::PI : Erubis
begin
klass = base_module.const_get(classname)
rescue NameError
klass = nil
end
unless klass
if lang
msg = "-l #{lang}: invalid language name (class #{base_module.name}::#{classname} not found)."
else
msg = "-c #{classname}: invalid class name."
end
raise CommandOptionError.new(msg)
end
return klass
end
def get_enhancers(enhancer_names)
return [] unless enhancer_names
enhancers = []
shortname = nil
begin
enhancer_names.split(/,/).each do |shortname|
enhancers << Erubis.const_get("#{shortname}Enhancer")
end
rescue NameError
raise CommandOptionError.new("#{shortname}: no such Enhancer (try '-E' to show all enhancers).")
end
return enhancers
end
def load_datafiles(filenames, opts)
context = Erubis::Context.new
return context unless filenames
filenames.split(/,/).each do |filename|
filename.strip!
test(?f, filename) or raise CommandOptionError.new("#{filename}: file not found.")
if filename =~ /\.ya?ml$/
if opts.unexpand
ydoc = YAML.load_file(filename)
else
ydoc = YAML.load(untabify(File.read(filename)))
end
ydoc.is_a?(Hash) or raise CommandOptionError.new("#{filename}: root object is not a mapping.")
intern_hash_keys(ydoc) if opts.intern
context.update(ydoc)
elsif filename =~ /\.rb$/
str = File.read(filename)
context2 = Erubis::Context.new
_instance_eval(context2, str)
context.update(context2)
else
CommandOptionError.new("#{filename}: '*.yaml', '*.yml', or '*.rb' required.")
end
end
return context
end
def _instance_eval(_context, _str)
_context.instance_eval(_str)
end
def parse_context_data(context_str, opts)
if context_str[0] == ?{
require 'yaml'
ydoc = YAML.load(context_str)
unless ydoc.is_a?(Hash)
raise CommandOptionError.new("-c: root object is not a mapping.")
end
intern_hash_keys(ydoc) if opts.intern
return ydoc
else
context = Erubis::Context.new
context.instance_eval(context_str, '-c')
return context
end
end
def intern_hash_keys(obj, done={})
return if done.key?(obj.__id__)
case obj
when Hash
done[obj.__id__] = obj
obj.keys.each do |key|
obj[key.intern] = obj.delete(key) if key.is_a?(String)
end
obj.values.each do |val|
intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array)
end
when Array
done[obj.__id__] = obj
obj.each do |val|
intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array)
end
end
end
def check_syntax(filename, src)
require 'open3'
stdin, stdout, stderr = Open3.popen3('ruby -wc')
stdin.write(src)
stdin.close
result = stdout.read()
stdout.close()
errmsg = stderr.read()
stderr.close()
return nil unless errmsg && !errmsg.empty?
errmsg =~ /\A-:(\d+): /
linenum, message = $1, $'
return "#{filename}:#{linenum}: #{message}"
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/converter.rb | gems/gems/erubis-2.6.0/lib/erubis/converter.rb | ##
## $Rev: 104 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'abstract'
module Erubis
##
## convert
##
module Converter
attr_accessor :preamble, :postamble, :escape
def self.supported_properties # :nodoc:
return [
[:preamble, nil, "preamble (no preamble when false)"],
[:postamble, nil, "postamble (no postamble when false)"],
[:escape, nil, "escape expression or not in default"],
]
end
def init_converter(properties={})
@preamble = properties[:preamble]
@postamble = properties[:postamble]
@escape = properties[:escape]
end
## convert input string into target language
def convert(input)
codebuf = "" # or []
@preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
convert_input(codebuf, input)
@postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
@_proc = nil # clear cached proc object
return codebuf # or codebuf.join()
end
protected
##
## detect spaces at beginning of line
##
def detect_spaces_at_bol(text, is_bol)
lspace = nil
if text.empty?
lspace = "" if is_bol
elsif text[-1] == ?\n
lspace = ""
else
rindex = text.rindex(?\n)
if rindex
s = text[rindex+1..-1]
if s =~ /\A[ \t]*\z/
lspace = s
#text = text[0..rindex]
text[rindex+1..-1] = ''
end
else
if is_bol && text =~ /\A[ \t]*\z/
#lspace = text
#text = nil
lspace = text.dup
text[0..-1] = ''
end
end
end
return lspace
end
##
## (abstract) convert input to code
##
def convert_input(codebuf, input)
not_implemented
end
end
module Basic
end
##
## basic converter which supports '<% ... %>' notation.
##
module Basic::Converter
include Erubis::Converter
def self.supported_properties # :nodoc:
return [
[:pattern, '<% %>', "embed pattern"],
[:trim, true, "trim spaces around <% ... %>"],
]
end
attr_accessor :pattern, :trim
def init_converter(properties={})
super(properties)
@pattern = properties[:pattern]
@trim = properties[:trim] != false
end
protected
## return regexp of pattern to parse eRuby script
def pattern_regexp(pattern)
@prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>'
#return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
#return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
end
module_function :pattern_regexp
#DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
#DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
DEFAULT_REGEXP = pattern_regexp('<% %>')
public
def convert_input(src, input)
pat = @pattern
regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
pos = 0
is_bol = true # is beginning of line
input.scan(regexp) do |indicator, code, tailch, rspace|
match = Regexp.last_match()
len = match.begin(0) - pos
text = input[pos, len]
pos = match.end(0)
ch = indicator ? indicator[0] : nil
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
is_bol = rspace ? true : false
add_text(src, text) if text && !text.empty?
## * when '<%= %>', do nothing
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
if ch == ?= # <%= %>
rspace = nil if tailch && !tailch.empty?
add_text(src, lspace) if lspace
add_expr(src, code, indicator)
add_text(src, rspace) if rspace
elsif ch == ?\# # <%# %>
n = code.count("\n") + (rspace ? 1 : 0)
if @trim && lspace && rspace
add_stmt(src, "\n" * n)
else
add_text(src, lspace) if lspace
add_stmt(src, "\n" * n)
add_text(src, rspace) if rspace
end
elsif ch == ?% # <%% %>
s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
add_text(src, s)
else # <% %>
if @trim && lspace && rspace
add_stmt(src, "#{lspace}#{code}#{rspace}")
else
add_text(src, lspace) if lspace
add_stmt(src, code)
add_text(src, rspace) if rspace
end
end
end
rest = $' || input # add input when no matched
add_text(src, rest)
end
## add expression code to src
def add_expr(src, code, indicator)
case indicator
when '='
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
when '=='
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
when '==='
add_expr_debug(src, code)
end
end
end
module PI
end
##
## Processing Instructions (PI) converter for XML.
## this class converts '<?rb ... ?>' and '${...}' notation.
##
module PI::Converter
include Erubis::Converter
def self.desc # :nodoc:
"use processing instructions (PI) instead of '<% %>'"
end
def self.supported_properties # :nodoc:
return [
[:trim, true, "trim spaces around <% ... %>"],
[:pi, 'rb', "PI (Processing Instrunctions) name"],
[:embchar, '@', "char for embedded expression pattern('@{...}@')"],
[:pattern, '<% %>', "embed pattern"],
]
end
attr_accessor :pi, :prefix
def init_converter(properties={})
super(properties)
@trim = properties.fetch(:trim, true)
@pi = properties[:pi] if properties[:pi]
@embchar = properties[:embchar] || '@'
@pattern = properties[:pattern]
@pattern = '<% %>' if @pattern.nil? #|| @pattern == true
end
def convert(input)
code = super(input)
return @header || @footer ? "#{@header}#{code}#{@footer}" : code
end
protected
def convert_input(codebuf, input)
unless @regexp
@pi ||= 'e'
ch = Regexp.escape(@embchar)
if @pattern
left, right = @pattern.split(' ')
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
else
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
end
end
#
is_bol = true
pos = 0
input.scan(@regexp) do |pi_arg, stmt, rspace,
indicator1, expr1, indicator2, expr2|
match = Regexp.last_match
len = match.begin(0) - pos
text = input[pos, len]
pos = match.end(0)
lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
is_bol = stmt && rspace ? true : false
add_text(codebuf, text) # unless text.empty?
#
if stmt
if @trim && lspace && rspace
add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
else
add_text(codebuf, lspace) if lspace
add_pi_stmt(codebuf, stmt, pi_arg)
add_text(codebuf, rspace) if rspace
end
else
add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
end
end
rest = $' || input
add_text(codebuf, rest)
end
#--
#def convert_input(codebuf, input)
# parse_stmts(codebuf, input)
# #parse_stmts2(codebuf, input)
#end
#
#def parse_stmts(codebuf, input)
# #regexp = pattern_regexp(@pattern)
# @pi ||= 'e'
# @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m
# is_bol = true
# pos = 0
# input.scan(@stmt_pattern) do |pi_arg, code, rspace|
# match = Regexp.last_match
# len = match.begin(0) - pos
# text = input[pos, len]
# pos = match.end(0)
# lspace = detect_spaces_at_bol(text, is_bol)
# is_bol = rspace ? true : false
# parse_exprs(codebuf, text) # unless text.empty?
# if @trim && lspace && rspace
# add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg)
# else
# add_text(codebuf, lspace)
# add_pi_stmt(codebuf, code, pi_arg)
# add_text(codebuf, rspace)
# end
# end
# rest = $' || input
# parse_exprs(codebuf, rest)
#end
#
#def parse_exprs(codebuf, input)
# unless @expr_pattern
# ch = Regexp.escape(@embchar)
# if @pattern
# left, right = @pattern.split(' ')
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/
# else
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/
# end
# end
# pos = 0
# input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2|
# indicator = indicator1 || indicator2
# code = code1 || code2
# match = Regexp.last_match
# len = match.begin(0) - pos
# text = input[pos, len]
# pos = match.end(0)
# add_text(codebuf, text) # unless text.empty?
# add_pi_expr(codebuf, code, indicator)
# end
# rest = $' || input
# add_text(codebuf, rest)
#end
#++
def add_pi_stmt(codebuf, code, pi_arg) # :nodoc:
case pi_arg
when nil ; add_stmt(codebuf, code)
when 'header' ; @header = code
when 'footer' ; @footer = code
when 'comment'; add_stmt(codebuf, "\n" * code.count("\n"))
when 'value' ; add_expr_literal(codebuf, code)
else ; add_stmt(codebuf, code)
end
end
def add_pi_expr(codebuf, code, indicator) # :nodoc:
case indicator
when nil, '', '==' # @{...}@ or <%== ... %>
@escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code)
when '!', '=' # @!{...}@ or <%= ... %>
@escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code)
when '!!', '===' # @!!{...}@ or <%=== ... %>
add_expr_debug(codebuf, code)
else
# ignore
end
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/enhancer.rb | gems/gems/erubis-2.6.0/lib/erubis/enhancer.rb | ##
## $Rev: 103 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
module Erubis
##
## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped
##
## ex.
## class XmlEruby < Eruby
## include EscapeEnhancer
## end
##
## this is language-indenedent.
##
module EscapeEnhancer
def self.desc # :nodoc:
"switch '<%= %>' to escaped and '<%== %>' to unescaped"
end
#--
#def self.included(klass)
# klass.class_eval <<-END
# alias _add_expr_literal add_expr_literal
# alias _add_expr_escaped add_expr_escaped
# alias add_expr_literal _add_expr_escaped
# alias add_expr_escaped _add_expr_literal
# END
#end
#++
def add_expr(src, code, indicator)
case indicator
when '='
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
when '=='
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
when '==='
add_expr_debug(src, code)
end
end
end
#--
## (obsolete)
#module FastEnhancer
#end
#++
##
## use $stdout instead of string
##
## this is only for Eruby.
##
module StdoutEnhancer
def self.desc # :nodoc:
"use $stdout instead of array buffer or string buffer"
end
def add_preamble(src)
src << "_buf = $stdout;"
end
def add_postamble(src)
src << "\n''\n"
end
end
##
## use print statement instead of '_buf << ...'
##
## this is only for Eruby.
##
module PrintOutEnhancer
def self.desc # :nodoc:
"use print statement instead of '_buf << ...'"
end
def add_preamble(src)
end
def add_text(src, text)
src << " print '" << escape_text(text) << "';" unless text.empty?
end
def add_expr_literal(src, code)
src << ' print((' << code << ').to_s);'
end
def add_expr_escaped(src, code)
src << ' print ' << escaped_expr(code) << ';'
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
end
end
##
## enable print function
##
## Notice: use Eruby#evaluate() and don't use Eruby#result()
## to be enable print function.
##
## this is only for Eruby.
##
module PrintEnabledEnhancer
def self.desc # :nodoc:
"enable to use print function in '<% %>'"
end
def add_preamble(src)
src << "@_buf = "
super
end
def print(*args)
args.each do |arg|
@_buf << arg.to_s
end
end
def evaluate(context=nil)
_src = @src
if context.is_a?(Hash)
context.each do |key, val| instance_variable_set("@#{key}", val) end
elsif context
context.instance_variables.each do |name|
instance_variable_set(name, context.instance_variable_get(name))
end
end
return instance_eval(_src, (@filename || '(erubis)'))
end
end
##
## return array instead of string
##
## this is only for Eruby.
##
module ArrayEnhancer
def self.desc # :nodoc:
"return array instead of string"
end
def add_preamble(src)
src << "_buf = [];"
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
src << "_buf\n"
end
end
##
## use an Array object as buffer (included in Eruby by default)
##
## this is only for Eruby.
##
module ArrayBufferEnhancer
def self.desc # :nodoc:
"use an Array object for buffering (included in Eruby class)"
end
def add_preamble(src)
src << "_buf = [];"
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
src << "_buf.join\n"
end
end
##
## use String class for buffering
##
## this is only for Eruby.
##
module StringBufferEnhancer
def self.desc # :nodoc:
"use a String object for buffering"
end
def add_preamble(src)
src << "_buf = '';"
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
src << "_buf.to_s\n"
end
end
##
## use StringIO class for buffering
##
## this is only for Eruby.
##
module StringIOEnhancer # :nodoc:
def self.desc # :nodoc:
"use a StringIO object for buffering"
end
def add_preamble(src)
src << "_buf = StringIO.new;"
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
src << "_buf.string\n"
end
end
##
## set buffer variable name to '_erbout' as well as '_buf'
##
## this is only for Eruby.
##
module ErboutEnhancer
def self.desc # :nodoc:
"set '_erbout = _buf = \"\";' to be compatible with ERB."
end
def add_preamble(src)
src << "_erbout = _buf = '';"
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
src << "_buf.to_s\n"
end
end
##
## remove text and leave code, especially useful when debugging.
##
## ex.
## $ erubis -s -E NoText file.eruby | more
##
## this is language independent.
##
module NoTextEnhancer
def self.desc # :nodoc:
"remove text and leave code (useful when debugging)"
end
def add_text(src, text)
src << ("\n" * text.count("\n"))
if text[-1] != ?\n
text =~ /^(.*?)\z/
src << (' ' * $1.length)
end
end
end
##
## remove code and leave text, especially useful when validating HTML tags.
##
## ex.
## $ erubis -s -E NoCode file.eruby | tidy -errors
##
## this is language independent.
##
module NoCodeEnhancer
def self.desc # :nodoc:
"remove code and leave text (useful when validating HTML)"
end
def add_preamble(src)
end
def add_postamble(src)
end
def add_text(src, text)
src << text
end
def add_expr(src, code, indicator)
src << "\n" * code.count("\n")
end
def add_stmt(src, code)
src << "\n" * code.count("\n")
end
end
##
## get convert faster, but spaces around '<%...%>' are not trimmed.
##
## this is language-independent.
##
module SimplifyEnhancer
def self.desc # :nodoc:
"get convert faster but leave spaces around '<% %>'"
end
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m
def convert(input)
src = ""
add_preamble(src)
#regexp = pattern_regexp(@pattern)
pos = 0
input.scan(SIMPLE_REGEXP) do |indicator, code|
match = Regexp.last_match
index = match.begin(0)
text = input[pos, index - pos]
pos = match.end(0)
add_text(src, text)
if !indicator # <% %>
add_stmt(src, code)
elsif indicator[0] == ?\# # <%# %>
n = code.count("\n")
add_stmt(src, "\n" * n)
else # <%= %>
add_expr(src, code, indicator)
end
end
rest = $' || input
add_text(src, rest)
add_postamble(src)
return src
end
end
##
## enable to use other embedded expression pattern (default is '\[= =\]').
##
## notice! this is an experimental. spec may change in the future.
##
## ex.
## input = <<END
## <% for item in list %>
## <%= item %> : <%== item %>
## [= item =] : [== item =]
## <% end %>
## END
##
## class BiPatternEruby
## include BiPatternEnhancer
## end
## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
## list = ['<a>', 'b&b', '"c"']
## print eruby.result(binding())
##
## ## output
## <a> : <a>
## <a> : <a>
## b&b : b&b
## b&b : b&b
## "c" : "c"
## "c" : "c"
##
## this is language independent.
##
module BiPatternEnhancer
def self.desc # :nodoc:
"another embedded expression pattern (default '\[= =\]')."
end
def initialize(input, properties={})
self.bipattern = properties[:bipattern] # or '\$\{ \}'
super
end
## when pat is nil then '\[= =\]' is used
def bipattern=(pat) # :nodoc:
@bipattern = pat || '\[= =\]'
pre, post = @bipattern.split()
@bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m
end
def add_text(src, text)
return unless text
text.scan(@bipattern_regexp) do |txt, indicator, code|
super(src, txt)
add_expr(src, code, '=' + indicator)
end
rest = $' || text
super(src, rest)
end
end
##
## regards lines starting with '%' as program code
##
## this is for compatibility to eruby and ERB.
##
## this is language-independent.
##
module PercentLineEnhancer
def self.desc # :nodoc:
"regard lines starting with '%' as program code"
end
def add_text(src, text)
pos = 0
text2 = ''
text.scan(/^\%(.*?\r?\n)/) do
line = $1
match = Regexp.last_match
len = match.begin(0) - pos
str = text[pos, len]
pos = match.end(0)
if text2.empty?
text2 = str
else
text2 << str
end
if line[0] == ?%
text2 << line
else
super(src, text2)
text2 = ''
add_stmt(src, line)
end
end
rest = pos == 0 ? text : $' # or $' || text
unless text2.empty?
text2 << rest if rest
rest = text2
end
super(src, rest)
end
end
##
## [experimental] allow header and footer in eRuby script
##
## ex.
## ====================
## ## without header and footer
## $ cat ex1.eruby
## <% def list_items(list) %>
## <% for item in list %>
## <li><%= item %></li>
## <% end %>
## <% end %>
##
## $ erubis -s ex1.eruby
## _buf = []; def list_items(list)
## ; for item in list
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
## '; end
## ; end
## ;
## _buf.join
##
## ## with header and footer
## $ cat ex2.eruby
## <!--#header:
## def list_items(list)
## #-->
## <% for item in list %>
## <li><%= item %></li>
## <% end %>
## <!--#footer:
## end
## #-->
##
## $ erubis -s -c HeaderFooterEruby ex4.eruby
##
## def list_items(list)
## _buf = []; _buf << '
## '; for item in list
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
## '; end
## ; _buf << '
## ';
## _buf.join
## end
##
## ====================
##
## this is language-independent.
##
module HeaderFooterEnhancer
def self.desc # :nodoc:
"allow header/footer in document (ex. '<!--#header: #-->')"
end
HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m
def add_text(src, text)
text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
flag_trim = @trim && lspace && rspace
super(src, txt)
content = "#{lspace}#{content}#{rspace}" if flag_trim
super(src, lspace) if !flag_trim && lspace
instance_variable_set("@#{word}", content)
super(src, rspace) if !flag_trim && rspace
end
rest = $' || text
super(src, rest)
end
attr_accessor :header, :footer
def convert(input)
source = super
return @src = "#{@header}#{source}#{@footer}"
end
end
##
## delete indentation of HTML.
##
## this is language-independent.
##
module DeleteIndentEnhancer
def self.desc # :nodoc:
"delete indentation of HTML."
end
def convert_input(src, input)
input = input.gsub(/^[ \t]+</, '<')
super(src, input)
end
end
##
## convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"
##
## this is only for Eruby.
##
module InterpolationEnhancer
def self.desc # :nodoc:
"convert '<p><%=text%></p>' into '_buf << %Q`<p>\#{text}</p>`'"
end
def convert_input(src, input)
pat = @pattern
regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
pos = 0
is_bol = true # is beginning of line
str = ''
input.scan(regexp) do |indicator, code, tailch, rspace|
match = Regexp.last_match()
len = match.begin(0) - pos
text = input[pos, len]
pos = match.end(0)
ch = indicator ? indicator[0] : nil
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
is_bol = rspace ? true : false
_add_text_to_str(str, text)
## * when '<%= %>', do nothing
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
if ch == ?= # <%= %>
rspace = nil if tailch && !tailch.empty?
str << lspace if lspace
add_expr(str, code, indicator)
str << rspace if rspace
elsif ch == ?\# # <%# %>
n = code.count("\n") + (rspace ? 1 : 0)
if @trim && lspace && rspace
add_text(src, str)
str = ''
add_stmt(src, "\n" * n)
else
str << lspace if lspace
add_text(src, str)
str = ''
add_stmt(src, "\n" * n)
str << rspace if rspace
end
else # <% %>
if @trim && lspace && rspace
add_text(src, str)
str = ''
add_stmt(src, "#{lspace}#{code}#{rspace}")
else
str << lspace if lspace
add_text(src, str)
str = ''
add_stmt(src, code)
str << rspace if rspace
end
end
end
rest = $' || input # add input when no matched
_add_text_to_str(str, rest)
add_text(src, str)
end
def add_text(src, text)
return if !text || text.empty?
#src << " _buf << %Q`" << text << "`;"
if text[-1] == ?\n
text[-1] = "\\n"
src << " _buf << %Q`" << text << "`\n"
else
src << " _buf << %Q`" << text << "`;"
end
end
def _add_text_to_str(str, text)
return if !text || text.empty?
text.gsub!(/['\#\\]/, '\\\\\&')
str << text
end
def add_expr_escaped(str, code)
str << "\#{#{escaped_expr(code)}}"
end
def add_expr_literal(str, code)
str << "\#{#{code}}"
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/preprocessing.rb | gems/gems/erubis-2.6.0/lib/erubis/preprocessing.rb | ###
### $Rev: 102 $
### $Release: 2.6.0 $
### copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
###
require 'cgi'
module Erubis
##
## for preprocessing
##
class PreprocessingEruby < Erubis::Eruby
def initialize(input, params={})
params = params.dup
params[:pattern] ||= '\[% %\]' # use '[%= %]' instead of '<%= %>'
#params[:escape] = true # transport '[%= %]' and '[%== %]'
super
end
def add_expr_escaped(src, code)
add_expr_literal(src, "_decode((#{code}))")
end
end
##
## helper methods for preprocessing
##
module PreprocessingHelper
module_function
def _p(arg)
return "<%=#{arg}%>"
end
def _P(arg)
return "<%=h(#{arg})%>"
end
alias _? _p
def _decode(arg)
arg = arg.to_s
arg.gsub!(/%3C%25(?:=|%3D)(.*?)%25%3E/) { "<%=#{CGI.unescape($1)}%>" }
arg.gsub!(/<%=(.*?)%>/) { "<%=#{CGI.unescapeHTML($1)}%>" }
return arg
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/local-setting.rb | gems/gems/erubis-2.6.0/lib/erubis/local-setting.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
##
## you can add site-local settings here.
## this files is required by erubis.rb
##
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/generator.rb | gems/gems/erubis-2.6.0/lib/erubis/generator.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'abstract'
module Erubis
##
## code generator, called by Converter module
##
module Generator
def self.supported_properties() # :nodoc:
return [
[:escapefunc, nil, "escape function name"],
]
end
attr_accessor :escapefunc
def init_generator(properties={})
@escapefunc = properties[:escapefunc]
end
## (abstract) escape text string
##
## ex.
## def escape_text(text)
## return text.dump
## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
## end
def escape_text(text)
not_implemented
end
## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)')
def escaped_expr(code)
code.strip!
return "#{@escapefunc}(#{code})"
end
## (abstract) add @preamble to src
def add_preamble(src)
not_implemented
end
## (abstract) add text string to src
def add_text(src, text)
not_implemented
end
## (abstract) add statement code to src
def add_stmt(src, code)
not_implemented
end
## (abstract) add expression literal code to src. this is called by add_expr().
def add_expr_literal(src, code)
not_implemented
end
## (abstract) add escaped expression code to src. this is called by add_expr().
def add_expr_escaped(src, code)
not_implemented
end
## (abstract) add expression code to src for debug. this is called by add_expr().
def add_expr_debug(src, code)
not_implemented
end
## (abstract) add @postamble to src
def add_postamble(src)
not_implemented
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/tiny.rb | gems/gems/erubis-2.6.0/lib/erubis/tiny.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
module Erubis
##
## tiny and the simplest implementation of eRuby
##
## ex.
## eruby = TinyEruby.new(File.read('example.rhtml'))
## print eruby.src # print ruby code
## print eruby.result(binding()) # eval ruby code with Binding object
## print eruby.evalute(context) # eval ruby code with context object
##
class TinyEruby
def initialize(input=nil)
@src = convert(input) if input
end
attr_reader :src
EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m
def convert(input)
src = "_buf = '';" # preamble
pos = 0
input.scan(EMBEDDED_PATTERN) do |indicator, code|
match = Regexp.last_match
len = match.begin(0) - pos
text = input[pos, len]
pos = match.end(0)
#src << " _buf << '" << escape_text(text) << "';"
text.gsub!(/['\\]/, '\\\\\&')
src << " _buf << '" << text << "';" unless text.empty?
if !indicator # <% %>
src << code << ";"
elsif indicator == '#' # <%# %>
src << ("\n" * code.count("\n"))
else # <%= %>
src << " _buf << (" << code << ").to_s;"
end
end
rest = $' || input
#src << " _buf << '" << escape_text(rest) << "';"
rest.gsub!(/['\\]/, '\\\\\&')
src << " _buf << '" << rest << "';" unless rest.empty?
src << "\n_buf.to_s\n" # postamble
return src
end
#def escape_text(text)
# return text.gsub!(/['\\]/, '\\\\\&') || text
#end
def result(_binding=TOPLEVEL_BINDING)
eval @src, _binding
end
def evaluate(_context=Object.new)
if _context.is_a?(Hash)
_obj = Object.new
_context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
_context = _obj
end
_context.instance_eval @src
end
end
module PI
end
class PI::TinyEruby
def initialize(input=nil, options={})
@escape = options[:escape] || 'Erubis::XmlHelper.escape_xml'
@src = convert(input) if input
end
attr_reader :src
EMBEDDED_PATTERN = /(^[ \t]*)?<\?rb(\s.*?)\?>([ \t]*\r?\n)?|@(!+)?\{(.*?)\}@/m
def convert(input)
src = "_buf = '';" # preamble
pos = 0
input.scan(EMBEDDED_PATTERN) do |lspace, stmt, rspace, indicator, expr|
match = Regexp.last_match
len = match.begin(0) - pos
text = input[pos, len]
pos = match.end(0)
#src << " _buf << '" << escape_text(text) << "';"
text.gsub!(/['\\]/, '\\\\\&')
src << " _buf << '" << text << "';" unless text.empty?
if stmt # <?rb ... ?>
if lspace && rspace
src << "#{lspace}#{stmt}#{rspace}"
else
src << " _buf << '" << lspace << "';" if lspace
src << stmt << ";"
src << " _buf << '" << rspace << "';" if rspace
end
else # ${...}, $!{...}
if !indicator
src << " _buf << " << @escape << "(" << expr << ");"
elsif indicator == '!'
src << " _buf << (" << expr << ").to_s;"
end
end
end
rest = $' || input
#src << " _buf << '" << escape_text(rest) << "';"
rest.gsub!(/['\\]/, '\\\\\&')
src << " _buf << '" << rest << "';" unless rest.empty?
src << "\n_buf.to_s\n" # postamble
return src
end
#def escape_text(text)
# return text.gsub!(/['\\]/, '\\\\\&') || text
#end
def result(_binding=TOPLEVEL_BINDING)
eval @src, _binding
end
def evaluate(_context=Object.new)
if _context.is_a?(Hash)
_obj = Object.new
_context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
_context = _obj
end
_context.instance_eval @src
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/helper.rb | gems/gems/erubis-2.6.0/lib/erubis/helper.rb | ##
## $Rev: 89 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
module Erubis
##
## helper for xml
##
module XmlHelper
module_function
ESCAPE_TABLE = {
'&' => '&',
'<' => '<',
'>' => '>',
'"' => '"',
"'" => ''',
}
def escape_xml(value)
value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/
#value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
end
def escape_xml2(value)
return value.to_s.gsub(/\&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
end
alias h escape_xml
alias html_escape escape_xml
def url_encode(str)
return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
s.unpack('C*').collect { |i| "%%%02X" % i }.join
}
end
alias u url_encode
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/context.rb | gems/gems/erubis-2.6.0/lib/erubis/context.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
module Erubis
##
## context object for Engine#evaluate
##
## ex.
## template = <<'END'
## Hello <%= @user %>!
## <% for item in @list %>
## - <%= item %>
## <% end %>
## END
##
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
## # or
## # context = Erubis::Context.new
## # context[:user] = 'World'
## # context[:list] = ['a', 'b', 'c']
##
## eruby = Erubis::Eruby.new(template)
## print eruby.evaluate(context)
##
class Context
include Enumerable
def initialize(hash=nil)
hash.each do |name, value|
self[name] = value
end if hash
end
def [](key)
return instance_variable_get("@#{key}")
end
def []=(key, value)
return instance_variable_set("@#{key}", value)
end
def keys
return instance_variables.collect { |name| name[1..-1] }
end
def each
instance_variables.each do |name|
key = name[1..-1]
value = instance_variable_get(name)
yield(key, value)
end
end
def to_hash
hash = {}
self.keys.each { |key| hash[key] = self[key] }
return hash
end
def update(context_or_hash)
arg = context_or_hash
if arg.is_a?(Hash)
arg.each do |key, val|
self[key] = val
end
else
arg.instance_variables.each do |varname|
key = varname[1..-1]
val = arg.instance_variable_get(varname)
self[key] = val
end
end
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine.rb | gems/gems/erubis-2.6.0/lib/erubis/engine.rb | ##
## $Rev: 104 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/generator'
require 'erubis/converter'
require 'erubis/evaluator'
require 'erubis/context'
module Erubis
##
## (abstract) abstract engine class.
## subclass must include evaluator and converter module.
##
class Engine
#include Evaluator
#include Converter
#include Generator
def initialize(input=nil, properties={})
#@input = input
init_generator(properties)
init_converter(properties)
init_evaluator(properties)
@src = convert(input) if input
end
##
## convert input string and set it to @src
##
def convert!(input)
@src = convert(input)
end
##
## load file, write cache file, and return engine object.
## this method create code cache file automatically.
## cachefile name can be specified with properties[:cachename],
## or filname + 'cache' is used as default.
##
def self.load_file(filename, properties={})
cachename = properties[:cachename] || (filename + '.cache')
properties[:filename] = filename
if test(?f, cachename) && File.mtime(filename) <= File.mtime(cachename)
engine = self.new(nil, properties)
engine.src = File.read(cachename)
else
input = File.open(filename, 'rb') {|f| f.read }
engine = self.new(input, properties)
File.open(cachename, 'wb') do |f|
f.flock(File::LOCK_EX)
f.write(engine.src)
f.flush()
end
end
engine.src.untaint # ok?
return engine
end
##
## helper method to convert and evaluate input text with context object.
## context may be Binding, Hash, or Object.
##
def process(input, context=nil, filename=nil)
code = convert(input)
filename ||= '(erubis)'
if context.is_a?(Binding)
return eval(code, context, filename)
else
context = Context.new(context) if context.is_a?(Hash)
return context.instance_eval(code, filename)
end
end
##
## helper method evaluate Proc object with contect object.
## context may be Binding, Hash, or Object.
##
def process_proc(proc_obj, context=nil, filename=nil)
if context.is_a?(Binding)
filename ||= '(erubis)'
return eval(proc_obj, context, filename)
else
context = Context.new(context) if context.is_a?(Hash)
return context.instance_eval(&proc_obj)
end
end
end # end of class Engine
##
## (abstract) base engine class for Eruby, Eperl, Ejava, and so on.
## subclass must include generator.
##
class Basic::Engine < Engine
include Evaluator
include Basic::Converter
include Generator
end
class PI::Engine < Engine
include Evaluator
include PI::Converter
include Generator
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/error.rb | gems/gems/erubis-2.6.0/lib/erubis/error.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
module Erubis
##
## base error class
##
class ErubisError < StandardError
end
##
## raised when method or function is not supported
##
class NotSupportedError < ErubisError
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/evaluator.rb | gems/gems/erubis-2.6.0/lib/erubis/evaluator.rb | ##
## $Rev: 94 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/error'
require 'erubis/context'
module Erubis
EMPTY_BINDING = binding()
##
## evaluate code
##
module Evaluator
def self.supported_properties # :nodoc:
return []
end
attr_accessor :src, :filename
def init_evaluator(properties)
@filename = properties[:filename]
end
def result(*args)
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
end
def evaluate(*args)
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
end
end
##
## evaluator for Ruby
##
module RubyEvaluator
include Evaluator
def self.supported_properties # :nodoc:
list = Evaluator.supported_properties
return list
end
## eval(@src) with binding object
def result(_binding_or_hash=TOPLEVEL_BINDING)
_arg = _binding_or_hash
if _arg.is_a?(Hash)
## load _context data as local variables by eval
#eval _arg.keys.inject("") { |s, k| s << "#{k.to_s} = _arg[#{k.inspect}];" }
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join
_arg = binding()
end
return eval(@src, _arg, (@filename || '(erubis)'))
end
## invoke context.instance_eval(@src)
def evaluate(context=Context.new)
context = Context.new(context) if context.is_a?(Hash)
#return context.instance_eval(@src, @filename || '(erubis)')
@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
return context.instance_eval(&@_proc)
end
## if object is an Class or Module then define instance method to it,
## else define singleton method to it.
def def_method(object, method_name, filename=nil)
m = object.is_a?(Module) ? :module_eval : :instance_eval
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/helpers/rails_helper.rb | gems/gems/erubis-2.6.0/lib/erubis/helpers/rails_helper.rb | ###
### $Rev: 109 $
### $Release: 2.6.0 $
### copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
###
require 'erubis'
require 'erubis/preprocessing'
module Erubis
class Eruby
include ErboutEnhancer # will generate '_erbout = _buf = ""; '
end
class FastEruby
include ErboutEnhancer # will generate '_erbout = _buf = ""; '
end
module Helpers
##
## helper module for Ruby on Rails
##
## howto:
##
## 1. add the folliwng code in your 'config/environment.rb'
##
## require 'erubis/helpers/rails_helper'
## #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby
## #Erubis::Helpers::RailsHelper.init_properties = {}
## #Erubis::Helpers::RailsHelper.show_src = false # set true for debugging
## #Erubis::Helpers::RailsHelper.preprocessing = true # set true to enable preprocessing
##
## 2. restart web server.
##
## if Erubis::Helper::Rails.show_src is true, Erubis prints converted Ruby code
## into log file ('log/development.log' or so). if false, it doesn't.
## if nil, Erubis prints converted Ruby code if ENV['RAILS_ENV'] == 'development'.
##
module RailsHelper
#cattr_accessor :init_properties
@@engine_class = ::Erubis::Eruby
#@@engine_class = ::Erubis::FastEruby
def self.engine_class
@@engine_class
end
def self.engine_class=(klass)
@@engine_class = klass
end
#cattr_accessor :init_properties
@@init_properties = {}
def self.init_properties
@@init_properties
end
def self.init_properties=(hash)
@@init_properties = hash
end
#cattr_accessor :show_src
@@show_src = nil
def self.show_src
@@show_src
end
def self.show_src=(flag)
@@show_src = flag
end
#cattr_accessor :preprocessing
@@preprocessing = false
def self.preprocessing
@@preprocessing
end
def self.preprocessing=(flag)
@@preprocessing = flag
end
## define class for backward-compatibility
class PreprocessingEruby < Erubis::PreprocessingEruby # :nodoc:
end
module TemplateConverter
## covert eRuby string into ruby code
def _convert_template(template) # :nodoc:
#src = ::Erubis::Eruby.new(template).src
klass = ::Erubis::Helpers::RailsHelper.engine_class
properties = ::Erubis::Helpers::RailsHelper.init_properties
show_src = ::Erubis::Helpers::RailsHelper.show_src
show_src = ENV['RAILS_ENV'] == 'development' if show_src.nil?
## preprocessing
if ::Erubis::Helpers::RailsHelper.preprocessing
preprocessor = _create_preprocessor(template)
template = preprocessor.evaluate(_preprocessing_context_object())
logger.info "** Erubis: preprocessed==<<'END'\n#{template}END\n" if show_src
end
## convert into ruby code
src = klass.new(template, properties).src
#src.insert(0, '_erbout = ')
logger.info "** Erubis: src==<<'END'\n#{src}END\n" if show_src
return src
end
def _create_preprocessor(template)
return PreprocessingEruby.new(template, :escape=>true)
end
def _preprocessing_context_object
return self
end
end
end
end
end
class ActionView::Base # :nodoc:
include ::Erubis::Helpers::RailsHelper::TemplateConverter
include ::Erubis::PreprocessingHelper
private
# convert template into ruby code
def convert_template_into_ruby_code(template)
#ERB.new(template, nil, @@erb_trim_mode).src
return _convert_template(template)
end
end
require 'action_pack/version'
if ActionPack::VERSION::MAJOR >= 2 ### Rails 2.X
if ActionPack::VERSION::MINOR > 0 || ActionPack::VERSION::TINY >= 2 ### Rails 2.0.2 or higher
module ActionView
module TemplateHandlers # :nodoc:
class Erubis < TemplateHandler
include ::Erubis::Helpers::RailsHelper::TemplateConverter
include ::Erubis::PreprocessingHelper
def compile(template)
return _convert_template(template)
end
def logger
return @view.controller.logger
end
def _preprocessing_context_object
return @view.controller.instance_variable_get('@template')
end
end
end
Base.class_eval do
register_default_template_handler :erb, TemplateHandlers::Erubis
register_template_handler :rhtml, TemplateHandlers::Erubis
end
end
else ### Rails 2.0.0 or 2.0.1
class ActionView::Base # :nodoc:
private
# Method to create the source code for a given template.
def create_template_source(extension, template, render_symbol, locals)
if template_requires_setup?(extension)
body = case extension.to_sym
when :rxml, :builder
content_type_handler = (controller.respond_to?(:response) ? "controller.response" : "controller")
"#{content_type_handler}.content_type ||= Mime::XML\n" +
"xml = Builder::XmlMarkup.new(:indent => 2)\n" +
template +
"\nxml.target!\n"
when :rjs
"controller.response.content_type ||= Mime::JS\n" +
"update_page do |page|\n#{template}\nend"
end
else
#body = ERB.new(template, nil, @@erb_trim_mode).src
body = convert_template_into_ruby_code(template)
end
#
@@template_args[render_symbol] ||= {}
locals_keys = @@template_args[render_symbol].keys | locals
@@template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h }
#
locals_code = ""
locals_keys.each do |key|
locals_code << "#{key} = local_assigns[:#{key}]\n"
end
#
"def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend"
end
end
end #if
else ### Rails 1.X
if ActionPack::VERSION::MINOR > 12 ### Rails 1.2
class ActionView::Base # :nodoc:
private
# Create source code for given template
def create_template_source(extension, template, render_symbol, locals)
if template_requires_setup?(extension)
body = case extension.to_sym
when :rxml
"controller.response.content_type ||= 'application/xml'\n" +
"xml = Builder::XmlMarkup.new(:indent => 2)\n" +
template
when :rjs
"controller.response.content_type ||= 'text/javascript'\n" +
"update_page do |page|\n#{template}\nend"
end
else
#body = ERB.new(template, nil, @@erb_trim_mode).src
body = convert_template_into_ruby_code(template)
end
#
@@template_args[render_symbol] ||= {}
locals_keys = @@template_args[render_symbol].keys | locals
@@template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h }
#
locals_code = ""
locals_keys.each do |key|
locals_code << "#{key} = local_assigns[:#{key}]\n"
end
#
"def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend"
end
end
else ### Rails 1.1
class ActionView::Base # :nodoc:
private
# Create source code for given template
def create_template_source(extension, template, render_symbol, locals)
if template_requires_setup?(extension)
body = case extension.to_sym
when :rxml
"xml = Builder::XmlMarkup.new(:indent => 2)\n" +
"@controller.headers['Content-Type'] ||= 'application/xml'\n" +
template
when :rjs
"@controller.headers['Content-Type'] ||= 'text/javascript'\n" +
"update_page do |page|\n#{template}\nend"
end
else
#body = ERB.new(template, nil, @@erb_trim_mode).src
body = convert_template_into_ruby_code(template)
end
#
@@template_args[render_symbol] ||= {}
locals_keys = @@template_args[render_symbol].keys | locals
@@template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h }
#
locals_code = ""
locals_keys.each do |key|
locals_code << "#{key} = local_assigns[:#{key}] if local_assigns.has_key?(:#{key})\n"
end
#
"def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend"
end
end
end #if
end ###
## make h() method faster
module ERB::Util # :nodoc:
ESCAPE_TABLE = { '&'=>'&', '<'=>'<', '>'=>'>', '"'=>'"', "'"=>''', }
def h(value)
value.to_s.gsub(/[&<>"]/) {|s| ESCAPE_TABLE[s] }
end
module_function :h
end
## finish
ac = ActionController::Base.new
ac.logger.info "** Erubis #{::Erubis::VERSION}"
#$stdout.puts "** Erubis #{::Erubis::VERSION}"
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/helpers/rails_form_helper.rb | gems/gems/erubis-2.6.0/lib/erubis/helpers/rails_form_helper.rb | ###
### $Rev: 109 $
### $Release: 2.6.0 $
### copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
###
module Erubis
module Helpers
module RailsFormHelper
end
end
end
module Erubis::Helpers::RailsFormHelper
if ActionPack::VERSION::MAJOR == 1 ### Rails 1.X
def pp_template_filename(basename)
return "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.rhtml"
end
else ### Rails 2.X
def pp_template_filename(basename)
fname = "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.html.erb"
return fname if test(?f, fname)
return "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.rhtml"
end
end
def pp_render_partial(basename)
basename = "_#{basename}" unless basename[0] == ?_
filename = pp_template_filename(basename)
preprocessor = _create_preprocessor(File.read(filename))
return preprocessor.evaluate(_preprocessing_context_object())
end
def pp_error_on(object_name, method)
s = ''
s << "<% _stag, _etag = _pp_error_tags(@#{object_name}.errors.on('#{method}')) %>"
s << "<%= _stag %>"
s << yield(object_name, method)
s << "<%= _etag %>"
return s
end
def _pp_error_tags(value)
return value ? ['<div class="fieldWithErrors">', '</div>'] : ['', '']
end
def _pp_remove_error_div(s)
s.sub!(/\A<div class="fieldWithErrors">(.*)<\/div>\z/, '\1')
return s
end
def pp_tag_helper(helper, object_name, method, options={})
if object_name.is_a?(ActionView::Helpers::FormHelper)
object_name = object_name.object_name
end
unless options.key?(:value) || options.key?('value')
options['value'] = _?("h @#{object_name}.#{method}")
end
#$stderr.puts "*** debug: pp_tag_helper(): options=#{options.inspect}"
return pp_error_on(object_name, method) {
s = __send__(helper, object_name, method, options)
_pp_remove_error_div(s)
}
end
def pp_form_tag(url_for_options={}, options={}, *parameters_for_url, &block)
return form_tag(url_for_options, options, *parameters_for_url, &block)
end
#--
#def pp_form_for(object_name, *args, &block)
# return form_for(object_name, *args, &block)
#end
#++
def pp_text_field(object_name, method, options={})
return pp_tag_helper(:text_field, object_name, method, options)
end
def pp_password_field(object_name, method, options={})
return pp_tag_helper(:password_field, object_name, method, options)
end
def pp_hidden_field(object_name, method, options={})
return pp_tag_helper(:hidden_field, object_name, method, options)
end
def pp_file_field(object_name, method, options={})
return pp_tag_helper(:file_field, object_name, method, options)
end
def pp_text_area(object_name, method, options={})
return pp_tag_helper(:text_area, object_name, method, options)
end
def pp_check_box(object_name, method, options={}, checked_value="1", unchecked_value="0")
s = check_box(object_name, method, options, checked_value, unchecked_value)
s.sub!(/\schecked=\"checked\"/, '')
s.sub!(/type="checkbox"/, "\\&<%= _pp_check_box_checked?(@#{object_name}.#{method}, #{checked_value.inspect}) ? ' checked=\"checked\"' : '' %>")
return pp_error_on(object_name, method) { _pp_remove_error_div(s) }
end
def _pp_check_box_checked?(value, checked_value)
return ActionView::Helpers::InstanceTag::check_box_checked?(value, checked_value)
end
def pp_radio_button(object_name, method, tag_value, options={})
s = radio_button(object_name, method, tag_value, options)
s.sub!(/\schecked=\"checked\"/, '')
s.sub!(/type="radio"/, "\\&<%= _pp_radio_button_checked?(@#{object_name}.#{method}, #{tag_value.inspect}) ? ' checked=\"checked\"' : '' %>")
return pp_error_on(object_name, method) { _pp_remove_error_div(s) }
end
def _pp_radio_button_checked?(value, tag_value)
return ActionView::Helpers::InstanceTag::radio_button_checked?(value, tag_value)
end
def _pp_select(object, method, collection, priority_collection, options={}, html_options={})
return pp_error_on(object, method) do
s = ""
## start tag
s << "<select id=\"#{object}_#{method}\" name=\"#{object}[#{method}]\""
for key, val in html_options:
s << " #{key}=\"#{val}\""
end
s << ">\n"
## selected table
key = options.key?(:value) ? :value : (options.key?('value') ? 'value' : nil)
if key.nil? ; selected = "@#{object}.#{method}"
elsif (val=options[key]).nil? ; selected = nil
elsif val =~ /\A<%=(.*)%>\z/ ; selected = $1
else ; selected = val.inspect
end
s << "<% _table = {#{selected}=>' selected=\"selected\"'} %>\n" if selected
## <option> tags
if options[:include_blank] || options['include_blank']
s << "<option value=\"\"></option>\n"
end
unless priority_collection.blank?
_pp_select_options(s, priority_collection, selected, 'delete')
s << "<option value=\"\">-------------</option>\n"
end
_pp_select_options(s, collection, selected, '[]')
## end tag
s << "</select>"
s
end
end
def _pp_select_options(s, collection, selected, operator)
for item in collection
value, text = item.is_a?(Array) ? item : [item, item]
if !selected
t = ''
elsif operator == 'delete'
t = "<%= _table.delete(#{value.inspect}) %>"
else
t = "<%= _table[#{value.inspect}] %>"
end
s << "<option value=\"#{h value}\"#{t}>#{h text}</option>\n"
end
end
def pp_select(object, method, collection, options={}, html_options={})
return _pp_select(object, method, collection, nil, options, html_options)
end
def pp_collection_select(object, method, collection, value_method, text_method, options={}, html_options={})
collection2 = collection.collect { |e|
[e.__send__(value_method), e.__send__(text_method)]
}
return _pp_select(object, method, collection2, nil, options, html_options)
end
def pp_country_select(object, method, priority_countries=nil, options={}, html_options={})
collection = ActionView::Helpers::FormOptionsHelper::COUNTRIES
return _pp_select(object, method, collection, priority_countries, options, html_options)
end
def pp_time_zone_select(object, method, priority_zones=nil, options={}, html_options={})
model = options[:model] || options['model'] || TimeZone
collection = model.all.collect { |e| [e.name, e.to_s] }
return _pp_select(object, method, collection, priority_zones, options, html_options)
end
def pp_submit_tag(value="Save changes", options={})
return submit_tag(value, options)
end
def pp_image_submit_tag(source, options={})
return image_submit_tag(source, options)
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/ephp.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/ephp.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
module PhpGenerator
include Generator
def self.supported_properties() # :nodoc:
return []
end
def init_generator(properties={})
super
@escapefunc ||= 'htmlspecialchars'
end
def add_preamble(src)
# empty
end
def escape_text(text)
return text.gsub!(/<\?xml\b/, '<<?php ?>?xml') || text
end
def add_text(src, text)
src << escape_text(text)
end
def add_expr_literal(src, code)
code.strip!
src << "<?php echo #{code}; ?>"
end
def add_expr_escaped(src, code)
add_expr_literal(src, escaped_expr(code))
end
def add_expr_debug(src, code)
code.strip!
s = code.gsub(/\'/, "\\'")
src << "<?php error_log('*** debug: #{s}='.(#{code}), 0); ?>"
end
def add_stmt(src, code)
src << "<?php"
src << " " if code[0] != ?\ #
if code[-1] == ?\n
code.chomp!
src << code << "?>\n"
else
src << code << "?>"
end
end
def add_postamble(src)
# empty
end
end
##
## engine for PHP
##
class Ephp < Basic::Engine
include PhpGenerator
end
class EscapedEphp < Ephp
include EscapeEnhancer
end
#class XmlEphp < Ephp
# include EscapeEnhancer
#end
class PI::Ephp < PI::Engine
include PhpGenerator
def init_converter(properties={})
@pi = 'php'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/eperl.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/eperl.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
module PerlGenerator
include Generator
def self.supported_properties() # :nodoc:
return [
[:func, 'print', "function name"],
]
end
def init_generator(properties={})
super
@escapefunc ||= 'encode_entities'
@func = properties[:func] || 'print'
end
def add_preamble(src)
src << "use HTML::Entities; ";
end
def escape_text(text)
return text.gsub!(/['\\]/, '\\\\\&') || text
end
def add_text(src, text)
src << @func << "('" << escape_text(text) << "'); " unless text.empty?
end
def add_expr_literal(src, code)
code.strip!
src << @func << "(" << code << "); "
end
def add_expr_escaped(src, code)
add_expr_literal(src, escaped_expr(code))
end
def add_expr_debug(src, code)
code.strip!
s = code.gsub(/\'/, "\\'")
src << @func << "('*** debug: #{code}=', #{code}, \"\\n\");"
end
def add_stmt(src, code)
src << code
end
def add_postamble(src)
src << "\n" unless src[-1] == ?\n
end
end
##
## engine for Perl
##
class Eperl < Basic::Engine
include PerlGenerator
end
class EscapedEperl < Eperl
include EscapeEnhancer
end
#class XmlEperl < Eperl
# include EscapeEnhancer
#end
class PI::Eperl < PI::Engine
include PerlGenerator
def init_converter(properties={})
@pi = 'perl'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/eruby.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/eruby.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
##
## code generator for Ruby
##
module RubyGenerator
include Generator
#include ArrayBufferEnhancer
include StringBufferEnhancer
def init_generator(properties={})
super
@escapefunc ||= "Erubis::XmlHelper.escape_xml"
end
def self.supported_properties() # :nodoc:
return []
end
def escape_text(text)
text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\'
end
def escaped_expr(code)
return "#{@escapefunc}(#{code})"
end
#--
#def add_preamble(src)
# src << "_buf = [];"
#end
#++
def add_text(src, text)
src << " _buf << '" << escape_text(text) << "';" unless text.empty?
end
def add_stmt(src, code)
#src << code << ';'
src << code
src << ';' unless code[-1] == ?\n
end
def add_expr_literal(src, code)
src << ' _buf << (' << code << ').to_s;'
end
def add_expr_escaped(src, code)
src << ' _buf << ' << escaped_expr(code) << ';'
end
def add_expr_debug(src, code)
code.strip!
s = (code.dump =~ /\A"(.*)"\z/) && $1
src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
end
#--
#def add_postamble(src)
# src << "\n_buf.join\n"
#end
#++
end
##
## engine for Ruby
##
class Eruby < Basic::Engine
include RubyEvaluator
include RubyGenerator
end
##
## fast engine for Ruby
##
class FastEruby < Eruby
include InterpolationEnhancer
end
##
## swtich '<%= %>' to escaped and '<%== %>' to not escaped
##
class EscapedEruby < Eruby
include EscapeEnhancer
end
##
## sanitize expression (<%= ... %>) by default
##
## this is equivalent to EscapedEruby and is prepared only for compatibility.
##
class XmlEruby < Eruby
include EscapeEnhancer
end
class PI::Eruby < PI::Engine
include RubyEvaluator
include RubyGenerator
def init_converter(properties={})
@pi = 'rb'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/optimized.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/optimized.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine/eruby'
module Erubis
module OptimizedGenerator
include Generator
def self.supported_properties() # :nodoc:
return []
end
def init_generator(properties={})
super
@escapefunc ||= "Erubis::XmlHelper.escape_xml"
@initialized = false
@prev_is_expr = false
end
protected
def escape_text(text)
text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\'
end
def escaped_expr(code)
@escapefunc ||= 'Erubis::XmlHelper.escape_xml'
return "#{@escapefunc}(#{code})"
end
def switch_to_expr(src)
return if @prev_is_expr
@prev_is_expr = true
src << ' _buf'
end
def switch_to_stmt(src)
return unless @prev_is_expr
@prev_is_expr = false
src << ';'
end
def add_preamble(src)
#@initialized = false
#@prev_is_expr = false
end
def add_text(src, text)
return if text.empty?
if @initialized
switch_to_expr(src)
src << " << '" << escape_text(text) << "'"
else
src << "_buf = '" << escape_text(text) << "';"
@initialized = true
end
end
def add_stmt(src, code)
switch_to_stmt(src) if @initialized
#super
src << code
src << ';' unless code[-1] == ?\n
end
def add_expr_literal(src, code)
unless @initialized; src << "_buf = ''"; @initialized = true; end
switch_to_expr(src)
src << " << (" << code << ").to_s"
end
def add_expr_escaped(src, code)
unless @initialized; src << "_buf = ''"; @initialized = true; end
switch_to_expr(src)
src << " << " << escaped_expr(code)
end
def add_expr_debug(src, code)
code.strip!
s = (code.dump =~ /\A"(.*)"\z/) && $1
src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
end
def add_postamble(src)
#super if @initialized
src << "\n_buf\n" if @initialized
end
end # end of class OptimizedEruby
##
## Eruby class which generates optimized ruby code
##
class OptimizedEruby < Basic::Engine # Eruby
include RubyEvaluator
include OptimizedGenerator
def init_converter(properties={})
@pi = 'rb'
super(properties)
end
end
##
## XmlEruby class which generates optimized ruby code
##
class OptimizedXmlEruby < OptimizedEruby
include EscapeEnhancer
def add_expr_debug(src, code)
switch_to_stmt(src) if indicator == '===' && !@initialized
super
end
end # end of class OptimizedXmlEruby
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/ejava.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/ejava.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
module JavaGenerator
include Generator
def self.supported_properties() # :nodoc:
return [
[:indent, '', "indent spaces (ex. ' ')"],
[:buf, '_buf', "output buffer name"],
[:bufclass, 'StringBuffer', "output buffer class (ex. 'StringBuilder')"],
]
end
def init_generator(properties={})
super
@escapefunc ||= 'escape'
@indent = properties[:indent] || ''
@buf = properties[:buf] || '_buf'
@bufclass = properties[:bufclass] || 'StringBuffer'
end
def add_preamble(src)
src << "#{@indent}#{@bufclass} #{@buf} = new #{@bufclass}();"
end
def escape_text(text)
@@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text
end
def add_text(src, text)
return if text.empty?
src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
src << @buf << ".append("
i = 0
text.each_line do |line|
src << "\n" << @indent << ' + ' if i > 0
i += 1
src << '"' << escape_text(line) << '"'
end
src << ");" << (text[-1] == ?\n ? "\n" : "")
end
def add_stmt(src, code)
src << code
end
def add_expr_literal(src, code)
src << @indent if src.empty? || src[-1] == ?\n
code.strip!
src << " #{@buf}.append(#{code});"
end
def add_expr_escaped(src, code)
add_expr_literal(src, escaped_expr(code))
end
def add_expr_debug(src, code)
code.strip!
src << @indent if src.empty? || src[-1] == ?\n
src << " System.err.println(\"*** debug: #{code}=\"+(#{code}));"
end
def add_postamble(src)
src << "\n" if src[-1] == ?;
src << @indent << "return " << @buf << ".toString();\n"
#src << @indent << "System.out.print(" << @buf << ".toString());\n"
end
end
##
## engine for Java
##
class Ejava < Basic::Engine
include JavaGenerator
end
class EscapedEjava < Ejava
include EscapeEnhancer
end
#class XmlEjava < Ejava
# include EscapeEnhancer
#end
class PI::Ejava < PI::Engine
include JavaGenerator
def init_converter(properties={})
@pi = 'java'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/ejavascript.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/ejavascript.rb | ##
## $Rev: 95 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
module JavascriptGenerator
include Generator
def self.supported_properties() # :nodoc:
list = []
#list << [:indent, '', "indent spaces (ex. ' ')"]
#list << [:buf, '_buf', "output buffer name"]
list << [:docwrite, true, "use 'document.write()' when true"]
return list
end
def init_generator(properties={})
super
@escapefunc ||= 'escape'
@indent = properties[:indent] || ''
@buf = properties[:out] || '_buf'
@docwrite = properties[:docwrite] != false # '!= false' will be removed in the next release
end
def add_preamble(src)
src << "#{@indent}var #{@buf} = [];"
end
def escape_text(text)
@@table_ ||= { "\r"=>"\\r", "\n"=>"\\n\\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text
end
def add_indent(src, indent)
src << (src.empty? || src[-1] == ?\n ? indent : ' ')
end
def add_text(src, text)
return if text.empty?
add_indent(src, @indent)
src << @buf << '.push("'
s = escape_text(text)
if s[-1] == ?\n
s[-2, 2] = ''
src << s << "\");\n"
else
src << s << "\");"
end
end
def add_stmt(src, code)
src << code
end
def add_expr_literal(src, code)
add_indent(src, @indent)
code.strip!
src << "#{@buf}.push(#{code});"
end
def add_expr_escaped(src, code)
add_expr_literal(src, escaped_expr(code))
end
def add_expr_debug(src, code)
add_indent(src, @indent)
code.strip!
src << "alert(\"*** debug: #{code}=\"+(#{code}));"
end
def add_postamble(src)
src << "\n" if src[-1] == ?;
if @docwrite
src << @indent << 'document.write(' << @buf << ".join(\"\"));\n"
else
src << @indent << @buf << ".join(\"\");\n"
end
end
end
##
## engine for JavaScript
##
class Ejavascript < Basic::Engine
include JavascriptGenerator
end
class EscapedEjavascript < Ejavascript
include EscapeEnhancer
end
#class XmlEjavascript < Ejavascript
# include EscapeEnhancer
#end
class PI::Ejavascript < PI::Engine
include JavascriptGenerator
def init_converter(properties={})
@pi = 'js'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/ec.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/ec.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
module CGenerator
include Generator
def self.supported_properties() # :nodoc:
return [
[:indent, '', "indent spaces (ex. ' ')"],
[:out, 'stdout', "output file pointer name"],
]
end
def init_generator(properties={})
super
@escapefunc ||= "escape"
@indent = properties[:indent] || ''
@out = properties[:out] || 'stdout'
end
def add_preamble(src)
src << "#line 1 \"#{self.filename}\"\n" if self.filename
end
def escape_text(text)
@@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] }
return text
end
def escaped_expr(code)
return "#{@escapefunc}(#{code.strip}, #{@out})"
end
def add_text(src, text)
return if text.empty?
src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
src << "fputs("
i = 0
text.each_line do |line|
src << "\n" << @indent << ' ' if i > 0
i += 1
src << '"' << escape_text(line) << '"'
end
src << ", #{@out});" #<< (text[-1] == ?\n ? "\n" : "")
src << "\n" if text[-1] == ?\n
end
def add_stmt(src, code)
src << code
end
def add_expr_literal(src, code)
src << @indent if src.empty? || src[-1] == ?\n
src << " fprintf(#{@out}, " << code.strip << ');'
end
def add_expr_escaped(src, code)
src << @indent if src.empty? || src[-1] == ?\n
src << ' ' << escaped_expr(code) << ';'
end
def add_expr_debug(src, code)
code.strip!
s = nil
if code =~ /\A\".*?\"\s*,\s*(.*)/
s = $1.gsub(/[%"]/, '\\\1') + '='
end
src << @indent if src.empty? || src[-1] == ?\n
src << " fprintf(stderr, \"*** debug: #{s}\" #{code});"
end
def add_postamble(src)
# empty
end
end
##
## engine for C
##
class Ec < Basic::Engine
include CGenerator
end
class EscapedEc < Ec
include EscapeEnhancer
end
#class XmlEc < Ec
# include EscapeEnhancer
#end
class PI::Ec < PI::Engine
include CGenerator
def init_converter(properties={})
@pi = 'c'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/enhanced.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/enhanced.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/enhancer'
require 'erubis/engine/eruby'
module Erubis
#--
## moved to engine/ruby.rb
#class EscapedEruby < Eruby
# include EscapeEnhancer
#end
#++
#--
### (obsolete)
#class FastEruby < Eruby
# include FastEnhancer
#end
#++
class StdoutEruby < Eruby
include StdoutEnhancer
end
class PrintOutEruby < Eruby
include PrintOutEnhancer
end
class PrintEnabledEruby < Eruby
include PrintEnabledEnhancer
end
class ArrayEruby < Eruby
include ArrayEnhancer
end
class ArrayBufferEruby < Eruby
include ArrayBufferEnhancer
end
class StringBufferEruby < Eruby
include StringBufferEnhancer
end
class StringIOEruby < Eruby
include StringIOEnhancer
end
class ErboutEruby < Eruby
include ErboutEnhancer
end
class NoTextEruby < Eruby
include NoTextEnhancer
end
class NoCodeEruby < Eruby
include NoCodeEnhancer
end
class SimplifiedEruby < Eruby
include SimplifyEnhancer
end
class StdoutSimplifiedEruby < Eruby
include StdoutEnhancer
include SimplifyEnhancer
end
class PrintOutSimplifiedEruby < Eruby
include PrintOutEnhancer
include SimplifyEnhancer
end
class BiPatternEruby < Eruby
include BiPatternEnhancer
end
class PercentLineEruby < Eruby
include PercentLineEnhancer
end
class HeaderFooterEruby < Eruby
include HeaderFooterEnhancer
end
class DeleteIndentEruby < Eruby
include DeleteIndentEnhancer
end
class InterpolationEruby < Eruby
include InterpolationEnhancer
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/erubis-2.6.0/lib/erubis/engine/escheme.rb | gems/gems/erubis-2.6.0/lib/erubis/engine/escheme.rb | ##
## $Rev: 77 $
## $Release: 2.6.0 $
## copyright(c) 2006-2008 kuwata-lab.com all rights reserved.
##
require 'erubis/engine'
require 'erubis/enhancer'
module Erubis
module SchemeGenerator
include Generator
def self.supported_properties() # :nodoc:
return [
[:func, '_add', "function name (ex. 'display')"],
]
end
def init_generator(properties={})
super
@escapefunc ||= 'escape'
@func = properties[:func] || '_add' # or 'display'
end
def add_preamble(src)
return unless @func == '_add'
src << "(let ((_buf '())) " + \
"(define (_add x) (set! _buf (cons x _buf))) "
#src << "(let* ((_buf '())" + \
# " (_add (lambda (x) (set! _buf (cons x _buf))))) "
end
def escape_text(text)
@table_ ||= { '"'=>'\\"', '\\'=>'\\\\' }
text.gsub!(/["\\]/) { |m| @table_[m] }
return text
end
def escaped_expr(code)
code.strip!
return "(#{@escapefunc} #{code})"
end
def add_text(src, text)
return if text.empty?
t = escape_text(text)
if t[-1] == ?\n
t[-1, 1] = ''
src << "(#{@func} \"" << t << "\\n\")\n"
else
src << "(#{@func} \"" << t << '")'
end
end
def add_stmt(src, code)
src << code
end
def add_expr_literal(src, code)
code.strip!
src << "(#{@func} #{code})"
end
def add_expr_escaped(src, code)
add_expr_literal(src, escaped_expr(code))
end
def add_expr_debug(src, code)
s = (code.strip! || code).gsub(/\"/, '\\"')
src << "(display \"*** debug: #{s}=\")(display #{code.strip})(display \"\\n\")"
end
def add_postamble(src)
return unless @func == '_add'
src << "\n" unless src[-1] == ?\n
src << " (reverse _buf))\n"
end
end
##
## engine for Scheme
##
class Escheme < Basic::Engine
include SchemeGenerator
end
class EscapedEscheme < Escheme
include EscapeEnhancer
end
#class XmlEscheme < Escheme
# include EscapeEnhancer
#end
class PI::Escheme < PI::Engine
include SchemeGenerator
def init_converter(properties={})
@pi = 'scheme'
super(properties)
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/autotest/discover.rb | autotest/discover.rb | Autotest.add_discovery { "merb" }
Autotest.add_discovery { "rspec" }
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/autotest/merb.rb | autotest/merb.rb | # Adapted from Autotest::Rails
require 'autotest'
class Autotest::Merb < Autotest
# +model_tests_dir+:: the directory to find model-centric tests
# +controller_tests_dir+:: the directory to find controller-centric tests
# +view_tests_dir+:: the directory to find view-centric tests
# +fixtures_dir+:: the directory to find fixtures in
attr_accessor :model_tests_dir, :controller_tests_dir, :view_tests_dir, :fixtures_dir
def initialize
super
initialize_test_layout
# Ignore any happenings in these directories
add_exception %r%^\./(?:doc|log|public|tmp|\.git|\.hg|\.svn|framework|gems|schema|\.DS_Store|autotest|bin|.*\.sqlite3)%
# Ignore SCM directories and custom Autotest mappings
%w[.svn .hg .git .autotest].each { |exception| add_exception(exception) }
# Ignore any mappings that Autotest may have already set up
clear_mappings
# Any changes to a file in the root of the 'lib' directory will run any
# model test with a corresponding name.
add_mapping %r%^lib\/.*\.rb% do |filename, _|
files_matching Regexp.new(["^#{model_test_for(filename)}$"])
end
# Any changes to a fixture will run corresponding view, controller and
# model tests
add_mapping %r%^#{fixtures_dir}/(.*)s.yml% do |_, m|
[
model_test_for(m[1]),
controller_test_for(m[1]),
view_test_for(m[1])
]
end
# Any change to a test will cause it to be run
add_mapping %r%^test/(unit|models|integration|controllers|views|functional)/.*rb$% do |filename, _|
filename
end
# Any change to a model will cause it's corresponding test to be run
add_mapping %r%^app/models/(.*)\.rb$% do |_, m|
model_test_for(m[1])
end
# Any change to the global helper will result in all view and controller
# tests being run
add_mapping %r%^app/helpers/global_helpers.rb% do
files_matching %r%^test/(views|functional|controllers)/.*_test\.rb$%
end
# Any change to a helper will run it's corresponding view and controller
# tests, unless the helper is the global helper. Changes to the global
# helper run all view and controller tests.
add_mapping %r%^app/helpers/(.*)_helper(s)?.rb% do |_, m|
if m[1] == "global" then
files_matching %r%^test/(views|functional|controllers)/.*_test\.rb$%
else
[
view_test_for(m[1]),
controller_test_for(m[1])
]
end
end
# Changes to views result in their corresponding view and controller test
# being run
add_mapping %r%^app/views/(.*)/% do |_, m|
[
view_test_for(m[1]),
controller_test_for(m[1])
]
end
# Changes to a controller result in its corresponding test being run. If
# the controller is the exception or application controller, all
# controller tests are run.
add_mapping %r%^app/controllers/(.*)\.rb$% do |_, m|
if ["application", "exception"].include?(m[1])
files_matching %r%^test/(controllers|views|functional)/.*_test\.rb$%
else
controller_test_for(m[1])
end
end
# If a change is made to the router, run all controller and view tests
add_mapping %r%^config/router.rb$% do # FIX
files_matching %r%^test/(controllers|views|functional)/.*_test\.rb$%
end
# If any of the major files governing the environment are altered, run
# everything
add_mapping %r%^test/test_helper.rb|config/(init|rack|environments/test.rb|database.yml)% do # FIX
files_matching %r%^test/(unit|models|controllers|views|functional)/.*_test\.rb$%
end
end
private
# Determines the paths we can expect tests or specs to reside, as well as
# corresponding fixtures.
def initialize_test_layout
self.model_tests_dir = "test/unit"
self.controller_tests_dir = "test/functional"
self.view_tests_dir = "test/views"
self.fixtures_dir = "test/fixtures"
end
# Given a filename and the test type, this method will return the
# corresponding test's or spec's name.
#
# ==== Arguments
# +filename+<String>:: the file name of the model, view, or controller
# +kind_of_test+<Symbol>:: the type of test we that we should run
#
# ==== Returns
# String:: the name of the corresponding test or spec
#
# ==== Example
#
# > test_for("user", :model)
# => "user_test.rb"
# > test_for("login", :controller)
# => "login_controller_test.rb"
# > test_for("form", :view)
# => "form_view_spec.rb" # If you're running a RSpec-like suite
def test_for(filename, kind_of_test)
name = [filename]
name << kind_of_test.to_s if kind_of_test == :view
name << "test"
return name.join("_") + ".rb"
end
def model_test_for(filename)
[model_tests_dir, test_for(filename, :model)].join("/")
end
def controller_test_for(filename)
[controller_tests_dir, test_for(filename, :controller)].join("/")
end
def view_test_for(filename)
[view_tests_dir, test_for(filename, :view)].join("/")
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/autotest/merb_rspec.rb | autotest/merb_rspec.rb | # Adapted from Autotest::Rails, RSpec's autotest class, as well as merb-core's.
require 'autotest'
class RspecCommandError < StandardError; end
# This class maps your application's structure so Autotest can understand what
# specs to run when files change.
#
# Fixtures are _not_ covered by this class. If you change a fixture file, you
# will have to run your spec suite manually, or, better yet, provide your own
# Autotest map explaining how your fixtures are set up.
class Autotest::MerbRspec < Autotest
def initialize
super
# Ignore any happenings in these directories
add_exception %r%^\./(?:doc|log|public|tmp|\.git|\.hg|\.svn|framework|gems|schema|\.DS_Store|autotest|bin|.*\.sqlite3|.*\.thor)%
# Ignore SCM directories and custom Autotest mappings
%w[.svn .hg .git .autotest].each { |exception| add_exception(exception) }
# Ignore any mappings that Autotest may have already set up
clear_mappings
# Anything in /lib could have a spec anywhere, if at all. So, look for
# files with roughly the same name as the file in /lib
add_mapping %r%^lib\/(.*)\.rb% do |_, m|
files_matching %r%^spec\/#{m[1]}%
end
add_mapping %r%^spec/(spec_helper|shared/.*)\.rb$% do
all_specs
end
# Changing a spec will cause it to run itself
add_mapping %r%^spec/.*\.rb$% do |filename, _|
filename
end
# Any change to a model will cause it's corresponding test to be run
add_mapping %r%^app/models/(.*)\.rb$% do |_, m|
spec_for(m[1], 'model')
end
# Any change to global_helpers will result in all view and controller
# tests being run
add_mapping %r%^app/helpers/global_helpers\.rb% do
files_matching %r%^spec/(views|controllers|helpers|requests)/.*_spec\.rb$%
end
# Any change to a helper will cause its spec to be run
add_mapping %r%^app/helpers/((.*)_helper(s)?)\.rb% do |_, m|
spec_for(m[1], 'helper')
end
# Changes to a view cause its spec to be run
add_mapping %r%^app/views/(.*)/% do |_, m|
spec_for(m[1], 'view')
end
# Changes to a controller result in its corresponding spec being run. If
# the controller is the exception or application controller, all
# controller specs are run.
add_mapping %r%^app/controllers/(.*)\.rb$% do |_, m|
if ["application", "exception"].include?(m[1])
files_matching %r%^spec/controllers/.*_spec\.rb$%
else
spec_for(m[1], 'controller')
end
end
# If a change is made to the router, run controller, view and helper specs
add_mapping %r%^config/router.rb$% do
files_matching %r%^spec/(controllers|views|helpers)/.*_spec\.rb$%
end
# If any of the major files governing the environment are altered, run
# everything
add_mapping %r%^config/(init|rack|environments/test).*\.rb|database\.yml% do
all_specs
end
end
def failed_results(results)
results.scan(/^\d+\)\n(?:\e\[\d*m)?(?:.*?Error in )?'([^\n]*)'(?: FAILED)?(?:\e\[\d*m)?\n(.*?)\n\n/m)
end
def handle_results(results)
@failures = failed_results(results)
@files_to_test = consolidate_failures(@failures)
@files_to_test.empty? && !$TESTING ? hook(:green) : hook(:red)
@tainted = !@files_to_test.empty?
end
def consolidate_failures(failed)
filters = Hash.new { |h,k| h[k] = [] }
failed.each do |spec, failed_trace|
if f = test_files_for(failed).find { |f| f =~ /spec\// }
filters[f] << spec
break
end
end
filters
end
def make_test_cmd(specs_to_runs)
[
ruby,
"-S",
spec_command,
add_options_if_present,
files_to_test.keys.flatten.join(' ')
].join(' ')
end
def add_options_if_present
File.exist?("spec/spec.opts") ? "-O spec/spec.opts " : ""
end
# Finds the proper spec command to use. Precendence is set in the
# lazily-evaluated method spec_commands. Alias + Override that in
# ~/.autotest to provide a different spec command then the default
# paths provided.
def spec_command(separator=File::ALT_SEPARATOR)
unless defined?(@spec_command)
@spec_command = spec_commands.find { |cmd| File.exists?(cmd) }
raise RspecCommandError, "No spec command could be found" unless @spec_command
@spec_command.gsub!(File::SEPARATOR, separator) if separator
end
@spec_command
end
# Autotest will look for spec commands in the following
# locations, in this order:
#
# * default spec bin/loader installed in Rubygems
# * any spec command found in PATH
def spec_commands
[File.join(Config::CONFIG['bindir'], 'spec'), 'spec']
end
private
# Runs +files_matching+ for all specs
def all_specs
files_matching %r%^spec/.*_spec\.rb$%
end
# Generates a path to some spec given its kind and the match from a mapping
#
# ==== Arguments
# match<String>:: the match from a mapping
# kind<String>:: the kind of spec that the match represents
#
# ==== Returns
# String
#
# ==== Example
# > spec_for('post', :view')
# => "spec/views/post_spec.rb"
def spec_for(match, kind)
File.join("spec", kind + 's', "#{match}_spec.rb")
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/bin/common.rb | bin/common.rb | # This was added via Merb's bundler
require "rubygems"
require "rubygems/source_index"
module Gem
BUNDLED_SPECS = File.join(Dir.pwd, "gems", "specifications")
MAIN_INDEX = Gem::SourceIndex.from_gems_in(BUNDLED_SPECS)
FALLBACK_INDEX = Gem::SourceIndex.from_installed_gems
def self.source_index
MultiSourceIndex.new
end
def self.searcher
MultiPathSearcher.new
end
class ArbitrarySearcher < GemPathSearcher
def initialize(source_index)
@source_index = source_index
super()
end
def init_gemspecs
@source_index.map { |_, spec| spec }.sort { |a,b|
(a.name <=> b.name).nonzero? || (b.version <=> a.version)
}
end
end
class MultiPathSearcher
def initialize
@main_searcher = ArbitrarySearcher.new(MAIN_INDEX)
@fallback_searcher = ArbitrarySearcher.new(FALLBACK_INDEX)
end
def find(path)
try = @main_searcher.find(path)
return try if try
@fallback_searcher.find(path)
end
def find_all(path)
try = @main_searcher.find_all(path)
return try unless try.empty?
@fallback_searcher.find_all(path)
end
end
class MultiSourceIndex
# Used by merb.thor to confirm; not needed when MSI is in use
def load_gems_in(*args)
end
def search(*args)
try = MAIN_INDEX.search(*args)
return try unless try.empty?
FALLBACK_INDEX.search(*args)
end
def find_name(*args)
try = MAIN_INDEX.find_name(*args)
return try unless try.empty?
FALLBACK_INDEX.find_name(*args)
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/user_spec_helper.rb | spec/user_spec_helper.rb | module UserHelper
def valid_user_hash
{ :login => "daniel",
:email => "daniel@example.com",
:password => "sekret",
:password_confirmation => "sekret"}
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/spec_helper.rb | spec/spec_helper.rb | require 'rubygems'
# Add the local gems dir if found within the app root; any dependencies loaded
# hereafter will try to load from the local gems before loading system gems.
if (local_gem_dir = File.join(File.dirname(__FILE__), '..', 'gems')) && $BUNDLE.nil?
$BUNDLE = true; Gem.clear_paths; Gem.path.unshift(local_gem_dir)
end
require 'merb-core'
require "spec" # Satisfies Autotest and anyone else not using the Rake tasks
Merb.start_environment(:testing => true, :adapter => 'runner', :environment => ENV['MERB_ENV'] || 'test')
Spec::Runner.configure do |config|
config.include(Merb::Test::ViewHelper)
config.include(Merb::Test::RouteHelper)
config.include(Merb::Test::ControllerHelper)
config.before(:all) do
DataMapper.auto_migrate! if Merb.orm == :datamapper
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/helpers/articles_helper_spec.rb | spec/helpers/articles_helper_spec.rb | require File.join(File.dirname(__FILE__), "..", 'spec_helper.rb')
describe Merb::Feather::ArticlesHelper do
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/helpers/admin/articles_helper_spec.rb | spec/helpers/admin/articles_helper_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
describe Merb::Feather::Admin::ArticlesHelper do
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/helpers/admin/plugins_helper_spec.rb | spec/helpers/admin/plugins_helper_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
describe Merb::Feather::Admin::PluginsHelper do
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/helpers/admin/dashboard_helper_spec.rb | spec/helpers/admin/dashboard_helper_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
describe Merb::Feather::Admin::DashboardHelper do
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/helpers/admin/configurations_helper_spec.rb | spec/helpers/admin/configurations_helper_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
describe Merb::Feather::Admin::ConfigurationsHelper do
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/controllers/articles_spec.rb | spec/controllers/articles_spec.rb | require File.join(File.dirname(__FILE__), "..", 'spec_helper.rb')
describe Feather::Articles do
before(:each) do
@article = mock(:article)
@articles = [@article]
end
describe "/" do
it "should return recent articles" do
Feather::Article.should_receive(:find_recent).and_return @articles
controller = dispatch_to(Feather::Articles, :index) do |controller|
controller.expire_all_pages
controller.should_receive(:display).with(@articles)
end
controller.assigns(:articles).should == @articles
controller.should be_successful
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/controllers/admin/articles_spec.rb | spec/controllers/admin/articles_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
module Feather::Admin
describe Articles do
before(:each) do
@article = mock(:article)
@articles = [@article]
end
describe "/admin/articles" do
it "should get all articles in descending created order" do
::Feather::Article.should_receive(:all).with(:order => [:created_at.desc], :offset => 0, :limit => 10).and_return(@articles)
controller = dispatch_to(Articles, :index) do |controller|
controller.should_receive(:login_required).and_return(true)
controller.should_receive(:display).with(@articles)
end
controller.assigns(:articles).should == @articles
controller.should be_successful
end
end
describe "/admin/articles/1" do
it "should display the article matching the id" do
::Feather::Article.should_receive("[]").with("1").and_return(@article)
controller = dispatch_to(Articles, :show, :id => "1") do |controller|
controller.should_receive(:login_required).and_return(true)
controller.should_receive(:display).with(@article)
end
controller.assigns(:article).should == @article
controller.should be_successful
end
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/controllers/admin/dashboard_spec.rb | spec/controllers/admin/dashboard_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
module Feather::Admin
describe Dashboards do
before(:each) do
@activity = [mock(:activity)]
end
describe "/admin" do
it "should request dashboard" do
::Feather::Activity.should_receive(:all).with(:order => [:created_at.desc], :limit => 5).and_return(@activity)
controller = dispatch_to(Dashboards, :index) do |controller|
controller.should_receive(:login_required).and_return(true)
controller.should_receive(:display).with(@activity)
end
controller.assigns(:activity).should == @activity
controller.should be_successful
end
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/controllers/admin/plugins_spec.rb | spec/controllers/admin/plugins_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
module Feather::Admin
describe Plugins do
before(:each) do
@plugin = mock(:plugin)
@plugins = [@plugin]
end
describe "/admin/plugins" do
it "should get all plugins" do
::Feather::Plugin.should_receive(:all).and_return(@plugins)
controller = dispatch_to(Plugins, :index) do |controller|
controller.should_receive(:login_required).and_return(true)
controller.should_receive(:load_plugins).and_return(true)
controller.should_receive(:display).with(@plugins)
end
controller.assigns(:plugins).should == @plugins
controller.should be_successful
end
end
describe "/admin/plugins/1" do
it "should display the plugin matching the id" do
::Feather::Plugin.should_receive("[]").with("1").and_return(@plugin)
controller = dispatch_to(Plugins, :show, :id => "1") do |controller|
controller.should_receive(:login_required).and_return(true)
controller.should_receive(:load_plugins).and_return(true)
controller.should_receive(:display).with(@plugin)
end
controller.assigns(:plugin).should == @plugin
controller.should be_successful
end
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/controllers/admin/configurations_spec.rb | spec/controllers/admin/configurations_spec.rb | require File.join(File.dirname(__FILE__), "../..", 'spec_helper.rb')
module Feather::Admin
describe Configurations do
before(:each) do
@configuration = mock(:configuration)
end
describe "/admin/configurations" do
it "should get current configuration" do
::Feather::Configuration.stub!(:current).and_return(@configuration)
controller = dispatch_to(Configurations, :show) do |controller|
controller.should_receive(:login_required).and_return(true)
controller.should_receive(:display).with(@configuration)
end
controller.assigns(:configuration).should == @configuration
controller.should be_successful
end
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/spec/models/article_spec.rb | spec/models/article_spec.rb | require File.join( File.dirname(__FILE__), "..", "spec_helper" )
describe Feather::Article do
before(:all) do
@article = mock(:article)
@articles = [@article]
end
describe Feather::Article do
it 'should create a new article' do
b = Feather::Article.new
b.user_id = 1
b.title = "hai"
b.content = "bai"
b.should be_valid
end
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather.rb | lib/feather.rb | if defined?(Merb::Plugins)
$:.unshift File.dirname(__FILE__)
$:.unshift File.join(File.dirname(__FILE__), "..", "app", "models")
$:.unshift File.join(File.dirname(__FILE__), "..", "app", "controllers")
$:.unshift File.join(File.dirname(__FILE__), "..", "app", "helpers")
dependency 'merb-slices'
Merb::Plugins.add_rakefiles "feather/merbtasks", "feather/slicetasks", "feather/spectasks"
# Register the Slice for the current host application
Merb::Slices::register(__FILE__)
# Slice configuration - set this in a before_app_loads callback.
# By default a Slice uses its own layout, so you can swicht to
# the main application layout or no layout at all if needed.
#
# Configuration options:
# :layout - the layout to use; defaults to :feather-slice
# :mirror - which path component types to use on copy operations; defaults to all
Merb::Slices::config[:feather][:layout] ||= :application
require 'config/dependencies.rb'
# All Slice code is expected to be namespaced inside a module
module Feather
# Slice metadata
self.description = "The slice version of Feather, the extensible, lightweight blogging engine for Merb"
self.version = "0.5"
self.author = "El Draper"
# Stub classes loaded hook - runs before LoadClasses BootLoader
# right after a slice's classes have been loaded internally.
def self.loaded
end
# Initialization hook - runs before AfterAppLoads BootLoader
def self.init
Merb::Authentication.user_class = Feather::User
end
# Activation hook - runs after AfterAppLoads BootLoader
def self.activate
end
# Deactivation hook - triggered by Merb::Slices.deactivate(Feather)
def self.deactivate
end
# Setup routes inside the host application
#
# @param scope<Merb::Router::Behaviour>
# Routes will be added within this scope (namespace). In fact, any
# router behaviour is a valid namespace, so you can attach
# routes at any level of your router setup.
#
# @note prefix your named routes with :feather_slice_
# to avoid potential conflicts with global named routes.
def self.setup_router(scope)
require File.join(File.dirname(__FILE__), "feather", "padding")
require File.join(File.dirname(__FILE__), "feather", "hooks")
require File.join(File.dirname(__FILE__), "feather", "database")
require File.join(File.dirname(__FILE__), "feather", "plugin_dependencies")
# This loads the plugins
begin
Feather::Plugin.all.each do |p|
begin
p.load
Merb.logger.info("\"#{p.name}\" loaded")
rescue Exception => e
Merb.logger.info("\"#{p.name}\" failed to load : #{e.message}")
end
end
rescue Exception => e
Merb.logger.info("Error loading plugins: #{e.message}")
end
# Load all plugin routes
Feather::Hooks::Routing.load_routes(scope)
# This deferred route allows permalinks to be handled, without a separate rack handler
scope.match("/:controller", :controller => '.*').defer_to do |request, params|
# Permalinks are relative to the slice mount point, so we'll need to remove that from the request before we look up the article
permalink = request.uri.to_s.chomp("/")
permalink.gsub!("/#{::Feather.config[:path_prefix]}", "") unless ::Feather.config[:path_prefix].blank?
# Attempt to find the article
unless (id = Feather::Article.routing[permalink]).nil?
params.merge!({:controller => "feather/articles", :action => "show", :id => id})
end
end
# Admin namespace
scope.namespace "admin", :path => "admin", :name_prefix => "admin" do
scope.resource :configuration, :path => "admin/configuration", :name_prefix => "admin", :controller => "admin/configurations"
scope.resources :plugins, :path => "admin/plugins", :name_prefix => "admin", :controller => "admin/plugins"
scope.resources :articles, :path => "admin/articles", :name_prefix => "admin", :controller => "admin/articles"
scope.resources :users, :path => "admin/users", :name_prefix => "admin", :controller => "admin/users"
scope.resource :dashboard, :path => "admin/dashboard", :name_prefix => "admin", :controller => "admin/dashboards"
end
scope.match("/admin").to(:action => "show", :controller => "admin/dashboards")
# Year/month/day routes
scope.match("/:year").to(:controller => "articles", :action => "index").name(:year)
scope.match("/:year/:month").to(:controller => "articles", :action => "index").name(:month)
scope.match("/:year/:month/:day").to(:controller => "articles", :action => "index").name(:day)
# Default routes, and index
scope.match("/").to(:controller => 'articles', :action =>'index')
end
end
# Setup the slice layout for Feather
#
# Use Feather.push_path and Feather.push_app_path
# to set paths to feather-level and app-level paths. Example:
#
# Feather.push_path(:application, Feather.root)
# Feather.push_app_path(:application, Merb.root / 'slices' / 'feather-slice')
# ...
#
# Any component path that hasn't been set will default to Feather.root
#
# Or just call setup_default_structure! to setup a basic Merb MVC structure.
Feather.setup_default_structure!
# Add dependencies for other Feather classes below. Example:
# dependency "feather/other"
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/merb_auth_setup.rb | lib/merb_auth_setup.rb | module Merb
class Authentication
def store_user(user)
return nil unless user
user.id
end
def fetch_user(session_info)
::Feather::User.get(session_info)
end
end # Authentication
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/slicetasks.rb | lib/feather/slicetasks.rb | namespace :slices do
namespace :feather do
# add your own feather tasks here
# implement this to test for structural/code dependencies
# like certain directories or availability of other files
desc "Test for any dependencies"
task :preflight do
end
# implement this to perform any database related setup steps
desc "Migrate the database"
task :migrate do
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/plugin_dependencies.rb | lib/feather/plugin_dependencies.rb | # Allows you to tell a plugin it depends on another, and will load the dependency first.
# Usage: Feather::PluginDependencies::register_dependency "feather-comments" in init.rb of your plugin.
module Feather
module PluginDependencies
class << self
def register_dependency(dependency)
p = Feather::Plugin.first(:name => dependency)
raise ArgumentError, "Plugin dependency: '#{dependency}' not installed" if p.nil?
p.load unless p.loaded?
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/hooks.rb | lib/feather/hooks.rb | require File.join(File.dirname(__FILE__), "hooks", "menu")
require File.join(File.dirname(__FILE__), "hooks", "view")
require File.join(File.dirname(__FILE__), "hooks", "events")
require File.join(File.dirname(__FILE__), "hooks", "formatters")
require File.join(File.dirname(__FILE__), "hooks", "routing")
module Feather
module Hooks
class << self
##
# This returns true if the hook is within a plugin that is active, false otherwise
def is_hook_valid?(hook)
plugin = get_plugin(hook)
!plugin.nil? && plugin.active
end
##
# This returns the plugin applicable for any given hook
def get_plugin(hook)
get_plugin_by_caller(eval("__FILE__", hook.binding))
end
##
# This returns the plugin applicable for the specified file
def get_plugin_by_caller(file)
Feather::Plugin.all.each do |plugin|
return plugin if file[0..plugin.path.length - 1] == plugin.path
end
nil
end
##
# This removes all hooks for the specified plugin
def remove_plugin_hooks(id)
Feather::Hooks::Menu.remove_plugin_hooks(id)
Feather::Hooks::View.remove_plugin_hooks(id)
end
##
# This returns the calling file that called the method that then called this helper method
def get_caller
caller[1].split(":")[0]
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/padding.rb | lib/feather/padding.rb | module Feather
class Padding
class << self
##
# This adds 0 to the beginning of the number if it's a single digit, or just returns the number as a string if it isn't a single digit
# e.g. 7 => "07", 11 => "11"
def pad_single_digit(number)
number.to_s.length == 1 ? "0#{number}" : number.to_s
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/merbtasks.rb | lib/feather/merbtasks.rb | namespace :slices do
namespace :feather do
desc "Install Feather"
task :install => [:preflight, :setup_directories, :copy_assets, :migrate]
desc "Test for any dependencies"
task :preflight do # see slicetasks.rb
end
desc "Setup directories"
task :setup_directories do
puts "Creating directories for host application"
Feather.mirrored_components.each do |type|
if File.directory?(Feather.dir_for(type))
if !File.directory?(dst_path = Feather.app_dir_for(type))
relative_path = dst_path.relative_path_from(Merb.root)
puts "- creating directory :#{type} #{File.basename(Merb.root) / relative_path}"
mkdir_p(dst_path)
end
end
end
end
desc "Copy stub files to host application"
task :stubs do
puts "Copying stubs for Feather - resolves any collisions"
copied, preserved = Feather.mirror_stubs!
puts "- no files to copy" if copied.empty? && preserved.empty?
copied.each { |f| puts "- copied #{f}" }
preserved.each { |f| puts "! preserved override as #{f}" }
end
desc "Copy stub files and views to host application"
task :patch => [ "stubs", "freeze:views" ]
desc "Copy public assets to host application"
task :copy_assets do
puts "Copying assets for Feather - resolves any collisions"
copied, preserved = Feather.mirror_public!
puts "- no files to copy" if copied.empty? && preserved.empty?
copied.each { |f| puts "- copied #{f}" }
preserved.each { |f| puts "! preserved override as #{f}" }
end
desc "Migrate the database"
task :migrate do # see slicetasks.rb
end
desc "Freeze Feather into your app (only feather/app)"
task :freeze => [ "freeze:app" ]
namespace :freeze do
desc "Freezes Feather by installing the gem into application/gems"
task :gem do
ENV["GEM"] ||= "feather"
Rake::Task['slices:install_as_gem'].invoke
end
desc "Freezes Feather by copying all files from feather/app to your application"
task :app do
puts "Copying all feather/app files to your application - resolves any collisions"
copied, preserved = Feather.mirror_app!
puts "- no files to copy" if copied.empty? && preserved.empty?
copied.each { |f| puts "- copied #{f}" }
preserved.each { |f| puts "! preserved override as #{f}" }
end
desc "Freeze all views into your application for easy modification"
task :views do
puts "Copying all view templates to your application - resolves any collisions"
copied, preserved = Feather.mirror_files_for :view
puts "- no files to copy" if copied.empty? && preserved.empty?
copied.each { |f| puts "- copied #{f}" }
preserved.each { |f| puts "! preserved override as #{f}" }
end
desc "Freeze all models into your application for easy modification"
task :models do
puts "Copying all models to your application - resolves any collisions"
copied, preserved = Feather.mirror_files_for :model
puts "- no files to copy" if copied.empty? && preserved.empty?
copied.each { |f| puts "- copied #{f}" }
preserved.each { |f| puts "! preserved override as #{f}" }
end
desc "Freezes Feather as a gem and copies over feather-slice/app"
task :app_with_gem => [:gem, :app]
desc "Freezes Feather by unpacking all files into your application"
task :unpack do
puts "Unpacking Feather files to your application - resolves any collisions"
copied, preserved = Feather.unpack_slice!
puts "- no files to copy" if copied.empty? && preserved.empty?
copied.each { |f| puts "- copied #{f}" }
preserved.each { |f| puts "! preserved override as #{f}" }
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/cache_helper.rb | lib/feather/cache_helper.rb | module Feather
module CacheHelper
def expire_index
expire_page(:controller => '/', :action => "index")
end
def expire_article(article)
# If an article is a draft, it will not have a published_at date to go by.
unless article.published_at.nil?
year = article.published_at.year
month = article.published_at.month
# We need to show single digit months like 04 so stick a 0 in there.
month = "0#{month}" if month < 10
# Expire the year.
expire_page(:controller => "/", :action => year)
# Expire the months
expire_page(:controller => "/", :action => "#{year}/#{month}")
expire_page(:controller => '/', :action => article.permalink)
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/spectasks.rb | lib/feather/spectasks.rb | namespace :slices do
namespace :feather do
desc "Run slice specs within the host application context"
task :spec => [ "spec:explain", "spec:default" ]
namespace :spec do
slice_root = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
task :explain do
puts "\nNote: By running Feather specs inside the application context any\n" +
"overrides could break existing specs. This isn't always a problem,\n" +
"especially in the case of views. Use these spec tasks to check how\n" +
"well your application conforms to the original slice implementation."
end
Spec::Rake::SpecTask.new('default') do |t|
t.spec_opts = ["--format", "specdoc", "--colour"]
t.spec_files = Dir["#{slice_root}/spec/**/*_spec.rb"].sort
end
desc "Run all model specs, run a spec for a specific Model with MODEL=MyModel"
Spec::Rake::SpecTask.new('model') do |t|
t.spec_opts = ["--format", "specdoc", "--colour"]
if(ENV['MODEL'])
t.spec_files = Dir["#{slice_root}/spec/models/**/#{ENV['MODEL']}_spec.rb"].sort
else
t.spec_files = Dir["#{slice_root}/spec/models/**/*_spec.rb"].sort
end
end
desc "Run all controller specs, run a spec for a specific Controller with CONTROLLER=MyController"
Spec::Rake::SpecTask.new('controller') do |t|
t.spec_opts = ["--format", "specdoc", "--colour"]
if(ENV['CONTROLLER'])
t.spec_files = Dir["#{slice_root}/spec/controllers/**/#{ENV['CONTROLLER']}_spec.rb"].sort
else
t.spec_files = Dir["#{slice_root}/spec/controllers/**/*_spec.rb"].sort
end
end
desc "Run all view specs, run specs for a specific controller (and view) with CONTROLLER=MyController (VIEW=MyView)"
Spec::Rake::SpecTask.new('view') do |t|
t.spec_opts = ["--format", "specdoc", "--colour"]
if(ENV['CONTROLLER'] and ENV['VIEW'])
t.spec_files = Dir["#{slice_root}/spec/views/**/#{ENV['CONTROLLER']}/#{ENV['VIEW']}*_spec.rb"].sort
elsif(ENV['CONTROLLER'])
t.spec_files = Dir["#{slice_root}/spec/views/**/#{ENV['CONTROLLER']}/*_spec.rb"].sort
else
t.spec_files = Dir["#{slice_root}/spec/views/**/*_spec.rb"].sort
end
end
desc "Run all specs and output the result in html"
Spec::Rake::SpecTask.new('html') do |t|
t.spec_opts = ["--format", "html"]
t.libs = ['lib', 'server/lib' ]
t.spec_files = Dir["#{slice_root}/spec/**/*_spec.rb"].sort
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/database.rb | lib/feather/database.rb | module Feather
module Database
class << self
CORE = [Feather::Activity, Feather::Article, Feather::Configuration, Feather::PluginSetting, Feather::User]
# This provides a helper method for data migration for plugins - we can then update this to use non-destructive migrations at a later date and existing plugins won't need to change
def migrate(klass)
# Validate
raise "Unable to perform migrations, class must be specified!" unless klass.class == Class
raise "Unable to perform migrations for core class!" if CORE.include?(klass)
raise "Class cannot be migrated!" unless klass.respond_to?(:auto_migrate!)
# Execute auto migrations for now
klass.auto_migrate!
end
# This does the initial auto migration of all core classes, as well as the session table
def initial_setup
CORE.each { |c| c.auto_migrate! }
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/hooks/events.rb | lib/feather/hooks/events.rb | module Feather
module Hooks
module Events
class << self
##
# Event registration
##
# This registers a block against an event
def register_event(event, &block)
@events = {} if @events.nil?
@events[event] = [] if @events[event].nil?
@events[event] << block
end
##
# This calls the event handlers for the specified event (wrapping errors)
def run_event(event, *args)
unless @events.nil? || @events.empty? || @events[event].nil? || @events[event].empty?
@events[event].each do |hook|
if Feather::Hooks::is_hook_valid?(hook)
begin
hook.call args
rescue
end
end
end
end
true
end
##
# Model events
##
# This gets called before article creation, and provides the article that is being created
def before_create_article(article)
run_event(:before_create_article, article)
end
##
# This gets called before article updating, and provides the article that is being updated
def before_update_article(article)
run_event(:before_update_article, article)
end
##
# This gets called before an article is saved (created or updated), and provides the article that is being saved
def before_save_article(article)
run_event(:before_save_article, article)
end
##
# This gets called before an article is published, and provides the article that is being published
def before_publish_article(article)
run_event(:before_publish_article, article)
end
##
# This gets called after an article is created, and provides the article that was created
def after_create_article(article)
run_event(:after_create_article, article)
end
##
# This gets called after an article is updated, and provides the article that was updated
def after_update_article(article)
run_event(:after_update_article, article)
end
##
# This gets called after an article is saved, and provides the article that was saved
def after_save_article(article)
run_event(:after_save_article, article)
end
##
# This gets called after an article is published, and provides the article that was published
def after_publish_article(article)
run_event(:after_publish_article, article)
end
##
# Controller events
##
# This gets called before any controller action
def application_before
run_event(:application_before)
end
##
# This gets called after the article index request, providing the articles from the index, and the request
def after_index_article_request(articles, request)
run_event(:after_index_article_request, articles, request)
end
##
# This gets called after the article show request, providing the article being shown, and the request
def after_show_article_request(article, request)
run_event(:after_show_article_request, article, request)
end
##
# This gets called after a request to create an article, providing the article that was created, and the request
def after_create_article_request(article, request)
run_event(:after_create_article_request, article, request)
end
##
# This gets called after a request to update an article, providing the article that was updated, and the request
def after_update_article_request(article, request)
run_event(:after_update_article_request, article, request)
end
##
# This gets called after a request to publish an article (a create or update where the article is marked as published), providing the article that was published, and the request
def after_publish_article_request(article, request)
run_event(:after_publish_article_request, article, request)
end
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/hooks/menu.rb | lib/feather/hooks/menu.rb | module Feather
module Hooks
module Menu
class << self
##
# This adds the specified menu items for the calling plugin
def add_menu_item(text, url)
@menu_item_hooks ||= {}
raise "Unable to add menu item for unrecognized plugin! (#{Hooks::get_caller})" if (plugin = Feather::Hooks::get_plugin_by_caller(Feather::Hooks::get_caller)).nil?
@menu_item_hooks[plugin.id] ||= []
@menu_item_hooks[plugin.id] << {:text => text, :url => url}
end
##
# This returns the menu items for any plugins that have used the above call (providing the plugins are active)
def menu_items
menu_items = []
unless @menu_item_hooks.nil?
Feather::Plugin.active.each do |plugin|
@menu_item_hooks[plugin.id].each { |item| menu_items << item } unless @menu_item_hooks[plugin.id].nil? || @menu_item_hooks[plugin.id].empty?
end
end
menu_items
end
##
# This removes any plugin hooks for the plugin with the specified id
def remove_plugin_hooks(id)
@menu_item_hooks.delete(id) unless @menu_item_hooks.nil? || @menu_item_hooks.empty?
end
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/hooks/routing.rb | lib/feather/hooks/routing.rb | module Feather
module Hooks
module Routing
class << self
##
# Route registration
##
# This registers a routing block
def register_route(&block)
@routes = [] if @routes.nil?
@routes << block
end
##
# This calls each individual routing block and passes in the router to run against
def load_routes(router)
return if @routes.nil? || @routes.empty?
@routes.each do |block|
block.call(router)
end
end
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/hooks/formatters.rb | lib/feather/hooks/formatters.rb | module Feather
module Hooks
module Formatters
class << self
##
# This registers a block to format article content
def register_formatter(name, &block)
@formatters = {"default" => default_formatter} if @formatters.nil?
raise "Formatter `#{name}` already registered!" unless @formatters[name].nil?
@formatters[name] = block
end
##
# This returns an array of available formatters that have been registered
def available_formatters
@formatters = {"default" => default_formatter} if @formatters.nil?
@formatters.keys.select { |key| key == "default" || Feather::Hooks::is_hook_valid?(@formatters[key]) }
end
##
# This returns a default formatter used for replacing line breaks within text
# This is the only formatter included within feather-core
def default_formatter
Proc.new do |text|
text.gsub("\r\n", "\n").gsub("\n", "<br />")
end
end
##
# This performs the relevant formatting for the article, and returns the formatted article content
def format_article(article)
format_text(article.formatter, article.content)
end
##
# This performs the requested formatting, returning the formatted text
def format_text(formatter, text)
formatter = "default" unless available_formatters.include?(formatter)
@formatters[formatter].call(text)
end
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/lib/feather/hooks/view.rb | lib/feather/hooks/view.rb | module Feather
module Hooks
module View
class << self
##
# This returns an array of the available view hooks
def available_hooks
["first_article_in_list", "last_article_in_list", "before_article", "before_article_in_list", "after_article", "after_article_in_list", "article_form_fields", "between_articles", "meta_section", "head", "header", "before_layout", "after_layout", "sidebar", "footer"]
end
##
# This returns true if the specified plugin has views registered, false otherwise
def has_views_registered?(plugin)
@view_hooks ||= {}
@view_hooks.include?(plugin.id)
end
##
# This registers a partial view, effectively adding a call to the specified partial for the specified view hook point
def register_partial_view(name, partial)
register_view(Feather::Hooks::get_caller, name, {:partial => partial})
end
##
# This registers a dynamic view, effectively adding string content to the specified view hook point, with a specified identifier
def register_dynamic_view(name, content, id = nil)
id.nil? ? register_view(Feather::Hooks::get_caller, name, {:content => content}) : register_view(Feather::Hooks::get_caller, name, {:content => content}, id)
end
##
# This registers a view with the specified id, for the specified view name, and with optional options
def register_view(caller, name, options, id = rand(1000000).to_s)
raise "Unable to register view for unrecognized plugin! (#{caller})" if (plugin = Feather::Hooks::get_plugin_by_caller(caller)).nil?
raise "View hook #{name} is not available!" unless available_hooks.include?(name)
@view_hooks ||= {}
@view_hooks[plugin.id] ||= []
@view_hooks[plugin.id] << {:id => id, :name => name}.merge(options)
end
##
# This removes any view hooks registered with the specified identifier
def deregister_dynamic_view(id)
@view_hooks.keys.each do |key|
@view_hooks[key].each do |view|
@view_hooks[key].delete(view) if view[:id] == id
end
end
end
##
# This iterates through all registered views (from active plugins), building an array to be rendered
def plugin_views
plugin_views = []
unless @view_hooks.nil? || @view_hooks.values.nil?
Feather::Plugin.active.each do |plugin|
@view_hooks[plugin.id].each { |view| plugin_views << view.merge({:plugin => plugin}) } unless @view_hooks[plugin.id].nil? || @view_hooks[plugin.id].empty?
end
end
plugin_views.sort { |a, b| a[:plugin].name <=> b[:plugin].name }
end
##
# This removes any view hooks for the specified plugin
def remove_plugin_hooks(id)
@view_hooks.delete(id) unless @view_hooks.nil? || @view_hooks.empty?
end
end
end
end
end | ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/rack.rb | config/rack.rb | # use PathPrefix Middleware if :path_prefix is set in Merb::Config
if prefix = ::Merb::Config[:path_prefix]
use Merb::Rack::PathPrefix, prefix
end
# comment this out if you are running merb behind a load balancer
# that serves static files
use Merb::Rack::Static, Merb.dir_for(:public)
# this is our main merb application
run Merb::Rack::Application.new
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/router.rb | config/router.rb | # Merb::Router is the request routing mapper for the merb framework.
#
# You can route a specific URL to a controller / action pair:
#
# match("/contact").
# to(:controller => "info", :action => "contact")
#
# You can define placeholder parts of the url with the :symbol notation. These
# placeholders will be available in the params hash of your controllers. For example:
#
# match("/books/:book_id/:action").
# to(:controller => "books")
#
# Or, use placeholders in the "to" results for more complicated routing, e.g.:
#
# match("/admin/:module/:controller/:action/:id").
# to(:controller => ":module/:controller")
#
# You can also use regular expressions, deferred routes, and many other options.
# See merb/specs/merb/routerb for a fairly complete usage sample.
Merb.logger.info("Compiling routes...")
Merb::Router.prepare do |router|
# Load all plugins
begin
Feather::Plugin.all.each do |p|
begin
p.load
Merb.logger.info("\"#{p.name}\" loaded")
rescue Exception => e
Merb.logger.info("\"#{p.name}\" failed to load : #{e.message}")
end
end
rescue Exception => e
Merb.logger.info("Error loading plugins: #{e.message}")
end
# Load all plugin routes
Feather::Hooks::Routing.load_routes(router)
slice(:merb_auth_slice_password, :name_prefix => nil, :path_prefix => "")
# This deferred route allows permalinks to be handled, without a separate rack handler
match(/.*/).defer_to do |request, params|
unless (id = Feather::Article.routing[request.uri.to_s.chomp("/")]).nil?
{:controller => "feather/articles", :action => "show", :id => id}
end
end
# Admin namespace
namespace "feather/admin", :path => "admin", :name_prefix => "admin" do
resource :configuration
resources :plugins
resources :articles
resources :users
resource :dashboard
end
match("/admin").to(:action => "show", :controller => "feather/admin/dashboards")
# Year/month/day routes
match("/:year").to(:controller => "feather/articles", :action => "index").name(:year)
match("/:year/:month").to(:controller => "feather/articles", :action => "index").name(:month)
match("/:year/:month/:day").to(:controller => "feather/articles", :action => "index").name(:day)
# Default routes, and index
default_routes
match("/").to(:controller => 'feather/articles', :action =>'index')
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/dependencies.rb | config/dependencies.rb | # dependencies are generated using a strict version, don't forget to edit the dependency versions when upgrading.
merb_gems_version = "1.0.11"
dm_gems_version = "0.9.11"
do_gems_version = "0.9.11"
dependency "merb-core", merb_gems_version
dependency "merb-action-args", merb_gems_version
dependency "merb-assets", merb_gems_version
dependency "merb-cache"
dependency "merb-helpers", merb_gems_version
dependency "merb-mailer", merb_gems_version
dependency "merb-slices", merb_gems_version
dependency "merb-auth-core", merb_gems_version
dependency "merb-auth-more", merb_gems_version
dependency "merb-auth-slice-password", merb_gems_version
dependency "merb-param-protection", merb_gems_version
dependency "merb-exceptions", merb_gems_version
dependency "data_objects", do_gems_version
dependency "dm-core", dm_gems_version
dependency "dm-aggregates", dm_gems_version
dependency "dm-migrations", dm_gems_version
dependency "dm-timestamps", dm_gems_version
dependency "dm-types", dm_gems_version
dependency "dm-validations", dm_gems_version
dependency "dm-serializer", dm_gems_version
dependency "dm-is-paginated"
dependency "merb_datamapper", merb_gems_version
dependency "tzinfo"
dependency "archive-tar-minitar", :require_as => 'archive/tar/minitar'
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/init.rb | config/init.rb | require 'config/dependencies.rb'
use_orm :datamapper
use_test :rspec
use_template_engine :erb
# Make the app's "gems" directory a place where gems are loaded from
Gem.clear_paths
Gem.path.unshift(Merb.root / "gems")
# Make the app's "lib" directory a place where ruby files get "require"d from
$LOAD_PATH.unshift(Merb.root / "lib")
Merb::Config.use do |c|
### Sets up a custom session id key, if you want to piggyback sessions of other applications
### with the cookie session store. If not specified, defaults to '_session_id'.
# c[:session_id_key] = '_session_id'
c[:session_secret_key] = '95bf50e5bb36b2a455611792c271f2581e6b21db'
c[:session_store] = 'datamapper'
c[:use_mutex] = false
c[:logfile] = Merb.log_path + "/merb.log"
end
Merb::BootLoader.before_app_loads do
Dir.glob("app/models/*/*.rb").each { |f| require f }
Merb::Authentication.user_class = Feather::User
Merb::Slices.config[:merb_auth] = {
:layout => :admin,
:login_field => :login
}
require "tzinfo"
require "net/http"
require "uri"
require "cgi"
require "erb"
require "zlib"
require "stringio"
require "archive/tar/minitar"
require File.join("lib", "feather", "padding")
require File.join("lib", "feather", "hooks")
require File.join("lib", "feather", "database")
require File.join("lib", "feather", "plugin_dependencies")
require File.join("lib", "merb_auth_setup")
end
Merb::BootLoader.after_app_loads do
Merb::Mailer.delivery_method = :sendmail
Merb::Cache.setup do
register(:feather, Merb::Cache::MemcachedStore, :namespace => "feather")
end
end
# require File.join(File.join(Merb.root_path, "lib"), "cache_helper")
# Merb::Plugins.config[:merb_cache] = {
# :cache_html_directory => Merb.dir_for(:public) / "cache",
# :store => "file",
# :cache_directory => Merb.root_path("tmp/cache"),
# :disable => "development"
# }
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/environments/test.rb | config/environments/test.rb | Merb.logger.info("Loaded TEST Environment...")
Merb::Config.use { |c|
c[:testing] = true
c[:exception_details] = true
c[:log_auto_flush ] = true
# log less in testing environment
c[:log_level] = :error
c[:log_file] = Merb.root / "log" / "test.log"
# or redirect logger using IO handle
# c[:log_stream] = STDOUT
}
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/environments/development.rb | config/environments/development.rb | Merb.logger.info("Loaded DEVELOPMENT Environment...")
Merb::Config.use { |c|
c[:exception_details] = true
c[:reload_templates] = true
c[:reload_classes] = true
c[:reload_time] = 0.5
c[:ignore_tampered_cookies] = true
c[:log_auto_flush ] = true
c[:log_level] = :debug
c[:log_stream] = STDOUT
c[:log_file] = nil
# Or redirect logging into a file:
# c[:log_file] = Merb.root / "log" / "development.log"
}
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/environments/staging.rb | config/environments/staging.rb | Merb.logger.info("Loaded STAGING Environment...")
Merb::Config.use { |c|
c[:exception_details] = false
c[:reload_classes] = false
c[:log_level] = :error
c[:log_file] = Merb.root / "log" / "staging.log"
# or redirect logger using IO handle
# c[:log_stream] = STDOUT
}
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/environments/production.rb | config/environments/production.rb | Merb.logger.info("Loaded PRODUCTION Environment...")
Merb::Config.use { |c|
c[:exception_details] = false
c[:reload_classes] = false
c[:log_level] = :error
c[:log_file] = Merb.root / "log" / "production.log"
# or redirect logger using IO handle
# c[:log_stream] = STDOUT
}
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/config/environments/rake.rb | config/environments/rake.rb | Merb.logger.info("Loaded RAKE Environment...")
Merb::Config.use { |c|
c[:exception_details] = true
c[:reload_classes] = false
c[:log_auto_flush ] = true
c[:log_stream] = STDOUT
c[:log_file] = nil
# Or redirect logging into a file:
# c[:log_file] = Merb.root / "log" / "development.log"
}
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/doc/rdoc/generators/merb_generator.rb | doc/rdoc/generators/merb_generator.rb |
# # We're responsible for generating all the HTML files
# from the object tree defined in code_objects.rb. We
# generate:
#
# [files] an html file for each input file given. These
# input files appear as objects of class
# TopLevel
#
# [classes] an html file for each class or module encountered.
# These classes are not grouped by file: if a file
# contains four classes, we'll generate an html
# file for the file itself, and four html files
# for the individual classes.
#
# Method descriptions appear in whatever entity (file, class,
# or module) that contains them.
#
# We generate files in a structure below a specified subdirectory,
# normally +doc+.
#
# opdir
# |
# |___ files
# | |__ per file summaries
# |
# |___ classes
# |__ per class/module descriptions
#
# HTML is generated using the Template class.
#
require 'ftools'
require 'rdoc/options'
require 'rdoc/template'
require 'rdoc/markup/simple_markup'
require 'rdoc/markup/simple_markup/to_html'
require 'cgi'
module Generators
# Name of sub-direcories that hold file and class/module descriptions
FILE_DIR = "files"
CLASS_DIR = "classes"
CSS_NAME = "stylesheet.css"
##
# Build a hash of all items that can be cross-referenced.
# This is used when we output required and included names:
# if the names appear in this hash, we can generate
# an html cross reference to the appropriate description.
# We also use this when parsing comment blocks: any decorated
# words matching an entry in this list are hyperlinked.
class AllReferences
@@refs = {}
def AllReferences::reset
@@refs = {}
end
def AllReferences.add(name, html_class)
@@refs[name] = html_class
end
def AllReferences.[](name)
@@refs[name]
end
def AllReferences.keys
@@refs.keys
end
end
##
# Subclass of the SM::ToHtml class that supports looking
# up words in the AllReferences list. Those that are
# found (like AllReferences in this comment) will
# be hyperlinked
class HyperlinkHtml < SM::ToHtml
# We need to record the html path of our caller so we can generate
# correct relative paths for any hyperlinks that we find
def initialize(from_path, context)
super()
@from_path = from_path
@parent_name = context.parent_name
@parent_name += "::" if @parent_name
@context = context
end
# We're invoked when any text matches the CROSSREF pattern
# (defined in MarkUp). If we fine the corresponding reference,
# generate a hyperlink. If the name we're looking for contains
# no punctuation, we look for it up the module/class chain. For
# example, HyperlinkHtml is found, even without the Generators::
# prefix, because we look for it in module Generators first.
def handle_special_CROSSREF(special)
name = special.text
if name[0,1] == '#'
lookup = name[1..-1]
name = lookup unless Options.instance.show_hash
else
lookup = name
end
if /([A-Z].*)[.\#](.*)/ =~ lookup
container = $1
method = $2
ref = @context.find_symbol(container, method)
else
ref = @context.find_symbol(lookup)
end
if ref and ref.document_self
"<a href=\"index.html?a=#{ref.aref}&name=#{name}\">#{name}</a>"
else
name #it does not need to be a link
end
end
# Generate a hyperlink for url, labeled with text. Handle the
# special cases for img: and link: described under handle_special_HYPEDLINK
def gen_url(url, text)
if url =~ /([A-Za-z]+):(.*)/
type = $1
path = $2
else
type = "http"
path = url
url = "http://#{url}"
end
if type == "link"
url = path
end
if (type == "http" || type == "link") && url =~ /\.(gif|png|jpg|jpeg|bmp)$/
"<img src=\"#{url}\">"
elsif (type == "http" || type == "link")
"<a href=\"#{url}\" target=\"_blank\">#{text}</a>"
else
"<a href=\"#\" onclick=\"jsHref('#{url}');\">#{text.sub(%r{^#{type}:/*}, '')}</a>"
end
end
# And we're invoked with a potential external hyperlink mailto:
# just gets inserted. http: links are checked to see if they
# reference an image. If so, that image gets inserted using an
# <img> tag. Otherwise a conventional <a href> is used. We also
# support a special type of hyperlink, link:, which is a reference
# to a local file whose path is relative to the --op directory.
def handle_special_HYPERLINK(special)
url = special.text
gen_url(url, url)
end
# HEre's a hypedlink where the label is different to the URL
# <label>[url]
#
def handle_special_TIDYLINK(special)
text = special.text
# unless text =~ /(\S+)\[(.*?)\]/
unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/
return text
end
label = $1
url = $2
gen_url(url, label)
end
end
#####################################################################
#
# Handle common markup tasks for the various Html classes
#
module MarkUp
# Convert a string in markup format into HTML. We keep a cached
# SimpleMarkup object lying around after the first time we're
# called per object.
def markup(str, remove_para=false)
return '' unless str
unless defined? @markup
@markup = SM::SimpleMarkup.new
# class names, variable names, file names, or instance variables
@markup.add_special(/(
\b([A-Z]\w*(::\w+)*[.\#]\w+) # A::B.meth
| \b([A-Z]\w+(::\w+)*) # A::B..
| \#\w+[!?=]? # #meth_name
| \b\w+([_\/\.]+\w+)+[!?=]? # meth_name
)/x, :CROSSREF)
# external hyperlinks
@markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK)
# and links of the form <text>[<url>]
@markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\.\S+?\])/, :TIDYLINK)
# @markup.add_special(/\b(\S+?\[\S+?\.\S+?\])/, :TIDYLINK)
end
unless defined? @html_formatter
@html_formatter = HyperlinkHtml.new(self.path, self)
end
# Convert leading comment markers to spaces, but only
# if all non-blank lines have them
if str =~ /^(?>\s*)[^\#]/
content = str
else
content = str.gsub(/^\s*(#+)/) { $1.tr('#',' ') }
end
res = @markup.convert(content, @html_formatter)
if remove_para
res.sub!(/^<p>/, '')
res.sub!(/<\/p>$/, '')
end
res
end
def style_url(path, css_name=nil)
css_name ||= CSS_NAME
end
# Build a webcvs URL with the given 'url' argument. URLs with a '%s' in them
# get the file's path sprintfed into them; otherwise they're just catenated
# together.
def cvs_url(url, full_path)
if /%s/ =~ url
return sprintf( url, full_path )
else
return url + full_path
end
end
end
#####################################################################
#
# A Context is built by the parser to represent a container: contexts
# hold classes, modules, methods, require lists and include lists.
# ClassModule and TopLevel are the context objects we process here
#
class ContextUser
include MarkUp
attr_reader :context
def initialize(context, options)
@context = context
@options = options
end
# convenience method to build a hyperlink # Where's the DRY in this?? Put this in the template where it belongs
def href(link, cls, name)
%{"<a href=\"#\" onclick=\"jsHref('#{link}');\" class=\"#{cls}\">#{name}</a>"}
end
# Create a list of HtmlMethod objects for each method
# in the corresponding context object. If the @options.show_all
# variable is set (corresponding to the <tt>--all</tt> option,
# we include all methods, otherwise just the public ones.
def collect_methods
list = @context.method_list
unless @options.show_all
list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation }
end
@methods = list.collect {|m| HtmlMethod.new(m, self, @options) }
end
# Build a summary list of all the methods in this context
def build_method_summary_list(path_prefix="")
collect_methods unless @methods
meths = @methods.sort
res = []
meths.each do |meth|
res << {
"name" => CGI.escapeHTML(meth.name),
"aref" => meth.aref,
"href" => meth.path
}
end
res
end
# Build a list of aliases for which we couldn't find a
# corresponding method
def build_alias_summary_list(section)
values = []
@context.aliases.each do |al|
next unless al.section == section
res = {
'old_name' => al.old_name,
'new_name' => al.new_name,
}
if al.comment && !al.comment.empty?
res['desc'] = markup(al.comment, true)
end
values << res
end
values
end
# Build a list of constants
def build_constants_summary_list(section)
values = []
@context.constants.each do |co|
next unless co.section == section
res = {
'name' => co.name,
'value' => CGI.escapeHTML(co.value)
}
res['desc'] = markup(co.comment, true) if co.comment && !co.comment.empty?
values << res
end
values
end
def build_requires_list(context)
potentially_referenced_list(context.requires) {|fn| [fn + ".rb"] }
end
def build_include_list(context)
potentially_referenced_list(context.includes)
end
# Build a list from an array of <i>Htmlxxx</i> items. Look up each
# in the AllReferences hash: if we find a corresponding entry,
# we generate a hyperlink to it, otherwise just output the name.
# However, some names potentially need massaging. For example,
# you may require a Ruby file without the .rb extension,
# but the file names we know about may have it. To deal with
# this, we pass in a block which performs the massaging,
# returning an array of alternative names to match
def potentially_referenced_list(array)
res = []
array.each do |i|
ref = AllReferences[i.name]
# if !ref
# container = @context.parent
# while !ref && container
# name = container.name + "::" + i.name
# ref = AllReferences[name]
# container = container.parent
# end
# end
ref = @context.find_symbol(i.name)
ref = ref.viewer if ref
if !ref && block_given?
possibles = yield(i.name)
while !ref and !possibles.empty?
ref = AllReferences[possibles.shift]
end
end
h_name = CGI.escapeHTML(i.name)
if ref and ref.document_self
path = ref.path
res << { "name" => h_name, "href" => path }
else
res << { "name" => h_name, "href" => "" }
end
end
res
end
# Build an array of arrays of method details. The outer array has up
# to six entries, public, private, and protected for both class
# methods, the other for instance methods. The inner arrays contain
# a hash for each method
def build_method_detail_list(section)
outer = []
methods = @methods.sort
for singleton in [true, false]
for vis in [ :public, :protected, :private ]
res = []
methods.each do |m|
if m.section == section and
m.document_self and
m.visibility == vis and
m.singleton == singleton
row = {}
if m.call_seq
row["callseq"] = m.call_seq.gsub(/->/, '→')
else
row["name"] = CGI.escapeHTML(m.name)
row["params"] = m.params
end
desc = m.description.strip
row["m_desc"] = desc unless desc.empty?
row["aref"] = m.aref
row["href"] = m.path
row["m_seq"] = m.seq
row["visibility"] = m.visibility.to_s
alias_names = []
m.aliases.each do |other|
if other.viewer # won't be if the alias is private
alias_names << {
'name' => other.name,
'href' => other.viewer.path,
'aref' => other.viewer.aref
}
end
end
unless alias_names.empty?
row["aka"] = alias_names
end
#if @options.inline_source
code = m.source_code
row["sourcecode"] = code if code
#else
# code = m.src_url
#if code
# row["codeurl"] = code
# row["imgurl"] = m.img_url
#end
#end
res << row
end
end
if res.size > 0
outer << {
"type" => vis.to_s.capitalize,
"category" => singleton ? "Class" : "Instance",
"methods" => res
}
end
end
end
outer
end
# Build the structured list of classes and modules contained
# in this context.
def build_class_list(level, from, section, infile=nil)
res = ""
prefix = " ::" * level;
from.modules.sort.each do |mod|
next unless mod.section == section
next if infile && !mod.defined_in?(infile)
if mod.document_self
res <<
prefix <<
"Module " <<
href(mod.viewer.path, "link", mod.full_name) <<
"<br />\n" <<
build_class_list(level + 1, mod, section, infile)
end
end
from.classes.sort.each do |cls|
next unless cls.section == section
next if infile && !cls.defined_in?(infile)
if cls.document_self
res <<
prefix <<
"Class " <<
href(cls.viewer.path, "link", cls.full_name) <<
"<br />\n" <<
build_class_list(level + 1, cls, section, infile)
end
end
res
end
def document_self
@context.document_self
end
def diagram_reference(diagram)
res = diagram.gsub(/((?:src|href)=")(.*?)"/) {
$1 + $2 + '"'
}
res
end
# Find a symbol in ourselves or our parent
def find_symbol(symbol, method=nil)
res = @context.find_symbol(symbol, method)
if res
res = res.viewer
end
res
end
# create table of contents if we contain sections
def add_table_of_sections
toc = []
@context.sections.each do |section|
if section.title
toc << {
'secname' => section.title,
'href' => section.sequence
}
end
end
@values['toc'] = toc unless toc.empty?
end
end
#####################################################################
#
# Wrap a ClassModule context
class HtmlClass < ContextUser
@@c_seq = "C00000000"
attr_reader :path
def initialize(context, html_file, prefix, options)
super(context, options)
@@c_seq = @@c_seq.succ
@c_seq = @@c_seq
@html_file = html_file
@is_module = context.is_module?
@values = {}
context.viewer = self
@path = http_url(context.full_name, prefix)
collect_methods
AllReferences.add(name, self)
end
# return the relative file name to store this class in,
# which is also its url
def http_url(full_name, prefix)
path = full_name.dup
if path['<<']
path.gsub!(/<<\s*(\w*)/) { "from-#$1" }
end
File.join(prefix, path.split("::")) + ".html"
end
def seq
@c_seq
end
def aref
@c_seq
end
def scope
a = @context.full_name.split("::")
if a.length > 1
a.pop
a.join("::")
else
""
end
end
def name
@context.full_name.gsub("#{scope}::", '')
end
def full_name
@context.full_name
end
def parent_name
@context.parent.full_name
end
def write_on(f)
value_hash
template = TemplatePage.new(RDoc::Page::BODY,
RDoc::Page::CLASS_PAGE,
RDoc::Page::METHOD_LIST)
template.write_html_on(f, @values)
end
def value_hash
class_attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
# Convert README to html
unless File.exist?('files/README.html')
File.open('files/README.html', 'w') do |file|
file << markup(File.read(File.expand_path(@options.main_page)))
end
end
d = markup(@context.comment)
@values["description"] = d unless d.empty?
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
il = build_include_list(@context)
@values["includes"] = il unless il.empty?
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
al = build_alias_summary_list(section)
secdata["aliases"] = al unless al.empty?
co = build_constants_summary_list(section)
secdata["constants"] = co unless co.empty?
al = build_attribute_list(section)
secdata["attributes"] = al unless al.empty?
cl = build_class_list(0, @context, section)
secdata["classlist"] = cl unless cl.empty?
mdl = build_method_detail_list(section)
secdata["method_list"] = mdl unless mdl.empty?
secdata
end
@values
end
def build_attribute_list(section)
atts = @context.attributes.sort
res = []
atts.each do |att|
next unless att.section == section
if att.visibility == :public || att.visibility == :protected || @options.show_all
entry = {
"name" => CGI.escapeHTML(att.name),
"rw" => att.rw,
"a_desc" => markup(att.comment, true)
}
unless att.visibility == :public || att.visibility == :protected
entry["rw"] << "-"
end
res << entry
end
end
res
end
def class_attribute_values
h_name = CGI.escapeHTML(name)
@values["classmod"] = @is_module ? "Module" : "Class"
@values["title"] = "#{@values['classmod']}: #{h_name}"
c = @context
c = c.parent while c and !c.diagram
if c && c.diagram
@values["diagram"] = diagram_reference(c.diagram)
end
@values["full_name"] = h_name
@values["class_seq"] = seq
parent_class = @context.superclass
if parent_class
@values["parent"] = CGI.escapeHTML(parent_class)
if parent_name
lookup = parent_name + "::" + parent_class
else
lookup = parent_class
end
parent_url = AllReferences[lookup] || AllReferences[parent_class]
if parent_url and parent_url.document_self
@values["par_url"] = parent_url.path
end
end
files = []
@context.in_files.each do |f|
res = {}
full_path = CGI.escapeHTML(f.file_absolute_name)
res["full_path"] = full_path
res["full_path_url"] = f.viewer.path if f.document_self
if @options.webcvs
res["cvsurl"] = cvs_url( @options.webcvs, full_path )
end
files << res
end
@values['infiles'] = files
end
def <=>(other)
self.name <=> other.name
end
end
#####################################################################
#
# Handles the mapping of a file's information to HTML. In reality,
# a file corresponds to a +TopLevel+ object, containing modules,
# classes, and top-level methods. In theory it _could_ contain
# attributes and aliases, but we ignore these for now.
class HtmlFile < ContextUser
@@f_seq = "F00000000"
attr_reader :path
attr_reader :name
def initialize(context, options, file_dir)
super(context, options)
@@f_seq = @@f_seq.succ
@f_seq = @@f_seq
@values = {}
@path = http_url(file_dir)
@source_file_path = File.expand_path(@context.file_relative_name).gsub("\/doc\/", "/")
@name = @context.file_relative_name
collect_methods
AllReferences.add(name, self)
context.viewer = self
end
def http_url(file_dir)
File.join(file_dir, @context.file_relative_name.tr('.', '_')) + ".html"
end
def filename_to_label
@context.file_relative_name.gsub(/%|\/|\?|\#/) {|s| '%' + ("%x" % s[0]) }
end
def seq
@f_seq
end
def aref
@f_seq
end
def name
full_path = @context.file_absolute_name
short_name = File.basename(full_path)
end
def full_name
@context.file_absolute_name
end
def scope
@context.file_relative_name.gsub(/\/#{name}$/, '')
end
def parent_name
nil
end
def full_file_source
ret_str = ""
File.open(@source_file_path, 'r') do |f|
while(!f.eof?) do
ret_str += f.readline()
end
end
ret_str
rescue
"file not found -#{@source_file_path}-"
#@source_file_path
end
def value_hash
file_attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["href"] = path
@values["style_url"] = style_url(path, @options.css)
@values["file_seq"] = seq
#pulling in the source for this file
#@values["source_code"] = @context.token_stream
@values["file_source_code"] = CGI.escapeHTML(full_file_source)
if @context.comment
d = markup(@context.comment)
@values["description"] = d if d.size > 0
end
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
il = build_include_list(@context)
@values["includes"] = il unless il.empty?
rl = build_requires_list(@context)
@values["requires"] = rl unless rl.empty?
file_context = @context
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
cl = build_class_list(0, @context, section, file_context)
@values["classlist"] = cl unless cl.empty?
mdl = build_method_detail_list(section)
secdata["method_list"] = mdl unless mdl.empty?
al = build_alias_summary_list(section)
secdata["aliases"] = al unless al.empty?
co = build_constants_summary_list(section)
@values["constants"] = co unless co.empty?
secdata
end
@values
end
def write_on(f)
value_hash
template = TemplatePage.new(RDoc::Page::SRC_BODY,RDoc::Page::FILE_PAGE, RDoc::Page::METHOD_LIST)
template.write_html_on(f, @values)
end
def file_attribute_values
full_path = @context.file_absolute_name
short_name = File.basename(full_path)
@values["title"] = CGI.escapeHTML("File: #{short_name}")
if @context.diagram
@values["diagram"] = diagram_reference(@context.diagram)
end
@values["short_name"] = CGI.escapeHTML(short_name)
@values["full_path"] = CGI.escapeHTML(full_path)
@values["dtm_modified"] = @context.file_stat.mtime.to_s
if @options.webcvs
@values["cvsurl"] = cvs_url( @options.webcvs, @values["full_path"] )
end
end
def <=>(other)
self.name <=> other.name
end
end
#####################################################################
class HtmlMethod
include MarkUp
attr_reader :context
attr_reader :src_url
attr_reader :img_url
attr_reader :source_code
@@m_seq = "M000000"
@@all_methods = []
def HtmlMethod::reset
@@all_methods = []
end
def initialize(context, html_class, options)
@context = context
@html_class = html_class
@options = options
@@m_seq = @@m_seq.succ
@m_seq = @@m_seq
@@all_methods << self
context.viewer = self
if (ts = @context.token_stream)
@source_code = markup_code(ts)
#unless @options.inline_source
# @src_url = create_source_code_file(@source_code)
# @img_url = MERBGenerator.gen_url(path, 'source.png')
#end
end
AllReferences.add(name, self)
end
def seq
@m_seq
end
def aref
@m_seq
end
def scope
@html_class.full_name
end
# return a reference to outselves to be used as an href=
# the form depends on whether we're all in one file
# or in multiple files
def name
@context.name
end
def section
@context.section
end
def parent_name
if @context.parent.parent
@context.parent.parent.full_name
else
nil
end
end
def path
@html_class.path
end
def description
markup(@context.comment)
end
def visibility
@context.visibility
end
def singleton
@context.singleton
end
def call_seq
cs = @context.call_seq
if cs
cs.gsub(/\n/, "<br />\n")
else
nil
end
end
def params
# params coming from a call-seq in 'C' will start with the
# method name
p = @context.params
if p !~ /^\w/
p = @context.params.gsub(/\s*\#.*/, '')
p = p.tr("\n", " ").squeeze(" ")
p = "(" + p + ")" unless p[0] == ?(
if (block = @context.block_params)
# If this method has explicit block parameters, remove any
# explicit &block
p.sub!(/,?\s*&\w+/, '')
block.gsub!(/\s*\#.*/, '')
block = block.tr("\n", " ").squeeze(" ")
if block[0] == ?(
block.sub!(/^\(/, '').sub!(/\)/, '')
end
p << " {|#{block.strip}| ...}"
end
end
CGI.escapeHTML(p)
end
def create_source_code_file(code_body)
meth_path = @html_class.path.sub(/\.html$/, '.src')
File.makedirs(meth_path)
file_path = File.join(meth_path, seq) + ".html"
template = TemplatePage.new(RDoc::Page::SRC_PAGE)
File.open(file_path, "w") do |f|
values = {
'title' => CGI.escapeHTML(name),
'code' => code_body,
'style_url' => style_url(file_path, @options.css),
'charset' => @options.charset
}
template.write_html_on(f, values)
end
file_path
end
def HtmlMethod.all_methods
@@all_methods
end
def <=>(other)
@context <=> other.context
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | true |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/doc/rdoc/generators/template/merb/merb.rb | doc/rdoc/generators/template/merb/merb.rb | module RDoc
module Page
STYLE = File.read(File.join(File.dirname(__FILE__), 'merb_doc_styles.css'))
FONTS = ""
###################################################################
CLASS_PAGE = <<HTML
<div id="%class_seq%">
<div class='banner'>
<span class="file-title-prefix">%classmod%</span><br />%full_name%<br/>
In:
START:infiles
<a href="#" onclick="jsHref('%full_path_url%');">%full_path%</a>
IF:cvsurl
(<a href="#" onclick="jsHref('%cvsurl%');">CVS</a>)
ENDIF:cvsurl
END:infiles
IF:parent
Parent:
IF:par_url
<a href="#" onclick="jsHref('%par_url%');">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
ENDIF:parent
</div>
HTML
###################################################################
METHOD_LIST = <<HTML
<div id="content">
IF:diagram
<table cellpadding='0' cellspacing='0' border='0' width="100%"><tr><td align="center">
%diagram%
</td></tr></table>
ENDIF:diagram
IF:description
<div class="description">%description%</div>
ENDIF:description
IF:requires
<div class="sectiontitle">Required Files</div>
<ul>
START:requires
<li><a href="#" onclick="jsHref('%href%');">%name%</a></li>
END:requires
</ul>
ENDIF:requires
IF:toc
<div class="sectiontitle">Contents</div>
<ul>
START:toc
<li><a href="#" onclick="jsHref('%href%');">%secname%</a></li>
END:toc
</ul>
ENDIF:toc
IF:methods
<div class="sectiontitle">Methods</div>
<ul>
START:methods
<li><a href="index.html?a=%href%&name=%name%" >%name%</a></li>
END:methods
</ul>
ENDIF:methods
IF:includes
<div class="sectiontitle">Included Modules</div>
<ul>
START:includes
<li><a href="#" onclick="jsHref('%href%');">%name%</a></li>
END:includes
</ul>
ENDIF:includes
START:sections
IF:sectitle
<div class="sectiontitle"><a href="%secsequence%">%sectitle%</a></div>
IF:seccomment
<div class="description">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
IF:classlist
<div class="sectiontitle">Classes and Modules</div>
%classlist%
ENDIF:classlist
IF:constants
<div class="sectiontitle">Constants</div>
<table border='0' cellpadding='5'>
START:constants
<tr valign='top'>
<td class="attr-name">%name%</td>
<td>=</td>
<td class="attr-value">%value%</td>
</tr>
IF:desc
<tr valign='top'>
<td> </td>
<td colspan="2" class="attr-desc">%desc%</td>
</tr>
ENDIF:desc
END:constants
</table>
ENDIF:constants
IF:attributes
<div class="sectiontitle">Attributes</div>
<table border='0' cellpadding='5'>
START:attributes
<tr valign='top'>
<td class='attr-rw'>
IF:rw
[%rw%]
ENDIF:rw
</td>
<td class='attr-name'>%name%</td>
<td class='attr-desc'>%a_desc%</td>
</tr>
END:attributes
</table>
ENDIF:attributes
IF:method_list
START:method_list
IF:methods
<div class="sectiontitle">%type% %category% methods</div>
START:methods
<div id="%m_seq%" class="method">
<div id="%m_seq%_title" class="title">
IF:callseq
<b>%callseq%</b>
ENDIF:callseq
IFNOT:callseq
<b>%name%</b>%params%
ENDIF:callseq
IF:codeurl
[ <a href="javascript:openCode('%codeurl%')">source</a> ]
ENDIF:codeurl
</div>
IF:m_desc
<div class="description">
%m_desc%
</div>
ENDIF:m_desc
IF:aka
<div class="aka">
This method is also aliased as
START:aka
<a href="index.html?a=%aref%&name=%name%">%name%</a>
END:aka
</div>
ENDIF:aka
IF:sourcecode
<div class="sourcecode">
<p class="source-link">[ <a href="javascript:toggleSource('%aref%_source')" id="l_%aref%_source">show source</a> ]</p>
<div id="%aref%_source" class="dyn-source">
<pre>
%sourcecode%
</pre>
</div>
</div>
ENDIF:sourcecode
</div>
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
END:sections
</div>
HTML
BODY = <<ENDBODY
!INCLUDE! <!-- banner header -->
<div id="bodyContent" >
#{METHOD_LIST}
</div>
ENDBODY
SRC_BODY = <<ENDSRCBODY
!INCLUDE! <!-- banner header -->
<div id="bodyContent" >
<h2>Source Code</h2>
<pre>%file_source_code%</pre>
</div>
ENDSRCBODY
###################### File Page ##########################
FILE_PAGE = <<HTML
<div id="fileHeader">
<h1>%short_name%</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>%dtm_modified%</td>
</tr>
</table>
</div>
HTML
#### This is not used but kept for historical purposes
########################## Source code ##########################
# Separate page onlye
SRC_PAGE = <<HTML
<html>
<head><title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style>
.ruby-comment { color: green; font-style: italic }
.ruby-constant { color: #4433aa; font-weight: bold; }
.ruby-identifier { color: #222222; }
.ruby-ivar { color: #2233dd; }
.ruby-keyword { color: #3333FF; font-weight: bold }
.ruby-node { color: #777777; }
.ruby-operator { color: #111111; }
.ruby-regexp { color: #662222; }
.ruby-value { color: #662222; font-style: italic }
.kw { color: #3333FF; font-weight: bold }
.cmt { color: green; font-style: italic }
.str { color: #662222; font-style: italic }
.re { color: #662222; }
</style>
</head>
<body bgcolor="white">
<pre>%code%</pre>
</body>
</html>
HTML
########################### source page body ###################
SCR_CODE_BODY = <<HTML
<div id="source">
%source_code%
</div>
HTML
########################## Index ################################
FR_INDEX_BODY = <<HTML
!INCLUDE!
HTML
FILE_INDEX = <<HTML
<ul>
START:entries
<li><a id="%seq_id%_link" href="index.html?a=%seq_id%&name=%name%" onclick="loadIndexContent('%href%','%seq_id%','%name%', '%scope%');">%name%</a><small>%scope%</small></li>
END:entries
</ul>
HTML
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = <<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="description" content="A nifty way to interact with the Merb API" />
<meta name="author" content="created by Brian Chamberlain. You can contact me using 'blchamberlain' on the gmail." />
<meta name="keywords" content="merb, ruby, purple, monkey, dishwasher" />
<title>Merb | %title% API Documentation</title>
<link rel="stylesheet" href="http://merbivore.com/documentation/stylesheet.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://merbivore.com/documentation/prototype.js" ></script>
<script type="text/javascript" src="http://merbivore.com/documentation/api_grease.js" ></script>
</head>
<body onload="setupPage();">
<ul id="groupType">
<li>methods</li>
<li>classes</li>
<li>files</li>
<li id="loadingStatus" style="display:none;"> loading...</li>
</ul>
<div id="listFrame">
<div id="listSearch">
<form id="searchForm" method="get" action="#" onsubmit="return false">
<input type="text" name="searchText" id="searchTextField" size="30" autocomplete="off" />
</form>
</div>
<div id="listScroller">
Loading via ajax... this could take a sec.
</div>
</div>
<div id="browserBar">
<span id="browserBarInfo">%title% README</span>
</div>
<div id="rdocContent">
%content%
</div>
<div id="floater">
<strong>Documentation for %title% </strong><a href="#" onmouseover="$('tips').show();" onmouseout="$('tips').hide();">usage tips</a>
<div id="tips" style="position:absolute;width:350px;top:15px;right:20px;padding:5px;border:1px solid #333;background-color:#fafafa;display:none;">
<p><strong>Some tips</strong>
<ul>
<li> Up/Down keys move through the search list</li>
<li> Return/enter key loads selected item</li>
<li> Want to use this RDOC template for your own project? Check out <br /> http://rubyforge.org/projects/jaxdoc</li>
</ul>
</p>
</div>
<div id="blowOutListBox" style="display:none;"> </div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-3085184-1";
urchinTracker();
</script>
</body>
</html>
HTML
API_GREASE_JS = File.read(File.join(File.dirname(__FILE__), 'api_grease.js'))
PROTOTYPE_JS = File.read(File.join(File.dirname(__FILE__), 'prototype.js'))
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/merb/session/session.rb | merb/session/session.rb | module Merb
module Session
# The Merb::Session module gets mixed into Merb::SessionContainer to allow
# app-level functionality; it will be included and methods will be available
# through request.session as instance methods.
end
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/merb/merb-auth/strategies.rb | merb/merb-auth/strategies.rb | # This file is specifically for you to define your strategies
#
# You should declare you strategies directly and/or use
# Merb::Authentication.activate!(:label_of_strategy)
#
# To load and set the order of strategy processing
Merb::Slices::config[:"merb-auth-slice-password"][:no_default_strategies] = true
Merb::Authentication.activate!(:default_password_form)
Merb::Authentication.activate!(:default_basic_auth)
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
mleung/feather | https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/merb/merb-auth/setup.rb | merb/merb-auth/setup.rb | # This file is specifically setup for use with the merb-auth plugin.
# This file should be used to setup and configure your authentication stack.
# It is not required and may safely be deleted.
#
# To change the parameter names for the password or login field you may set either of these two options
#
# Merb::Plugins.config[:"merb-auth"][:login_param] = :email
# Merb::Plugins.config[:"merb-auth"][:password_param] = :my_password_field_name
begin
# Sets the default class ofr authentication. This is primarily used for
# Plugins and the default strategies
Merb::Authentication.user_class = User
# Mixin the salted user mixin
require 'merb-auth-more/mixins/salted_user'
Merb::Authentication.user_class.class_eval{ include Merb::Authentication::Mixins::SaltedUser }
# Setup the session serialization
class Merb::Authentication
def fetch_user(session_user_id)
Merb::Authentication.user_class.get(session_user_id)
end
def store_user(user)
user.nil? ? user : user.id
end
end
rescue
Merb.logger.error <<-TEXT
You need to setup some kind of user class with merb-auth.
Merb::Authentication.user_class = User
If you want to fully customize your authentication you should use merb-core directly.
See merb/merb-auth/setup.rb and strategies.rb to customize your setup
TEXT
end
| ruby | MIT | 8039b8a99883597deeb3d03f67216755f101f667 | 2026-01-04T17:49:41.524706Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/tasks/changelog.rb | tasks/changelog.rb | # frozen_string_literal: true
# Changelog utility
class Changelog # rubocop:disable Metrics/ClassLength
ENTRIES_PATH = 'changelog/'
FIRST_HEADER = /#{Regexp.escape("## master (unreleased)\n")}/m.freeze
ENTRIES_PATH_TEMPLATE = "#{ENTRIES_PATH}%<type>s_%<name>s.md"
TYPE_REGEXP = /#{Regexp.escape(ENTRIES_PATH)}([a-z]+)_/.freeze
TYPE_TO_HEADER = { new: 'New features', fix: 'Bug fixes', change: 'Changes' }.freeze
HEADER = /### (.*)/.freeze
PATH = 'CHANGELOG.md'
REF_URL = 'https://github.com/rubocop/rubocop-ast'
MAX_LENGTH = 40
CONTRIBUTOR = '[@%<user>s]: https://github.com/%<user>s'
SIGNATURE = Regexp.new(format(Regexp.escape("([@%<user>s][])\n"), user: '(\w+)'))
# New entry
Entry = Struct.new(:type, :body, :ref_type, :ref_id, :user, keyword_init: true) do
def initialize(type:, body: last_commit_title, ref_type: :pull, ref_id: nil, user: github_user)
id, body = extract_id(body)
ref_id ||= id || 'x'
super
end
def write
FileUtils.mkdir_p(ENTRIES_PATH)
File.write(path, content)
path
end
def path
format(ENTRIES_PATH_TEMPLATE, type: type, name: str_to_filename(body))
end
def content
period = '.' unless body.end_with? '.'
"* #{ref}: #{body}#{period} ([@#{user}][])\n"
end
def ref
"[##{ref_id}](#{REF_URL}/#{ref_type}/#{ref_id})"
end
def last_commit_title
`git log -1 --pretty=%B`.lines.first.chomp
end
def extract_id(body)
/^\[Fixes #(\d+)\] (.*)/.match(body)&.captures || [nil, body]
end
def str_to_filename(str)
str
.downcase
.split
.each { |s| s.gsub!(/\W/, '') }
.reject(&:empty?)
.inject do |result, word|
s = "#{result}_#{word}"
return result if s.length > MAX_LENGTH
s
end
end
def github_user
user = `git config --global credential.username`.chomp
if user.empty?
warn 'Set your username with `git config --global credential.username "myusernamehere"`'
end
user
end
end
def self.pending?
entry_paths.any?
end
def self.entry_paths
Dir["#{ENTRIES_PATH}*"]
end
def self.read_entries
entry_paths.to_h do |path|
[path, File.read(path)]
end
end
attr_reader :header, :rest
def initialize(content: File.read(PATH), entries: Changelog.read_entries)
require 'strscan'
parse(content)
@entries = entries
end
def and_delete!
@entries.each_key do |path|
File.delete(path)
end
end
def merge!
File.write(PATH, merge_content)
self
end
def unreleased_content
entry_map = parse_entries(@entries)
merged_map = merge_entries(entry_map)
merged_map.flat_map do |header, things|
[
"### #{header}\n",
*things,
''
]
end.join("\n")
end
def merge_content
[
@header,
unreleased_content,
@rest,
*new_contributor_lines
].join("\n")
end
def new_contributor_lines
unique_contributor_names = contributors.map { |user| format(CONTRIBUTOR, user: user) }.uniq
unique_contributor_names.reject { |line| @rest.include?(line) }
end
def contributors
@entries.values.join("\n")
.scan(SIGNATURE).flatten
end
private
def merge_entries(entry_map)
all = @unreleased.merge(entry_map) { |_k, v1, v2| v1.concat(v2) }
canonical = TYPE_TO_HEADER.values.to_h { |v| [v, nil] }
canonical.merge(all).compact
end
def parse(content)
ss = StringScanner.new(content)
@header = ss.scan_until(FIRST_HEADER)
@unreleased = parse_release(ss.scan_until(/\n(?=## )/m))
@rest = ss.rest
end
# @return [Hash<type, Array<String>]]
def parse_release(unreleased)
unreleased
.lines
.map(&:chomp)
.reject(&:empty?)
.slice_before(HEADER)
.to_h do |header, *entries|
[HEADER.match(header)[1], entries]
end
end
def parse_entries(path_content_map)
changes = Hash.new { |h, k| h[k] = [] }
path_content_map.each do |path, content|
header = TYPE_TO_HEADER.fetch(TYPE_REGEXP.match(path)[1].to_sym)
changes[header].concat(content.lines.map(&:chomp))
end
changes
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'yaml'
$VERBOSE = true
if ENV.fetch('COVERAGE', 'f').start_with? 't'
require 'simplecov'
SimpleCov.start
end
ENV['RUBOCOP_DEBUG'] = 't'
require 'rubocop-ast'
if ENV['MODERNIZE']
RuboCop::AST::Builder.modernize
RuboCop::AST::Builder.emit_forward_arg = false # inverse of default
RuboCop::AST::Builder.emit_match_pattern = false # inverse of default
end
RSpec.shared_context 'ruby 2.3', :ruby23 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.3 }
end
RSpec.shared_context 'ruby 2.4', :ruby24 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.4 }
end
RSpec.shared_context 'ruby 2.5', :ruby25 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.5 }
end
RSpec.shared_context 'ruby 2.6', :ruby26 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.6 }
end
RSpec.shared_context 'ruby 2.7', :ruby27 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.7 }
end
RSpec.shared_context 'ruby 3.0', :ruby30 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 3.0 }
end
RSpec.shared_context 'ruby 3.1', :ruby31 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 3.1 }
end
RSpec.shared_context 'ruby 3.2', :ruby32 do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 3.2 }
end
RSpec.shared_context 'ruby 3.3', :ruby33 do
let(:ruby_version) { 3.3 }
end
RSpec.shared_context 'ruby 3.4', :ruby34 do
# Parser supports parsing Ruby <= 3.3.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.4 : 3.3 }
end
RSpec.shared_context 'ruby 4.0', :ruby40 do
# Parser supports parsing Ruby <= 3.3.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 4.0 : 3.3 }
end
RSpec.shared_context 'ruby 4.1', :ruby41 do
# Parser supports parsing Ruby <= 3.3.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 4.1 : 3.3 }
end
# ...
module DefaultRubyVersion
extend RSpec::SharedContext
# The minimum version Prism can parse is 3.3.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.4 }
end
module DefaultParserEngine
extend RSpec::SharedContext
let(:parser_engine) { ENV.fetch('PARSER_ENGINE', :parser_whitequark).to_sym }
end
module RuboCop
module AST
# patch class
class ProcessedSource
attr_accessor :node
end
end
end
# ...
module ParseSourceHelper
def parse_source(source)
lookup = nil
ruby = source.gsub(/>>(.*)<</) { lookup = Regexp.last_match(1).strip }
source = RuboCop::AST::ProcessedSource.new(ruby, ruby_version, nil, parser_engine: parser_engine)
source.node = if lookup
source.ast.each_node.find(
-> { raise "No node corresponds to source '#{lookup}'" }
) { |node| node.source == lookup }
else
source.ast
end
source
end
end
RSpec.configure do |config|
config.include ParseSourceHelper
config.include DefaultRubyVersion
config.include DefaultParserEngine
config.shared_context_metadata_behavior = :apply_to_host_groups
config.filter_run_when_matching :focus
config.example_status_persistence_file_path = 'spec/examples.txt'
config.disable_monkey_patching!
config.warnings = true
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
config.filter_run_excluding broken_on: :prism if ENV['PARSER_ENGINE'] == 'parser_prism'
config.filter_run_excluding broken_on: :parser if ENV['PARSER_ENGINE'] != 'parser_prism'
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/tasks/changelog_spec.rb | spec/tasks/changelog_spec.rb | # frozen_string_literal: true
require_relative '../../tasks/changelog'
RSpec.describe Changelog do
subject(:changelog) do
list = entries.to_h { |e| [e.path, e.content] }
described_class.new(content: <<~CHANGELOG, entries: list)
# Change log
## master (unreleased)
### New features
* [#bogus] Bogus feature
* [#bogus] Other bogus feature
## 0.7.1 (2020-09-28)
### Bug fixes
* [#127](https://github.com/rubocop/rubocop-ast/pull/127): Fix dependency issue for JRuby. ([@marcandre][])
## 0.7.0 (2020-09-27)
### New features
* [#105](https://github.com/rubocop/rubocop-ast/pull/105): `NodePattern` stuff...
* [#109](https://github.com/rubocop/rubocop-ast/pull/109): Add `NodePattern` debugging rake tasks: `test_pattern`, `compile`, `parse`. See also [this app](https://nodepattern.herokuapp.com) ([@marcandre][])
* [#110](https://github.com/rubocop/rubocop-ast/pull/110): Add `NodePattern` support for multiple terms unions. ([@marcandre][])
* [#111](https://github.com/rubocop/rubocop-ast/pull/111): Optimize some `NodePattern`s by using `Set`s. ([@marcandre][])
* [#112](https://github.com/rubocop/rubocop-ast/pull/112): Add `NodePattern` support for Regexp literals. ([@marcandre][])
more stuf....
[@marcandre]: https://github.com/marcandre
[@johndoexx]: https://github.com/johndoexx
CHANGELOG
end
let(:duplicate_entry) do
described_class::Entry.new(type: :fix, body: 'Duplicate contributor name entry', user: 'johndoe')
end
let(:entries) do
%i[fix new fix].map.with_index do |type, i|
described_class::Entry.new(type: type, body: "Do something cool#{'x' * i}",
user: "johndoe#{'x' * i}")
end << duplicate_entry
end
let(:entry) { entries.first }
it 'Changelog::Entry generates correct content' do
expect(entry.content).to eq <<~MD
* [#x](https://github.com/rubocop/rubocop-ast/pull/x): Do something cool. ([@johndoe][])
MD
end
it 'parses correctly' do
expect(changelog.rest).to start_with('## 0.7.1 (2020-09-28)')
end
it 'merges correctly' do
expect(changelog.unreleased_content).to eq(<<~CHANGELOG)
### New features
* [#bogus] Bogus feature
* [#bogus] Other bogus feature
* [#x](https://github.com/rubocop/rubocop-ast/pull/x): Do something coolx. ([@johndoex][])
### Bug fixes
* [#x](https://github.com/rubocop/rubocop-ast/pull/x): Do something cool. ([@johndoe][])
* [#x](https://github.com/rubocop/rubocop-ast/pull/x): Do something coolxx. ([@johndoexx][])
* [#x](https://github.com/rubocop/rubocop-ast/pull/x): Duplicate contributor name entry. ([@johndoe][])
CHANGELOG
expect(changelog.new_contributor_lines).to eq(
[
'[@johndoe]: https://github.com/johndoe',
'[@johndoex]: https://github.com/johndoex'
]
)
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/simple_forwardable_spec.rb | spec/rubocop/simple_forwardable_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::SimpleForwardable do
let(:delegator) do
Class.new do
attr_reader :target
def initialize
@target = Struct.new(:foo).new
end
extend RuboCop::SimpleForwardable
def_delegators :target, :foo=, :foo
end
end
it 'correctly delegates to writer methods' do
d = delegator.new
d.foo = 123
expect(d.foo).to eq(123)
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/rescue_node_spec.rb | spec/rubocop/ast/rescue_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::RescueNode do
subject(:ast) { parse_source(source).ast }
let(:rescue_node) { ast.children.first }
describe '.new' do
let(:source) { <<~RUBY }
begin
rescue => e
end
RUBY
it { expect(rescue_node).to be_a(described_class) }
end
describe '#body' do
let(:source) { <<~RUBY }
begin
foo
rescue => e
end
RUBY
it { expect(rescue_node.body).to be_send_type }
context 'with multiple lines in body' do
let(:source) { <<~RUBY }
begin
foo
bar
rescue => e
baz
end
RUBY
it { expect(rescue_node.body).to be_begin_type }
end
end
describe '#resbody_branches' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
rescue BarError, BazError then bar_and_baz
end
RUBY
it { expect(rescue_node.resbody_branches.size).to eq(2) }
it { expect(rescue_node.resbody_branches).to all(be_resbody_type) }
end
describe '#branches' do
context 'when there is an else' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
rescue BarError then # do nothing
else 'bar'
end
RUBY
it 'returns all the bodies' do
expect(rescue_node.branches).to match [be_send_type, nil, be_str_type]
end
context 'with an empty else' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
rescue BarError then # do nothing
else # do nothing
end
RUBY
it 'returns all the bodies' do
expect(rescue_node.branches).to match [be_send_type, nil, nil]
end
end
end
context 'when there is no else keyword' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
rescue BarError then # do nothing
end
RUBY
it 'returns only then rescue bodies' do
expect(rescue_node.branches).to match [be_send_type, nil]
end
end
end
describe '#else_branch' do
context 'without an else statement' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
end
RUBY
it { expect(rescue_node.else_branch).to be_nil }
end
context 'with an else statement' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
else bar
end
RUBY
it { expect(rescue_node.else_branch).to be_send_type }
end
end
describe '#else?' do
context 'without an else statement' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
end
RUBY
it { expect(rescue_node).not_to be_else }
end
context 'with an else statement' do
let(:source) { <<~RUBY }
begin
rescue FooError then foo
else bar
end
RUBY
it { expect(rescue_node).to be_else }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/range_node_spec.rb | spec/rubocop/ast/range_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::RangeNode do
subject(:range_node) { parse_source(source).ast }
describe '.new' do
context 'with an inclusive range' do
let(:source) do
'1..2'
end
it { is_expected.to be_a(described_class) }
it { is_expected.to be_range_type }
end
context 'with an exclusive range' do
let(:source) do
'1...2'
end
it { is_expected.to be_a(described_class) }
it { is_expected.to be_range_type }
end
context 'with an infinite range', :ruby26 do
let(:source) do
'1..'
end
it { is_expected.to be_a(described_class) }
it { is_expected.to be_range_type }
end
context 'with a beignless range', :ruby27 do
let(:source) do
'..42'
end
it { is_expected.to be_a(described_class) }
it { is_expected.to be_range_type }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/and_asgn_node_spec.rb | spec/rubocop/ast/and_asgn_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::AndAsgnNode do
let(:or_asgn_node) { parse_source(source).ast }
let(:source) { 'var &&= value' }
describe '.new' do
it { expect(or_asgn_node).to be_a(described_class) }
end
describe '#assignment_node' do
subject { or_asgn_node.assignment_node }
it { is_expected.to be_a(RuboCop::AST::AsgnNode) }
end
describe '#name' do
subject { or_asgn_node.name }
it { is_expected.to eq(:var) }
end
describe '#operator' do
subject { or_asgn_node.operator }
it { is_expected.to eq(:'&&') }
end
describe '#expression' do
include AST::Sexp
subject { or_asgn_node.expression }
it { is_expected.to eq(s(:send, nil, :value)) }
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/until_node_spec.rb | spec/rubocop/ast/until_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::UntilNode do
subject(:until_node) { parse_source(source).ast }
describe '.new' do
context 'with a statement until' do
let(:source) { 'until foo; bar; end' }
it { is_expected.to be_a(described_class) }
end
context 'with a modifier until' do
let(:source) { 'begin foo; end until bar' }
it { is_expected.to be_a(described_class) }
end
end
describe '#keyword' do
let(:source) { 'until foo; bar; end' }
it { expect(until_node.keyword).to eq('until') }
end
describe '#inverse_keyword' do
let(:source) { 'until foo; bar; end' }
it { expect(until_node.inverse_keyword).to eq('while') }
end
describe '#do?' do
context 'with a do keyword' do
let(:source) { 'until foo do; bar; end' }
it { is_expected.to be_do }
end
context 'without a do keyword' do
let(:source) { 'until foo; bar; end' }
it { is_expected.not_to be_do }
end
end
describe '#post_condition_loop?' do
context 'with a statement until' do
let(:source) { 'until foo; bar; end' }
it { is_expected.not_to be_post_condition_loop }
end
context 'with a modifier until' do
let(:source) { 'begin foo; end until bar' }
it { is_expected.to be_post_condition_loop }
end
end
describe '#loop_keyword?' do
context 'with a statement until' do
let(:source) { 'until foo; bar; end' }
it { is_expected.to be_loop_keyword }
end
context 'with a modifier until' do
let(:source) { 'begin foo; end until bar' }
it { is_expected.to be_loop_keyword }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/in_pattern_node_spec.rb | spec/rubocop/ast/in_pattern_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::InPatternNode do
context 'when using Ruby 2.7 or newer', :ruby27 do
let(:in_pattern_node) { parse_source(source).ast.children[1] }
describe '.new' do
let(:source) do
['case condition',
'in [42] then foo',
'end'].join("\n")
end
it { expect(in_pattern_node).to be_a(described_class) }
end
describe '#pattern' do
context 'with a value pattern' do
let(:source) do
['case condition',
'in 42 then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_int_type }
end
context 'with a variable pattern' do
let(:source) do
['case condition',
'in var then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_match_var_type }
end
context 'with an alternative pattern' do
let(:source) do
['case condition',
'in :foo | :bar | :baz then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_match_alt_type }
end
context 'with an as pattern' do
let(:source) do
['case condition',
'in Integer => var then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_match_as_type }
end
context 'with an array pattern' do
let(:source) do
['case condition',
'in :foo, :bar, :baz then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_array_pattern_type }
end
context 'with a hash pattern' do
let(:source) do
['case condition',
'in foo:, bar:, baz: then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_hash_pattern_type }
end
context 'with a pin operator', :ruby31 do
let(:source) do
['case condition',
'in ^(2 + 2) then foo',
'end'].join("\n")
end
it { expect(in_pattern_node.pattern).to be_pin_type }
end
end
describe '#then?' do
context 'with a then keyword' do
let(:source) do
['case condition',
'in [42] then foo',
'end'].join("\n")
end
it { expect(in_pattern_node).to be_then }
end
context 'without a then keyword' do
let(:source) do
['case condition',
'in [42]',
' foo',
'end'].join("\n")
end
it { expect(in_pattern_node).not_to be_then }
end
end
describe '#body' do
context 'with a then keyword' do
let(:source) do
['case condition',
'in [42] then :foo',
'end'].join("\n")
end
it { expect(in_pattern_node.body).to be_sym_type }
end
context 'without a then keyword' do
let(:source) do
['case condition',
'in [42]',
' [:foo, :bar]',
'end'].join("\n")
end
it { expect(in_pattern_node.body).to be_array_type }
end
end
describe '#branch_index' do
let(:source) do
['case condition',
'in [42] then 1',
'in [43] then 2',
'in [44] then 3',
'end'].join("\n")
end
let(:in_patterns) { parse_source(source).ast.children[1...-1] }
it { expect(in_patterns[0].branch_index).to eq(0) }
it { expect(in_patterns[1].branch_index).to eq(1) }
it { expect(in_patterns[2].branch_index).to eq(2) }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/keyword_begin_node_spec.rb | spec/rubocop/ast/keyword_begin_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::KeywordBeginNode do
let(:parsed_source) { parse_source(source) }
let(:kwbegin_node) { parsed_source.ast }
describe '.new' do
let(:source) do
<<~RUBY
begin
foo
end
RUBY
end
it { expect(kwbegin_node).to be_a(described_class) }
end
describe '#body' do
subject(:body) { kwbegin_node.body }
let(:node) { parsed_source.node }
context 'when the `kwbegin` node is empty' do
let(:source) do
<<~RUBY
begin
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when the `kwbegin` node only contains a single line' do
let(:source) do
<<~RUBY
begin
>> foo <<
end
RUBY
end
it { is_expected.to eq(node) }
end
context 'when the body has multiple lines' do
let(:source) do
<<~RUBY
begin
foo
bar
end
RUBY
end
it 'returns the entire `kwbegin` node' do
expect(body).to eq(kwbegin_node)
end
end
context 'when there is a `rescue` node' do
let(:source) do
<<~RUBY
begin
>>foo<<
rescue
bar
end
RUBY
end
it { is_expected.to eq(node) }
end
context 'when there is an `ensure` node' do
let(:source) do
<<~RUBY
begin
>>foo<<
ensure
bar
end
RUBY
end
it { is_expected.to eq(node) }
end
context 'when there is a `rescue` and `ensure` node' do
let(:source) do
<<~RUBY
begin
>>foo<<
rescue
bar
ensure
baz
end
RUBY
end
it { is_expected.to eq(node) }
end
end
describe '#ensure_node' do
subject(:ensure_node) { kwbegin_node.ensure_node }
context 'when the `kwbegin` node is empty' do
let(:source) do
<<~RUBY
begin
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when the `kwbegin` node only contains a single line' do
let(:source) do
<<~RUBY
begin
foo
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when the body has multiple lines' do
let(:source) do
<<~RUBY
begin
foo
bar
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when there is a `rescue` node without `ensure`' do
let(:source) do
<<~RUBY
begin
foo
rescue
bar
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when there is an `ensure` node' do
let(:source) do
<<~RUBY
begin
foo
ensure
bar
end
RUBY
end
it { is_expected.to be_a(RuboCop::AST::EnsureNode) }
end
context 'when there is a `rescue` and `ensure` node' do
let(:source) do
<<~RUBY
begin
foo
rescue
bar
ensure
baz
end
RUBY
end
it { is_expected.to be_a(RuboCop::AST::EnsureNode) }
end
end
describe '#rescue_node' do
subject(:rescue_node) { kwbegin_node.rescue_node }
context 'when the `kwbegin` node is empty' do
let(:source) do
<<~RUBY
begin
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when the `kwbegin` node only contains a single line' do
let(:source) do
<<~RUBY
begin
foo
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when the body has multiple lines' do
let(:source) do
<<~RUBY
begin
foo
bar
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when there is a `rescue` node without `ensure`' do
let(:source) do
<<~RUBY
begin
foo
rescue
bar
end
RUBY
end
it { is_expected.to be_a(RuboCop::AST::RescueNode) }
end
context 'when there is an `ensure` node without `rescue`' do
let(:source) do
<<~RUBY
begin
foo
ensure
bar
end
RUBY
end
it { is_expected.to be_nil }
end
context 'when there is a `rescue` and `ensure` node' do
let(:source) do
<<~RUBY
begin
foo
rescue
bar
ensure
baz
end
RUBY
end
it { is_expected.to be_a(RuboCop::AST::RescueNode) }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/when_node_spec.rb | spec/rubocop/ast/when_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::WhenNode do
let(:when_node) { parse_source(source).ast.children[1] }
describe '.new' do
let(:source) do
['case',
'when :foo then bar',
'end'].join("\n")
end
it { expect(when_node).to be_a(described_class) }
end
describe '#conditions' do
context 'with a single condition' do
let(:source) do
['case',
'when :foo then bar',
'end'].join("\n")
end
it { expect(when_node.conditions.size).to eq(1) }
it { expect(when_node.conditions).to all(be_literal) }
end
context 'with a multiple conditions' do
let(:source) do
['case',
'when :foo, :bar, :baz then bar',
'end'].join("\n")
end
it { expect(when_node.conditions.size).to eq(3) }
it { expect(when_node.conditions).to all(be_literal) }
end
end
describe '#each_condition' do
let(:source) do
['case',
'when :foo, :bar, :baz then bar',
'end'].join("\n")
end
context 'when not passed a block' do
it { expect(when_node.each_condition).to be_a(Enumerator) }
end
context 'when passed a block' do
it 'yields all the conditions' do
expect { |b| when_node.each_condition(&b) }
.to yield_successive_args(*when_node.conditions)
end
end
end
describe '#then?' do
context 'with a then keyword' do
let(:source) do
['case',
'when :foo then bar',
'end'].join("\n")
end
it { expect(when_node).to be_then }
end
context 'without a then keyword' do
let(:source) do
['case',
'when :foo',
' bar',
'end'].join("\n")
end
it { expect(when_node).not_to be_then }
end
end
describe '#body' do
context 'with a then keyword' do
let(:source) do
['case',
'when :foo then :bar',
'end'].join("\n")
end
it { expect(when_node.body).to be_sym_type }
end
context 'without a then keyword' do
let(:source) do
['case',
'when :foo',
' [:bar, :baz]',
'end'].join("\n")
end
it { expect(when_node.body).to be_array_type }
end
end
describe '#branch_index' do
let(:source) do
['case',
'when :foo then 1',
'when :bar then 2',
'when :baz then 3',
'end'].join("\n")
end
let(:whens) { parse_source(source).ast.children[1...-1] }
it { expect(whens[0].branch_index).to eq(0) }
it { expect(whens[1].branch_index).to eq(1) }
it { expect(whens[2].branch_index).to eq(2) }
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/or_asgn_node_spec.rb | spec/rubocop/ast/or_asgn_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::OrAsgnNode do
let(:or_asgn_node) { parse_source(source).ast }
let(:source) { 'var ||= value' }
describe '.new' do
it { expect(or_asgn_node).to be_a(described_class) }
end
describe '#assignment_node' do
subject { or_asgn_node.assignment_node }
it { is_expected.to be_a(RuboCop::AST::AsgnNode) }
end
describe '#name' do
subject { or_asgn_node.name }
it { is_expected.to eq(:var) }
end
describe '#operator' do
subject { or_asgn_node.operator }
it { is_expected.to eq(:'||') }
end
describe '#expression' do
include AST::Sexp
subject { or_asgn_node.expression }
it { is_expected.to eq(s(:send, nil, :value)) }
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/for_node_spec.rb | spec/rubocop/ast/for_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::ForNode do
subject(:for_node) { parse_source(source).ast }
describe '.new' do
let(:source) { 'for foo in bar; baz; end' }
it { is_expected.to be_a(described_class) }
end
describe '#keyword' do
let(:source) { 'for foo in bar; baz; end' }
it { expect(for_node.keyword).to eq('for') }
end
describe '#do?' do
context 'with a do keyword' do
let(:source) { 'for foo in bar do baz; end' }
it { is_expected.to be_do }
end
context 'without a do keyword' do
let(:source) { 'for foo in bar; baz; end' }
it { is_expected.not_to be_do }
end
end
describe '#void_context?' do
context 'with a do keyword' do
let(:source) { 'for foo in bar do baz; end' }
it { is_expected.to be_void_context }
end
context 'without a do keyword' do
let(:source) { 'for foo in bar; baz; end' }
it { is_expected.to be_void_context }
end
end
describe '#variable' do
let(:source) { 'for foo in :bar; :baz; end' }
it { expect(for_node.variable).to be_lvasgn_type }
end
describe '#collection' do
let(:source) { 'for foo in :bar; baz; end' }
it { expect(for_node.collection).to be_sym_type }
end
describe '#body' do
let(:source) { 'for foo in bar; :baz; end' }
it { expect(for_node.body).to be_sym_type }
end
describe '#post_condition_loop?' do
let(:source) { 'for foo in bar; baz; end' }
it { is_expected.not_to be_post_condition_loop }
end
describe '#loop_keyword?' do
let(:source) { 'for foo in bar; baz; end' }
it { is_expected.to be_loop_keyword }
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/str_node_spec.rb | spec/rubocop/ast/str_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::StrNode do
subject(:str_node) { parsed_source.ast }
let(:parsed_source) { parse_source(source) }
describe '.new' do
context 'with a normal string' do
let(:source) { "'foo'" }
it { is_expected.to be_a(described_class) }
end
context 'with a string with interpolation' do
let(:source) { '"#{foo}"' }
it { is_expected.to be_a(described_class) }
end
context 'with a heredoc' do
let(:source) do
<<~RUBY
<<-CODE
foo
bar
CODE
RUBY
end
it { is_expected.to be_a(described_class) }
end
end
describe '#single_quoted?' do
context 'with a single-quoted string' do
let(:source) { "'foo'" }
it { is_expected.to be_single_quoted }
end
context 'with a double-quoted string' do
let(:source) { '"foo"' }
it { is_expected.not_to be_single_quoted }
end
context 'with a %() delimited string' do
let(:source) { '%(foo)' }
it { is_expected.not_to be_single_quoted }
end
context 'with a %q() delimited string' do
let(:source) { '%q(foo)' }
it { is_expected.not_to be_single_quoted }
end
context 'with a %Q() delimited string' do
let(:source) { '%Q(foo)' }
it { is_expected.not_to be_single_quoted }
end
context 'with a character literal' do
let(:source) { '?x' }
it { is_expected.not_to be_single_quoted }
end
context 'with an undelimited string within another node' do
subject(:str_node) { parsed_source.ast.child_nodes.first }
let(:source) { '/string/' }
it { is_expected.not_to be_single_quoted }
end
end
describe '#double_quoted?' do
context 'with a single-quoted string' do
let(:source) { "'foo'" }
it { is_expected.not_to be_double_quoted }
end
context 'with a double-quoted string' do
let(:source) { '"foo"' }
it { is_expected.to be_double_quoted }
end
context 'with a %() delimited string' do
let(:source) { '%(foo)' }
it { is_expected.not_to be_double_quoted }
end
context 'with a %q() delimited string' do
let(:source) { '%q(foo)' }
it { is_expected.not_to be_double_quoted }
end
context 'with a %Q() delimited string' do
let(:source) { '%Q(foo)' }
it { is_expected.not_to be_double_quoted }
end
context 'with a character literal' do
let(:source) { '?x' }
it { is_expected.not_to be_double_quoted }
end
context 'with an undelimited string within another node' do
subject(:str_node) { parsed_source.ast.child_nodes.first }
let(:source) { '/string/' }
it { is_expected.not_to be_single_quoted }
end
end
describe '#character_literal?' do
context 'with a character literal' do
let(:source) { '?\n' }
it { is_expected.to be_character_literal }
end
context 'with a normal string literal' do
let(:source) { '"\n"' }
it { is_expected.not_to be_character_literal }
end
context 'with a heredoc' do
let(:source) do
<<~RUBY
<<-CODE
foo
bar
CODE
RUBY
end
it { is_expected.not_to be_character_literal }
end
end
describe '#heredoc?' do
context 'with a normal string' do
let(:source) { "'foo'" }
it { is_expected.not_to be_heredoc }
end
context 'with a string with interpolation' do
let(:source) { '"#{foo}"' }
it { is_expected.not_to be_heredoc }
end
context 'with a heredoc' do
let(:source) do
<<~RUBY
<<-CODE
foo
bar
CODE
RUBY
end
it { is_expected.to be_heredoc }
end
end
describe '#percent_literal?' do
context 'with a single-quoted string' do
let(:source) { "'foo'" }
it { is_expected.not_to be_percent_literal }
it { is_expected.not_to be_percent_literal(:%) }
it { is_expected.not_to be_percent_literal(:q) }
it { is_expected.not_to be_percent_literal(:Q) }
end
context 'with a double-quoted string' do
let(:source) { '"foo"' }
it { is_expected.not_to be_percent_literal }
it { is_expected.not_to be_percent_literal(:%) }
it { is_expected.not_to be_percent_literal(:q) }
it { is_expected.not_to be_percent_literal(:Q) }
end
context 'with a %() delimited string' do
let(:source) { '%(foo)' }
it { is_expected.to be_percent_literal }
it { is_expected.to be_percent_literal(:%) }
it { is_expected.not_to be_percent_literal(:q) }
it { is_expected.not_to be_percent_literal(:Q) }
end
context 'with a %q() delimited string' do
let(:source) { '%q(foo)' }
it { is_expected.to be_percent_literal }
it { is_expected.not_to be_percent_literal(:%) }
it { is_expected.to be_percent_literal(:q) }
it { is_expected.not_to be_percent_literal(:Q) }
end
context 'with a %Q() delimited string' do
let(:source) { '%Q(foo)' }
it { is_expected.to be_percent_literal }
it { is_expected.not_to be_percent_literal(:%) }
it { is_expected.not_to be_percent_literal(:q) }
it { is_expected.to be_percent_literal(:Q) }
end
context 'with a character literal?' do
let(:source) { '?x' }
it { is_expected.not_to be_percent_literal }
it { is_expected.not_to be_percent_literal(:%) }
it { is_expected.not_to be_percent_literal(:q) }
it { is_expected.not_to be_percent_literal(:Q) }
end
context 'with an undelimited string within another node' do
subject(:str_node) { parsed_source.ast.child_nodes.first }
let(:source) { '/string/' }
it { is_expected.not_to be_percent_literal }
it { is_expected.not_to be_percent_literal(:%) }
it { is_expected.not_to be_percent_literal(:q) }
it { is_expected.not_to be_percent_literal(:Q) }
end
context 'when given an invalid type' do
subject { str_node.percent_literal?(:x) }
let(:source) { '%q(foo)' }
it 'raises a KeyError' do
expect { str_node.percent_literal?(:x) }.to raise_error(KeyError, 'key not found: :x')
end
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/token_spec.rb | spec/rubocop/ast/token_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::Token do
let(:processed_source) { parse_source(source) }
let(:source) { <<~RUBY }
# comment
def some_method
[ 1, 2 ];
foo[0] = 3.to_i
1..42
1...42
end
RUBY
let(:first_token) { processed_source.tokens.first }
let(:comment_token) do
processed_source.find_token do |t|
t.text.start_with?('#') && t.line == 1
end
end
let(:left_array_bracket_token) do
processed_source.find_token { |t| t.text == '[' && t.line == 3 }
end
let(:comma_token) { processed_source.find_token { |t| t.text == ',' } }
let(:irange_token) { processed_source.find_token { |t| t.text == '..' } }
let(:erange_token) { processed_source.find_token { |t| t.text == '...' } }
let(:dot_token) { processed_source.find_token { |t| t.text == '.' } }
let(:right_array_bracket_token) do
processed_source.find_token { |t| t.text == ']' && t.line == 3 }
end
let(:semicolon_token) { processed_source.find_token { |t| t.text == ';' } }
let(:left_ref_bracket_token) do
processed_source.find_token { |t| t.text == '[' && t.line == 4 }
end
let(:zero_token) { processed_source.find_token { |t| t.text == '0' } }
let(:right_ref_bracket_token) do
processed_source.find_token { |t| t.text == ']' && t.line == 4 }
end
let(:equals_token) { processed_source.find_token { |t| t.text == '=' } }
let(:end_token) { processed_source.find_token { |t| t.text == 'end' } }
let(:new_line_token) { processed_source.find_token { |t| t.line == 7 && t.column == 3 } }
describe '.from_parser_token' do
subject(:token) { described_class.from_parser_token(parser_token) }
let(:parser_token) { [type, [text, range]] }
let(:type) { :kDEF }
let(:text) { 'def' }
let(:range) do
instance_double(Parser::Source::Range, line: 42, column: 30)
end
it "sets parser token's type to rubocop token's type" do
expect(token.type).to eq(type)
end
it "sets parser token's text to rubocop token's text" do
expect(token.text).to eq(text)
end
it "sets parser token's range to rubocop token's pos" do
expect(token.pos).to eq(range)
end
it 'returns a #to_s useful for debugging' do
expect(token.to_s).to eq('[[42, 30], kDEF, "def"]')
end
end
describe '#line' do
it 'returns line of token' do
expect(first_token.line).to eq 1
expect(zero_token.line).to eq 4
expect(end_token.line).to eq 7
end
end
describe '#column' do
it 'returns index of first char in token range on that line' do
expect(first_token.column).to eq 0
expect(zero_token.column).to eq 6
expect(end_token.column).to eq 0
end
end
describe '#begin_pos' do
it 'returns index of first char in token range of entire source' do
expect(first_token.begin_pos).to eq 0
expect(zero_token.begin_pos).to eq 44
expect(end_token.begin_pos).to eq 73
end
end
describe '#end_pos' do
it 'returns index of last char in token range of entire source' do
expect(first_token.end_pos).to eq 9
expect(zero_token.end_pos).to eq 45
expect(end_token.end_pos).to eq 76
end
end
describe '#space_after' do
it 'returns truthy MatchData when there is a space after token' do
expect(left_array_bracket_token.space_after?).to be_a(MatchData)
expect(right_ref_bracket_token.space_after?).to be_a(MatchData)
expect(left_array_bracket_token).to be_space_after
expect(right_ref_bracket_token).to be_space_after
end
it 'returns nil when there is not a space after token' do
expect(left_ref_bracket_token.space_after?).to be_nil
expect(zero_token.space_after?).to be_nil
end
end
describe '#to_s' do
it 'returns string of token data' do
expect(end_token.to_s).to include end_token.line.to_s
expect(end_token.to_s).to include end_token.column.to_s
expect(end_token.to_s).to include end_token.type.to_s
expect(end_token.to_s).to include end_token.text.to_s
end
end
describe '#space_before' do
it 'returns truthy MatchData when there is a space before token' do
expect(left_array_bracket_token.space_before?).to be_a(MatchData)
expect(equals_token.space_before?).to be_a(MatchData)
expect(left_array_bracket_token).to be_space_before
expect(equals_token).to be_space_before
end
it 'returns nil when there is not a space before token' do
expect(semicolon_token.space_before?).to be_nil
expect(zero_token.space_before?).to be_nil
end
it 'returns nil when it is on the first line' do
expect(processed_source.tokens[0].space_before?).to be_nil
end
end
context 'type predicates' do
describe '#comment?' do
it 'returns true for comment tokens' do
expect(comment_token).to be_comment
end
it 'returns false for non comment tokens' do
expect(zero_token).not_to be_comment
expect(semicolon_token).not_to be_comment
end
end
describe '#semicolon?' do
it 'returns true for semicolon tokens' do
expect(semicolon_token).to be_semicolon
end
it 'returns false for non semicolon tokens' do
expect(comment_token).not_to be_semicolon
expect(comma_token).not_to be_semicolon
end
end
describe '#left_array_bracket?' do
it 'returns true for left_array_bracket tokens' do
expect(left_array_bracket_token).to be_left_array_bracket
end
it 'returns false for non left_array_bracket tokens' do
expect(left_ref_bracket_token).not_to be_left_array_bracket
expect(right_array_bracket_token).not_to be_left_array_bracket
end
end
describe '#left_ref_bracket?' do
it 'returns true for left_ref_bracket tokens' do
expect(left_ref_bracket_token).to be_left_ref_bracket
end
it 'returns false for non left_ref_bracket tokens' do
expect(left_array_bracket_token).not_to be_left_ref_bracket
expect(right_ref_bracket_token).not_to be_left_ref_bracket
end
end
describe '#left_bracket?' do
it 'returns true for all left_bracket tokens' do
expect(left_ref_bracket_token).to be_left_bracket
expect(left_array_bracket_token).to be_left_bracket
end
it 'returns false for non left_bracket tokens' do
expect(right_ref_bracket_token).not_to be_left_bracket
expect(right_array_bracket_token).not_to be_left_bracket
end
end
describe '#right_bracket?' do
it 'returns true for all right_bracket tokens' do
expect(right_ref_bracket_token).to be_right_bracket
expect(right_array_bracket_token).to be_right_bracket
end
it 'returns false for non right_bracket tokens' do
expect(left_ref_bracket_token).not_to be_right_bracket
expect(left_array_bracket_token).not_to be_right_bracket
end
end
describe '#left_brace?' do
it 'returns true for right_bracket tokens' do
expect(right_ref_bracket_token).to be_right_bracket
expect(right_array_bracket_token).to be_right_bracket
end
it 'returns false for non right_bracket tokens' do
expect(left_ref_bracket_token).not_to be_right_bracket
expect(left_array_bracket_token).not_to be_right_bracket
end
end
describe '#comma?' do
it 'returns true for comma tokens' do
expect(comma_token).to be_comma
end
it 'returns false for non comma tokens' do
expect(semicolon_token).not_to be_comma
expect(right_ref_bracket_token).not_to be_comma
end
end
describe '#dot?' do
it 'returns true for dot tokens' do
expect(dot_token).to be_dot
end
it 'returns false for non dot tokens' do
expect(semicolon_token).not_to be_dot
expect(right_ref_bracket_token).not_to be_dot
end
end
describe '#regexp_dots?' do
it 'returns true for regexp tokens' do
expect(irange_token).to be_regexp_dots
expect(erange_token).to be_regexp_dots
end
it 'returns false for non comma tokens' do
expect(semicolon_token).not_to be_regexp_dots
expect(right_ref_bracket_token).not_to be_regexp_dots
end
end
describe '#rescue_modifier?' do
let(:source) { <<~RUBY }
def foo
bar rescue qux
end
RUBY
let(:rescue_modifier_token) do
processed_source.find_token { |t| t.text == 'rescue' }
end
it 'returns true for rescue modifier tokens' do
expect(rescue_modifier_token).to be_rescue_modifier
end
it 'returns false for non rescue modifier tokens' do
expect(first_token).not_to be_rescue_modifier
expect(end_token).not_to be_rescue_modifier
end
end
describe '#end?' do
it 'returns true for end tokens' do
expect(end_token).to be_end
end
it 'returns false for non end tokens' do
expect(semicolon_token).not_to be_end
expect(comment_token).not_to be_end
end
end
describe '#equals_sign?' do
it 'returns true for equals sign tokens' do
expect(equals_token).to be_equal_sign
end
it 'returns false for non equals sign tokens' do
expect(semicolon_token).not_to be_equal_sign
expect(comma_token).not_to be_equal_sign
end
end
describe '#new_line?' do
it 'returns true for new line tokens' do
expect(new_line_token).to be_a_new_line
end
it 'returns false for non new line tokens' do
expect(end_token).not_to be_a_new_line
expect(semicolon_token).not_to be_a_new_line
end
end
context 'with braces & parens' do
let(:source) { <<~RUBY }
{ a: 1 }
foo { |f| bar(f) }
-> { f }
RUBY
let(:left_hash_brace_token) do
processed_source.find_token { |t| t.text == '{' && t.line == 1 }
end
let(:right_hash_brace_token) do
processed_source.find_token { |t| t.text == '}' && t.line == 1 }
end
let(:left_block_brace_token) do
processed_source.find_token { |t| t.text == '{' && t.line == 2 }
end
let(:left_lambda_brace_token) do
processed_source.find_token { |t| t.text == '{' && t.line == 3 }
end
let(:left_parens_token) do
processed_source.find_token { |t| t.text == '(' }
end
let(:right_parens_token) do
processed_source.find_token { |t| t.text == ')' }
end
let(:right_block_brace_token) do
processed_source.find_token { |t| t.text == '}' && t.line == 2 }
end
describe '#left_brace?' do
it 'returns true for left hash brace tokens' do
expect(left_hash_brace_token).to be_left_brace
end
it 'returns false for non left hash brace tokens' do
expect(left_block_brace_token).not_to be_left_brace
expect(right_hash_brace_token).not_to be_left_brace
end
end
describe '#left_curly_brace?' do
it 'returns true for left block brace tokens' do
expect(left_block_brace_token).to be_left_curly_brace
expect(left_lambda_brace_token).to be_left_curly_brace
end
it 'returns false for non left block brace tokens' do
expect(left_hash_brace_token).not_to be_left_curly_brace
expect(right_block_brace_token).not_to be_left_curly_brace
end
end
describe '#right_curly_brace?' do
it 'returns true for all right brace tokens' do
expect(right_hash_brace_token).to be_right_curly_brace
expect(right_block_brace_token).to be_right_curly_brace
end
it 'returns false for non right brace tokens' do
expect(left_hash_brace_token).not_to be_right_curly_brace
expect(left_parens_token).not_to be_right_curly_brace
end
end
describe '#left_parens?' do
it 'returns true for left parens tokens' do
expect(left_parens_token).to be_left_parens
end
it 'returns false for non left parens tokens' do
expect(left_hash_brace_token).not_to be_left_parens
expect(right_parens_token).not_to be_left_parens
end
end
describe '#right_parens?' do
it 'returns true for right parens tokens' do
expect(right_parens_token).to be_right_parens
end
it 'returns false for non right parens tokens' do
expect(right_hash_brace_token).not_to be_right_parens
expect(left_parens_token).not_to be_right_parens
end
end
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/wrapped_arguments_node.rb | spec/rubocop/ast/wrapped_arguments_node.rb | # frozen_string_literal: true
RSpec.shared_examples 'wrapped arguments node' do |keyword|
subject(:return_node) { parse_source(source).ast.body }
describe '.new' do
context 'without arguments' do
let(:source) { "x { #{keyword} }" }
it { is_expected.to be_a(described_class) }
end
context 'with arguments' do
let(:source) { "x { #{keyword} :foo }" }
it { is_expected.to be_a(described_class) }
end
end
describe '#arguments' do
context 'with no arguments' do
let(:source) { "x { #{keyword} }" }
it { expect(return_node.arguments).to be_empty }
end
context 'with no arguments and braces' do
let(:source) { "x { #{keyword}() }" }
it { expect(return_node.arguments).to be_empty }
end
context 'with a single argument' do
let(:source) { "x { #{keyword} :foo }" }
it { expect(return_node.arguments.size).to eq(1) }
end
context 'with a single argument and braces' do
let(:source) { "x { #{keyword}(:foo) }" }
it { expect(return_node.arguments.size).to eq(1) }
end
context 'with a single splat argument' do
let(:source) { "x { #{keyword} *baz }" }
it { expect(return_node.arguments.size).to eq(1) }
end
context 'with multiple literal arguments' do
let(:source) { "x { #{keyword} :foo, :bar }" }
it { expect(return_node.arguments.size).to eq(2) }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/self_class_node_spec.rb | spec/rubocop/ast/self_class_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::SelfClassNode do
subject(:self_class_node) { parse_source(source).ast }
describe '.new' do
let(:source) do
'class << self; end'
end
it { is_expected.to be_a(described_class) }
end
describe '#identifier' do
let(:source) do
'class << self; end'
end
it { expect(self_class_node.identifier).to be_self_type }
end
describe '#body' do
context 'with a single expression body' do
let(:source) do
'class << self; bar; end'
end
it { expect(self_class_node.body).to be_send_type }
end
context 'with a multi-expression body' do
let(:source) do
'class << self; bar; baz; end'
end
it { expect(self_class_node.body).to be_begin_type }
end
context 'with an empty body' do
let(:source) do
'class << self; end'
end
it { expect(self_class_node.body).to be_nil }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/rational_node_spec.rb | spec/rubocop/ast/rational_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::RationalNode do
subject(:rational_node) { parse_source(source).ast }
describe '.new' do
let(:source) { '0.2r' }
it { is_expected.to be_a(described_class) }
end
describe '#sign?' do
subject { rational_node.sign? }
context 'when explicit positive rational' do
let(:source) { '+0.2r' }
it { is_expected.to be(true) }
end
context 'when explicit negative rational' do
let(:source) { '-0.2r' }
it { is_expected.to be(true) }
end
end
describe '#value' do
let(:source) do
'0.4r'
end
it { expect(rational_node.value).to eq(0.4r) }
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/if_node_spec.rb | spec/rubocop/ast/if_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::IfNode do
subject(:if_node) { parse_source(source).ast }
describe '.new' do
context 'with a regular if statement' do
let(:source) { 'if foo?; :bar; end' }
it { is_expected.to be_a(described_class) }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { is_expected.to be_a(described_class) }
end
context 'with a modifier statement' do
let(:source) { ':foo if bar?' }
it { is_expected.to be_a(described_class) }
end
end
describe '#keyword' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.keyword).to eq('if') }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.keyword).to eq('unless') }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.keyword).to eq('') }
end
end
describe '#inverse_keyword?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.inverse_keyword).to eq('unless') }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.inverse_keyword).to eq('if') }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.inverse_keyword).to eq('') }
end
end
describe '#if?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { is_expected.to be_if }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { is_expected.not_to be_if }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { is_expected.not_to be_if }
end
end
describe '#unless?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { is_expected.not_to be_unless }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { is_expected.to be_unless }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { is_expected.not_to be_unless }
end
end
describe '#ternary?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { is_expected.not_to be_ternary }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { is_expected.not_to be_ternary }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { is_expected.to be_ternary }
end
end
describe '#then?' do
context 'with `then` keyword' do
let(:source) do
<<~SOURCE
if foo? then
1
end
SOURCE
end
it { is_expected.to be_then }
end
context 'without `then` keyword' do
let(:source) do
<<~SOURCE
if foo?
1
end
SOURCE
end
it { is_expected.not_to be_then }
end
end
describe '#elsif?' do
context 'with an elsif statement' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'end'].join("\n")
end
let(:elsif_node) { if_node.else_branch }
it { expect(elsif_node).to be_elsif }
end
context 'with an if statement containing an elsif' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'end'].join("\n")
end
it { is_expected.not_to be_elsif }
end
context 'without an elsif statement' do
let(:source) do
['if foo?',
' 1',
'end'].join("\n")
end
it { is_expected.not_to be_elsif }
end
end
describe '#else?' do
context 'with an elsif statement' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'end'].join("\n")
end
# NOTE: This is a legacy behavior.
it { is_expected.to be_else }
end
context 'without an else statement' do
let(:source) do
['if foo?',
' 1',
'else',
' 2',
'end'].join("\n")
end
it { is_expected.not_to be_elsif }
end
end
describe '#modifier_form?' do
context 'with a non-modifier if statement' do
let(:source) { 'if foo?; :bar; end' }
it { is_expected.not_to be_modifier_form }
end
context 'with a non-modifier unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { is_expected.not_to be_modifier_form }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { is_expected.not_to be_modifier_form }
end
context 'with a modifier if statement' do
let(:source) { ':bar if foo?' }
it { is_expected.to be_modifier_form }
end
context 'with a modifier unless statement' do
let(:source) { ':bar unless foo?' }
it { is_expected.to be_modifier_form }
end
end
describe '#nested_conditional?' do
context 'with no nested conditionals' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
it { is_expected.not_to be_nested_conditional }
end
context 'with nested conditionals in if clause' do
let(:source) do
['if foo?',
' if baz; 4; end',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
it { is_expected.to be_nested_conditional }
end
context 'with nested conditionals in elsif clause' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' if baz; 4; end',
'else',
' 3',
'end'].join("\n")
end
it { is_expected.to be_nested_conditional }
end
context 'with nested conditionals in else clause' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' if baz; 4; end',
'end'].join("\n")
end
it { is_expected.to be_nested_conditional }
end
context 'with nested ternary operators' do
context 'when nested in the truthy branch' do
let(:source) { 'foo? ? bar? ? 1 : 2 : 3' }
it { is_expected.to be_nested_conditional }
end
context 'when nested in the falsey branch' do
let(:source) { 'foo? ? 3 : bar? ? 1 : 2' }
it { is_expected.to be_nested_conditional }
end
end
end
describe '#elsif_conditional?' do
context 'with one elsif conditional' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
it { is_expected.to be_elsif_conditional }
end
context 'with multiple elsif conditionals' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'elsif baz?',
' 3',
'else',
' 4',
'end'].join("\n")
end
it { is_expected.to be_elsif_conditional }
end
context 'with nested conditionals in if clause' do
let(:source) do
['if foo?',
' if baz; 1; end',
'else',
' 2',
'end'].join("\n")
end
it { is_expected.not_to be_elsif_conditional }
end
context 'with nested conditionals in else clause' do
let(:source) do
['if foo?',
' 1',
'else',
' if baz; 2; end',
'end'].join("\n")
end
it { is_expected.not_to be_elsif_conditional }
end
context 'with nested ternary operators' do
context 'when nested in the truthy branch' do
let(:source) { 'foo? ? bar? ? 1 : 2 : 3' }
it { is_expected.not_to be_elsif_conditional }
end
context 'when nested in the falsey branch' do
let(:source) { 'foo? ? 3 : bar? ? 1 : 2' }
it { is_expected.not_to be_elsif_conditional }
end
end
end
describe '#if_branch' do
context 'with an if statement' do
let(:source) do
['if foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.if_branch).to be_sym_type }
end
context 'with an unless statement' do
let(:source) do
['unless foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.if_branch).to be_sym_type }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :foo : 42' }
it { expect(if_node.if_branch).to be_sym_type }
end
end
describe '#else_branch' do
context 'with an if statement' do
let(:source) do
['if foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.else_branch).to be_int_type }
end
context 'with an unless statement' do
let(:source) do
['unless foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.else_branch).to be_int_type }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :foo : 42' }
it { expect(if_node.else_branch).to be_int_type }
end
end
describe '#branches' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.branches.size).to eq(1) }
it { expect(if_node.branches).to all(be_literal) }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :foo : 42' }
it { expect(if_node.branches.size).to eq(2) }
it { expect(if_node.branches).to all(be_literal) }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.branches.size).to eq(1) }
it { expect(if_node.branches).to all(be_literal) }
end
context 'with an else statement' do
let(:source) do
['if foo?',
' 1',
'else',
' 2',
'end'].join("\n")
end
it { expect(if_node.branches.size).to eq(2) }
it { expect(if_node.branches).to all(be_literal) }
end
context 'with an elsif statement' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
it { expect(if_node.branches.size).to eq(3) }
it { expect(if_node.branches).to all(be_literal) }
end
end
describe '#each_branch' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
context 'when not passed a block' do
it { expect(if_node.each_branch).to be_a(Enumerator) }
end
context 'when passed a block' do
it 'yields all the branches' do
expect { |b| if_node.each_branch(&b) }
.to yield_successive_args(*if_node.branches)
end
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/masgn_node_spec.rb | spec/rubocop/ast/masgn_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::MasgnNode do
let(:masgn_node) { parse_source(source).ast }
let(:source) { 'x, y = z' }
describe '.new' do
context 'with a `masgn` node' do
it { expect(masgn_node).to be_a(described_class) }
end
end
describe '#names' do
subject { masgn_node.names }
let(:source) { 'a, @b, @@c, $d, E, *f = z' }
it { is_expected.to eq(%i[a @b @@c $d E f]) }
context 'with nested `mlhs` nodes' do
let(:source) { 'a, (b, c) = z' }
it { is_expected.to eq(%i[a b c]) }
end
context 'with array setter' do
let(:source) { 'a, b[c] = z' }
it { is_expected.to eq(%i[a []=]) }
end
context 'with a method chain' do
let(:source) { 'a, b.c = z' }
it { is_expected.to eq(%i[a c=]) }
end
end
describe '#expression' do
include AST::Sexp
subject { masgn_node.expression }
context 'with a single RHS value' do
it { is_expected.to eq(s(:send, nil, :z)) }
end
context 'with multiple RHS values' do
let(:source) { 'x, y = 1, 2' }
it { is_expected.to eq(s(:array, s(:int, 1), s(:int, 2))) }
end
end
describe '#values' do
include AST::Sexp
subject { masgn_node.values }
context 'when the RHS has a single value' do
let(:source) { 'x, y = z' }
it { is_expected.to eq([s(:send, nil, :z)]) }
end
context 'when the RHS is an array literal' do
let(:source) { 'x, y = [z, a]' }
it { is_expected.to eq([s(:array, s(:send, nil, :z), s(:send, nil, :a))]) }
end
context 'when the RHS has a multiple values' do
let(:source) { 'x, y = u, v' }
it { is_expected.to eq([s(:send, nil, :u), s(:send, nil, :v)]) }
end
context 'when the RHS has a splat' do
let(:source) { 'x, y = *z' }
it { is_expected.to eq([s(:splat, s(:send, nil, :z))]) }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/alias_node_spec.rb | spec/rubocop/ast/alias_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::AliasNode do
subject(:alias_node) { parse_source(source).ast }
describe '.new' do
let(:source) do
'alias foo bar'
end
it { is_expected.to be_a(described_class) }
end
describe '#new_identifier' do
let(:source) do
'alias foo bar'
end
it { expect(alias_node.new_identifier).to be_sym_type }
it { expect(alias_node.new_identifier.children.first).to eq(:foo) }
end
describe '#old_identifier' do
let(:source) do
'alias foo bar'
end
it { expect(alias_node.old_identifier).to be_sym_type }
it { expect(alias_node.old_identifier.children.first).to eq(:bar) }
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/arg_node_spec.rb | spec/rubocop/ast/arg_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::ArgNode do
let(:args_node) { parse_source(source).ast.arguments }
let(:arg_node) { args_node.first }
describe '.new' do
context 'with a method definition' do
let(:source) { 'def foo(x) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with a block' do
let(:source) { 'foo { |x| bar }' }
if RuboCop::AST::Builder.emit_procarg0
it { expect(arg_node).to be_a(RuboCop::AST::Procarg0Node) }
else
it { expect(arg_node).to be_a(described_class) }
end
end
context 'with a lambda literal' do
let(:source) { '-> (x) { bar }' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with a keyword argument' do
let(:source) { 'def foo(x:) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with an optional argument' do
let(:source) { 'def foo(x = 42) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with an optional keyword argument' do
let(:source) { 'def foo(x: 42) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with a splatted argument' do
let(:source) { 'def foo(*x) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with a double splatted argument' do
let(:source) { 'def foo(**x) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with a block argument' do
let(:source) { 'def foo(&x) end' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with a shadow argument' do
let(:source) { 'foo { |; x| }' }
it { expect(arg_node).to be_a(described_class) }
end
context 'with argument forwarding' do
context 'with Ruby >= 2.7', :ruby27 do
let(:source) { 'def foo(...); end' }
if RuboCop::AST::Builder.emit_forward_arg
it { expect(arg_node).to be_a(described_class) }
else
it { expect(arg_node).to be_forward_args_type }
end
end
context 'with Ruby >= 3.0', :ruby30 do
let(:source) { 'def foo(x, ...); end' }
let(:arg_node) { args_node.last }
it { expect(arg_node).to be_a(described_class) }
end
end
end
describe '#name' do
subject { arg_node.name }
context 'with a regular argument' do
let(:source) { 'def foo(x) end' }
it { is_expected.to eq(:x) }
end
context 'with a block' do
let(:source) { 'foo { |x| x }' }
it { is_expected.to eq(:x) }
end
context 'with a keyword argument' do
let(:source) { 'def foo(x:) end' }
it { is_expected.to eq(:x) }
end
context 'with an optional argument' do
let(:source) { 'def foo(x = 42) end' }
it { is_expected.to eq(:x) }
end
context 'with an optional keyword argument' do
let(:source) { 'def foo(x: 42) end' }
it { is_expected.to eq(:x) }
end
context 'with a splatted argument' do
let(:source) { 'def foo(*x) end' }
it { is_expected.to eq(:x) }
end
context 'with a nameless splatted argument' do
let(:source) { 'def foo(*) end' }
it { is_expected.to be_nil }
end
context 'with a double splatted argument' do
let(:source) { 'def foo(**x) end' }
it { is_expected.to eq(:x) }
end
context 'with a nameless double splatted argument' do
let(:source) { 'def foo(**) end' }
it { is_expected.to be_nil }
end
context 'with a block argument' do
let(:source) { 'def foo(&x) end' }
it { is_expected.to eq(:x) }
end
context 'with a shadow argument' do
let(:source) { 'foo { |; x| x = 5 }' }
it { is_expected.to eq(:x) }
end
context 'with argument forwarding' do
context 'with Ruby >= 2.7', :ruby27 do
let(:source) { 'def foo(...); end' }
it { is_expected.to be_nil } if RuboCop::AST::Builder.emit_forward_arg
end
context 'with Ruby >= 3.0', :ruby30 do
let(:source) { 'def foo(x, ...); end' }
let(:arg_node) { args_node.last }
it { is_expected.to be_nil }
end
end
end
describe '#default_value' do
include AST::Sexp
subject { arg_node.default_value }
context 'with a regular argument' do
let(:source) { 'def foo(x) end' }
it { is_expected.to be_nil }
end
context 'with a block' do
let(:source) { 'foo { |x| x }' }
it { is_expected.to be_nil }
end
context 'with an optional argument' do
let(:source) { 'def foo(x = 42) end' }
it { is_expected.to eq(s(:int, 42)) }
end
context 'with an optional keyword argument' do
let(:source) { 'def foo(x: 42) end' }
it { is_expected.to eq(s(:int, 42)) }
end
context 'with a splatted argument' do
let(:source) { 'def foo(*x) end' }
it { is_expected.to be_nil }
end
context 'with a double splatted argument' do
let(:source) { 'def foo(**x) end' }
it { is_expected.to be_nil }
end
context 'with a block argument' do
let(:source) { 'def foo(&x) end' }
it { is_expected.to be_nil }
end
context 'with a shadow argument' do
let(:source) { 'foo { |; x| x = 5 }' }
it { is_expected.to be_nil }
end
context 'with argument forwarding' do
context 'with Ruby >= 2.7', :ruby27 do
let(:source) { 'def foo(...); end' }
it { is_expected.to be_nil } if RuboCop::AST::Builder.emit_forward_arg
end
context 'with Ruby >= 3.0', :ruby30 do
let(:source) { 'def foo(x, ...); end' }
let(:arg_node) { args_node.last }
it { is_expected.to be_nil }
end
end
end
describe '#default?' do
subject { arg_node.default? }
context 'with a regular argument' do
let(:source) { 'def foo(x) end' }
it { is_expected.to be(false) }
end
context 'with a block' do
let(:source) { 'foo { |x| x }' }
it { is_expected.to be(false) }
end
context 'with an optional argument' do
let(:source) { 'def foo(x = 42) end' }
it { is_expected.to be(true) }
end
context 'with an optional keyword argument' do
let(:source) { 'def foo(x: 42) end' }
it { is_expected.to be(true) }
end
context 'with a splatted argument' do
let(:source) { 'def foo(*x) end' }
it { is_expected.to be(false) }
end
context 'with a double splatted argument' do
let(:source) { 'def foo(**x) end' }
it { is_expected.to be(false) }
end
context 'with a block argument' do
let(:source) { 'def foo(&x) end' }
it { is_expected.to be(false) }
end
context 'with a shadow argument' do
let(:source) { 'foo { |; x| x = 5 }' }
it { is_expected.to be(false) }
end
context 'with argument forwarding' do
context 'with Ruby >= 2.7', :ruby27 do
let(:source) { 'def foo(...); end' }
it { is_expected.to be(false) } if RuboCop::AST::Builder.emit_forward_arg
end
context 'with Ruby >= 3.0', :ruby30 do
let(:source) { 'def foo(x, ...); end' }
let(:arg_node) { args_node.last }
it { is_expected.to be(false) }
end
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
rubocop/rubocop-ast | https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/spec/rubocop/ast/def_node_spec.rb | spec/rubocop/ast/def_node_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::AST::DefNode do
subject(:def_node) { parse_source(source).ast }
describe '.new' do
context 'with a def node' do
let(:source) { 'def foo(bar); end' }
it { is_expected.to be_a(described_class) }
end
context 'with a defs node' do
let(:source) { 'def self.foo(bar); end' }
it { is_expected.to be_a(described_class) }
end
end
describe '#method_name' do
context 'with a plain method' do
let(:source) { 'def foo; end' }
it { expect(def_node.method_name).to eq(:foo) }
end
context 'with a setter method' do
let(:source) { 'def foo=(bar); end' }
it { expect(def_node.method_name).to eq(:foo=) }
end
context 'with an operator method' do
let(:source) { 'def ==(bar); end' }
it { expect(def_node.method_name).to eq(:==) }
end
context 'with a unary method' do
let(:source) { 'def -@; end' }
it { expect(def_node.method_name).to eq(:-@) }
end
end
describe '#method?' do
context 'when message matches' do
context 'when argument is a symbol' do
let(:source) { 'bar(:baz)' }
it { is_expected.to be_method(:bar) }
end
context 'when argument is a string' do
let(:source) { 'bar(:baz)' }
it { is_expected.to be_method('bar') }
end
end
context 'when message does not match' do
context 'when argument is a symbol' do
let(:source) { 'bar(:baz)' }
it { is_expected.not_to be_method(:foo) }
end
context 'when argument is a string' do
let(:source) { 'bar(:baz)' }
it { is_expected.not_to be_method('foo') }
end
end
end
describe '#arguments' do
context 'with no arguments' do
let(:source) { 'def foo; end' }
it { expect(def_node.arguments).to be_empty }
end
context 'with a single regular argument' do
let(:source) { 'def foo(bar); end' }
it { expect(def_node.arguments.size).to eq(1) }
end
context 'with a single rest argument' do
let(:source) { 'def foo(*baz); end' }
it { expect(def_node.arguments.size).to eq(1) }
end
context 'with multiple regular arguments' do
let(:source) { 'def foo(bar, baz); end' }
it { expect(def_node.arguments.size).to eq(2) }
end
context 'with multiple mixed arguments' do
let(:source) { 'def foo(bar, *baz); end' }
it { expect(def_node.arguments.size).to eq(2) }
end
context 'with argument forwarding', :ruby27 do
let(:source) { 'def foo(...); end' }
it { expect(def_node.arguments.size).to eq(1) }
end
end
describe '#first_argument' do
context 'with no arguments' do
let(:source) { 'def foo; end' }
it { expect(def_node.first_argument).to be_nil }
end
context 'with a single regular argument' do
let(:source) { 'def foo(bar); end' }
it { expect(def_node.first_argument).to be_arg_type }
end
context 'with a single rest argument' do
let(:source) { 'def foo(*bar); end' }
it { expect(def_node.first_argument).to be_restarg_type }
end
context 'with a single keyword argument' do
let(:source) { 'def foo(bar: :baz); end' }
it { expect(def_node.first_argument).to be_kwoptarg_type }
end
context 'with multiple regular arguments' do
let(:source) { 'def foo(bar, baz); end' }
it { expect(def_node.first_argument).to be_arg_type }
end
context 'with multiple mixed arguments' do
let(:source) { 'def foo(bar, *baz); end' }
it { expect(def_node.first_argument).to be_arg_type }
end
end
describe '#last_argument' do
context 'with no arguments' do
let(:source) { 'def foo; end' }
it { expect(def_node.last_argument).to be_nil }
end
context 'with a single regular argument' do
let(:source) { 'def foo(bar); end' }
it { expect(def_node.last_argument).to be_arg_type }
end
context 'with a single rest argument' do
let(:source) { 'def foo(*bar); end' }
it { expect(def_node.last_argument).to be_restarg_type }
end
context 'with a single keyword argument' do
let(:source) { 'def foo(bar: :baz); end' }
it { expect(def_node.last_argument).to be_kwoptarg_type }
end
context 'with multiple regular arguments' do
let(:source) { 'def foo(bar, baz); end' }
it { expect(def_node.last_argument).to be_arg_type }
end
context 'with multiple mixed arguments' do
let(:source) { 'def foo(bar, *baz); end' }
it { expect(def_node.last_argument).to be_restarg_type }
end
end
describe '#arguments?' do
context 'with no arguments' do
let(:source) { 'def foo; end' }
it { is_expected.not_to be_arguments }
end
context 'with a single regular argument' do
let(:source) { 'def foo(bar); end' }
it { is_expected.to be_arguments }
end
context 'with a single rest argument' do
let(:source) { 'def foo(*bar); end' }
it { is_expected.to be_arguments }
end
context 'with a single keyword argument' do
let(:source) { 'def foo(bar: :baz); end' }
it { is_expected.to be_arguments }
end
context 'with multiple regular arguments' do
let(:source) { 'def foo(bar, baz); end' }
it { is_expected.to be_arguments }
end
context 'with multiple mixed arguments' do
let(:source) { 'def foo(bar, *baz); end' }
it { is_expected.to be_arguments }
end
end
describe '#rest_argument?' do
context 'with a rest argument' do
let(:source) { 'def foo(*bar); end' }
it { is_expected.to be_rest_argument }
end
context 'with no arguments' do
let(:source) { 'def foo; end' }
it { is_expected.not_to be_rest_argument }
end
context 'with regular arguments' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_rest_argument }
end
context 'with mixed arguments' do
let(:source) { 'def foo(bar, *baz); end' }
it { is_expected.to be_rest_argument }
end
end
describe '#operator_method?' do
context 'with a binary operator method' do
let(:source) { 'def ==(bar); end' }
it { is_expected.to be_operator_method }
end
context 'with a unary operator method' do
let(:source) { 'def -@; end' }
it { is_expected.to be_operator_method }
end
context 'with a setter method' do
let(:source) { 'def foo=(bar); end' }
it { is_expected.not_to be_operator_method }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_operator_method }
end
end
describe '#comparison_method?' do
context 'with a comparison method' do
let(:source) { 'def <=(bar); end' }
it { is_expected.to be_comparison_method }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_comparison_method }
end
end
describe '#assignment_method?' do
context 'with an assignment method' do
let(:source) { 'def foo=(bar); end' }
it { is_expected.to be_assignment_method }
end
context 'with a bracket assignment method' do
let(:source) { 'def []=(bar); end' }
it { is_expected.to be_assignment_method }
end
context 'with a comparison method' do
let(:source) { 'def ==(bar); end' }
it { is_expected.not_to be_assignment_method }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_assignment_method }
end
end
describe '#void_context?' do
context 'with an initializer method' do
let(:source) { 'def initialize(bar); end' }
it { is_expected.to be_void_context }
end
context 'with a class method called "initialize"' do
let(:source) { 'def self.initialize(bar); end' }
it { is_expected.not_to be_void_context }
end
context 'with a regular assignment method' do
let(:source) { 'def foo=(bar); end' }
it { is_expected.to be_void_context }
end
context 'with a bracket assignment method' do
let(:source) { 'def []=(bar); end' }
it { is_expected.to be_void_context }
end
context 'with a comparison method' do
let(:source) { 'def ==(bar); end' }
it { is_expected.not_to be_void_context }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_void_context }
end
end
context 'when using Ruby 2.7 or newer', :ruby27 do
describe '#argument_forwarding?' do
let(:source) { 'def foo(...); end' }
it { is_expected.to be_argument_forwarding }
end
end
describe '#receiver' do
context 'with an instance method definition' do
let(:source) { 'def foo(bar); end' }
it { expect(def_node.receiver).to be_nil }
end
context 'with a class method definition' do
let(:source) { 'def self.foo(bar); end' }
it { expect(def_node.receiver).to be_self_type }
end
context 'with a singleton method definition' do
let(:source) { 'def Foo.bar(baz); end' }
it { expect(def_node.receiver).to be_const_type }
end
end
describe '#self_receiver?' do
context 'with an instance method definition' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_self_receiver }
end
context 'with a class method definition' do
let(:source) { 'def self.foo(bar); end' }
it { is_expected.to be_self_receiver }
end
context 'with a singleton method definition' do
let(:source) { 'def Foo.bar(baz); end' }
it { is_expected.not_to be_self_receiver }
end
end
describe '#const_receiver?' do
context 'with an instance method definition' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_const_receiver }
end
context 'with a class method definition' do
let(:source) { 'def self.foo(bar); end' }
it { is_expected.not_to be_const_receiver }
end
context 'with a singleton method definition' do
let(:source) { 'def Foo.bar(baz); end' }
it { is_expected.to be_const_receiver }
end
end
describe '#predicate_method?' do
context 'with a predicate method' do
let(:source) { 'def foo?(bar); end' }
it { is_expected.to be_predicate_method }
end
context 'with a bang method' do
let(:source) { 'def foo!(bar); end' }
it { is_expected.not_to be_predicate_method }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_predicate_method }
end
end
describe '#bang_method?' do
context 'with a bang method' do
let(:source) { 'def foo!(bar); end' }
it { is_expected.to be_bang_method }
end
context 'with a predicate method' do
let(:source) { 'def foo?(bar); end' }
it { is_expected.not_to be_bang_method }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_bang_method }
end
end
describe '#camel_case_method?' do
context 'with a camel case method' do
let(:source) { 'def Foo(bar); end' }
it { is_expected.to be_camel_case_method }
end
context 'with a regular method' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_camel_case_method }
end
end
describe '#block_argument?' do
context 'with a block argument' do
let(:source) { 'def foo(&bar); end' }
it { is_expected.to be_block_argument }
end
context 'with no arguments' do
let(:source) { 'def foo; end' }
it { is_expected.not_to be_block_argument }
end
context 'with regular arguments' do
let(:source) { 'def foo(bar); end' }
it { is_expected.not_to be_block_argument }
end
context 'with mixed arguments' do
let(:source) { 'def foo(bar, &baz); end' }
it { is_expected.to be_block_argument }
end
end
describe '#body' do
context 'with no body' do
let(:source) { 'def foo(bar); end' }
it { expect(def_node.body).to be_nil }
end
context 'with a single expression body' do
let(:source) { 'def foo(bar); baz; end' }
it { expect(def_node.body).to be_send_type }
end
context 'with a multi-expression body' do
let(:source) { 'def foo(bar); baz; qux; end' }
it { expect(def_node.body).to be_begin_type }
end
end
describe '#endless?' do
context 'with standard method definition' do
let(:source) { 'def foo; 42; end' }
it { is_expected.not_to be_endless }
end
context 'with endless method definition', :ruby30 do
let(:source) { 'def foo() = 42' }
it { is_expected.to be_endless }
end
end
end
| ruby | MIT | 69036498c11ca944c6099d1b672ba408f34a3eb4 | 2026-01-04T17:49:41.556809Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.