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
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/folder.rb
lib/gzr/modules/folder.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Folder def self.included klass require_relative '../modules/user' klass.class_eval do include Gzr::User end end def create_folder(name, parent_id) begin req = {:name => name, :parent_id => parent_id} @sdk.create_folder(req).to_attrs rescue LookerSDK::Error => e say_error "Error creating folder(#{JSON.pretty_generate(req)})" say_error e raise end end def search_folders(name,fields=nil) begin req = {:name => name} req[:fields] = fields if fields @sdk.search_folders(req).collect { |e| e.to_attrs } rescue LookerSDK::NotFound => e [] rescue LookerSDK::Error => e say_error "Error querying search_folders(#{JSON.pretty_generate(req)})" say_error e raise end end def query_folder(id,fields=nil) begin req = {} req[:fields] = fields if fields @sdk.folder(id, req).to_attrs rescue LookerSDK::NotFound return nil rescue LookerSDK::Error => e say_error "Error querying folder(#{id},#{JSON.pretty_generate(req)})" say_error e raise end end def process_args(args) folder_ids = [] begin user = query_me("home_folder_id") folder_ids << user[:home_folder_id] end unless args && args.length > 0 && !(args[0].nil?) if args[0] == 'lookml' folder_ids << 'lookml' elsif args[0] =~ /^[0-9]+$/ then folder_ids << args[0].to_i elsif args[0] == "~" then user = query_me("personal_folder_id") folder_ids << user[:personal_folder_id] elsif args[0] =~ /^~[0-9]+$/ then user = query_user(args[0].sub('~',''), "personal_folder_id") folder_ids << user[:personal_folder_id] elsif args[0] =~ /^~.+@.+$/ then search_results = search_users( { :email=>args[0].sub('~','') },"personal_folder_id" ) folder_ids += search_results.map { |r| r[:personal_folder_id] } elsif args[0] =~ /^~.+$/ then first_name, last_name = args[0].sub('~','').split(' ') search_results = search_users( { :first_name=>first_name, :last_name=>last_name },"personal_folder_id" ) folder_ids += search_results.map { |r| r[:personal_folder_id] } else search_results = search_folders(args[0],"id") folder_ids += search_results.map { |r| r[:id] } # The built in Shared folder is only availabe by # searching for Home. https://github.com/looker/helltool/issues/34994 if args[0] == 'Shared' then search_results = search_folders('Home',"id,is_shared_root") folder_ids += search_results.select { |r| r[:is_shared_root] }.map { |r| r[:id] } end end if args && args.length > 0 && !args[0].nil? return folder_ids end def all_folders(fields=nil) begin req = {} req[:fields] = fields if fields @sdk.all_folders(req).collect { |e| e.to_attrs } rescue LookerSDK::Error => e say_error "Error querying all_folders(#{JSON.pretty_generate(req)})" say_error e raise end end def query_folder_children(folder_id, fields=nil) req = {} req[:fields] = fields if fields begin @sdk.folder_children(folder_id, req).collect { |e| e.to_attrs } rescue LookerSDK::NotFound return [] rescue LookerSDK::Error => e say_error "Error querying folder_children(#{folder_id}, #{JSON.pretty_generate(req)})" say_error e raise end end def delete_folder(folder_id) begin @sdk.delete_folder(folder_id) rescue LookerSDK::NotFound say_error "folder #{folder_id} not found" say_error e raise rescue LookerSDK::Error => e say_error "Error deleting folder #{folder_id}" say_error e raise end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/role.rb
lib/gzr/modules/role.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Role def query_all_roles(fields=nil) req = Hash.new req[:fields] = fields if fields begin @sdk.all_roles(req).collect { |r| r.to_attrs } rescue LookerSDK::NotFound => e [] rescue LookerSDK::Error => e say_error "Unable to get all_roles(#{JSON.pretty_generate(req)})" say_error e say_error e.errors if e.errors raise end end def query_role(role_id) begin @sdk.role(role_id).to_attrs rescue LookerSDK::NotFound => e say_error "role(#{role_id}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Unable to get role(#{role_id})" say_error e say_error e.errors if e.errors raise end end def trim_role(data) trimmed = data.select do |k,v| (keys_to_keep('create_role') + [:id]).include? k end trimmed[:permission_set] = data[:permission_set].select do |k,v| (keys_to_keep('create_permission_set') + [:id,:built_in,:all_access]).include? k end trimmed[:model_set] = data[:model_set].select do |k,v| (keys_to_keep('create_model_set') + [:id,:built_in,:all_access]).include? k end trimmed end def delete_role(role_id) begin @sdk.delete_role(role_id) rescue LookerSDK::NotFound => e say_error "role(#{role_id}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Unable to delete_role(#{role_id})" say_error e say_error e.errors if e.errors raise end end def query_role_groups(role_id,fields=nil) req = Hash.new req[:fields] = fields if fields begin @sdk.role_groups(role_id, req).collect { |g| g.to_attrs } rescue LookerSDK::NotFound => e say_error "role_groups(#{role_id},#{JSON.pretty_generate(req)}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Unable to get role_groups(#{role_id},#{JSON.pretty_generate(req)})" say_error e say_error e.errors if e.errors raise end end def query_role_users(role_id,fields=nil,direct_association_only=true) req = Hash.new req[:fields] = fields if fields req[:direct_association_only] = direct_association_only begin @sdk.role_users(role_id, req).collect { |u| u.to_attrs } rescue LookerSDK::NotFound => e say_error "role_users(#{role_id},#{JSON.pretty_generate(req)}) not found" say_error e say_error e.errors if e.errors raise rescue LookerSDK::Error => e say_error "Unable to get role_users(#{role_id},#{JSON.pretty_generate(req)})" say_error e say_error e.errors if e.errors raise end end def set_role_groups(role_id,groups=[]) begin @sdk.set_role_groups(role_id, groups) rescue LookerSDK::NotFound => e say_error "set_role_groups(#{role_id},#{JSON.pretty_generate(groups)}) not found" say_error e say_error e.errors if e.errors raise rescue LookerSDK::Error => e say_error "Unable to call set_role_groups(#{role_id},#{JSON.pretty_generate(groups)})" say_error e say_error e.errors if e.errors raise end end def set_role_users(role_id,users=[]) begin @sdk.set_role_users(role_id, users) rescue LookerSDK::NotFound => e say_error "set_role_users(#{role_id},#{JSON.pretty_generate(users)}) not found" say_error e say_error e.errors if e.errors raise rescue LookerSDK::Error => e say_error "Unable to call set_role_users(#{role_id},#{JSON.pretty_generate(users)})" say_error e say_error e.errors if e.errors raise end end def create_role(name,pset,mset) req = { name: name, permission_set_id: pset, model_set_id: mset } begin @sdk.create_role(req)&.to_attrs rescue LookerSDK::Error => e say_error "Unable to call create_role(#{JSON.pretty_generate(req)})" say_error e raise end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/look.rb
lib/gzr/modules/look.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Look def query_look(look_id) begin @sdk.look(look_id).to_attrs rescue LookerSDK::NotFound => e say_error "look(#{look_id}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Error querying look(#{look_id})" say_error e raise end end def search_looks_by_slug(slug, folder_id=nil) data = [] begin req = { :slug => slug } req[:folder_id] = folder_id if folder_id data = @sdk.search_looks(req).collect { |l| l.to_attrs } req[:deleted] = true data = @sdk.search_looks(req).collect { |l| l.to_attrs } if data.empty? rescue LookerSDK::Error => e say_error "Error search_looks_by_slug(#{JSON.pretty_generate(req)})" say_error e raise end data end def search_looks_by_title(title, folder_id=nil) data = [] begin req = { :title => title } req[:folder_id] = folder_id if folder_id data = @sdk.search_looks(req).collect { |l| l.to_attrs } req[:deleted] = true data = @sdk.search_looks(req).collect { |l| l.to_attrs } if data.empty? rescue LookerSDK::Error => e say_error "Error search_looks_by_title(#{JSON.pretty_generate(req)})" say_error e raise end data end def create_look(look) begin look[:public] = false unless look[:public] @sdk.create_look(look).to_attrs rescue LookerSDK::Error => e say_error "Error creating look(#{JSON.pretty_generate(look)})" say_error e raise end end def update_look(id,look) begin @sdk.update_look(id,look).to_attrs rescue LookerSDK::NotFound => e say_error "look(#{id}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Error updating look(#{id},#{JSON.pretty_generate(look)})" say_error e raise end end def delete_look(look_id) begin @sdk.delete_look(look_id) rescue LookerSDK::Error => e say_error "Error deleting look(#{look_id})" say_error e raise end end def upsert_look(user_id, query_id, folder_id, source, output: $stdout) # try to find look by slug in target folder existing_look = search_looks_by_slug(source[:slug], folder_id).fetch(0,nil) if source[:slug] # check for look of same title in target folder title_used = search_looks_by_title(source[:title], folder_id).fetch(0,nil) # If there is no match by slug in target folder or no slug given, then we match by title existing_look ||= title_used # same_title is now a flag indicating that there is already a look in the same folder with # that title, and it is the one we are updating. same_title = (title_used&.fetch(:id,nil) == existing_look&.fetch(:id,nil)) # check if the slug is used by any look slug_used = search_looks_by_slug(source[:slug]).fetch(0,nil) if source[:slug] # same_slug is now a flag indicating that there is already a look with # that slug, but it is the one we are updating. same_slug = (slug_used&.fetch(:id,nil) == existing_look&.fetch(:id,nil)) if slug_used && !same_slug then say_warning "slug #{slug_used[:slug]} already used for look #{slug_used[:title]} in folder #{slug_used[:folder_id]}", output: output say_warning("That look is in the 'Trash' but not fully deleted yet", output: output) if slug_used[:deleted] say_warning "look will be imported with new slug", output: output end if existing_look then if title_used && !same_title then raise Gzr::CLI::Error, "Look #{source[:title]} already exists in folder #{folder_id}\nDelete it before trying to upate another Look to have that title." end raise Gzr::CLI::Error, "Look #{existing_look[:title]} with slug #{existing_look[:slug]} already exists in folder #{folder_id}\nUse --force if you want to overwrite it" unless @options[:force] say_ok "Modifying existing Look #{existing_look[:id]} #{existing_look[:title]} in folder #{folder_id}", output: output new_look = source.select do |k,v| (keys_to_keep('update_look') - [:space_id,:folder_id,:user_id,:query_id,:slug]).include? k end new_look[:slug] = source[:slug] if source[:slug] && !slug_used new_look[:deleted] = false if existing_look[:deleted] new_look[:query_id] = query_id return update_look(existing_look[:id],new_look) else new_look = source.select do |k,v| (keys_to_keep('create_look') - [:space_id,:folder_id,:user_id,:query_id,:slug]).include? k end new_look[:slug] = source[:slug] unless slug_used new_look[:query_id] = query_id new_look[:user_id] = user_id new_look[:folder_id] = folder_id find_vis_config_reference(new_look) do |vis_config| find_color_palette_reference(vis_config) do |o,default_colors| update_color_palette!(o,default_colors) end end return create_look(new_look) end end def create_fetch_query(source_query) new_query = source_query.select do |k,v| (keys_to_keep('create_query') - [:client_id]).include? k end find_vis_config_reference(new_query) do |vis_config| find_color_palette_reference(vis_config) do |o,default_colors| update_color_palette!(o,default_colors) end end return create_query(new_query) end def create_merge_result(merge_result) new_merge_result = merge_result.select do |k,v| (keys_to_keep('create_merge_query') - [:client_id,:source_queries]).include? k end new_merge_result[:source_queries] = merge_result[:source_queries].map do |query| new_query = {} new_query[:query_id] = create_fetch_query(query[:query]).id new_query[:name] = query[:name] new_query[:merge_fields] = query[:merge_fields] new_query end find_vis_config_reference(new_merge_result) do |vis_config| find_color_palette_reference(vis_config) do |o,default_colors| update_color_palette!(o,default_colors) end end return create_merge_query(new_merge_result) end def cat_look(look_id) data = query_look(look_id) find_vis_config_reference(data) do |vis_config| find_color_palette_reference(vis_config) do |o,default_colors| rewrite_color_palette!(o,default_colors) end end data[:scheduled_plans] = query_scheduled_plans_for_look(@look_id,"all") if @options[:plans] data end def trim_look(data) trimmed = data.select do |k,v| (keys_to_keep('update_look') + [:id,:query]).include? k end trimmed[:query] = data[:query].select do |k,v| (keys_to_keep('create_query') + [:id]).include? k end trimmed[:scheduled_plans] = data[:scheduled_plans].map do |sp| sp.select do |k,v| (keys_to_keep('create_scheduled_plan') + [:id]).include? k end end if data[:scheduled_plans] trimmed end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/model.rb
lib/gzr/modules/model.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Model def query_all_lookml_models(fields=nil, progress=false) data = [] begin req = Hash.new req[:fields] = fields if fields req[:limit] = 16 loop do puts "fetching #{req[:limit]} offset #{req[:offset] || 0}" if progress page = @sdk.all_lookml_models(req).collect { |m| m.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::Error => e say_error "Error querying all_lookml_models(#{JSON.pretty_generate(req)})" say_error e raise end data end def cat_model(model_name) begin @sdk.lookml_model(model_name)&.to_attrs rescue LookerSDK::NotFound => e return nil rescue LookerSDK::Error => e say_error "Error getting lookml_model(#{model_name})" say_error e raise end end def trim_model(data) data.select do |k,v| keys_to_keep('create_lookml_model').include? k end end def create_model(body) begin @sdk.create_lookml_model(body)&.to_attrs rescue LookerSDK::Error => e say_error "Error running create_lookml_model(#{JSON.pretty_generate(body)})" say_error e raise end end def update_model(model_name,body) begin @sdk.update_lookml_model(model_name,body)&.to_attrs rescue LookerSDK::Error => e say_error "Error running update_lookml_model(#{model_name},#{JSON.pretty_generate(body)})" say_error e raise end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/alert.rb
lib/gzr/modules/alert.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Alert def get_alert(alert_id) data = nil begin data = @sdk.get_alert(alert_id).to_attrs rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::Error => e say_error "Error querying get_alert(#{alert_id})" say_error e raise end if data and data[:owner_id] owner = get_user_by_id(data[:owner_id]) data[:owner] = owner.select do |k,v| [:email,:last_name,:first_name].include?(k) && !(v.nil? || v.empty?) end if owner end data end def search_alerts(group_by: nil, fields: nil, disabled: nil, frequency: nil, condition_met: nil, last_run_start: nil, last_run_end: nil, all_owners: nil) data = [] begin req = {} req[:group_by] = group_by unless group_by.nil? req[:fields] = fields unless fields.nil? req[:disabled] = disabled unless disabled.nil? req[:frequency] = frequency unless frequency.nil? req[:condition_met] = condition_met unless condition_met.nil? req[:last_run_start] = last_run_start unless last_run_start.nil? req[:last_run_end] = last_run_end unless last_run_end.nil? req[:all_owners] = all_owners unless all_owners.nil? req[:limit] = 64 loop do page = @sdk.search_alerts(req).collect { |a| a.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::Error => e say_error "Error querying search_alerts(#{JSON.pretty_generate(req)})" say_error e raise end data end def follow_alert(alert_id) begin @sdk.follow_alert(alert_id) rescue LookerSDK::NotFound => e say_error "Alert #{alert_id} not found" say_error e raise rescue LookerSDK::Error => e say_error "Error following alert(#{alert_id})" say_error e raise end end def unfollow_alert(alert_id) begin @sdk.unfollow_alert(alert_id) rescue LookerSDK::NotFound => e say_error "Alert #{alert_id} not found" say_error e raise rescue LookerSDK::Error => e say_error "Error unfollowing alert(#{alert_id})" say_error e raise end end def update_alert_field(alert_id, owner_id: nil, is_disabled: nil, disabled_reason: nil, is_public: nil, threshold: nil) req = {} req[:owner_id] = owner_id unless owner_id.nil? req[:is_disabled] = is_disabled unless is_disabled.nil? req[:disabled_reason] = disabled_reason unless disabled_reason.nil? req[:is_public] = is_public unless is_public.nil? req[:threshold] = threshold unless threshold.nil? begin @sdk.update_alert_field(alert_id, req).to_attrs rescue LookerSDK::NotFound => e say_error "Alert #{alert_id} not found" say_error e raise rescue LookerSDK::Error => e say_error "Error calling update_alert_field(#{alert_id},#{JSON.pretty_generate(req)})" say_error e raise end end def delete_alert(alert_id) begin @sdk.delete_alert(alert_id) rescue LookerSDK::NotFound => e say_error "Alert #{alert_id} not found" say_error e raise rescue LookerSDK::Error => e say_error "Error calling delete_alert(#{alert_id})" say_error e raise end end def alert_notifications() data = [] req = {} begin req[:limit] = 64 loop do page = @sdk.alert_notifications(req).collect { |a| a.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::Error => e say_error "Error querying alert_notifications()" say_error e raise end data end def read_alert_notification(notification_id) begin @sdk.read_alert_notification(notification_id).to_attrs rescue LookerSDK::NotFound => e say_error "Alert notification #{notification_id} not found" say_error e raise rescue LookerSDK::Error => e say_error "Error calling read_alert_notification(#{notification_id})" say_error e raise end end def create_alert(req) begin @sdk.create_alert(req).to_attrs rescue LookerSDK::Error => e say_error "Error calling create_alert(#{JSON.pretty_generate(req)})" say_error e raise end end def update_alert(alert_id,req) begin @sdk.update_alert(alert_id,req).to_attrs rescue LookerSDK::Error => e say_error "Error calling update_alert(#{alert_id}, #{JSON.pretty_generate(req)})" say_error e raise end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/user.rb
lib/gzr/modules/user.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module User def query_me(fields='id') begin @sdk.me(fields ? {:fields=>fields} : nil ).to_attrs rescue LookerSDK::Error => e say_error "Error querying me({:fields=>\"#{fields}\"})" say_error e raise end end def query_user(id,fields='id') begin @sdk.user(id, fields ? {:fields=>fields} : nil ).to_attrs rescue LookerSDK::NotFound => e say_error "user(#{id}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Error querying user(#{id},{:fields=>\"#{fields}\"})" say_error e raise end end def search_users(filter, fields=nil, sorts=nil) req = { :limit=>64 } req.merge!(filter) req[:fields] = fields if fields req[:sorts] = sorts if sorts data = Array.new begin loop do page = @sdk.search_users(req).collect { |r| r.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::ClientError => e say_error "Unable to get search_users(#{JSON.pretty_generate(req)})" say_error e raise end data end def query_all_users(fields=nil, sorts=nil) req = { :limit=>64 } req[:fields] = fields if fields req[:sorts] = sorts if sorts data = Array.new begin loop do page = @sdk.all_users(req).collect { |r| r.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::ClientError => e say_error "Unable to get all_users(#{JSON.pretty_generate(req)})" say_error e raise end data end def update_user(id,req) begin @sdk.update_user(id,req)&.to_attrs rescue LookerSDK::NotFound => e say_error "updating user(#{id},#{JSON.pretty_generate(req)}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Error updating user(#{id},#{JSON.pretty_generate(req)})" say_error e raise end end def delete_user(id) begin @sdk.delete_user(id) rescue LookerSDK::NotFound => e say_error "delete user(#{id},#{JSON.pretty_generate(req)}) not found" say_error e raise rescue LookerSDK::Error => e say_error "Error deleting user(#{id})" say_error e raise end end def trim_user(data) data.select do |k,v| (keys_to_keep('create_user') + [:id]).include? k end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/model/set.rb
lib/gzr/modules/model/set.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Model module Set def all_model_sets(fields=nil) req = {} req[:fields] = fields if fields begin @sdk.all_model_sets(req).collect { |s| s.to_attrs } rescue LookerSDK::NotFound => e return nil rescue LookerSDK::Error => e say_error "Error querying all_model_sets(#{JSON.pretty_generate(req)})" say_error e raise end end def cat_model_set(set_id, fields=nil) req = {} req[:fields] = fields if fields begin @sdk.model_set(set_id,req)&.to_attrs rescue LookerSDK::NotFound => e return nil rescue LookerSDK::Error => e say_error "Error querying model_set(#{set_id},#{JSON.pretty_generate(req)})" say_error e raise end end def trim_model_set(data) trimmed = data.select do |k,v| (keys_to_keep('update_model_set') + [:id,:built_in]).include? k end trimmed end def search_model_sets(fields: nil, sorts: nil, id: nil, name: nil, all_access: nil, built_in: nil, filter_or: nil) data = [] begin req = {} req[:fields] = fields unless fields.nil? req[:sorts] = sorts unless sorts.nil? req[:id] = id unless id.nil? req[:name] = name unless name.nil? req[:all_access] = all_access unless all_access.nil? req[:built_in] = built_in unless built_in.nil? req[:filter_or] = filter_or unless filter_or.nil? req[:limit] = 64 loop do page = @sdk.search_model_sets(req).collect { |s| s.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::Error => e say_error "Error calling search_model_sets(#{JSON.pretty_generate(req)})" say_error e raise end data end def update_model_set(model_set_id, data) begin @sdk.update_model_set(model_set_id, data)&.to_attrs rescue LookerSDK::Error => e say_error "Error calling update_model_set(#{model_set_id},#{JSON.pretty_generate(data)})" say_error e raise end end def create_model_set(data) begin @sdk.create_model_set(data)&.to_attrs rescue LookerSDK::Error => e say_error "Error calling create_model_set(#{JSON.pretty_generate(data)})" say_error e raise end end def delete_model_set(model_set_id) begin @sdk.delete_model_set(model_set_id) rescue LookerSDK::Error => e say_error "Error calling delete_model_set(#{model_set_id}})" say_error e raise end end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
looker-open-source/gzr
https://github.com/looker-open-source/gzr/blob/329fd27a33941ecabc87192a5460efdf34352806/lib/gzr/modules/permission/set.rb
lib/gzr/modules/permission/set.rb
# The MIT License (MIT) # Copyright (c) 2023 Mike DeAngelo Google, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # frozen_string_literal: true module Gzr module Permission module Set def all_permission_sets(fields=nil) req = {} req[:fields] = fields if fields begin @sdk.all_permission_sets(req).collect { |s| s.to_attrs } rescue LookerSDK::NotFound => e return nil rescue LookerSDK::Error => e say_error "Error querying all_permission_sets(#{JSON.pretty_generate(req)})" say_error e raise end end def cat_permission_set(set_id, fields=nil) req = {} req[:fields] = fields if fields begin return @sdk.permission_set(set_id,req)&.to_attrs rescue LookerSDK::NotFound => e return nil rescue LookerSDK::Error => e say_error "Error querying permission_set(#{set_id},#{JSON.pretty_generate(req)})" say_error e raise end end def trim_permission_set(data) trimmed = data.select do |k,v| (keys_to_keep('update_permission_set') + [:id,:built_in]).include? k end trimmed end def search_permission_sets(fields: nil, sorts: nil, id: nil, name: nil, all_access: nil, built_in: nil, filter_or: nil) data = [] begin req = {} req[:fields] = fields unless fields.nil? req[:sorts] = sorts unless sorts.nil? req[:id] = id unless id.nil? req[:name] = name unless name.nil? req[:all_access] = all_access unless all_access.nil? req[:built_in] = built_in unless built_in.nil? req[:filter_or] = filter_or unless filter_or.nil? req[:limit] = 64 loop do page = @sdk.search_permission_sets(req).collect { |s| s.to_attrs } data+=page break unless page.length == req[:limit] req[:offset] = (req[:offset] || 0) + req[:limit] end rescue LookerSDK::NotFound => e # do nothing rescue LookerSDK::Error => e say_error "Error calling search_permission_sets(#{JSON.pretty_generate(req)})" say_error e raise end data end def update_permission_set(permission_set_id, data) begin return @sdk.update_permission_set(permission_set_id, data)&.to_attrs rescue LookerSDK::Error => e say_error "Error calling update_permission_set(#{permission_set_id},#{JSON.pretty_generate(data)})" say_error e raise end end def create_permission_set(data) begin return @sdk.create_permission_set(data)&.to_attrs rescue LookerSDK::Error => e say_error "Error calling create_permission_set(#{JSON.pretty_generate(data)})" say_error e raise end end def delete_permission_set(permission_set_id) begin return @sdk.delete_permission_set(permission_set_id) rescue LookerSDK::Error => e say_error "Error calling delete_permission_set(#{permission_set_id}})" say_error e raise end end end end end
ruby
MIT
329fd27a33941ecabc87192a5460efdf34352806
2026-01-04T17:49:18.520281Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/spec/csv-mapper_spec.rb
spec/csv-mapper_spec.rb
require File.dirname(__FILE__) + '/spec_helper.rb' describe CsvMapper do describe "included" do before(:each) do @mapped_klass = Class.new do include CsvMapper def upcase_name(row, index) row[index].upcase end end @mapped = @mapped_klass.new end it "should allow the creation of CSV mappings" do mapping = @mapped.map_csv do start_at_row 2 end mapping.should be_instance_of(CsvMapper::RowMap) mapping.start_at_row.should == 2 end it "should import a CSV IO" do io = 'foo,bar,00,01' results = @mapped.import(io, :type => :io) do first second end results.should be_kind_of(Enumerable) results.should have(1).things results[0].first.should == 'foo' results[0].second.should == 'bar' end it "should import a CSV File IO" do results = @mapped.import(File.dirname(__FILE__) + '/test.csv') do start_at_row 1 [first_name, last_name, age] end results.size.should == 3 end it "should stop importing at a specified row" do results = @mapped.import(File.dirname(__FILE__) + '/test.csv') do start_at_row 1 stop_at_row 2 [first_name, last_name, age] end results.size.should == 2 end it "should be able to read attributes from a csv file" do results = @mapped.import(File.dirname(__FILE__) + '/test.csv') do # we'll alias age here just as an example read_attributes_from_file('Age' => 'number_of_years_old') end results[1].first_name.should == 'Jane' results[1].last_name.should == 'Doe' results[1].number_of_years_old.should == '26' end it "should import non-comma delimited files" do piped_io = 'foo|bar|00|01' results = @mapped.import(piped_io, :type => :io) do delimited_by '|' [first, second] end results.should have(1).things results[0].first.should == 'foo' results[0].second.should == 'bar' end it "should allow named tranformation mappings" do def upcase_name(row) row[0].upcase end results = @mapped.import(File.dirname(__FILE__) + '/test.csv') do start_at_row 1 first_name.map :upcase_name end results[0].first_name.should == 'JOHN' end end describe "extended" do it "should allow the creation of CSV mappings" do mapping = CsvMapper.map_csv do start_at_row 2 end mapping.should be_instance_of(CsvMapper::RowMap) mapping.start_at_row.should == 2 end it "should import a CSV IO" do io = 'foo,bar,00,01' results = CsvMapper.import(io, :type => :io) do first second end results.should be_kind_of(Enumerable) results.should have(1).things results[0].first.should == 'foo' results[0].second.should == 'bar' end it "should import a CSV File IO" do results = CsvMapper.import(File.dirname(__FILE__) + '/test.csv') do start_at_row 1 [first_name, last_name, age] end results.size.should == 3 end it "should stop importing at a specified row" do results = CsvMapper.import(File.dirname(__FILE__) + '/test.csv') do start_at_row 1 stop_at_row 2 [first_name, last_name, age] end results.size.should == 2 end it "should be able to read attributes from a csv file" do results = CsvMapper.import(File.dirname(__FILE__) + '/test.csv') do # we'll alias age here just as an example read_attributes_from_file('Age' => 'number_of_years_old') end results[1].first_name.should == 'Jane' results[1].last_name.should == 'Doe' results[1].number_of_years_old.should == '26' end it "should import non-comma delimited files" do piped_io = 'foo|bar|00|01' results = CsvMapper.import(piped_io, :type => :io) do delimited_by '|' [first, second] end results.should have(1).things results[0].first.should == 'foo' results[0].second.should == 'bar' end it "should not allow tranformation mappings" do def upcase_name(row) row[0].upcase end (lambda do results = CsvMapper.import(File.dirname(__FILE__) + '/test.csv') do start_at_row 1 first_name.map :upcase_name end end).should raise_error(Exception) end end end
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'csv-mapper' require 'spec' require 'spec/autorun' Spec::Runner.configure do |config| end
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/spec/csv-mapper/attribute_map_spec.rb
spec/csv-mapper/attribute_map_spec.rb
require File.dirname(__FILE__) + '/../spec_helper.rb' describe CsvMapper::AttributeMap do class TestContext def transform_it(row, index) :transform_it_success end end before(:each) do @row_attr = CsvMapper::AttributeMap.new('foo', 1, TestContext.new) @csv_row = ['first_name', 'last_name'] end it "should map a destination attribute name" do @row_attr.name.should == 'foo' end it "should map a CSV column index" do @row_attr.index.should be(1) end it "should map a transformation between the CSV value and destination value and chain method calls" do @row_attr.map(:named_transform).should be(@row_attr) end it "should provide ability to set the index and chain method calls" do @row_attr.at(9).should be(@row_attr) @row_attr.index.should be(9) end it "should parse values" do @row_attr.parse(@csv_row).should == @csv_row[1] end it "should parse values using a mapped lambda transformers" do @row_attr.map( lambda{|row, index| :success } ) @row_attr.parse(@csv_row).should == :success end it "should parse values using a mapped lambda transformer that only accepts the row" do @row_attr.map( lambda{|row| :success } ) @row_attr.parse(@csv_row).should == :success end it "should parse values using a mapped block transformers" do @row_attr.map {|row, index| :success } @row_attr.parse(@csv_row).should == :success end it "should parse values using a mapped block transformer that only accepts the row" do @row_attr.map {|row, index| :success } @row_attr.parse(@csv_row).should == :success end it "should parse values using a named method on the context" do @row_attr.map(:transform_it).parse(@csv_row).should == :transform_it_success end it "should provide access to the raw value" do @row_attr.raw_value(@csv_row).should be(@csv_row[@row_attr.index]) end end
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/spec/csv-mapper/row_map_spec.rb
spec/csv-mapper/row_map_spec.rb
require File.dirname(__FILE__) + '/../spec_helper.rb' describe CsvMapper::RowMap do class TestMapToClass attr_accessor :foo, :bar, :baz end class TestMapContext def transform(row, index) :transform_success end def change_name(row, target) row[0] = :changed_name end end before(:each) do @row_map = CsvMapper::RowMap.new(TestMapContext.new) @csv_row = ['first_name', 'last_name'] end it "should parse a CSV row" do @row_map.parse(@csv_row).should_not be_nil end it "should map to a Struct by default" do @row_map.parse(@csv_row).should be_kind_of(Struct) end it "should parse a CSV row returning the mapped result" do @row_map.fname @row_map.lname result = @row_map.parse(@csv_row) result.fname.should == @csv_row[0] result.lname.should == @csv_row[1] end it "should map to a ruby class with optional default attribute values" do @row_map.map_to TestMapToClass, :baz => :default_baz @row_map.foo @row_map.bar (result = @row_map.parse(@csv_row)).should be_instance_of(TestMapToClass) result.foo.should == @csv_row[0] result.bar.should == @csv_row[1] result.baz.should == :default_baz end it "should define Infinity" do CsvMapper::RowMap::Infinity.should == 1.0/0 end it "should start at the specified CSV row" do @row_map.start_at_row.should == 0 @row_map.start_at_row(1) @row_map.start_at_row.should == 1 end it "should stop at the specified row" do @row_map.stop_at_row.should be(CsvMapper::RowMap::Infinity) @row_map.stop_at_row(6) @row_map.stop_at_row.should == 6 end it "should allow before row processing" do @row_map.before_row :change_name, lambda{|row, target| row[1] = 'bar'} @row_map.first_name @row_map.foo result = @row_map.parse(@csv_row) result.first_name.should == :changed_name result.foo.should == 'bar' end it "should allow after row processing" do filter_var = nil @row_map.after_row lambda{|row, target| filter_var = :woot} @row_map.parse(@csv_row) filter_var.should == :woot end it "should have a moveable cursor" do @row_map.cursor.should be(0) @row_map.move_cursor @row_map.cursor.should be(1) @row_map.move_cursor 3 @row_map.cursor.should be(4) end it "should skip indexes" do pre_cursor = @row_map.cursor @row_map._SKIP_ @row_map.cursor.should be(pre_cursor + 1) end it "should accept FasterCSV parser options" do @row_map.parser_options :row_sep => :auto @row_map.parser_options[:row_sep].should == :auto end it "should have a configurable the column delimiter" do @row_map.delimited_by '|' @row_map.delimited_by.should == '|' end it "should maintain a collection of attribute mappings" do @row_map.mapped_attributes.should be_kind_of(Enumerable) end it "should lazy initialize attribute maps and move the cursor" do pre_cursor = @row_map.cursor (attr_map = @row_map.first_name).should be_instance_of(CsvMapper::AttributeMap) attr_map.index.should be(pre_cursor) @row_map.cursor.should be(pre_cursor + 1) end it "should lazy initialize attribute maps with optional cursor position" do pre_cursor = @row_map.cursor @row_map.last_name(1).index.should be(1) @row_map.cursor.should be(1) end it "should share its context with its mappings" do @row_map.first_name.map(:transform) @row_map.parse(@csv_row).first_name.should == :transform_success end end
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper.rb
lib/csv-mapper.rb
dir = File.dirname(__FILE__) $LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir) require 'rubygems' # the following is slightly modified from Gregory Brown's # solution on the Ruport Blaag: # http://ruport.blogspot.com/2008/03/fastercsv-api-shim-for-19.html if RUBY_VERSION > "1.9" require "csv" unless defined? FCSV class Object FasterCSV = CSV alias_method :FasterCSV, :CSV end end else require "fastercsv" end # This module provides the main interface for importing CSV files & data to mapped Ruby objects. # = Usage # Including CsvMapper will provide two methods: # - +import+ # - +map_csv+ # # See csv-mapper.rb[link:files/lib/csv-mapper_rb.html] for method docs. # # === Import From File # results = import('/path/to/file.csv') do # # declare mapping here # end # # === Import From String or IO # results = import(csv_data, :type => :io) do # # declare mapping here # end # # === Mapping # Mappings are built inside blocks. All three of CsvMapper's main API methods accept a block containing a mapping. # Maps are defined by using +map_to+, +start_at_row+, +before_row+, and +after_row+ (methods on CsvMapper::RowMap) and # by defining your own mapping attributes. # A mapping block uses an internal cursor to keep track of the order the mapping attributes are declared and use that order to # know the corresponding CSV column index to associate with the attribute. # # ===== The Basics # * +map_to+ - Override the default Struct target. Accepts a class and an optional hash of default attribute names and values. # * +start_at_row+ - Specify what row to begin parsing at. Use this to skip headers. # * +before_row+ - Accepts an Array of method name symbols or lambdas to be invoked before parsing each row. # * +after_row+ - Accepts an Array of method name symbols or lambdas to be invoked after parsing each row. # * +delimited_by+ - Accepts a character to be used to delimit columns. Use this to specify pipe-delimited files. # * <tt>\_SKIP_</tt> - Use as a placehold to skip a CSV column index. # * +parser_options+ - Accepts a hash of FasterCSV options. Can be anything FasterCSV::new()[http://fastercsv.rubyforge.org/classes/FasterCSV.html#M000018] understands # # ===== Attribute Mappings # Attribute mappings are created by using the name of the attribute to be mapped to. # The order in which attribute mappings are declared determines the index of the corresponding CSV row. # All mappings begin at the 0th index of the CSV row. # foo # maps the 0th CSV row position value to the value of the 'foo' attribute on the target object. # bar # maps the 1st row position to 'bar' # This could also be a nice one liner for easy CSV format conversion # [foo, bar] # creates the same attribute maps as above. # The mapping index may be specifically declared in two additional ways: # foo(2) # maps the 2nd CSV row position value to 'foo' and moves the cursor to 3 # bar # maps the 3rd CSV row position to 'bar' due to the current cursor position # baz.at(0) # maps the 0th CSV row position to 'baz' but only increments the cursor 1 position to 4 # Each attribute mapping may be configured to parse the record using a lambda or a method name # foo.map lambda{|row| row[2].strip } # maps the 2nd row position value with leading and trailing whitespace removed to 'foo'. # bar.map :clean_bar # maps the result of the clean_bar method to 'bar'. clean_bar must accept the row as a parameter. # Attribute mapping declarations and "modifiers" may be chained # foo.at(4).map :some_transform # # === Create Reusable Mappings # The +import+ method accepts an instance of RowMap as an optional mapping parameter. # The easiest way to create an instance of a RowMap is by using +map_csv+. # a_row_map = map_csv do # # declare mapping here # end # Then you can reuse the mapping # results = import(some_string, :type => :io, :map => a_row_map) # other_results = import('/path/to/file.csv', :map => a_row_map) # module CsvMapper # Create a new RowMap instance from the definition in the given block. def map_csv(&map_block) CsvMapper::RowMap.new(self, &map_block) end # Load CSV data and map the values according to the definition in the given block. # Accepts either a file path, String, or IO as +data+. Defaults to file path. # # The following +options+ may be used: # <tt>:type</tt>:: defaults to <tt>:file_path</tt>. Use <tt>:io</tt> to specify data as String or IO. # <tt>:map</tt>:: Specify an instance of a RowMap to take presidence over a given block defintion. # def import(data, options={}, &map_block) csv_data = options[:type] == :io ? data : File.new(data, 'r') config = { :type => :file_path, :map => map_csv_with_data(csv_data, &map_block) }.merge!(options) map = config[:map] results = [] FasterCSV.new(csv_data, map.parser_options ).each_with_index do |row, i| results << map.parse(row) if i >= map.start_at_row && i <= map.stop_at_row end results end protected # Create a new RowMap instance from the definition in the given block and pass the csv_data. def map_csv_with_data(csv_data, &map_block) # :nodoc: CsvMapper::RowMap.new(self, csv_data, &map_block) end extend self end require 'csv-mapper/row_map'
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper/row_map.rb
lib/csv-mapper/row_map.rb
require 'csv-mapper/attribute_map' module CsvMapper # CsvMapper::RowMap provides a simple, DSL-like interface for constructing mappings. # A CsvMapper::RowMap provides the main functionality of the library. It will mostly be used indirectly through the CsvMapper API, # but may be useful to use directly for the dynamic CSV mappings. class RowMap #Start with a 'blank slate' instance_methods.each { |m| undef_method m unless m =~ /^__||instance_eval/ } Infinity = 1.0/0 attr_reader :mapped_attributes # Create a new instance with access to an evaluation context def initialize(context, csv_data = nil, &map_block) @context = context @csv_data = csv_data @before_filters = [] @after_filters = [] @parser_options = {} @start_at_row = 0 @stop_at_row = Infinity @delimited_by = FasterCSV::DEFAULT_OPTIONS[:col_sep] @mapped_attributes = [] self.instance_eval(&map_block) if block_given? end # Each row of a CSV is parsed and mapped to a new instance of a Ruby class; Struct by default. # Use this method to change the what class each row is mapped to. # The given class must respond to a parameter-less #new and all attribute mappings defined. # Providing a hash of defaults will ensure that each resulting object will have the providing name and attribute values # unless overridden by a mapping def map_to(klass, defaults={}) @map_to_klass = klass defaults.each do |name, value| self.add_attribute(name, -99).map lambda{|row, index| value} end end # Allow us to read the first line of a csv file to automatically generate the attribute names. # Spaces are replaced with underscores and non-word characters are removed. # # Keep in mind that there is potential for overlap in using this (i.e. you have a field named # files+ and one named files- and they both get named 'files'). # # You can specify aliases to rename fields to prevent conflicts and/or improve readability and compatibility. # # i.e. read_attributes_from_file('files+' => 'files_plus', 'files-' => 'files_minus) def read_attributes_from_file aliases = {} attributes = FasterCSV.new(@csv_data, @parser_options).readline @start_at_row = [ @start_at_row, 1 ].max @csv_data.rewind attributes.each_with_index do |name, index| name.strip! use_name = aliases[name] || name.gsub(/\s+/, '_').gsub(/[\W]+/, '').downcase add_attribute use_name, index end end # Specify a hash of FasterCSV options to be used for CSV parsing # # Can be anything FasterCSV::new()[http://fastercsv.rubyforge.org/classes/FasterCSV.html#M000018] accepts def parser_options(opts=nil) @parser_options = opts if opts @parser_options.merge :col_sep => @delimited_by end # Convenience method to 'move' the cursor skipping the current index. def _SKIP_ self.move_cursor end # Specify the CSV column delimiter. Defaults to comma. def delimited_by(delimiter=nil) @delimited_by = delimiter if delimiter @delimited_by end # Declare what row to begin parsing the CSV. # This is useful for skipping headers and such. def start_at_row(row_number=nil) @start_at_row = row_number if row_number @start_at_row end # Declare the last row to be parsed in a CSV. def stop_at_row(row_number=nil) @stop_at_row = row_number if row_number @stop_at_row end # Declare method name symbols and/or lambdas to be executed before each row. # Each method or lambda must accept to parameters: +csv_row+, +target_object+ # Methods names should refer to methods available within the RowMap's provided context def before_row(*befores) self.add_filters(@before_filters, *befores) end # Declare method name symbols and/or lambdas to be executed before each row. # Each method or lambda must accept to parameters: +csv_row+, +target_object+ # Methods names should refer to methods available within the RowMap's provided context def after_row(*afters) self.add_filters(@after_filters, *afters) end # Add a new attribute to this map. Mostly used internally, but is useful for dynamic map creation. # returns the newly created CsvMapper::AttributeMap def add_attribute(name, index=nil) attr_mapping = CsvMapper::AttributeMap.new(name.to_sym, index, @context) self.mapped_attributes << attr_mapping attr_mapping end # The current cursor location def cursor # :nodoc: @cursor ||= 0 end # Move the cursor relative to it's current position def move_cursor(positions=1) # :nodoc: self.cursor += positions end # Given a CSV row return an instance of an object defined by this mapping def parse(csv_row) target = self.map_to_class.new @before_filters.each {|filter| filter.call(csv_row, target) } self.mapped_attributes.each do |attr_map| target.send("#{attr_map.name}=", attr_map.parse(csv_row)) end @after_filters.each {|filter| filter.call(csv_row, target) } return target end protected # :nodoc: # The Hacktastic "magic" # Used to dynamically create CsvMapper::AttributeMaps based on unknown method calls that # should represent the names of mapped attributes. # # An optional first argument is used to move this maps cursor position and as the index of the # new AttributeMap def method_missing(name, *args) # :nodoc: if index = args[0] self.move_cursor(index - self.cursor) else index = self.cursor self.move_cursor end add_attribute(name, index) end def add_filters(to_hook, *filters) # :nodoc: (to_hook << filters.collect do |filter| filter.is_a?(Symbol) ? lambda{|row, target| @context.send(filter, row, target)} : filter end).flatten! end def map_to_class # :nodoc: unless @map_to_klass attrs = mapped_attributes.collect {|attr_map| attr_map.name} @map_to_klass = Struct.new(nil, *attrs) end @map_to_klass end def cursor=(value) # :nodoc: @cursor=value end end end
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
pillowfactory/csv-mapper
https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper/attribute_map.rb
lib/csv-mapper/attribute_map.rb
module CsvMapper # A CsvMapper::AttributeMap contains the instructions to parse a value from a CSV row and to know the # name of the attribute it is targeting. class AttributeMap attr_reader :name, :index # Creates a new instance using the provided attribute +name+, CSV row +index+, and evaluation +map_context+ def initialize(name, index, map_context) @name, @index, @map_context = name, index, map_context end # Set the index that this map is targeting. # # Returns this AttributeMap for chainability def at(index) @index = index self end # Provide a lambda or the symbol name of a method on this map's evaluation context to be used when parsing # the value from a CSV row. # Both the lambda or the method provided should accept a single +row+ parameter # # Returns this AttributeMap for chainability def map(transform=nil, &block_transform) @transformer = block_transform || transform self end # Given a CSV row, return the value at this AttributeMap's index using any provided map transforms (see map) def parse(csv_row) @transformer ? parse_transform(csv_row) : raw_value(csv_row) end # Access the raw value of the CSV row without any map transforms applied. def raw_value(csv_row) csv_row[self.index] end private def parse_transform(csv_row) if @transformer.is_a? Symbol transform_name = @transformer @transformer = lambda{|row, index| @map_context.send(transform_name, row, index) } end if @transformer.arity == 1 @transformer.call(csv_row) else @transformer.call(csv_row, @index) end end end end
ruby
MIT
4eb58109cd9f70e29312d150e39a5d18fe1813e6
2026-01-04T17:49:23.915869Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/dat_analysis_subclassing_test.rb
test/dat_analysis_subclassing_test.rb
require "minitest/autorun" require "mocha/setup" require "dat/analysis" # helper class to provide mismatch results class TestCookedAnalyzer < Dat::Analysis attr_accessor :mismatches def initialize(experiment_name) super @mismatches = [] # use a simple array for a mismatch store end # load data files from our fixtures path def path File.expand_path('fixtures/', __FILE__) end def cook(raw_result) return "cooked" unless raw_result "cooked-#{raw_result}" end def count mismatches.size end def read mismatches.pop end # neuter formatter to take simple non-structured results def readable current.inspect end # neuter calls to `puts`, make it possible to test them. def puts(*args) @last_printed = args.join('') nil end attr_reader :last_printed # for tests: last call to puts # neuter calls to 'print' to eliminate test output clutter def print(*args) end end class DatAnalysisSubclassingTest < MiniTest::Unit::TestCase def setup @experiment_name = 'test-suite-experiment' @analyzer = ::TestCookedAnalyzer.new @experiment_name end def test_is_0_when_count_is_overridden_and_there_are_no_mismatches assert_equal 0, @analyzer.count end def test_returns_the_count_of_mismatches_when_count_is_overridden @analyzer.mismatches.push 'mismatch' @analyzer.mismatches.push 'mismatch' assert_equal 2, @analyzer.count end def test_fetch_returns_nil_when_read_is_overridden_and_read_returns_no_mismatches assert_nil @analyzer.fetch end def test_fetch_returns_the_cooked_version_of_the_next_mismatch_from_read_when_read_is_overridden @analyzer.mismatches.push 'mismatch' assert_equal 'cooked-mismatch', @analyzer.fetch end def test_raw_returns_nil_when_no_mismatches_have_been_fetched_and_cook_is_overridden assert_nil @analyzer.raw end def test_current_returns_nil_when_no_mismatches_have_been_fetch_and_cook_is_overridden assert_nil @analyzer.current end def test_raw_returns_nil_when_last_fetched_returns_no_results_and_cook_is_overridden @analyzer.fetch assert_nil @analyzer.raw end def test_current_returns_nil_when_last_fetched_returns_no_results_and_cook_is_overridden @analyzer.fetch assert_nil @analyzer.current end def test_raw_returns_unprocess_mismatch_when_cook_is_overridden @analyzer.mismatches.push 'mismatch-1' result = @analyzer.fetch assert_equal 'mismatch-1', @analyzer.raw end def test_current_returns_a_cooked_mismatch_when_cook_is_overridden @analyzer.mismatches.push 'mismatch-1' result = @analyzer.fetch assert_equal 'cooked-mismatch-1', @analyzer.current end def test_raw_updates_with_later_fetches_when_cook_is_overridden @analyzer.mismatches.push 'mismatch-1' @analyzer.mismatches.push 'mismatch-2' @analyzer.fetch # discard the first one @analyzer.fetch assert_equal 'mismatch-1', @analyzer.raw end def test_current_updates_with_later_fetches_when_cook_is_overridden @analyzer.mismatches.push 'mismatch-1' @analyzer.mismatches.push 'mismatch-2' @analyzer.fetch # discard the first one @analyzer.fetch assert_equal 'cooked-mismatch-1', @analyzer.current end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/dat_analysis_test.rb
test/dat_analysis_test.rb
require "minitest/autorun" require "mocha/setup" require "dat/analysis" require "time" # helper class to provide mismatch results class TestMismatchAnalysis < Dat::Analysis attr_accessor :mismatches def initialize(experiment_name) super @mismatches = [] # use a simple array for a mismatch store end # load data files from our fixtures path def path File.expand_path(File.join(File.dirname(__FILE__), 'fixtures')) end def count mismatches.size end def read mismatches.pop end # neuter formatter to take simple non-structured results def readable current.inspect end # neuter calls to `puts`, make it possible to test them. def puts(*args) @last_printed = args.join('') nil end attr_reader :last_printed # for tests: last call to puts # neuter calls to 'print' to eliminate test output clutter def print(*args) end end # for testing that a non-registered Recognizer class can still # supply a default `#readable` method to subclasses class TestSubclassRecognizer < Dat::Analysis::Matcher def readable "experiment-formatter: #{result['extra']}" end end class DatAnalysisTest < MiniTest::Unit::TestCase def setup Dat::Analysis::Tally.any_instance.stubs(:puts) @experiment_name = 'test-suite-experiment' @analyzer = TestMismatchAnalysis.new @experiment_name @timestamp = Time.now @result = { 'experiment' => @experiment_name, 'control' => { 'duration' => 0.03, 'exception' => nil, 'value' => true, }, 'candidate' => { 'duration' => 1.03, 'exception' => nil, 'value' => false, }, 'first' => 'candidate', 'extra' => 'bacon', 'timestamp' => @timestamp.to_s } end def test_preserves_the_experiment_name assert_equal @experiment_name, @analyzer.experiment_name end def test_analyze_returns_nil_if_there_is_no_current_result_and_no_additional_results assert_nil @analyzer.analyze end def test_analyze_leaves_tallies_empty_if_there_is_no_current_result_and_no_additional_results @analyzer.analyze assert_equal({}, @analyzer.tally.tally) end def test_analyze_returns_nil_if_there_is_a_current_result_but_no_additional_results @analyzer.mismatches.push @result @analyzer.fetch assert @analyzer.current assert_nil @analyzer.analyze end def test_analyze_leaves_tallies_empty_if_there_is_a_current_result_but_no_additional_results @analyzer.mismatches.push @result @analyzer.fetch assert @analyzer.current @analyzer.analyze assert_equal({}, @analyzer.tally.tally) end def test_analyze_outputs_default_result_summary_and_tally_summary_when_one_unrecognized_result_is_present @analyzer.expects(:summarize_unknown_result) @analyzer.mismatches.push @result @analyzer.analyze end def test_analyze_returns_nil_when_one_unrecognized_result_is_present @analyzer.mismatches.push @result assert_nil @analyzer.analyze end def test_analyze_leaves_current_result_set_to_first_result_when_one_unrecognized_result_is_present @analyzer.mismatches.push @result @analyzer.analyze assert_equal @result, @analyzer.current end def test_analyze_leaves_tallies_empty_when_one_unrecognized_result_is_present @analyzer.mismatches.push @result @analyzer.analyze assert_equal({}, @analyzer.tally.tally) end def test_analyze_outputs_default_results_summary_for_first_unrecognized_result_and_tally_summary_when_recognized_and_unrecognized_results_are_present matcher = Class.new(Dat::Analysis::Matcher) do def match? result['extra'] =~ /^known-/ end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'known-1') @analyzer.mismatches.push @result.merge('extra' => 'unknown-1') @analyzer.mismatches.push @result.merge('extra' => 'known-2') @analyzer.expects(:summarize_unknown_result) @analyzer.analyze end def test_analyze_returns_number_of_unanalyzed_results_when_recognized_and_unrecognized_results_are_present matcher = Class.new(Dat::Analysis::Matcher) do def match? result['extra'] =~ /^known-/ end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'known-1') @analyzer.mismatches.push @result.merge('extra' => 'unknown-1') @analyzer.mismatches.push @result.merge('extra' => 'known-2') assert_equal 1, @analyzer.analyze end def test_analyze_leaves_current_result_set_to_first_unrecognized_result_when_recognized_and_unrecognized_results_are_present matcher = Class.new(Dat::Analysis::Matcher) do def match? result['extra'] =~ /^known/ end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'known-1') @analyzer.mismatches.push @result.merge('extra' => 'unknown-1') @analyzer.mismatches.push @result.merge('extra' => 'known-2') @analyzer.analyze assert_equal 'unknown-1', @analyzer.current['extra'] end def test_analyze_leaves_recognized_result_counts_in_tally_when_recognized_and_unrecognized_results_are_present matcher1 = Class.new(Dat::Analysis::Matcher) do def self.name() "RecognizerOne" end def match? result['extra'] =~ /^known-1/ end end matcher2 = Class.new(Dat::Analysis::Matcher) do def self.name() "RecognizerTwo" end def match? result['extra'] =~ /^known-2/ end end @analyzer.add matcher1 @analyzer.add matcher2 @analyzer.mismatches.push @result.merge('extra' => 'known-1-last') @analyzer.mismatches.push @result.merge('extra' => 'unknown-1') @analyzer.mismatches.push @result.merge('extra' => 'known-10') @analyzer.mismatches.push @result.merge('extra' => 'known-20') @analyzer.mismatches.push @result.merge('extra' => 'known-11') @analyzer.mismatches.push @result.merge('extra' => 'known-21') @analyzer.mismatches.push @result.merge('extra' => 'known-12') @analyzer.analyze tally = @analyzer.tally.tally assert_equal [ 'RecognizerOne', 'RecognizerTwo' ], tally.keys.sort assert_equal 3, tally['RecognizerOne'] assert_equal 2, tally['RecognizerTwo'] end def test_analyze_proceeds_from_stop_point_when_analyzing_with_more_results matcher = Class.new(Dat::Analysis::Matcher) do def match? result['extra'] =~ /^known-/ end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'known-1') @analyzer.mismatches.push @result.merge('extra' => 'unknown-1') @analyzer.mismatches.push @result.merge('extra' => 'known-2') @analyzer.mismatches.push @result.merge('extra' => 'unknown-2') @analyzer.mismatches.push @result.merge('extra' => 'known-3') assert_equal 3, @analyzer.analyze assert_equal 'unknown-2', @analyzer.current['extra'] assert_equal 1, @analyzer.analyze assert_equal 'unknown-1', @analyzer.current['extra'] assert_equal @analyzer.readable, @analyzer.last_printed end def test_analyze_resets_tally_between_runs_when_analyzing_later_results_after_a_stop matcher1 = Class.new(Dat::Analysis::Matcher) do def self.name() "RecognizerOne" end def match? result['extra'] =~ /^known-1/ end end matcher2 = Class.new(Dat::Analysis::Matcher) do def self.name() "RecognizerTwo" end def match? result['extra'] =~ /^known-2/ end end @analyzer.add matcher1 @analyzer.add matcher2 @analyzer.mismatches.push @result.merge('extra' => 'known-1-last') @analyzer.mismatches.push @result.merge('extra' => 'unknown-1') @analyzer.mismatches.push @result.merge('extra' => 'known-10') @analyzer.mismatches.push @result.merge('extra' => 'known-20') @analyzer.mismatches.push @result.merge('extra' => 'known-11') @analyzer.mismatches.push @result.merge('extra' => 'known-21') @analyzer.mismatches.push @result.merge('extra' => 'known-12') @analyzer.analyze # proceed to first stop point @analyzer.analyze # and continue analysis assert_equal({'RecognizerOne' => 1}, @analyzer.tally.tally) end def test_skip_fails_if_no_block_is_provided assert_raises(ArgumentError) do @analyzer.skip end end def test_skip_returns_nil_if_there_is_no_current_result remaining = @analyzer.skip do |result| true end assert_nil remaining end def test_skip_leaves_current_alone_if_the_current_result_satisfies_the_block @analyzer.mismatches.push @result @analyzer.skip do |result| true end end def test_skip_returns_0_if_the_current_result_does_not_satisfy_the_block_and_no_other_results_are_available @analyzer.mismatches.push @result remaining = @analyzer.skip do |result| false end assert_equal 0, remaining end def test_skip_returns_the_number_of_additional_results_if_the_current_result_does_not_satisfy_the_block_and_other_results_are_available @analyzer.mismatches.push @result @analyzer.mismatches.push @result @analyzer.mismatches.push @result remaining = @analyzer.skip do |result| false end assert_equal 2, remaining end def test_skip_returns_nil_if_all_results_are_satisfying @analyzer.mismatches.push @result @analyzer.mismatches.push @result @analyzer.mismatches.push @result remaining = @analyzer.skip do |result| true end assert_nil remaining end def test_skip_skips_all_results_if_all_results_are_satisfying @analyzer.mismatches.push @result @analyzer.mismatches.push @result @analyzer.mismatches.push @result remaining = @analyzer.skip do |result| true end assert !@analyzer.more? end def test_skip_leaves_current_as_nil_if_all_results_are_satisfying @analyzer.mismatches.push @result @analyzer.mismatches.push @result @analyzer.mismatches.push @result remaining = @analyzer.skip do |result| true end assert_nil @analyzer.current end def test_more_is_false_when_there_are_no_mismatches assert !@analyzer.more? end def test_more_is_true_when_there_are_mismatches @analyzer.mismatches.push @result assert @analyzer.more? end def test_count_fails assert_raises(NoMethodError) do Dat::Analysis.new(@experiment_name).count end end def test_fetch_fails_unless_read_is_implemented_by_a_subclass assert_raises(NameError) do Dat::Analysis.new(@experiment_name).fetch end end def test_current_returns_nil_when_no_mismmatches_have_been_fetched assert_nil @analyzer.current end def test_current_returns_nil_when_last_fetch_returned_no_results @analyzer.fetch assert_nil @analyzer.current end def test_current_returns_the_most_recent_mismatch_when_one_has_been_fetched @analyzer.mismatches.push @result @analyzer.fetch assert_equal @result, @analyzer.current end def test_current_updates_with_later_fetches @analyzer.mismatches.push @result @analyzer.mismatches.push @result @analyzer.fetch result = @analyzer.fetch assert_equal result, @analyzer.current end def test_result_is_an_alias_for_current @analyzer.mismatches.push @result @analyzer.mismatches.push @result @analyzer.fetch result = @analyzer.fetch assert_equal result, @analyzer.result end def test_raw_returns_nil_when_no_mismatches_have_been_fetched assert_nil @analyzer.raw end def test_raw_returns_nil_when_last_fetched_returned_no_results @analyzer.fetch assert_nil @analyzer.raw end def test_raw_returns_an_unprocessed_version_of_the_most_recent_mismatch @analyzer.mismatches.push @result result = @analyzer.fetch assert_equal @result, @analyzer.raw end def test_raw_updates_with_later_fetches @analyzer.mismatches.push 'mismatch-1' @analyzer.mismatches.push 'mismatch-2' @analyzer.fetch # discard the first one @analyzer.fetch assert_equal 'mismatch-1', @analyzer.raw end def test_when_loading_support_classes_loads_no_matchers_if_no_matcher_files_exist_on_load_path analyzer = TestMismatchAnalysis.new('experiment-with-no-classes') analyzer.load_classes assert_equal [], analyzer.matchers assert_equal [], analyzer.wrappers end def test_when_loading_support_classes_loads_matchers_and_wrappers_if_they_exist_on_load_path analyzer = TestMismatchAnalysis.new('experiment-with-classes') analyzer.load_classes assert_equal ["MatcherA", "MatcherB", "MatcherC"], analyzer.matchers.map(&:name) assert_equal ["WrapperA", "WrapperB", "WrapperC"], analyzer.wrappers.map(&:name) end def test_when_loading_support_classes_ignores_extraneous_classes_on_load_path analyzer = TestMismatchAnalysis.new('experiment-with-good-and-extraneous-classes') analyzer.load_classes assert_equal ["MatcherX", "MatcherY", "MatcherZ"], analyzer.matchers.map(&:name) assert_equal ["WrapperX", "WrapperY", "WrapperZ"], analyzer.wrappers.map(&:name) end def test_when_loading_support_classes_loads_classes_at_initialization_time_if_they_are_available analyzer = TestMismatchAnalysis.new('initialize-classes') assert_equal ["MatcherM", "MatcherN"], analyzer.matchers.map(&:name) assert_equal ["WrapperM", "WrapperN"], analyzer.wrappers.map(&:name) end def test_when_loading_support_classes_does_not_load_classes_at_initialization_time_if_they_cannot_be_loaded analyzer = TestMismatchAnalysis.new('invalid-matcher') assert_equal [], analyzer.matchers end def test_loading_classes_post_initialization_fails_if_loading_has_errors # fails at #load_classes time since we define #path later analyzer = Dat::Analysis.new('invalid-matcher') analyzer.path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures')) assert_raises(Errno::EACCES) do analyzer.load_classes end end def test_result_has_an_useful_timestamp @analyzer.mismatches.push(@result) result = @analyzer.fetch assert_equal @timestamp.to_i, result.timestamp.to_i end def test_result_has_a_method_for_first @analyzer.mismatches.push(@result) result = @analyzer.fetch assert_equal @result['first'], result.first end def test_result_has_a_method_for_control @analyzer.mismatches.push(@result) result = @analyzer.fetch assert_equal @result['control'], result.control end def test_result_has_a_method_for_candidate @analyzer.mismatches.push(@result) result = @analyzer.fetch assert_equal @result['candidate'], result.candidate end def test_result_has_a_method_for_experiment_name @analyzer.mismatches.push(@result) result = @analyzer.fetch assert_equal @result['experiment'], result.experiment_name end def test_results_helper_methods_are_not_available_on_results_unless_loaded @analyzer.mismatches.push @result result = @analyzer.fetch assert_raises(NoMethodError) do result.repository end end def test_results_helper_methods_are_made_available_on_returned_results wrapper = Class.new(Dat::Analysis::Result) do def repository 'github/dat-science' end end @analyzer.add wrapper @analyzer.mismatches.push @result result = @analyzer.fetch assert_equal 'github/dat-science', result.repository end def test_results_helper_methods_can_be_loaded_from_multiple_classes wrapper1 = Class.new(Dat::Analysis::Result) do def repository 'github/dat-science' end end wrapper2 = Class.new(Dat::Analysis::Result) do def user :rick end end @analyzer.add wrapper1 @analyzer.add wrapper2 @analyzer.mismatches.push @result result = @analyzer.fetch assert_equal 'github/dat-science', result.repository assert_equal :rick, result.user end def test_results_helper_methods_are_made_available_in_the_order_loaded wrapper1 = Class.new(Dat::Analysis::Result) do def repository 'github/dat-science' end end wrapper2 = Class.new(Dat::Analysis::Result) do def repository 'github/linguist' end def user :rick end end @analyzer.add wrapper1 @analyzer.add wrapper2 @analyzer.mismatches.push @result result = @analyzer.fetch assert_equal 'github/dat-science', result.repository assert_equal :rick, result.user end def test_results_helper_methods_do_not_hide_existing_result_methods wrapper = Class.new(Dat::Analysis::Result) do def size 'huge' end end @analyzer.add wrapper @analyzer.mismatches.push 'mismatch-1' result = @analyzer.fetch assert_equal 10, result.size end def test_methods_can_access_the_result_using_the_result_method wrapper = Class.new(Dat::Analysis::Result) do def esrever result.reverse end end @analyzer.add wrapper @analyzer.mismatches.push 'mismatch-1' result = @analyzer.fetch assert_equal 'mismatch-1'.reverse, result.esrever end def test_summarize_returns_nil_and_prints_the_empty_string_if_no_result_is_current assert_nil @analyzer.summarize assert_equal "", @analyzer.last_printed end def test_summarize_returns_nil_and_prints_the_default_readable_result_if_a_result_is_current_but_no_matchers_are_known @analyzer.mismatches.push @result @analyzer.fetch assert_nil @analyzer.summarize assert_equal @analyzer.readable, @analyzer.last_printed end def test_summarize_returns_nil_and_prints_the_default_readable_result_if_a_result_is_current_but_not_matched_by_any_known_matchers matcher = Class.new(Dat::Analysis::Matcher) do def match? false end def readable 'this should never run' end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_nil @analyzer.summarize assert_equal @analyzer.readable, @analyzer.last_printed end def test_summarize_returns_nil_and_prints_the_matchers_readable_result_when_a_result_is_current_and_matched_by_a_matcher matcher = Class.new(Dat::Analysis::Matcher) do def match? true end def readable "recognized: #{result['extra']}" end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'mismatch-1') @analyzer.fetch assert_nil @analyzer.summarize assert_equal "recognized: mismatch-1", @analyzer.last_printed end def test_summarize_returns_nil_and_prints_the_default_readable_result_when_a_result_is_matched_by_a_matcher_with_no_formatter matcher = Class.new(Dat::Analysis::Matcher) do def match? true end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_nil @analyzer.summarize assert_equal @analyzer.readable, @analyzer.last_printed end def test_summarize_supports_use_of_a_matcher_base_class_for_shared_formatting matcher = Class.new(TestSubclassRecognizer) do def match? true end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'mismatch-1') @analyzer.fetch assert_nil @analyzer.summarize assert_equal "experiment-formatter: mismatch-1", @analyzer.last_printed end def test_summary_returns_nil_if_no_result_is_current assert_nil @analyzer.summary end def test_summary_returns_the_default_readable_result_if_a_result_is_current_but_no_matchers_are_known @analyzer.mismatches.push @result @analyzer.fetch assert_equal @analyzer.readable, @analyzer.summary end def test_summary_returns_the_default_readable_result_if_a_result_is_current_but_not_matched_by_any_known_matchers matcher = Class.new(Dat::Analysis::Matcher) do def match? false end def readable 'this should never run' end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_equal @analyzer.readable, @analyzer.summary end def test_summary_returns_the_matchers_readable_result_when_a_result_is_current_and_matched_by_a_matcher matcher = Class.new(Dat::Analysis::Matcher) do def match? true end def readable "recognized: #{result['extra']}" end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'mismatch-1') @analyzer.fetch assert_equal "recognized: mismatch-1", @analyzer.summary end def test_summary_formats_with_the_default_formatter_if_a_matching_matcher_does_not_define_a_formatter matcher = Class.new(Dat::Analysis::Matcher) do def match? true end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_equal @analyzer.readable, @analyzer.summary end def test_summary_supports_use_of_a_matcher_base_class_for_shared_formatting matcher = Class.new(TestSubclassRecognizer) do def match? true end end @analyzer.add matcher @analyzer.mismatches.push @result.merge('extra' => 'mismatch-1') @analyzer.fetch assert_equal "experiment-formatter: mismatch-1", @analyzer.summary end def test_unknown_returns_nil_if_no_result_is_current assert_nil @analyzer.unknown? end def test_unknown_returns_true_if_a_result_is_current_but_no_matchers_are_known @analyzer.mismatches.push @result @analyzer.fetch assert_equal true, @analyzer.unknown? end def test_unknown_returns_true_if_current_result_is_not_matched_by_any_known_matchers matcher = Class.new(Dat::Analysis::Matcher) do def match? false end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_equal true, @analyzer.unknown? end def test_unknown_returns_false_if_a_matcher_class_matches_the_current_result matcher = Class.new(Dat::Analysis::Matcher) do def match? true end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_equal false, @analyzer.unknown? end def test_identify_returns_nil_if_no_result_is_current assert_nil @analyzer.identify end def test_identify_returns_nil_if_a_result_is_current_but_no_matchers_are_known @analyzer.mismatches.push @result @analyzer.fetch assert_nil @analyzer.identify end def test_identify_returns_nil_if_current_result_is_not_matched_by_any_known_matchers matcher = Class.new(Dat::Analysis::Matcher) do def match? false end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_nil @analyzer.identify end def test_identify_returns_the_matcher_class_which_matches_the_current_result matcher = Class.new(Dat::Analysis::Matcher) do def match? true end end @analyzer.add matcher @analyzer.mismatches.push @result @analyzer.fetch assert_equal matcher, @analyzer.identify.class end def test_identify_fails_if_more_than_one_matcher_class_matches_the_current_result matcher1 = Class.new(Dat::Analysis::Matcher) do def match? true end end matcher2 = Class.new(Dat::Analysis::Matcher) do def match? true end end @analyzer.add matcher1 @analyzer.add matcher2 @analyzer.mismatches.push @result @analyzer.fetch assert_raises(RuntimeError) do @analyzer.identify end end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/invalid-matcher/matcher.rb
test/fixtures/invalid-matcher/matcher.rb
raise Errno::EACCES
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-good-and-extraneous-classes/wrapper_y.rb
test/fixtures/experiment-with-good-and-extraneous-classes/wrapper_y.rb
class WrapperX < Dat::Analysis::Result def user 'wrapper-x-user' end end class WrapperY < Dat::Analysis::Result def user 'wrapper-y-user' end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-good-and-extraneous-classes/wrapper_w.rb
test/fixtures/experiment-with-good-and-extraneous-classes/wrapper_w.rb
class WrapperW def match? true end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-good-and-extraneous-classes/wrapper_z.rb
test/fixtures/experiment-with-good-and-extraneous-classes/wrapper_z.rb
class WrapperZ < Dat::Analysis::Result def user 'wrapper-z-user' end end class WrapperV def user 'wrapper-v-user' end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-good-and-extraneous-classes/matcher_w.rb
test/fixtures/experiment-with-good-and-extraneous-classes/matcher_w.rb
class MatcherW def match? true end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-good-and-extraneous-classes/matcher_y.rb
test/fixtures/experiment-with-good-and-extraneous-classes/matcher_y.rb
class MatcherX < Dat::Analysis::Matcher def match? result =~ /b/ end end class MatcherY < Dat::Analysis::Matcher def match? result =~ /c/ end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-good-and-extraneous-classes/matcher_z.rb
test/fixtures/experiment-with-good-and-extraneous-classes/matcher_z.rb
class MatcherZ < Dat::Analysis::Matcher def match? result =~ /^known/ end end class MatcherV def match? true end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/analysis/test-suite-experiment/matcher.rb
test/fixtures/analysis/test-suite-experiment/matcher.rb
class MatcherA < Dat::Analysis::Matcher end class MatcherB < Dat::Analysis::Matcher end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-classes/matcher_b.rb
test/fixtures/experiment-with-classes/matcher_b.rb
class MatcherB < Dat::Analysis::Matcher def match? result =~ /b/ end end class MatcherC < Dat::Analysis::Matcher def match? result =~ /c/ end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-classes/matcher_a.rb
test/fixtures/experiment-with-classes/matcher_a.rb
class MatcherA < Dat::Analysis::Matcher def match? result =~ /^known/ end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-classes/wrapper_b.rb
test/fixtures/experiment-with-classes/wrapper_b.rb
class WrapperB < Dat::Analysis::Result def repository 'wrapper-b-repository' end end class WrapperC < Dat::Analysis::Result def repository 'wrapper-c-repository' end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/experiment-with-classes/wrapper_a.rb
test/fixtures/experiment-with-classes/wrapper_a.rb
class WrapperA < Dat::Analysis::Result def repository 'wrapper-a-repository' end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/initialize-classes/matcher_m.rb
test/fixtures/initialize-classes/matcher_m.rb
class MatcherM < Dat::Analysis::Matcher def match? result =~ /^known/ end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/initialize-classes/wrapper_m.rb
test/fixtures/initialize-classes/wrapper_m.rb
class WrapperM < Dat::Analysis::Result def repository 'wrapper-m-repository' end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/initialize-classes/matcher_n.rb
test/fixtures/initialize-classes/matcher_n.rb
class MatcherN < Dat::Analysis::Matcher def match? result =~ /n/ end end class MatcherO def match? true end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/test/fixtures/initialize-classes/wrapper_n.rb
test/fixtures/initialize-classes/wrapper_n.rb
class WrapperN < Dat::Analysis::Result def repository 'wrapper-n-repository' end end class WrapperO def repository 'wrapper-o-repository' end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/lib/dat/analysis.rb
lib/dat/analysis.rb
module Dat # Public: Analyze the findings of an Experiment # # Typically implementors will wish to subclass this to provide their own # implementations of the following methods suited to the environment where # `dat-science` is being used: `#read`, `#count`, `#cook`. # # Example: # # class AnalyzeThis < Dat::Analysis # # Read a result out of our redis stash # def read # RedisHandle.rpop "scienceness.#{experiment_name}.results" # end # # # Query our redis stash to see how many new results are pending # def count # RedisHandle.llen("scienceness.#{experiment_name}.results") # end # # # Deserialize a JSON-encoded result from redis # def cook(raw_result) # return nil unless raw_result # JSON.parse raw_result # end # end class Analysis # Public: Returns the name of the experiment attr_reader :experiment_name # Public: Returns the current science mismatch result attr_reader :current # Public: an alias for #current alias_method :result, :current # Public: Returns a raw ("un-cooked") version of the current science mismatch result attr_reader :raw # Public: Gets/Sets the base path for loading matcher and wrapper classes. # Note that the base path will be appended with the experiment name # before searching for wrappers and matchers. attr_accessor :path # Public: Create a new Dat::Analysis object. Will load any matcher and # wrapper classes for this experiment if `#path` is non-nil. # # experiment_name - The String naming the experiment to analyze. # # Examples # # analyzer = Dat::Analysis.new('bcrypt-passwords') # => #<Dat::Analysis:...> def initialize(experiment_name) @experiment_name = experiment_name @wrappers = [] load_classes unless path.nil? rescue nil end # Public: process a raw science mismatch result to make it usable in analysis. # This is typically overridden by subclasses to do any sort of unmarshalling # or deserialization required. # # raw_result - a raw science mismatch result, typically, as returned by `#read` # # Returns a "cooked" science mismatch result. def cook(raw_result) raw_result end # Public: fetch and summarize pending science mismatch results until an # an unrecognized result is found. Outputs summaries to STDOUT. May # modify current mismatch result. # # Returns nil. Leaves current mismatch result set to first unknown result, # if one is found. def analyze track do while true unless more? fetch # clear current result return summarize_unknown_result end fetch break if unknown? summarize count_as_seen identify end print "\n" summarize_unknown_result end end # Public: skip pending mismatch results satisfying the provided block. # May modify current mismatch result. # # &block - block accepting a prepared mismatch result and returning true # if the result should be skipped and false otherwise. # # Examples: # # skip do |result| # result.user.staff? # end # # skip do |result| # result['group']['id'] > 100 && result['url'] =~ %r{/admin} # end # # skip do |result| # result['timestamp'].to_i > 1.hour.ago # end # # Returns nil if all results are skipped. Current result will be nil. # Returns count of remaining results if a result not matching the skip # condition is found. Leaves current result set to first result for # which block returns a falsey value. def skip(&block) raise ArgumentError, "a block is required" unless block_given? while more? fetch return count unless yield(current) end # clear current result since nothing of interest was found. @current = @identified = nil end # Public: Are additional science mismatch results available? # # Returns true if more results can be fetched. # Returns false if no more results can be fetched. def more? count != 0 end # Public: retrieve a new science mismatch result, as returned by `#read`. # # Returns nil if no new science mismatch results are available. # Returns a cooked and wrapped science mismatch result if available. # Raises NoMethodError if `#read` is not defined on this class. def fetch @identified = nil @raw = read @current = raw ? prepare(raw) : nil end # Public: Return a readable representation of the current science mismatch # result. This will utilize the `#readable` methods declared on a matcher # which identifies the current result. # # Returns a string containing a readable representation of the current # science mismatch result. # Returns nil if there is no current result. def summary return nil unless current recognizer = identify return readable unless recognizer && recognizer.respond_to?(:readable) recognizer.readable end # Public: Print a readable summary for the current science mismatch result # to STDOUT. # # Returns nil. def summarize puts summary end # Public: Is the current science mismatch result unidentifiable? # # Returns nil if current result is nil. # Returns true if no matcher can identify current result. # Returns false if a single matcher can identify the current result. # Raises RuntimeError if multiple matchers can identify the current result. def unknown? return nil if current.nil? !identify end # Public: Find a matcher which can identify the current science mismatch result. # # Returns nil if current result is nil. # Returns matcher class if a single matcher can identify current result. # Returns false if no matcher can identify the current result. # Raises RuntimeError if multiple matchers can identify the current result. def identify return @identified if @identified results = registry.identify(current) if results.size > 1 report_multiple_matchers(results) end @identified = results.first end # Internal: Output failure message about duplicate matchers for a science # mismatch result. # # dupes - Array of Dat::Analysis::Matcher instances, initialized with a result # # Raises RuntimeError. def report_multiple_matchers(dupes) puts "\n\nMultiple matchers identified result:" puts dupes.each_with_index do |matcher, i| print " #{i+1}. " if matcher.respond_to?(:readable) puts matcher.readable else puts readable end end puts raise "Result cannot be uniquely identified." end # Internal: cook and wrap a raw science mismatch result. # # raw_result - an unmodified result, typically, as returned by `#read` # # Returns the science mismatch result processed by `#cook` and then by `#wrap`. def prepare(raw_result) wrap(cook(raw_result)) end # Internal: wrap a "cooked" science mismatch result with any known wrapper methods # # cooked_result - a "cooked" mismatch result, as returned by `#cook` # # Returns the cooked science mismatch result, which will now respond to any # instance methods found on our known wrapper classes def wrap(cooked_result) cooked_result.extend Dat::Analysis::Result::DefaultMethods if !wrappers.empty? cooked_result.send(:instance_variable_set, '@analyzer', self) class << cooked_result define_method(:method_missing) do |meth, *args| found = nil @analyzer.wrappers.each do |wrapper| next unless wrapper.public_instance_methods.detect {|m| m.to_s == meth.to_s } found = wrapper.new(self).send(meth, *args) break end found end end end cooked_result end # Internal: Return the *default* readable representation of the current science # mismatch result. This method is typically overridden by subclasses or defined # in matchers which wish to customize the readable representation of a science # mismatch result. This implementation is provided as a default. # # Returns a string containing a readable representation of the current # science mismatch result. def readable synopsis = [] synopsis << "Experiment %-20s first: %10s @ %s" % [ "[#{current['experiment']}]", current['first'], current['timestamp'] ] synopsis << "Duration: control (%6.2f) | candidate (%6.2f)" % [ current['control']['duration'], current['candidate']['duration'] ] synopsis << "" if current['control']['exception'] synopsis << "Control raised exception:\n\t#{current['control']['exception'].inspect}" else synopsis << "Control value: [#{current['control']['value']}]" end if current['candidate']['exception'] synopsis << "Candidate raised exception:\n\t#{current['candidate']['exception'].inspect}" else synopsis << "Candidate value: [#{current['candidate']['value']}]" end synopsis << "" remaining = current.keys - ['control', 'candidate', 'experiment', 'first', 'timestamp'] remaining.sort.each do |key| if current[key].respond_to?(:keys) # do ordered sorting of hash keys subkeys = key_sort(current[key].keys) synopsis << "\t%15s => {" % [ key ] subkeys.each do |subkey| synopsis << "\t%15s %15s => %-20s" % [ '', subkey, current[key][subkey].inspect ] end synopsis << "\t%15s }" % [ '' ] else synopsis << "\t%15s => %-20s" % [ key, current[key] ] end end synopsis.join "\n" end def preferred_fields %w(id name title owner description login username) end def key_sort(keys) str_keys = keys.map {|k| k.to_s } (preferred_fields & str_keys) + (str_keys - preferred_fields) end # Public: Which matcher classes are known? # # Returns: list of Dat::Analysis::Matcher classes known to this analyzer. def matchers registry.matchers end # Public: Which wrapper classes are known? # # Returns: list of Dat::Analysis::Result classes known to this analyzer. def wrappers registry.wrappers end # Public: Add a matcher or wrapper class to this analyzer. # # klass - a subclass of either Dat::Analysis::Matcher or Dat::Analysis::Result # to be registered with this analyzer. # # Returns the list of known matchers and wrappers for this analyzer. def add(klass) klass.add_to_analyzer(self) end # Public: Load matcher and wrapper classes from the library for our experiment. # # Returns: a list of loaded matcher and wrapper classes. def load_classes new_classes = library.select_classes do experiment_files.each { |file| load file } end new_classes.map {|klass| add klass } end # Internal: Print to STDOUT a readable summary of the current (unknown) science # mismatch result, as well a summary of the tally of identified science mismatch # results analyzed to this point. # # Returns nil if there are no pending science mismatch results. # Returns the number of pending science mismatch results. def summarize_unknown_result tally.summarize if current puts "\nFirst unidentifiable result:\n\n" summarize else puts "\nNo unidentifiable results found. \\m/\n" end more? ? count : nil end # Internal: keep a tally of analyzed science mismatch results. # # &block: block which will presumably call `#count_as_seen` to update # tallies of identified science mismatch results. # # Returns: value returned by &block. def track(&block) @tally = Tally.new yield end # Internal: Increment count for an object in an ongoing tally. # # obj - an Object for which we are recording occurrence counts # # Returns updated tally count for obj. def count_as_seen(obj) tally.count(obj.class.name || obj.class.inspect) end # Internal: The current Tally instance. Cached between calls to `#track`. # # Returns the current Tally instance object. def tally @tally ||= Tally.new end # Internal: handle to the library, used for collecting newly discovered # matcher and wrapper classes. # # Returns: handle to the library class. def library Dat::Analysis::Library end # Internal: registry of wrapper and matcher classes known to this analyzer. # # Returns a (cached between calls) handle to our registry instance. def registry @registry ||= Dat::Analysis::Registry.new end # Internal: which class files are candidates for loading matchers and wrappers # for this experiment? # # Returns: sorted Array of paths to ruby files which may contain declarations # of matcher and wrapper classes for this experiment. def experiment_files Dir[File.join(path, experiment_name, '*.rb')].sort end # Internal: Add a matcher class to this analyzer's registry. # (Intended to be called only by Dat::Analysis::Matcher and subclasses) def add_matcher(matcher_class) puts "Loading matcher class [#{matcher_class}]" registry.add matcher_class end # Internal: Add a wrapper class to this analyzer's registry. # (Intended to be called only by Dat::Analysis::Result and its subclasses) def add_wrapper(wrapper_class) puts "Loading results wrapper class [#{wrapper_class}]" registry.add wrapper_class end end end require 'dat/analysis/library' require 'dat/analysis/matcher' require 'dat/analysis/result' require 'dat/analysis/registry' require 'dat/analysis/tally'
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/lib/dat/analysis/library.rb
lib/dat/analysis/library.rb
module Dat # Internal: Keep a registry of Dat::Analysis::Matcher and # Dat::Analysis::Result subclasses for use by an Dat::Analysis::Analysis # instance. class Analysis::Library @@known_classes = [] # Public: Collect matcher and results classes created by the # provided block. # # &block - Block which instantiates matcher and results classes. # # Returns the newly-instantiated matcher and results classes. def self.select_classes(&block) @@known_classes = [] # prepare for registering new classes yield @@known_classes # return all the newly-registered classes end # Public: register a matcher or results class. # # klass - a Dat::Analysis::Matcher or Dat::Analysis::Result subclass. # # Returns the current list of registered classes. def self.add(klass) @@known_classes << klass end end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/lib/dat/analysis/registry.rb
lib/dat/analysis/registry.rb
module Dat # Internal: Registry of Dat::Analysis::Matcher and Dat::Analysis::Result # classes. This is used to maintain the mapping of matchers and # results wrappers for a particular Dat::Analysis instance. class Analysis::Registry # Public: Create a new Registry instance. def initialize @known_classes = [] end # Public: Add a matcher or results wrapper class to the registry # # klass - a Dat::Analysis::Matcher subclass or a Dat::Analysis::Result # subclass, to be added to the registry. # # Returns the list of currently registered classes. def add(klass) @known_classes << klass end # Public: Get the list of known Dat::Analysis::Matcher subclasses # # Returns the list of currently known matcher classes. def matchers @known_classes.select {|c| c <= ::Dat::Analysis::Matcher } end # Public: Get the list of known Dat::Analysis::Result subclasses # # Returns the list of currently known result wrapper classes. def wrappers @known_classes.select {|c| c <= ::Dat::Analysis::Result } end # Public: Get list of Dat::Analysis::Matcher subclasses for which # `#match?` is truthy for the given result. # # result - a cooked science mismatch result # # Returns a list of matchers initialized with the provided result. def identify(result) matchers.inject([]) do |hits, matcher| instance = matcher.new(result) hits << instance if instance.match? hits end end end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/lib/dat/analysis/result.rb
lib/dat/analysis/result.rb
require "time" module Dat # Public: Base class for wrappers around science mismatch results. # # Instance methods defined on subclasses will be added as instance methods # on science mismatch results handled by Dat::Analysis instances which # add the wrapper subclass via Dat::Analysis#add or Dat::Analysis#load_classes. class Analysis::Result # Public: return the current science mismatch result attr_reader :result # Internal: Called at subclass instantiation time to register the subclass # with Dat::Analysis::Library. # # subclass - The Dat::Analysis::Result subclass being instantiated. # # Not intended to be called directly. def self.inherited(subclass) Dat::Analysis::Library.add subclass end # Internal: Add this class to a Dat::Analysis instance. Intended to be # called from Dat::Analysis to dispatch registration. # # analyzer - a Dat::Analysis instance for an experiment # # Returns the analyzer's updated list of known result wrapper classes. def self.add_to_analyzer(analyzer) analyzer.add_wrapper self end # Public: create a new Result wrapper. # # result - a science mismatch result, to be wrapped with our instance methods. def initialize(result) @result = result end end module Analysis::Result::DefaultMethods # Public: Get the result data for the 'control' code path. # # Returns the 'control' field of the result hash. def control self['control'] end # Public: Get the result data for the 'candidate' code path. # # Returns the 'candidate' field of the result hash. def candidate self['candidate'] end # Public: Get the timestamp when the result was recorded. # # Returns a Time object for the timestamp for this result. def timestamp @timestamp ||= Time.parse(self['timestamp']) end # Public: Get which code path was run first. # # Returns the 'first' field of the result hash. def first self['first'] end # Public: Get the experiment name # # Returns the 'experiment' field of the result hash. def experiment_name self['experiment'] end end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/lib/dat/analysis/matcher.rb
lib/dat/analysis/matcher.rb
module Dat # Public: Base class for science mismatch results matchers. Subclasses # implement the `#match?` instance method, which returns true when # a provided science mismatch result is recognized by the matcher. # # Subclasses are expected to define `#match?`. # # Subclasses may optionally define `#readable` to return an alternative # readable String representation of a cooked science mismatch result. The # default implementation is defined in Dat::Analysis#readable. class Analysis::Matcher # Public: The science mismatch result to be matched. attr_reader :result # Internal: Called at subclass instantiation time to register the subclass # with Dat::Analysis::Library. # # subclass - The Dat::Analysis::Matcher subclass being instantiated. # # Not intended to be called directly. def self.inherited(subclass) Dat::Analysis::Library.add subclass end # Internal: Add this class to a Dat::Analysis instance. Intended to be # called from Dat::Analysis to dispatch registration. # # analyzer - a Dat::Analysis instance for an experiment # # Returns the analyzer's updated list of known matcher classes. def self.add_to_analyzer(analyzer) analyzer.add_matcher self end # Public: create a new Matcher. # # result - a science mismatch result, to be tested via `#match?` def initialize(result) @result = result end end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
github/dat-analysis
https://github.com/github/dat-analysis/blob/d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8/lib/dat/analysis/tally.rb
lib/dat/analysis/tally.rb
module Dat # Internal: Track and summarize counts of occurrences of mismatch objects. # # Examples # # tally = Dat::Analysis::Tally.new # tally.count('foo') # => 1 # tally.count('bar') # => 1 # tally.count('foo') # => 2 # puts tally.summary # Summary of known mismatches found: # foo 2 # bar 1 # TOTAL: 3 # => nil # class Analysis::Tally # Public: Returns the hash of recorded mismatches. attr_reader :tally def initialize @tally = {} end # Public: record an occurrence of a mismatch class. def count(klass) tally[klass] ||= 0 tally[klass] += 1 end # Public: Return a String summary of mismatches seen so far. # # Returns a printable String summarizing the counts of mismatches seen, # sorted in descending count order. def summary return "\nNo results identified.\n" if tally.keys.empty? result = [ "\nSummary of identified results:\n" ] sum = 0 tally.keys.sort_by {|k| -1*tally[k] }.each do |k| sum += tally[k] result << "%30s: %6d" % [k, tally[k]] end result << "%30s: %6d" % ['TOTAL', sum] result.join "\n" end # Public: prints a summary of mismatches seen so far to STDOUT (see # `#summary` above). # # Returns nil. def summarize puts summary end end end
ruby
MIT
d931a35bc1688cc5d8cfdcc5ce08e92af8603ea8
2026-01-04T17:49:25.973580Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/test/test_prompts.rb
test/test_prompts.rb
# frozen_string_literal: true require "test_helper" class TestPrompts < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Prompts::VERSION end def test_it_does_something_useful assert true end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "prompts" require "minitest/autorun"
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts.rb
lib/prompts.rb
# frozen_string_literal: true require "io/console" require "reline" require "rainbow" # this needs to come before require "fmt" require "fmt" require_relative "prompts/version" require_relative "prompts/prompt" require_relative "prompts/text_utils" require_relative "prompts/content" require_relative "prompts/paragraph" require_relative "prompts/box" require_relative "prompts/pause_prompt" require_relative "prompts/confirm_prompt" require_relative "prompts/text_prompt" require_relative "prompts/select_prompt" require_relative "prompts/form" module Prompts EMPTY = "" SPACE = " " MAX_WIDTH = 80 OUTPUT = $stdout class Error < StandardError; end class << self def Form(&block) form = Prompts::Form.new yield(form) form.start end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/content.rb
lib/prompts/content.rb
# frozen_string_literal: false module Prompts class Content attr_reader :slots def initialize(width: MAX_WIDTH) @slots = [] @frame_stack = [] @width = width end def paragraph(text) paragraph = Paragraph.new(text, width: @width) @slots.concat paragraph.lines self end def gap @slots << SPACE self end def box(padded: false, border_color: nil, &block) box = Box.new(width: @width, padded: padded, border_color: border_color) yield(box) @slots.concat box.lines self end def render clear_screen render_frame end def reset! @slots = @frame_stack.first.dup end def prepend(*lines) @slots.unshift(*lines) end private def clear_screen jump_cursor_to_top erase_down end def render_frame @frame_stack << @slots.dup OUTPUT.puts SPACE return if @slots.empty? OUTPUT.puts @slots.join("\n") OUTPUT.puts SPACE @slots.clear end def jump_cursor_to_top OUTPUT.print "\033[H" end def erase_down OUTPUT.print "\e[2J\e[H" end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/select_prompt.rb
lib/prompts/select_prompt.rb
# frozen_string_literal: true module Prompts class SelectPrompt < Prompt def self.ask(options: nil, **kwargs) instance = new(options: options, **kwargs) yield instance if block_given? instance.ask end def initialize(options: nil, **kwargs) super(**kwargs) @options = options.is_a?(Array) ? options.to_h { |item| [item, item] } : options @default = if (index = @options.keys.index(@default)) index + 1 end @instructions = "Enter the number of your choice" @hint ||= "Type your response and press Enter ⏎" @validations << ->(choice) { "Invalid choice." if !choice.to_i.between?(1, @options.size) } end # standard:disable Style/TrivialAccessors def options(options) @options = options end # standard:enable Style/TrivialAccessors def prepare_content super @options.each_with_index do |(key, value), index| @content.paragraph Fmt("%{prefix}|>faint|>bold %{option}", prefix: "#{index + 1}.", option: value) end @content end private def resolve_choice_from(response) choice = response.to_i key, _value = @options.to_a[choice - 1] key end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/version.rb
lib/prompts/version.rb
# frozen_string_literal: true module Prompts VERSION = "0.3.1" end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/text_utils.rb
lib/prompts/text_utils.rb
# frozen_string_literal: true require "unicode/display_width" require "unicode/emoji" module Prompts module TextUtils ANSI_REGEX = /\e\[[0-9;]*[a-zA-Z]/ def wrap_text(text, width:, line_prefix: EMPTY, line_suffix: EMPTY, alignment: :left) words = text.scan(Regexp.union(/\S+/, ANSI_REGEX)) lines = [] line = +EMPTY line_width = 0 prefix_width = Unicode::DisplayWidth.of(strip_ansi(line_prefix), 1, {}, emoji: true) suffix_width = Unicode::DisplayWidth.of(strip_ansi(line_suffix), 1, {}, emoji: true) available_width = width - prefix_width - suffix_width words.each do |word| word_width = Unicode::DisplayWidth.of(strip_ansi(word), 1, {}, emoji: true) if (line_width + word_width) > available_width lines << format_line(line.rstrip, available_width, alignment, line_prefix, line_suffix) line = +EMPTY line_width = 0 end line << word + SPACE line_width += word_width + 1 end lines << format_line(line.rstrip, available_width, alignment, line_prefix, line_suffix) lines end def format_line(line, available_width, alignment, prefix, suffix) line_width = Unicode::DisplayWidth.of(strip_ansi(line), 1, {}, emoji: true) padding = [available_width - line_width, 0].max case alignment when :none prefix + line + suffix when :left prefix + line + (SPACE * padding) + suffix when :right prefix + (SPACE * padding) + line + suffix when :center left_padding = padding / 2 right_padding = padding - left_padding prefix + (SPACE * left_padding) + line + (SPACE * right_padding) + suffix end end def strip_ansi(text) text.gsub(ANSI_REGEX, EMPTY) end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/pause_prompt.rb
lib/prompts/pause_prompt.rb
# frozen_string_literal: true module Prompts class PausePrompt < Prompt def initialize(...) super @prompt = "Press Enter ⏎ to continue..." end def resolve_choice_from(response) true end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/confirm_prompt.rb
lib/prompts/confirm_prompt.rb
# frozen_string_literal: true module Prompts class ConfirmPrompt < Prompt def initialize(...) super @prompt = if @default == false "Choose [y/N]:" elsif @default == true "Choose [Y/n]:" else "Choose [y/n]:" end @default_boolean = @default @default = nil @instructions = "Press Enter to submit" @validations << ->(choice) { "Invalid choice." if !["y", "n", "Y", "N", ""].include?(choice) } end private def resolve_choice_from(response) case response when "y", "Y" then true when "n", "N" then false when "" then @default_boolean end end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/form.rb
lib/prompts/form.rb
# frozen_string_literal: true module Prompts class Form def self.submit(&block) instance = new yield instance if block instance.submit end def initialize @content = Prompts::Content.new @index = 0 @prompts = {} @results = {} end def content(&block) yield @content @content end def text(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, name: nil, &block) prompt = TextPrompt.new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) key = name || (@index += 1) @prompts[key] = prompt end def select(label: nil, options: nil, prompt: "> ", hint: nil, default: nil, validate: nil, name: nil, &block) prompt = SelectPrompt.new(label: label, options: options, prompt: prompt, hint: hint, default: default, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) key = name || (@index += 1) @prompts[key] = prompt end def pause(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, name: nil, &block) prompt = PausePrompt.new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) key = name || (@index += 1) @prompts[key] = prompt end def confirm(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, name: nil, &block) prompt = ConfirmPrompt.new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) key = name || (@index += 1) @prompts[key] = prompt end def submit @prompts.each do |key, prompt| @results[key] = prompt.ask end @results end private def prepend_form_content_to_prompt(prompt) prompt.prepare_content prompt.prepend_content([SPACE]) prompt.prepend_content(*@content.slots) end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/text_prompt.rb
lib/prompts/text_prompt.rb
# frozen_string_literal: true module Prompts class TextPrompt < Prompt def initialize(...) super @instructions = "Press Enter to submit" @hint ||= "Type your response and press Enter ⏎" end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/box.rb
lib/prompts/box.rb
# frozen_string_literal: true module Prompts class Box include TextUtils SOLID_BORDER = {top_left: "┌", top_right: "┐", bottom_left: "└", bottom_right: "┘", horizontal: "─", vertical: "│"}.freeze DOUBLE_BORDER = {top_left: "╔", top_right: "╗", bottom_left: "╚", bottom_right: "╝", horizontal: "═", vertical: "║"}.freeze HEAVY_BORDER = {top_left: "┏", top_right: "┓", bottom_left: "┗", bottom_right: "┛", horizontal: "━", vertical: "┃"}.freeze ROUNDED_BORDER = {top_left: "╭", top_right: "╮", bottom_left: "╰", bottom_right: "╯", horizontal: "─", vertical: "│"}.freeze def initialize(width: MAX_WIDTH, padded: false, border_color: nil, border_style: :rounded) @width = width @padded = padded @border_color = border_color @line_padding = SPACE * 1 @border_parts = case border_style when :solid then SOLID_BORDER when :double then DOUBLE_BORDER when :heavy then HEAVY_BORDER else ROUNDED_BORDER end @content = [] end def centered(text) @content.concat align(text, :center) end def left(text) @content.concat align(text, :left) end def right(text) @content.concat align(text, :right) end def gap @content.concat align(EMPTY, :center) end def lines [].tap do |output| output << top_border align(EMPTY, :center).each { |line| output << @line_padding + line } if @padded @content.each do |line| output << @line_padding + line end align(EMPTY, :center).each { |line| output << @line_padding + line } if @padded output << bottom_border end end private def top_border border = @border_parts[:top_left] + @border_parts[:horizontal] * (@width - 2) + @border_parts[:top_right] Fmt("#{@line_padding}%{border}|>#{@border_color}", border: border) end def bottom_border border = @border_parts[:bottom_left] + @border_parts[:horizontal] * (@width - 2) + @border_parts[:bottom_right] Fmt("#{@line_padding}%{border}|>#{@border_color}", border: border) end def align(text, alignment, between: @border_parts[:vertical]) formatted_boundary = Fmt("%{boundary}|>#{@border_color}", boundary: between) wrap_text(text, width: @width, line_prefix: formatted_boundary + SPACE, line_suffix: SPACE + formatted_boundary, alignment: alignment) end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/prompt.rb
lib/prompts/prompt.rb
# frozen_string_literal: true require "reline" module Prompts class Prompt def self.ask(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil) instance = new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield instance if block_given? instance.ask end def initialize(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil) @label = label @prompt = prompt @hint = hint @default = default @required = required @validate = validate @content = nil @error = nil @attempts = 0 @instructions = nil @validations = [] @choice = nil @content_prepared = false end def content(&block) @content ||= Prompts::Content.new yield @content @content end # standard:disable Style/TrivialAccessors def label(label) @label = label end def hint(hint) @hint = hint end def default(default) @default = default end # standard:enable Style/TrivialAccessors def ask prepare_content if !@content_prepared prepare_default if @default prepare_validations loop do @content.render *initial_prompt_lines, last_prompt_line = formatted_prompt puts initial_prompt_lines.join("\n") if initial_prompt_lines.any? response = Reline.readline(last_prompt_line, _history = false).chomp @choice = resolve_choice_from(response) if (@error = ensure_validity(response)) @content.reset! @content.paragraph Fmt("%{error}|>red|>bold", error: @error + " Try again (×#{@attempts})...") @attempts += 1 next else break @choice end end @choice rescue Interrupt exit 0 end def prepend_content(*lines) @content.prepend(*lines) end def prepare_content @content ||= Prompts::Content.new @content.paragraph formatted_label if @label @content.paragraph formatted_hint if @hint @content.paragraph formatted_error if @error @content_prepared = true @content end private def prepare_default Reline.pre_input_hook = -> do Reline.insert_text @default.to_s # Remove the hook right away. Reline.pre_input_hook = nil end end def prepare_validations if @required error_message = @required.is_a?(String) ? @required : "Value cannot be empty." @validations << ->(input) { error_message if input.empty? } end if @validate @validations << @validate end end def resolve_choice_from(response) response end def formatted_prompt prompt_with_space = @prompt.end_with?(SPACE) ? @prompt : @prompt + SPACE ansi_prompt = Fmt("%{prompt}|>faint|>bold", prompt: prompt_with_space) @formatted_prompt ||= Paragraph.new(ansi_prompt, width: MAX_WIDTH).lines end def formatted_label Fmt("%{label}|>cyan|>bold %{instructions}|>faint|>italic", label: @label, instructions: @instructions ? "(#{@instructions})" : "") end def formatted_hint Fmt("%{hint}|>faint|>bold", hint: @hint) end def formatted_error Fmt("%{error}|>red|>bold", error: @error + " Try again (×#{@attempts})...") end def ensure_validity(response) @validations.each do |validation| result = validation.call(response) return result if result end nil end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
fractaledmind/prompts
https://github.com/fractaledmind/prompts/blob/fe252adedfac5fa19b5cdc82d073a2212834b254/lib/prompts/paragraph.rb
lib/prompts/paragraph.rb
# frozen_string_literal: true module Prompts class Paragraph include TextUtils LINE_PADDING = 3 def initialize(text, width: 60) @text = text @width = width - (LINE_PADDING + 1) @line_padding = SPACE * LINE_PADDING end def lines wrap_text(@text, width: @width, line_prefix: @line_padding, alignment: :none) end end end
ruby
MIT
fe252adedfac5fa19b5cdc82d073a2212834b254
2026-01-04T17:49:30.304472Z
false
ARMmbed/homebrew-formulae
https://github.com/ARMmbed/homebrew-formulae/blob/d333d7f6e81df43e592c55f3fdd531bb6205ba44/arm-none-eabi-gcc.rb
arm-none-eabi-gcc.rb
require 'formula' class ArmNoneEabiGcc < Formula homepage 'https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads' version '10.3-2021.10' url 'https://developer.arm.com/-/media/Files/downloads/gnu-rm/10.3-2021.10/gcc-arm-none-eabi-10.3-2021.10-mac.tar.bz2' sha256 'fb613dacb25149f140f73fe9ff6c380bb43328e6bf813473986e9127e2bc283b' def install (prefix/"gcc").install Dir["./*"] Dir.glob(prefix/"gcc/bin/*") { |file| bin.install_symlink file } end end
ruby
Apache-2.0
d333d7f6e81df43e592c55f3fdd531bb6205ba44
2026-01-04T17:49:37.580746Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/tasks/merb.thor/common.rb
tasks/merb.thor/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/tasks/merb.thor/ops.rb
tasks/merb.thor/ops.rb
module Thor::Tasks module Merb class Collector attr_reader :dependencies def self.collect(str) collector = new collector.instance_eval(str) collector.dependencies end def initialize @dependencies = [] end def dependency(name, *versions) versions.pop if versions.last.is_a?(Hash) @dependencies << [name, versions] end end class Gem < Thor def full_list @idx.load_gems_in("gems/specifications") @list.map do |name, versions| dep = ::Gem::Dependency.new(name, versions) spec = @idx.search(dep).last unless spec self.class.error "A required dependency #{dep} was not found" self.class.rollback_trans end deps = spec.recursive_dependencies(dep, @idx) [spec] + deps end.flatten.uniq end def rescue_failures(error = StandardError, prc = nil) begin yield rescue error => e if prc prc.call(e) else puts e.message puts e.backtrace end self.class.rollback_trans end end def self.begin_trans note "Beginning transaction" FileUtils.cp_r(Dir.pwd / "gems", Dir.pwd / ".original_gems") end def self.commit_trans note "Committing transaction" FileUtils.rm_rf(Dir.pwd / ".original_gems") end def self.rollback_trans if File.exist?(Dir.pwd / ".original_gems") note "Rolling back transaction" FileUtils.rm_rf(Dir.pwd / "gems") FileUtils.mv(Dir.pwd / ".original_gems", Dir.pwd / "gems") end exit! end private def _install(dep) @idx.load_gems_in("gems/specifications") return if @idx.search(dep).last installer = ::Gem::DependencyInstaller.new( :bin_dir => Dir.pwd / "bin", :install_dir => Dir.pwd / "gems", :user_install => false) begin installer.install dep.name, dep.version_requirements rescue ::Gem::GemNotFoundException => e puts "Cannot find #{dep}" rescue ::Gem::RemoteFetcher::FetchError => e puts e.message puts "Retrying..." retry end end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/tasks/merb.thor/utils.rb
tasks/merb.thor/utils.rb
class String def /(other) (Pathname.new(self) + other).to_s end end module ColorfulMessages # red def error(*messages) puts messages.map { |msg| "\033[1;31m#{msg}\033[0m" } end # yellow def warning(*messages) puts messages.map { |msg| "\033[1;33m#{msg}\033[0m" } end # green def success(*messages) puts messages.map { |msg| "\033[1;32m#{msg}\033[0m" } end alias_method :message, :success # magenta def note(*messages) puts messages.map { |msg| "\033[1;35m#{msg}\033[0m" } end # blue def info(*messages) puts messages.map { |msg| "\033[1;34m#{msg}\033[0m" } end end module ThorUI extend ColorfulMessages end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/tasks/merb.thor/app_script.rb
tasks/merb.thor/app_script.rb
#!/usr/bin/env ruby # This was added by Merb's bundler require "rubygems" require File.join(File.dirname(__FILE__), "common") gems_dir = File.join(File.dirname(__FILE__), '..', 'gems') if File.directory?(gems_dir) $BUNDLE = true Gem.clear_paths Gem.path.replace([File.expand_path(gems_dir)]) ENV["PATH"] = "#{File.dirname(__FILE__)}:#{ENV["PATH"]}" gem_file = File.join(gems_dir, "specifications", "<%= spec.name %>-*.gemspec") if local_gem = Dir[gem_file].last version = File.basename(local_gem)[/-([\.\d]+)\.gemspec$/, 1] end end version ||= "<%= Gem::Requirement.default %>" if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then version = $1 ARGV.shift end gem '<%= @spec.name %>', version load '<%= bin_file_name %>'
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/tasks/merb.thor/gem_ext.rb
tasks/merb.thor/gem_ext.rb
require "erb" Gem.pre_install_hooks.push(proc do |installer| unless File.file?(installer.bin_dir / "common.rb") FileUtils.mkdir_p(installer.bin_dir) FileUtils.cp(File.dirname(__FILE__) / "common.rb", installer.bin_dir / "common.rb") end include ColorfulMessages name = installer.spec.name if $GEMS && versions = ($GEMS.assoc(name) || [])[1] dep = Gem::Dependency.new(name, versions) unless dep.version_requirements.satisfied_by?(installer.spec.version) error "Cannot install #{installer.spec.full_name} " \ "for #{$INSTALLING}; " \ "you required #{dep}" ::Thor::Tasks::Merb::Gem.rollback_trans exit! end end success "Installing #{installer.spec.full_name}" end) class ::Gem::Uninstaller def self._with_silent_ui ui = Gem::DefaultUserInteraction.ui def ui.say(str) puts "- #{str}" end yield class << Gem::DefaultUserInteraction.ui remove_method :say end end def self._uninstall(source_index, name, op, version) unless source_index.find_name(name, "#{op} #{version}").empty? uninstaller = Gem::Uninstaller.new( name, :version => "#{op} #{version}", :install_dir => Dir.pwd / "gems", :all => true, :ignore => true ) _with_silent_ui { uninstaller.uninstall } end end def self._uninstall_others(source_index, name, version) _uninstall(source_index, name, "<", version) _uninstall(source_index, name, ">", version) end end Gem.post_install_hooks.push(proc do |installer| source_index = installer.instance_variable_get("@source_index") ::Gem::Uninstaller._uninstall_others( source_index, installer.spec.name, installer.spec.version ) end) class ::Gem::DependencyInstaller alias old_fg find_gems_with_sources def find_gems_with_sources(dep) if @source_index.any? { |_, installed_spec| installed_spec.satisfies_requirement?(dep) } return [] end old_fg(dep) end end class ::Gem::SpecFetcher alias old_fetch fetch def fetch(dependency, all = false, matching_platform = true) idx = Gem::SourceIndex.from_installed_gems reqs = dependency.version_requirements.requirements if reqs.size == 1 && reqs[0][0] == "=" dep = idx.search(dependency).sort.last end if dep file = dep.loaded_from.dup file.gsub!(/specifications/, "cache") file.gsub!(/gemspec$/, "gem") spec = ::Gem::Format.from_file_by_path(file).spec [[spec, file]] else old_fetch(dependency, all, matching_platform) end end end class ::Gem::Installer def app_script_text(bin_file_name) template = File.read(File.dirname(__FILE__) / "app_script.rb") erb = ERB.new(template) erb.result(binding) end end class ::Gem::Specification def recursive_dependencies(from, index = Gem.source_index) specs = self.runtime_dependencies.map do |dep| spec = index.search(dep).last unless spec from_name = from.is_a?(::Gem::Specification) ? from.full_name : from.to_s wider_net = index.find_name(dep.name).last ThorUI.error "Needed #{dep} for #{from_name}, but could not find it" ThorUI.error "Found #{wider_net.full_name}" if wider_net ::Thor::Tasks::Merb::Gem.rollback_trans end spec end specs + specs.map {|s| s.recursive_dependencies(self, index)}.flatten.uniq end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/helpers/articles_helper.rb
app/helpers/articles_helper.rb
module Merb module Feather module ArticlesHelper end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/helpers/global_helpers.rb
app/helpers/global_helpers.rb
module Merb module GlobalHelpers # Returns true if the app is running as a slice, false otherwise def is_slice? ::Feather.respond_to?(:public_path_for) end # This wraps whether the app is a slice or not, and then will create the appropriate stylesheet include def css_include(*args) output = "" args.each do |stylesheet| output << (is_slice? ? "<link type=\"text/css\" href=\"#{File.join(::Feather.public_path_for(:stylesheet), stylesheet.to_s + ".css")}\" charset=\"utf-8\" rel=\"Stylesheet\" media=\"all\" />" : css_include_tag(stylesheet.to_s)) end output end # This wraps whether the app is a slice or not, and then will create the appropriate js include def js_include(*args) output = "" args.each do |javascript| output << (is_slice? ? "<script type=\"text/javascript\" src=\"#{File.join(::Feather.public_path_for(:javascript), javascript.to_s + ".js")}\"></script>" : js_include_tag(javascript.to_s)) end output end def render_title @settings[:title] end def render_tag_line @settings[:tag_line] end ## # This formats the specified text using the specified formatter, returning the result def render_text(formatter, text) ::Feather::Hooks::Formatters.format_text(formatter, text) end ## # This formats the specified article, using it's configured formatter, returning the result def render_article(article) ::Feather::Hooks::Formatters.format_article(article) end ## # This builds the menu list from the menu items, returning the markup def render_menu menu = "" menu_items.each_with_index do |item, index| menu += "<li>#{link_to item[:text], item[:url]} #{render_link_dot(index, menu_items.size - 1)}</li>" end menu end ## # This returns the date as a relative date (today, yesterday etc) def render_relative_date(date) date = Date.parse(date, true) unless /Date.*/ =~ date.class.to_s days = (date - Date.today).to_i return 'today' if days >= 0 and days < 1 return 'tomorrow' if days >= 1 and days < 2 return 'yesterday' if days >= -1 and days < 0 return "in #{days} days" if days.abs < 60 and days > 0 return "#{days.abs} days ago" if days.abs < 60 and days < 0 return date.strftime('%A, %B %e') if days.abs < 182 return date.strftime('%A, %B %e, %Y') end ## # This returns the contents of the notifications in the session, clearing it at the same time def notifications notifications = session[:notifications] session[:notifications] = nil notifications end ## # This returns the names of all possible timezones def get_timezones TZInfo::Timezone.all.collect { |tz| tz.name } end ## # This returns the published at date for an article as a relative date (taking into account timezones) def render_relative_published_at(article) article.published_at.nil? ? "Not yet" : render_relative_date(TZInfo::Timezone.get(logged_in? ? session.user.time_zone : article.user.time_zone).utc_to_local(article.published_at)) end ## # This returns the markup for the about text in the sidebar def render_about_text unless @settings.nil? || @settings[:about].blank? markup = <<-MARKUP <div class="sidebar-node"> <h3>About</h3> <p>#{render_text(@settings[:about_formatter], @settings[:about])}</p> </div> MARKUP end markup end ## # This returns the url for the year article index def year_url(year) url(:year, {:year => year}) end ## # This returns the url for the month article index def month_url(year, month) url(:month, {:year => year, :month => ::Feather::Padding::pad_single_digit(month)}) end ## # This returns the url for the day article index def day_url(year, month, day) url(:day, {:year => year, :month => ::Feather::Padding::pad_single_digit(month), :day => ::Feather::Padding::pad_single_digit(day)}) end ## # This returns all menu items, including those provided by plugins def menu_items items = [] items << {:text => "Dashboard", :url => url(:admin_dashboard)} items << {:text => "Articles", :url => url(:admin_articles)} items << {:text => "Plugins", :url => url(:admin_plugins)} items << {:text => "Users", :url => url(:admin_users)} items << {:text => "Settings", :url => url(:admin_configuration)} root_url = url(:admin_dashboard).gsub("/admin/dashboard", "") ::Feather::Hooks::Menu.menu_items.each { |item| items << item.merge(:url => "#{root_url}#{item[:url]}") } items << {:text => "Logout", :url => url(:logout)} items end ## # This either adds the breaking • character unless we're at the end of the collection (based on index and size) def render_link_dot(index, collection_size) "&nbsp;•" unless index == collection_size end ## # This renders all plugin views for the specified hook def render_plugin_views(name, options = {}) output = "" ::Feather::Hooks::View.plugin_views.each do |view| if view[:name] == name if view[:partial] # Set the template root, create the template method and call the partial _template_root = File.join(view[:plugin].path.gsub(Merb.root, "."), "views") template_location = _template_root / _template_location("#{view[:partial]}", content_type, view[:name]) # Make the location relative to the root template_location = "../../" / template_location output << partial(template_location, { :with => options[:with], :as => options[:with].class.to_s.downcase.singular.split("::").last }) else # Render the specified text using ERB and the options output << Proc.new { |args| ERB.new(view[:content]).result(binding) }.call(options[:with]) end end end # Return the view markup generated by plugins output end ## # This returns the full url for an article def get_full_url(article) "http://#{request.host}#{article.permalink}" end ## # This escapes the specified url def escape_url(url) CGI.escape(url) end ## # This returns true if the specified plugin is active, false if it isn't or is unavailable def is_plugin_active(name) plugin = ::Feather::Plugin.get(name) plugin && plugin.active end def link_to_article(text, article) if is_slice? && !::Feather.config[:path_prefix].empty? link_to(text, '/' + ::Feather.config[:path_prefix] + article.permalink) else link_to(text, article.permalink) end end def link_to_author(author) link_to author["name"], author["homepage"] end # This returns true if the user is logged in, false otherwise def logged_in? !session.user.nil? end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/helpers/admin/dashboard_helper.rb
app/helpers/admin/dashboard_helper.rb
module Merb module Feather module Admin module DashboardHelper end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/helpers/admin/configurations_helper.rb
app/helpers/admin/configurations_helper.rb
module Merb module Feather module Admin module ConfigurationsHelper end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/articles.rb
app/controllers/articles.rb
module Feather class Articles < Application # This handles the index (recent articles), or the year/month/day views def index if params[:day] Merb::Cache[:feather].fetch "#{Feather::Articles.name}/#{params[:year]}/#{params[:month]}/#{params[:day]}" do @archives = Feather::Article.get_archive_hash @articles = Feather::Article.find_by_year_month_day(params[:year], params[:month], params[:day]) display @articles end elsif params[:month] Merb::Cache[:feather].fetch "#{Feather::Articles.name}/#{params[:year]}/#{params[:month]}" do @archives = Feather::Article.get_archive_hash @articles = Feather::Article.find_by_year_month(params[:year], params[:month]) display @articles end elsif params[:year] Merb::Cache[:feather].fetch "#{Feather::Articles.name}/#{params[:year]}" do @archives = Feather::Article.get_archive_hash @articles = Feather::Article.find_by_year(params[:year]) display @articles end else Merb::Cache[:feather].fetch Feather::Articles.name do @archives = Feather::Article.get_archive_hash @articles = Feather::Article.find_recent display @articles end end end def show(id) Merb::Cache[:feather].fetch "#{Feather::Articles.name}/#{id}" do @archives = Feather::Article.get_archive_hash @article = Feather::Article[id] display @article end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/application.rb
app/controllers/application.rb
module Feather class Application < Merb::Controller include Merb::AssetsMixin # include CacheHelper before :get_settings before :load_plugins before :fire_before_event # before :fix_cache_issue_with_merb_093 ## # This just makes sure that params[:format] isn't null, to get around the merb 0.9.3 cache issue def fix_cache_issue_with_merb_093 params[:format] = [] if params[:format].nil? end ## # This grabs settings def get_settings @settings = Feather::Configuration.current end ## # This ensures all plugins are loaded before any requests are dealt with - if one of the other server processes in a cluster adds one, it needs to be picked up def load_plugins # Loop through all plugins by name Feather::Plugin.all.each do |plugin| # Load the plugin plugin.load unless plugin.loaded? end end ## # This fires the application before event for any subscribing plugins def fire_before_event Feather::Hooks::Events.application_before end ## # This puts notification text in the session, to be rendered in any view def notify(text) session[:notifications] = text end ## # This allows a view to expand its template roots to include its own custom views def self.include_plugin_views(plugin) self._template_roots << [File.join(Feather::Hooks::get_plugin_by_caller(plugin).path, "views"), :_template_location] end self._template_roots << [File.join(File.dirname(__FILE__), "..", "views"), :_template_location] end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/exceptions.rb
app/controllers/exceptions.rb
class Exceptions < Merb::Controller self._template_roots << [Feather.slice_path_for(:view), :_template_location] if Feather.respond_to?(:slice_path_for) # handle NotFound exceptions (404) def not_found render :format => :html end # handle NotAcceptable exceptions (406) def not_acceptable render :format => :html end def unauthenticated render :format => :html, :layout => "admin" end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/admin/plugins.rb
app/controllers/admin/plugins.rb
require File.join(File.dirname(__FILE__), "base") module Feather module Admin class Plugins < Base before :find_plugin, :only => %w(update delete show) def index @plugins = Feather::Plugin.all display @plugins end def show(id) display @plugin end def new @plugin = Feather::Plugin.new display @plugin end def create(plugin) if (@plugin = Feather::Plugin.install(plugin[:url])) # Expire cached pages Feather::Article.expire_article_index_page Feather::Article.expire_article_pages # Redirect to the plugin view redirect url(:admin_plugin, @plugin.name) else render :new end end def update(id) # Set the plugin to be active (this writes to plugin settings) @plugin.active = params[:active] == "true" unless params[:active].blank? # Expire cached pages Feather::Article.expire_article_index_page Feather::Article.expire_article_pages # Respond with JS render_js end def delete(id) @plugin.destroy redirect url(:admin_plugins) end private def find_plugin @plugin = Feather::Plugin.get(params[:id]) end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/admin/users.rb
app/controllers/admin/users.rb
require File.join(File.dirname(__FILE__), "base") module Feather module Admin class Users < Base before :find_user, :only => %w(edit update delete show) def index @users = Feather::User.all display @users end def show display @user end def new @user = Feather::User.new display @user end def create(user) @user = Feather::User.new(user) if @user.save redirect(url(:admin_users)) else render :new end end def edit display @user end def update(user) if user[:password] && user[:password_confirmation] @user.salt = nil @user.crypted_password = nil end if @user.update_attributes(user) redirect(url(:admin_user, @user)) else display @user, :edit end end def destroy @user.destroy redirect(url(:admin_users)) end private def find_user @user = Feather::User[params[:id]] end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/admin/configurations.rb
app/controllers/admin/configurations.rb
require File.join(File.dirname(__FILE__), "base") module Feather module Admin class Configurations < Base before :find_configuration def show display @configuration end def update @configuration = Feather::Configuration.first @configuration.title = params[:title] unless params[:title].nil? @configuration.tag_line = params[:tag_line] unless params[:tag_line].nil? @configuration.about = params[:about] unless params[:about].nil? @configuration.about_formatter = params[:about_formatter] unless params[:about_formatter].nil? @configuration.permalink_format = params[:permalink_format] unless params[:permalink_format].nil? @configuration.save @configuration = Feather::Configuration.current # Expire all pages as the configuration settings affect the overall template # expire_all_pages render_js end private def find_configuration @configuration = Feather::Configuration.current end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/admin/articles.rb
app/controllers/admin/articles.rb
require File.join(File.dirname(__FILE__), "base") module Feather module Admin class Articles < Base before :find_article, :only => %w(edit update delete show) def index @page_count, @articles = Feather::Article.paginated(:page => (params[:page] || 1).to_i, :per_page => 10, :order => [:created_at.desc]) display @articles end def show display @article end def new only_provides :html @article = Feather::Article.new display @article end def create(article) @article = Feather::Article.new(article) @article.user_id = session.user.id if @article.save # Expire the article index to reflect the newly published article # expire_index if @article.published render_then_call(redirect(url(:admin_articles))) do # Call events after the redirect # Feather::Hooks::Events.after_publish_article_request(@article, request) if @article.published? # Feather::Hooks::Events.after_create_article_request(@article, request) end else render :new end end def edit display @article end def update(article) article.keys.each { |key| @article.send("#{key}=", article[key]) } @article.published = article["published"] if @article.save # Expire the index and article to reflect the updated article # expire_index # expire_article(@article) render_then_call(redirect(url(:admin_article, @article))) do # Call events after the redirect # Feather::Hooks::Events.after_publish_article_request(@article, request) if @article.published? # Feather::Hooks::Events.after_update_article_request(@article, request) end else display @article, :edit # render :edit end end def delete @article.destroy # Expire the index and article to reflect the removal of the article # expire_index # expire_article(@article) redirect url(:admin_articles) end private def find_article @article = Feather::Article[params[:id]] end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/admin/dashboards.rb
app/controllers/admin/dashboards.rb
require File.join(File.dirname(__FILE__), "base") module Feather module Admin class Dashboards < Base before :check_for_user skip_before :ensure_authenticated def show @activity = Feather::Activity.all(:order => [:created_at.desc], :limit => 5) display @activity end private ## # This checks to see if there are no users (such as when it's a fresh install) - if so, it creates a default user and redirects the user to login with those details def check_for_user if Feather::User.count == 0 Feather::User.create!({:login => "admin", :password => "password", :password_confirmation => "password", :name => 'blog owner', :email => "none@none", :time_zone => "Europe/London"}) # Display the newly created users details notify "No users found so created the default user, \"admin\", password is \"password\"." end ensure_authenticated end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/controllers/admin/base.rb
app/controllers/admin/base.rb
module Feather module Admin class Base < Feather::Application layout :admin before :ensure_authenticated end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/models/feather/plugin.rb
app/models/feather/plugin.rb
require "fileutils" module Feather class Plugin attr_accessor :url, :name, :version, :author, :author_name, :author_email, :author_homepage, :homepage, :about attr_reader :path def initialize(plugin = nil) if plugin @path = Merb.root / "app" / "plugins" / plugin manifest = YAML::load_file(File.join(self.path, 'manifest.yml')) @name = manifest["name"] @version = manifest["version"] @homepage = manifest["homepage"] @author = manifest["author"] if @author @author_name = @author["name"] @author_email = @author["email"] @author_homepage = @author["homepage"] end @about = manifest["about"] end end def id self.name end def errors DataMapper::Validate::ValidationErrors.new end def destroy FileUtils.rm_rf(self.path) unless self.path.nil? Feather::Hooks.remove_plugin_hooks(self.id) end ## # This loads the plugin, first loading any gems it may have def load # Plugin dependencies let you load a plugin before this one, # so we don't want to load that sucker twice, now do we? unless loaded? # Setup the Gem path to the plugin Gem.use_paths(Gem.dir, ((Gem.path - [Gem.dir]) + [self.path])) # Load the plugin init script Kernel.load(File.join(self.path, "init.rb")) # Add the plugin to the array of loaded plugins @@loaded << self.name end end ## # This returns true if the plugin has been loaded, false otherwise def loaded? @@loaded.include?(self.name) end # This retrieves whether or not the plugin is active def active active = Feather::PluginSetting.read("active", self) !active.nil? && (active == "true" || active == true || active == 1 || active == "1") end # This sets the plugin to be active def active=(value) Feather::PluginSetting.write("active", (value == "true" || value == true || value == 1 || value == "1"), self) end # This uses the ID (name) as the param for routes etc def to_param self.id end class << self @@loaded = [] # This returns all plugins found def all if File.exists?(Merb.root / "app" / "plugins") # Grab all plugin folders @plugins = Dir.open(Merb.root / "app" / "plugins"). reject { |file| ['.', '..'].include?(file) }. select { |file| File.directory?(File.join(Merb.root / "app" / "plugins", file)) && File.exists?(Merb.root / "app" / "plugins" / file / "manifest.yml") }. collect { |file| Feather::Plugin.new(file) } @plugins.sort { |a, b| a.name <=> b.name } else @plugins = [] end end # This returns all plugins found that are active def active self.all.select { |p| p.active } end # This retrieves a plugin with the specified name def get(plugin) path = File.join(Merb.root / "app" / "plugins", plugin) if File.exists?(path) return Feather::Plugin.new(plugin) else raise "Plugin not found" end end # This method executes the block provided, and if an exception is thrown by that block, will re-raise # it with the specified message - good for trapping lots of code with more friendly error messages def run_or_error(message, &block) yield rescue Exception => ex raise "#{message} (#{ex.message})" end ## # This grabs the plugin using its url, unpacks it, and loads the metadata for it def install(manifest_url) # Load the manifest yaml manifest = run_or_error("Unable to access manifest!") do YAML::load(Net::HTTP.get(::URI.parse(manifest_url))) end # Build the path path = run_or_error("Unable to build plugin path!") do File.join(Merb.root, "app", "plugins", manifest["name"]) end # Remove any existing plugin at the path run_or_error("Unable to remove existing plugin path!") do FileUtils.rm_rf(path) end # Create new plugin path run_or_error("Unable to create new plugin path!") do FileUtils.mkdir_p(path) end # Download the package package = run_or_error("Unable to retrieve package!") do package_url = File.join(manifest_url.split('/').slice(0..-2).join('/'), manifest["package"]) Net::HTTP.get(::URI.parse(package_url)) end # Unzip the package run_or_error("Unable to unpack zipped plugin package!") do Archive::Tar::Minitar.unpack(Zlib::GzipReader.new(StringIO.new(package)), path) end # Unpack any gems downloaded run_or_error("Unable to unpack gems provided by the plugin package!") do unpack_gems(Dir.glob(File.join(path, "gems", "*.gem")).collect { |p| p.split("/").last }, path) end # Grab the plugin plugin = run_or_error("Cannot instantiate the plugin!") do Feather::Plugin.new(manifest["name"]) end # Load the plugin run_or_error("Cannot load the plugin!") do plugin.load end # Install the plugin run_or_error("Cannot install the plugin!") do load File.join(path, "install.rb") if File.exists?(File.join(path, "install.rb")) end # Reload the routes run_or_error("Cannot reload the routes!") do load Merb.root / "config" / "router.rb" end # Return the plugin plugin end ## # This recursively unpacks the gems used by the plugin def unpack_gems(gems, path) gems.each do |gem| # Unpack the gem `cd #{File.join(path, "gems")}; gem unpack #{File.join(File.join(path, "gems"), gem)}` end end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/models/feather/article.rb
app/models/feather/article.rb
module Feather class Article include DataMapper::Resource include DataMapper::Validate is_paginated property :id, Integer, :key => true, :serial => true property :title, String, :nullable => false, :length => 255 property :content, Text, :nullable => false property :created_at, DateTime property :published_at, DateTime property :user_id, Integer, :nullable => false property :permalink, String, :length => 255 property :published, Boolean, :default => true property :formatter, String, :default => "default" validates_present :title, :key => "uniq_title" validates_present :content, :key => "uniq_content" validates_present :user_id, :key => "uniq_user_id" belongs_to :user # Core filters before :save, :set_published_permalink after :create, :set_create_activity after :update, :set_update_activity # Event hooks for plugins before :create, :fire_before_create_event before :update, :fire_before_update_event before :save, :fire_before_save_event after :create, :fire_after_create_event after :update, :fire_after_update_event after :save, :fire_after_save_event after :save, :reload_cache after :destroy, :reload_cache def reload_cache Feather::Article.expire_routing Feather::Article.routing Feather::Article.expire_article_index_page Feather::Article.expire_article_page(self.id) Feather::Article.expire_article_archive(self) end ## # This sets the published date and permalink when an article is published def set_published_permalink # Check to see if we are publishing if self.published? # Set the date, only if we haven't already self.published_at ||= Time.now # Set the permalink, only if we haven't already self.permalink = create_permalink else self.published_at = self.permalink = nil end true end def set_create_activity a = Feather::Activity.new a.message = "Article \"#{self.title}\" created" a.save end def set_update_activity a = Feather::Activity.new a.message = "Article \"#{self.title}\" updated" a.save end def fire_before_create_event Feather::Hooks::Events.before_create_article(self) end def fire_before_update_event Feather::Hooks::Events.before_update_article(self) unless new_record? end def fire_before_save_event Feather::Hooks::Events.before_save_article(self) Feather::Hooks::Events.before_publish_article(self) if self.published? end def fire_after_create_event Feather::Hooks::Events.after_create_article(self) end def fire_after_update_event Feather::Hooks::Events.after_update_article(self) unless new_record? end def fire_after_save_event Feather::Hooks::Events.after_save_article(self) Feather::Hooks::Events.after_publish_article(self) if self.published? end def published=(binary_string) # We need this because the values get populated from the params attribute_set(:published, binary_string == "1") end def create_permalink permalink = Feather::Configuration.current[:permalink_format].gsub(/:year/,self.published_at.year.to_s) permalink.gsub!(/:month/, Feather::Padding::pad_single_digit(self.published_at.month)) permalink.gsub!(/:day/, Feather::Padding::pad_single_digit(self.published_at.day)) title = self.title.gsub(/\W+/, ' ') # all non-word chars to spaces title.strip! # ohh la la title.downcase! # title.gsub!(/\ +/, '-') # spaces to dashes, preferred separator char everywhere permalink.gsub!(/:title/,title) permalink end def user_name self.user.nil? ? "unknown" : self.user.name end class << self # This expires the pages for all of the individual article pages, along with the index def expire_article_index_page Merb::Cache[:feather].delete Feather::Articles.name end # Expire this specific article page def expire_article_page(id) Merb::Cache[:feather].delete "#{Feather::Articles.name}/#{id}" end # Expire all of the article pages def expire_article_pages Feather::Article.all.each { |article| expire_article_page(article.id) } end # This expires the archives for an article def expire_article_archive(article) unless article.published_at.nil? Merb::Cache[:feather].delete "#{Feather::Articles.name}/#{article.published_at.year}" Merb::Cache[:feather].delete "#{Feather::Articles.name}/#{article.published_at.year}/#{article.published_at.month}" Merb::Cache[:feather].delete "#{Feather::Articles.name}/#{article.published_at.year}/#{Feather::Padding.pad_single_digit(article.published_at.month)}" Merb::Cache[:feather].delete "#{Feather::Articles.name}/#{article.published_at.year}/#{article.published_at.month}/#{article.published_at.day}" Merb::Cache[:feather].delete "#{Feather::Articles.name}/#{article.published_at.year}/#{Feather::Padding.pad_single_digit(article.published_at.month)}/#{Feather::Padding.pad_single_digit(article.published_at.day)}" end end # This expires the routing mappings def expire_routing Merb::Cache[:feather].delete "#{Feather::Article.name}::Routing" end # A mapping of ID's to permalinks for the router def routing Merb::Cache[:feather].fetch "#{Feather::Article.name}::Routing" do routing = {} Feather::Article.all.each { |a| routing[a.permalink] = a.id } routing end end ## # Custom finders def find_recent self.all(:published => true, :limit => 10, :order => [:published_at.desc]) end def find_by_year(year) self.all(:published_at.like => "#{year}%", :published => true, :order => [:published_at.desc]) end def find_by_year_month(year, month) month = Feather::Padding::pad_single_digit(month) self.all(:published_at.like => "#{year}-#{month}%", :published => true, :order => [:published_at.desc]) end def find_by_year_month_day(year, month, day) month = Feather::Padding::pad_single_digit(month) day = Feather::Padding::pad_single_digit(day) self.all(:published_at.like => "#{year}-#{month}-#{day}%", :published => true, :order => [:published_at.desc]) end def find_by_permalink(permalink) Merb.logger.debug!("permalink: #{permalink}") self.first(:permalink => permalink) end def get_archive_hash counts = repository.adapter.query("SELECT COUNT(*) as count, #{specific_date_function} FROM feather_articles WHERE published_at IS NOT NULL AND (published = 'true' OR published = 't' OR published = 1) GROUP BY year, month ORDER BY year DESC, month DESC") archives = counts.map do |entry| { :name => "#{Date::MONTHNAMES[entry.month.to_i]} #{entry.year}", :month => entry.month.to_i, :year => entry.year.to_i, :article_count => entry.count } end archives end private def specific_date_function if Merb::Orms::DataMapper.config[:adapter] == "sqlite3" "strftime('%Y', published_at) as year, strftime('%m', published_at) as month" else "extract(year from published_at) as year, extract(month from published_at) as month" end end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/models/feather/configuration.rb
app/models/feather/configuration.rb
module Feather class Configuration include DataMapper::Resource property :id, Integer, :key => true, :serial => true property :title, String property :tag_line, String, :length => 255 # TODO: was TEXT, is VARCHAR now, should be TEXT again property :about, String property :about_formatter, String property :permalink_format, String after :save, :set_activity before :save, :prepend_slash_on_permalink after :save, :reload_cache def reload_cache Feather::Configuration.expire_current Feather::Configuration.current Feather::Article.expire_article_index_page Feather::Article.expire_article_pages end def set_activity a = Feather::Activity.new a.message = "Configuration updated" a.save end def prepend_slash_on_permalink self.permalink_format = '/' + self.permalink_format if !self.permalink_format.nil? && self.permalink_format.index('/') != 0 end ## # This returns a shortened about for displaying on the settings screen, if the about is multiple lines def about_summary summary = self.about unless summary.nil? || summary.empty? summary = summary.gsub("\r\n", "\n") summary = "#{summary[0..summary.index("\n") - 1]}..." if summary.index("\n") summary = summary.gsub(/"/, "'") end summary end class << self # This expires the current configuration def expire_current Merb::Cache[:feather].delete Feather::Configuration.name end ## # This returns the current configuration, creating the record if it isn't found def current Merb::Cache[:feather].fetch Feather::Configuration.name do configuration = Feather::Configuration.first configuration = Feather::Configuration.create(:title => "My new Feather blog", :tag_line => "Feather rocks!", :about => "I rock, and so does my Feather blog", :about_formatter => "default", :permalink_format => "/:year/:month/:day/:title") if configuration.nil? configuration.attributes.merge({:about_summary => configuration.about_summary}) end end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/models/feather/plugin_setting.rb
app/models/feather/plugin_setting.rb
module Feather class PluginSetting include DataMapper::Resource property :id, Integer, :key => true, :serial => true property :handle, String property :value, String property :plugin_id, String # This handles cache expirations for settings being created/updated/deleted after(:save, :reload_cache) after(:destroy, :reload_cache) def reload_cache Feather::PluginSetting.reload_cache end class << self # This keeps a cache of the plugin settings def cache Merb::Cache[:feather].fetch Feather::PluginSetting.name do cached_settings = {} Feather::PluginSetting.all.each do |s| cached_settings[s.plugin_id] = {} if cached_settings[s.plugin_id].nil? cached_settings[s.plugin_id][s.handle] = s.value end cached_settings end end # This clears and reloads the cache def reload_cache Merb::Cache[:feather].delete Feather::PluginSetting.name self.cache end # This retrieves a value from the cache using the handle and plugin def find_by_handle_and_plugin(handle, plugin) self.cache[plugin][handle] unless self.cache[plugin].nil? end # This reads a plugin setting and returns the value def read(handle, plugin = Feather::Hooks.get_plugin_by_caller(Feather::Hooks.get_caller)) # Work out the plugin name (depends on whether we were passed an actual plugin, or just the name) plugin_name = (plugin.is_a?(Feather::Plugin) ? plugin.name : plugin) # Locate and return the setting self.find_by_handle_and_plugin(handle, plugin_name) end # This writes a plugin setting, either overwriting the existing value, or creating it if doesn't yet exist def write(handle, value, plugin = Feather::Hooks.get_plugin_by_caller(Feather::Hooks.get_caller)) # Work out the plugin name (depends on whether we were passed an actual plugin, or just the name) plugin_name = (plugin.is_a?(Feather::Plugin) ? plugin.name : plugin) # See if we can find a setting for this handle and plugin already if self.find_by_handle_and_plugin(handle, plugin_name) # If so, lets grab it and set the value setting = self.first(:handle => handle, :plugin_id => plugin_name) setting.value = value else # Otherwise, we'll create a new one setting = new({:handle => handle, :value => value, :plugin_id => plugin_name}) end # Now let's save the setting setting.save end end end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/models/feather/activity.rb
app/models/feather/activity.rb
module Feather class Activity include DataMapper::Validate include DataMapper::Resource property :id, Integer, :key => true, :serial => true property :message, String, :length => 255 property :created_at, DateTime validates_present :message, :key => "uniq_msg" end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/app/models/feather/user.rb
app/models/feather/user.rb
# This is a default user class used to activate merb-auth. Feel free to change from a User to # Some other class, or to remove it altogether. If removed, merb-auth may not work by default. # # Don't forget that by default the salted_user mixin is used from merb-more # You'll need to setup your db as per the salted_user mixin, and you'll need # To use :password, and :password_confirmation when creating a user # # see config/merb-auth/setup.rb to see how to disable the salted_user mixin # # You will need to setup your database and create a user. module Feather class User include DataMapper::Resource property :id, Serial property :login, String property :name, String property :email, String property :crypted_password, String, :length => 150 property :salt, String, :length => 150 property :active, Boolean, :default => false # property :identity_url, String property :time_zone, String property :default_formatter, String after :save, :set_create_activity after :save, :set_update_activity validates_present :login, :email validates_is_unique :login, :email validates_format :email, :as => :email_address attr_accessor :password, :password_confirmation validates_is_confirmed :password before :save, :encrypt_password def active? !!self.active end def self.encrypt(salt, password = nil) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end def self.authenticate(login, password) u = self.first(:login => login) return nil unless u u.crypted_password == encrypt(u.salt, password) ? u : nil end def encrypt_password self.salt ||= Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") self.crypted_password ||= Feather::User.encrypt(salt, password) end def set_create_activity if new_record? a = Feather::Activity.new a.message = "User \"#{self.login}\" created" a.save end end def set_update_activity unless new_record? a = Feather::Activity.new a.message = "User \"#{self.login}\" updated" a.save 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/abstract-1.0.0/setup.rb
gems/gems/abstract-1.0.0/setup.rb
# # setup.rb # # Copyright (c) 2000-2004 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2.1. # # # For backward compatibility # unless Enumerable.method_defined?(:map) module Enumerable alias map collect end end unless Enumerable.method_defined?(:detect) module Enumerable alias detect find end end unless Enumerable.method_defined?(:select) module Enumerable alias select find_all end end unless Enumerable.method_defined?(:reject) module Enumerable def reject result = [] each do |i| result.push i unless yield(i) end result end end end unless Enumerable.method_defined?(:inject) module Enumerable def inject(result) each do |i| result = yield(result, i) end result end end end unless Enumerable.method_defined?(:any?) module Enumerable def any? each do |i| return true if yield(i) end false end end end unless File.respond_to?(:read) def File.read(fname) open(fname) {|f| return f.read } end end # # Application independent utilities # def File.binread(fname) open(fname, 'rb') {|f| return f.read } end # for corrupted windows stat(2) def File.dir?(path) File.directory?((path[-1,1] == '/') ? path : path + '/') end # # Config # if arg = ARGV.detect{|arg| /\A--rbconfig=/ =~ arg } ARGV.delete(arg) require arg.split(/=/, 2)[1] $".push 'rbconfig.rb' else require 'rbconfig' end def multipackage_install? FileTest.directory?(File.dirname($0) + '/packages') end class ConfigTable c = ::Config::CONFIG rubypath = c['bindir'] + '/' + c['ruby_install_name'] major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) subprefix = lambda {|path| path.sub(/\A#{Regexp.quote(c['prefix'])}/o, '$prefix') } if c['rubylibdir'] # V < 1.6.3 stdruby = subprefix.call(c['rubylibdir']) siteruby = subprefix.call(c['sitedir']) versite = subprefix.call(c['sitelibdir']) sodir = subprefix.call(c['sitearchdir']) elsif newpath_p # 1.4.4 <= V <= 1.6.3 stdruby = "$prefix/lib/ruby/#{version}" siteruby = subprefix.call(c['sitedir']) versite = siteruby + '/' + version sodir = "$site-ruby/#{c['arch']}" else # V < 1.4.4 stdruby = "$prefix/lib/ruby/#{version}" siteruby = "$prefix/lib/ruby/#{version}/site_ruby" versite = siteruby sodir = "$site-ruby/#{c['arch']}" end if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } makeprog = arg.sub(/'/, '').split(/=/, 2)[1] else makeprog = 'make' end common_descripters = [ [ 'prefix', [ c['prefix'], 'path', 'path prefix of target environment' ] ], [ 'std-ruby', [ stdruby, 'path', 'the directory for standard ruby libraries' ] ], [ 'site-ruby-common', [ siteruby, 'path', 'the directory for version-independent non-standard ruby libraries' ] ], [ 'site-ruby', [ versite, 'path', 'the directory for non-standard ruby libraries' ] ], [ 'bin-dir', [ '$prefix/bin', 'path', 'the directory for commands' ] ], [ 'rb-dir', [ '$site-ruby', 'path', 'the directory for ruby scripts' ] ], [ 'so-dir', [ sodir, 'path', 'the directory for ruby extentions' ] ], [ 'data-dir', [ '$prefix/share', 'path', 'the directory for shared data' ] ], [ 'ruby-path', [ rubypath, 'path', 'path to set to #! line' ] ], [ 'ruby-prog', [ rubypath, 'name', 'the ruby program using for installation' ] ], [ 'make-prog', [ makeprog, 'name', 'the make program to compile ruby extentions' ] ], [ 'without-ext', [ 'no', 'yes/no', 'does not compile/install ruby extentions' ] ] ] multipackage_descripters = [ [ 'with', [ '', 'name,name...', 'package names that you want to install', 'ALL' ] ], [ 'without', [ '', 'name,name...', 'package names that you do not want to install', 'NONE' ] ] ] if multipackage_install? DESCRIPTER = common_descripters + multipackage_descripters else DESCRIPTER = common_descripters end SAVE_FILE = 'config.save' def ConfigTable.each_name(&block) keys().each(&block) end def ConfigTable.keys DESCRIPTER.map {|name, *dummy| name } end def ConfigTable.each_definition(&block) DESCRIPTER.each(&block) end def ConfigTable.get_entry(name) name, ent = DESCRIPTER.assoc(name) ent end def ConfigTable.get_entry!(name) get_entry(name) or raise ArgumentError, "no such config: #{name}" end def ConfigTable.add_entry(name, vals) ConfigTable::DESCRIPTER.push [name,vals] end def ConfigTable.remove_entry(name) get_entry(name) or raise ArgumentError, "no such config: #{name}" DESCRIPTER.delete_if {|n, arr| n == name } end def ConfigTable.config_key?(name) get_entry(name) ? true : false end def ConfigTable.bool_config?(name) ent = get_entry(name) or return false ent[1] == 'yes/no' end def ConfigTable.value_config?(name) ent = get_entry(name) or return false ent[1] != 'yes/no' end def ConfigTable.path_config?(name) ent = get_entry(name) or return false ent[1] == 'path' end class << self alias newobj new end def ConfigTable.new c = newobj() c.initialize_from_table c end def ConfigTable.load c = newobj() c.initialize_from_file c end def initialize_from_table @table = {} DESCRIPTER.each do |k, (default, vname, desc, default2)| @table[k] = default end end def initialize_from_file raise InstallError, "#{File.basename $0} config first"\ unless File.file?(SAVE_FILE) @table = {} File.foreach(SAVE_FILE) do |line| k, v = line.split(/=/, 2) @table[k] = v.strip end end def save File.open(SAVE_FILE, 'w') {|f| @table.each do |k, v| f.printf "%s=%s\n", k, v if v end } end def []=(k, v) raise InstallError, "unknown config option #{k}"\ unless ConfigTable.config_key?(k) @table[k] = v end def [](key) return nil unless @table[key] @table[key].gsub(%r<\$([^/]+)>) { self[$1] } end def set_raw(key, val) @table[key] = val end def get_raw(key) @table[key] end end module MetaConfigAPI def eval_file_ifexist(fname) instance_eval File.read(fname), fname, 1 if File.file?(fname) end def config_names ConfigTable.keys end def config?(name) ConfigTable.config_key?(name) end def bool_config?(name) ConfigTable.bool_config?(name) end def value_config?(name) ConfigTable.value_config?(name) end def path_config?(name) ConfigTable.path_config?(name) end def add_config(name, argname, default, desc) ConfigTable.add_entry name,[default,argname,desc] end def add_path_config(name, default, desc) add_config name, 'path', default, desc end def add_bool_config(name, default, desc) add_config name, 'yes/no', default ? 'yes' : 'no', desc end def set_config_default(name, default) if bool_config?(name) ConfigTable.get_entry!(name)[0] = (default ? 'yes' : 'no') else ConfigTable.get_entry!(name)[0] = default end end def remove_config(name) ent = ConfigTable.get_entry(name) ConfigTable.remove_entry name ent end end # # File Operations # module FileOperations def mkdir_p(dirname, prefix = nil) dirname = prefix + dirname if prefix $stderr.puts "mkdir -p #{dirname}" if verbose? return if no_harm? # does not check '/'... it's too abnormal case dirs = dirname.split(%r<(?=/)>) if /\A[a-z]:\z/i =~ dirs[0] disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless File.dir?(path) end end def rm_f(fname) $stderr.puts "rm -f #{fname}" if verbose? return if no_harm? if File.exist?(fname) or File.symlink?(fname) File.chmod 0777, fname File.unlink fname end end def rm_rf(dn) $stderr.puts "rm -rf #{dn}" if verbose? return if no_harm? Dir.chdir dn Dir.foreach('.') do |fn| next if fn == '.' next if fn == '..' if File.dir?(fn) verbose_off { rm_rf fn } else verbose_off { rm_f fn } end end Dir.chdir '..' Dir.rmdir dn end def move_file(src, dest) File.unlink dest if File.exist?(dest) begin File.rename src, dest rescue File.open(dest, 'wb') {|f| f.write File.binread(src) } File.chmod File.stat(src).mode, dest File.unlink src end end def install(from, dest, mode, prefix = nil) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix + dest if prefix realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) str = File.binread(from) if diff?(str, realdest) verbose_off { rm_f realdest if File.exist?(realdest) } File.open(realdest, 'wb') {|f| f.write str } File.chmod mode, realdest File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| if prefix f.puts realdest.sub(prefix, '') else f.puts realdest end } end end def diff?(new_content, path) return true unless File.exist?(path) new_content != File.binread(path) end def command(str) $stderr.puts str if verbose? system str or raise RuntimeError, "'system #{str}' failed" end def ruby(str) command config('ruby-prog') + ' ' + str end def make(task = '') command config('make-prog') + ' ' + task end def extdir?(dir) File.exist?(dir + '/MANIFEST') end def all_files_in(dirname) Dir.open(dirname) {|d| return d.select {|ent| File.file?("#{dirname}/#{ent}") } } end REJECT_DIRS = %w( CVS SCCS RCS CVS.adm ) def all_dirs_in(dirname) Dir.open(dirname) {|d| return d.select {|n| File.dir?("#{dirname}/#{n}") } - %w(. ..) - REJECT_DIRS } end end # # Main Installer # class InstallError < StandardError; end module HookUtils def run_hook(name) try_run_hook "#{curr_srcdir()}/#{name}" or try_run_hook "#{curr_srcdir()}/#{name}.rb" end def try_run_hook(fname) return false unless File.file?(fname) begin instance_eval File.read(fname), fname, 1 rescue raise InstallError, "hook #{fname} failed:\n" + $!.message end true end end module HookScriptAPI def get_config(key) @config[key] end alias config get_config def set_config(key, val) @config[key] = val end # # srcdir/objdir (works only in the package directory) # #abstract srcdir_root #abstract objdir_root #abstract relpath def curr_srcdir "#{srcdir_root()}/#{relpath()}" end def curr_objdir "#{objdir_root()}/#{relpath()}" end def srcfile(path) "#{curr_srcdir()}/#{path}" end def srcexist?(path) File.exist?(srcfile(path)) end def srcdirectory?(path) File.dir?(srcfile(path)) end def srcfile?(path) File.file? srcfile(path) end def srcentries(path = '.') Dir.open("#{curr_srcdir()}/#{path}") {|d| return d.to_a - %w(. ..) } end def srcfiles(path = '.') srcentries(path).select {|fname| File.file?(File.join(curr_srcdir(), path, fname)) } end def srcdirectories(path = '.') srcentries(path).select {|fname| File.dir?(File.join(curr_srcdir(), path, fname)) } end end class ToplevelInstaller Version = '3.2.4' Copyright = 'Copyright (c) 2000-2004 Minero Aoki' TASKS = [ [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles ruby extentions and others' ], [ 'install', 'installs files' ], [ 'clean', "does `make clean' for each extention" ], [ 'distclean',"does `make distclean' for each extention" ] ] def ToplevelInstaller.invoke instance().invoke end @singleton = nil def ToplevelInstaller.instance @singleton ||= new(File.dirname($0)) @singleton end include MetaConfigAPI def initialize(ardir_root) @config = nil @options = { 'verbose' => true } @ardir = File.expand_path(ardir_root) end def inspect "#<#{self.class} #{__id__()}>" end def invoke run_metaconfigs task = parsearg_global() @config = load_config(task) __send__ "parsearg_#{task}" init_installers __send__ "exec_#{task}" end def run_metaconfigs eval_file_ifexist "#{@ardir}/metaconfig" end def load_config(task) case task when 'config' ConfigTable.new when 'clean', 'distclean' if File.exist?('config.save') then ConfigTable.load else ConfigTable.new end else ConfigTable.load end end def init_installers @installer = Installer.new(@config, @options, @ardir, File.expand_path('.')) end # # Hook Script API bases # def srcdir_root @ardir end def objdir_root '.' end def relpath '.' end # # Option Parsing # def parsearg_global valid_task = /\A(?:#{TASKS.map {|task,desc| task }.join '|'})\z/ while arg = ARGV.shift case arg when /\A\w+\z/ raise InstallError, "invalid task: #{arg}" unless valid_task =~ arg return arg when '-q', '--quiet' @options['verbose'] = false when '--verbose' @options['verbose'] = true when '-h', '--help' print_usage $stdout exit 0 when '-v', '--version' puts "#{File.basename($0)} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else raise InstallError, "unknown global option '#{arg}'" end end raise InstallError, <<EOS No task or global option given. Typical installation procedure is: $ ruby #{File.basename($0)} config $ ruby #{File.basename($0)} setup # ruby #{File.basename($0)} install (may require root privilege) EOS end def parsearg_no_options raise InstallError, "#{task}: unknown options: #{ARGV.join ' '}"\ unless ARGV.empty? end alias parsearg_show parsearg_no_options alias parsearg_setup parsearg_no_options alias parsearg_clean parsearg_no_options alias parsearg_distclean parsearg_no_options def parsearg_config re = /\A--(#{ConfigTable.keys.join '|'})(?:=(.*))?\z/ @options['config-opt'] = [] while i = ARGV.shift if /\A--?\z/ =~ i @options['config-opt'] = ARGV.dup break end m = re.match(i) or raise InstallError, "config: unknown option #{i}" name, value = m.to_a[1,2] if value if ConfigTable.bool_config?(name) raise InstallError, "config: --#{name} allows only yes/no for argument"\ unless /\A(y(es)?|n(o)?|t(rue)?|f(alse))\z/i =~ value value = (/\Ay(es)?|\At(rue)/i =~ value) ? 'yes' : 'no' end else raise InstallError, "config: --#{name} requires argument"\ unless ConfigTable.bool_config?(name) value = 'yes' end @config[name] = value end end def parsearg_install @options['no-harm'] = false @options['install-prefix'] = '' while a = ARGV.shift case a when /\A--no-harm\z/ @options['no-harm'] = true when /\A--prefix=(.*)\z/ path = $1 path = File.expand_path(path) unless path[0,1] == '/' @options['install-prefix'] = path else raise InstallError, "install: unknown option #{a}" end end end def print_usage(out) out.puts 'Typical Installation Procedure:' out.puts " $ ruby #{File.basename $0} config" out.puts " $ ruby #{File.basename $0} setup" out.puts " # ruby #{File.basename $0} install (may require root privilege)" out.puts out.puts 'Detailed Usage:' out.puts " ruby #{File.basename $0} <global option>" out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" fmt = " %-20s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, '-h,--help', 'print this message' out.printf fmt, '-v,--version', 'print version and quit' out.printf fmt, ' --copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf " %-10s %s\n", name, desc end out.puts out.puts 'Options for config:' ConfigTable.each_definition do |name, (default, arg, desc, default2)| out.printf " %-20s %s [%s]\n", '--'+ name + (ConfigTable.bool_config?(name) ? '' : '='+arg), desc, default2 || default end out.printf " %-20s %s [%s]\n", '--rbconfig=path', 'your rbconfig.rb to load', "running ruby's" out.puts out.puts 'Options for install:' out.printf " %-20s %s [%s]\n", '--no-harm', 'only display what to do if given', 'off' out.printf " %-20s %s [%s]\n", '--prefix', 'install path prefix', '$prefix' out.puts end # # Task Handlers # def exec_config @installer.exec_config @config.save # must be final end def exec_setup @installer.exec_setup end def exec_install @installer.exec_install end def exec_show ConfigTable.each_name do |k| v = @config.get_raw(k) if not v or v.empty? v = '(not specified)' end printf "%-10s %s\n", k, v end end def exec_clean @installer.exec_clean end def exec_distclean @installer.exec_distclean end end class ToplevelInstallerMulti < ToplevelInstaller include HookUtils include HookScriptAPI include FileOperations def initialize(ardir) super @packages = all_dirs_in("#{@ardir}/packages") raise 'no package exists' if @packages.empty? end def run_metaconfigs eval_file_ifexist "#{@ardir}/metaconfig" @packages.each do |name| eval_file_ifexist "#{@ardir}/packages/#{name}/metaconfig" end end def init_installers @installers = {} @packages.each do |pack| @installers[pack] = Installer.new(@config, @options, "#{@ardir}/packages/#{pack}", "packages/#{pack}") end with = extract_selection(config('with')) without = extract_selection(config('without')) @selected = @installers.keys.select {|name| (with.empty? or with.include?(name)) \ and not without.include?(name) } end def extract_selection(list) a = list.split(/,/) a.each do |name| raise InstallError, "no such package: #{name}" \ unless @installers.key?(name) end a end def print_usage(f) super f.puts 'Inluded packages:' f.puts ' ' + @packages.sort.join(' ') f.puts end # # multi-package metaconfig API # attr_reader :packages def declare_packages(list) raise 'package list is empty' if list.empty? list.each do |name| raise "directory packages/#{name} does not exist"\ unless File.dir?("#{@ardir}/packages/#{name}") end @packages = list end # # Task Handlers # def exec_config run_hook 'pre-config' each_selected_installers {|inst| inst.exec_config } run_hook 'post-config' @config.save # must be final end def exec_setup run_hook 'pre-setup' each_selected_installers {|inst| inst.exec_setup } run_hook 'post-setup' end def exec_install run_hook 'pre-install' each_selected_installers {|inst| inst.exec_install } run_hook 'post-install' end def exec_clean rm_f 'config.save' run_hook 'pre-clean' each_selected_installers {|inst| inst.exec_clean } run_hook 'post-clean' end def exec_distclean rm_f 'config.save' run_hook 'pre-distclean' each_selected_installers {|inst| inst.exec_distclean } run_hook 'post-distclean' end # # lib # def each_selected_installers Dir.mkdir 'packages' unless File.dir?('packages') @selected.each do |pack| $stderr.puts "Processing the package `#{pack}' ..." if @options['verbose'] Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") Dir.chdir "packages/#{pack}" yield @installers[pack] Dir.chdir '../..' end end def verbose? @options['verbose'] end def no_harm? @options['no-harm'] end end class Installer FILETYPES = %w( bin lib ext data ) include HookScriptAPI include HookUtils include FileOperations def initialize(config, opt, srcroot, objroot) @config = config @options = opt @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{self.class} #{File.basename(@srcdir)}>" end # # Hook Script API bases # def srcdir_root @srcdir end def objdir_root @objdir end def relpath @currdir end # # configs/options # def no_harm? @options['no-harm'] end def verbose? @options['verbose'] end def verbose_off begin save, @options['verbose'] = @options['verbose'], false yield ensure @options['verbose'] = save end end # # TASK config # def exec_config exec_task_traverse 'config' end def config_dir_bin(rel) end def config_dir_lib(rel) end def config_dir_ext(rel) extconf if extdir?(curr_srcdir()) end def extconf opt = @options['config-opt'].join(' ') command "#{config('ruby-prog')} #{curr_srcdir()}/extconf.rb #{opt}" end def config_dir_data(rel) end # # TASK setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin(rel) all_files_in(curr_srcdir()).each do |fname| adjust_shebang "#{curr_srcdir()}/#{fname}" end end # modify: #!/usr/bin/ruby # modify: #! /usr/bin/ruby # modify: #!ruby # not modify: #!/usr/bin/env ruby SHEBANG_RE = /\A\#!\s*\S*ruby\S*/ def adjust_shebang(path) return if no_harm? tmpfile = File.basename(path) + '.tmp' begin File.open(path, 'rb') {|r| File.open(tmpfile, 'wb') {|w| first = r.gets return unless SHEBANG_RE =~ first $stderr.puts "adjusting shebang: #{File.basename path}" if verbose? w.print first.sub(SHEBANG_RE, '#!' + config('ruby-path')) w.write r.read } } move_file tmpfile, File.basename(path) ensure File.unlink tmpfile if File.exist?(tmpfile) end end def setup_dir_lib(rel) end def setup_dir_ext(rel) make if extdir?(curr_srcdir()) end def setup_dir_data(rel) end # # TASK install # def exec_install exec_task_traverse 'install' end def install_dir_bin(rel) install_files collect_filenames_auto(), "#{config('bin-dir')}/#{rel}", 0755 end def install_dir_lib(rel) install_files ruby_scripts(), "#{config('rb-dir')}/#{rel}", 0644 end def install_dir_ext(rel) return unless extdir?(curr_srcdir()) install_files ruby_extentions('.'), "#{config('so-dir')}/#{File.dirname(rel)}", 0555 end def install_dir_data(rel) install_files collect_filenames_auto(), "#{config('data-dir')}/#{rel}", 0644 end def install_files(list, dest, mode) mkdir_p dest, @options['install-prefix'] list.each do |fname| install fname, dest, mode, @options['install-prefix'] end end def ruby_scripts collect_filenames_auto().select {|n| /\.rb\z/ =~ n } end # picked up many entries from cvs-1.11.1/src/ignore.c reject_patterns = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ *.org *.in .* ) mapping = { '.' => '\.', '$' => '\$', '#' => '\#', '*' => '.*' } REJECT_PATTERNS = Regexp.new('\A(?:' + reject_patterns.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| mapping[ch] } }.join('|') + ')\z') def collect_filenames_auto mapdir((existfiles() - hookfiles()).reject {|fname| REJECT_PATTERNS =~ fname }) end def existfiles all_files_in(curr_srcdir()) | all_files_in('.') end def hookfiles %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| %w( config setup install clean ).map {|t| sprintf(fmt, t) } }.flatten end def mapdir(filelist) filelist.map {|fname| if File.exist?(fname) # objdir fname else # srcdir File.join(curr_srcdir(), fname) end } end def ruby_extentions(dir) _ruby_extentions(dir) or raise InstallError, "no ruby extention exists: 'ruby #{$0} setup' first" end DLEXT = /\.#{ ::Config::CONFIG['DLEXT'] }\z/ def _ruby_extentions(dir) Dir.open(dir) {|d| return d.select {|fname| DLEXT =~ fname } } end # # TASK clean # def exec_clean exec_task_traverse 'clean' rm_f 'config.save' rm_f 'InstalledFiles' end def clean_dir_bin(rel) end def clean_dir_lib(rel) end def clean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'clean' if File.file?('Makefile') end def clean_dir_data(rel) end # # TASK distclean # def exec_distclean exec_task_traverse 'distclean' rm_f 'config.save' rm_f 'InstalledFiles' end def distclean_dir_bin(rel) end def distclean_dir_lib(rel) end def distclean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'distclean' if File.file?('Makefile') end # # lib # def exec_task_traverse(task) run_hook "pre-#{task}" FILETYPES.each do |type| if config('without-ext') == 'yes' and type == 'ext' $stderr.puts 'skipping ext/* by user option' if verbose? next end traverse task, type, "#{task}_dir_#{type}" end run_hook "post-#{task}" end def traverse(task, rel, mid) dive_into(rel) { run_hook "pre-#{task}" __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') all_dirs_in(curr_srcdir()).each do |d| traverse task, "#{rel}/#{d}", mid end run_hook "post-#{task}" } end def dive_into(rel) return unless File.dir?("#{@srcdir}/#{rel}") dir = File.basename(rel) Dir.mkdir dir unless File.dir?(dir) prevdir = Dir.pwd Dir.chdir dir $stderr.puts '---> ' + rel if verbose? @currdir = rel yield Dir.chdir prevdir $stderr.puts '<--- ' + rel if verbose? @currdir = File.dirname(rel) end end if $0 == __FILE__ begin if multipackage_install? ToplevelInstallerMulti.invoke else ToplevelInstaller.invoke end rescue raise if $DEBUG $stderr.puts $!.message $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." exit 1 end end
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false
mleung/feather
https://github.com/mleung/feather/blob/8039b8a99883597deeb3d03f67216755f101f667/gems/gems/abstract-1.0.0/test/test.rb
gems/gems/abstract-1.0.0/test/test.rb
## ## $Rev: 1 $ ## $Release: 1.0.0 $ ## copyright(c) 2006 kuwata-lab.com all rights reserved. ## testdir = File.dirname(File.expand_path(__FILE__)) libdir = File.dirname(testdir) + "/lib" $: << libdir require 'test/unit' require 'abstract' class Foo abstract_method "arg1, arg2=''", :m1, :m2, :m3 end class Bar def m1(arg1, arg2='') not_implemented end end class AbstractTest < Test::Unit::TestCase def _test(obj) assert_raise(NotImplementedError) do begin obj = Foo.new obj.m1 'a' rescue => ex linenum = (ex.backtrace[0] =~ /:(\d+)/) && $1 raise ex end end end def test_abstract_method1 obj = Foo.new assert_raise(NotImplementedError) { obj.m1 'a' } assert_raise(NotImplementedError) { obj.m2 'a', 'b' } end def test_abstract_method2 begin obj = Foo.new linenum = __LINE__; obj.m1 'a' rescue NotImplementedError => ex actual_linenum = (ex.backtrace[0] =~ /:(\d+)/) && $1.to_i end assert_equal linenum, actual_linenum end def test_not_implemented1 obj = Bar.new assert_raise(NotImplementedError) { obj.m1 123 } end def test_not_implemented2 begin obj = Bar.new linenum = __LINE__; obj.m1 'a' rescue NotImplementedError => ex actual_linenum = (ex.backtrace[0] =~ /:(\d+)/) && $1.to_i end assert_equal linenum, actual_linenum end def test_not_implemented3 begin obj = Bar.new obj.not_implemented rescue Exception => ex assert_instance_of(NoMethodError, ex) assert_match(/private method/, ex.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/abstract-1.0.0/lib/abstract.rb
gems/gems/abstract-1.0.0/lib/abstract.rb
## ## $Rev: 1 $ ## $Release: 1.0.0 $ ## copyright(c) 2006 kuwata-lab.com all rights reserved. ## ## ## helper to define abstract method in Ruby. ## ## ## example1. (shorter notation) ## ## require 'abstract' ## class Foo ## abstract_method 'arg1, arg2=""', :method1, :method2, :method3 ## end ## ## ## example2. (RDoc friendly notation) ## ## require 'abstract' ## class Bar ## # ... method1 description ... ## def method1(arg1, arg2="") ## not_implemented ## end ## ## # ... method2 description ... ## def method2(arg1, arg2="") ## not_implemented ## end ## end ## ## class Module ## ## define abstract methods ## def abstract_method args_str, *method_names method_names.each do |name| module_eval <<-END def #{name}(#{args_str}) mesg = "class \#{self.class.name} must implement abstract method `#{self.name}##{name}()'." #mesg = "\#{self.class.name}##{name}() is not implemented." err = NotImplementedError.new mesg err.set_backtrace caller() raise err end END end end end ## module Kernel ## ## raise NotImplementedError ## def not_implemented #:doc: backtrace = caller() method_name = (backtrace.shift =~ /`(\w+)'$/) && $1 mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'." #mesg = "#{self.class.name}##{method_name}() is not implemented." err = NotImplementedError.new mesg err.set_backtrace backtrace raise err end private :not_implemented 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/setup.rb
gems/gems/erubis-2.6.0/setup.rb
# # setup.rb # # Copyright (c) 2000-2004 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2.1. # # # For backward compatibility # unless Enumerable.method_defined?(:map) module Enumerable alias map collect end end unless Enumerable.method_defined?(:detect) module Enumerable alias detect find end end unless Enumerable.method_defined?(:select) module Enumerable alias select find_all end end unless Enumerable.method_defined?(:reject) module Enumerable def reject result = [] each do |i| result.push i unless yield(i) end result end end end unless Enumerable.method_defined?(:inject) module Enumerable def inject(result) each do |i| result = yield(result, i) end result end end end unless Enumerable.method_defined?(:any?) module Enumerable def any? each do |i| return true if yield(i) end false end end end unless File.respond_to?(:read) def File.read(fname) open(fname) {|f| return f.read } end end # # Application independent utilities # def File.binread(fname) open(fname, 'rb') {|f| return f.read } end # for corrupted windows stat(2) def File.dir?(path) File.directory?((path[-1,1] == '/') ? path : path + '/') end # # Config # if arg = ARGV.detect{|arg| /\A--rbconfig=/ =~ arg } ARGV.delete(arg) require arg.split(/=/, 2)[1] $".push 'rbconfig.rb' else require 'rbconfig' end def multipackage_install? FileTest.directory?(File.dirname($0) + '/packages') end class ConfigTable c = ::Config::CONFIG rubypath = c['bindir'] + '/' + c['ruby_install_name'] major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) subprefix = lambda {|path| path.sub(/\A#{Regexp.quote(c['prefix'])}/o, '$prefix') } if c['rubylibdir'] # V < 1.6.3 stdruby = subprefix.call(c['rubylibdir']) siteruby = subprefix.call(c['sitedir']) versite = subprefix.call(c['sitelibdir']) sodir = subprefix.call(c['sitearchdir']) elsif newpath_p # 1.4.4 <= V <= 1.6.3 stdruby = "$prefix/lib/ruby/#{version}" siteruby = subprefix.call(c['sitedir']) versite = siteruby + '/' + version sodir = "$site-ruby/#{c['arch']}" else # V < 1.4.4 stdruby = "$prefix/lib/ruby/#{version}" siteruby = "$prefix/lib/ruby/#{version}/site_ruby" versite = siteruby sodir = "$site-ruby/#{c['arch']}" end if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } makeprog = arg.sub(/'/, '').split(/=/, 2)[1] else makeprog = 'make' end common_descripters = [ [ 'prefix', [ c['prefix'], 'path', 'path prefix of target environment' ] ], [ 'std-ruby', [ stdruby, 'path', 'the directory for standard ruby libraries' ] ], [ 'site-ruby-common', [ siteruby, 'path', 'the directory for version-independent non-standard ruby libraries' ] ], [ 'site-ruby', [ versite, 'path', 'the directory for non-standard ruby libraries' ] ], [ 'bin-dir', [ '$prefix/bin', 'path', 'the directory for commands' ] ], [ 'rb-dir', [ '$site-ruby', 'path', 'the directory for ruby scripts' ] ], [ 'so-dir', [ sodir, 'path', 'the directory for ruby extentions' ] ], [ 'data-dir', [ '$prefix/share', 'path', 'the directory for shared data' ] ], [ 'ruby-path', [ rubypath, 'path', 'path to set to #! line' ] ], [ 'ruby-prog', [ rubypath, 'name', 'the ruby program using for installation' ] ], [ 'make-prog', [ makeprog, 'name', 'the make program to compile ruby extentions' ] ], [ 'without-ext', [ 'no', 'yes/no', 'does not compile/install ruby extentions' ] ] ] multipackage_descripters = [ [ 'with', [ '', 'name,name...', 'package names that you want to install', 'ALL' ] ], [ 'without', [ '', 'name,name...', 'package names that you do not want to install', 'NONE' ] ] ] if multipackage_install? DESCRIPTER = common_descripters + multipackage_descripters else DESCRIPTER = common_descripters end SAVE_FILE = 'config.save' def ConfigTable.each_name(&block) keys().each(&block) end def ConfigTable.keys DESCRIPTER.map {|name, *dummy| name } end def ConfigTable.each_definition(&block) DESCRIPTER.each(&block) end def ConfigTable.get_entry(name) name, ent = DESCRIPTER.assoc(name) ent end def ConfigTable.get_entry!(name) get_entry(name) or raise ArgumentError, "no such config: #{name}" end def ConfigTable.add_entry(name, vals) ConfigTable::DESCRIPTER.push [name,vals] end def ConfigTable.remove_entry(name) get_entry(name) or raise ArgumentError, "no such config: #{name}" DESCRIPTER.delete_if {|n, arr| n == name } end def ConfigTable.config_key?(name) get_entry(name) ? true : false end def ConfigTable.bool_config?(name) ent = get_entry(name) or return false ent[1] == 'yes/no' end def ConfigTable.value_config?(name) ent = get_entry(name) or return false ent[1] != 'yes/no' end def ConfigTable.path_config?(name) ent = get_entry(name) or return false ent[1] == 'path' end class << self alias newobj new end def ConfigTable.new c = newobj() c.initialize_from_table c end def ConfigTable.load c = newobj() c.initialize_from_file c end def initialize_from_table @table = {} DESCRIPTER.each do |k, (default, vname, desc, default2)| @table[k] = default end end def initialize_from_file raise InstallError, "#{File.basename $0} config first"\ unless File.file?(SAVE_FILE) @table = {} File.foreach(SAVE_FILE) do |line| k, v = line.split(/=/, 2) @table[k] = v.strip end end def save File.open(SAVE_FILE, 'w') {|f| @table.each do |k, v| f.printf "%s=%s\n", k, v if v end } end def []=(k, v) raise InstallError, "unknown config option #{k}"\ unless ConfigTable.config_key?(k) @table[k] = v end def [](key) return nil unless @table[key] @table[key].gsub(%r<\$([^/]+)>) { self[$1] } end def set_raw(key, val) @table[key] = val end def get_raw(key) @table[key] end end module MetaConfigAPI def eval_file_ifexist(fname) instance_eval File.read(fname), fname, 1 if File.file?(fname) end def config_names ConfigTable.keys end def config?(name) ConfigTable.config_key?(name) end def bool_config?(name) ConfigTable.bool_config?(name) end def value_config?(name) ConfigTable.value_config?(name) end def path_config?(name) ConfigTable.path_config?(name) end def add_config(name, argname, default, desc) ConfigTable.add_entry name,[default,argname,desc] end def add_path_config(name, default, desc) add_config name, 'path', default, desc end def add_bool_config(name, default, desc) add_config name, 'yes/no', default ? 'yes' : 'no', desc end def set_config_default(name, default) if bool_config?(name) ConfigTable.get_entry!(name)[0] = (default ? 'yes' : 'no') else ConfigTable.get_entry!(name)[0] = default end end def remove_config(name) ent = ConfigTable.get_entry(name) ConfigTable.remove_entry name ent end end # # File Operations # module FileOperations def mkdir_p(dirname, prefix = nil) dirname = prefix + dirname if prefix $stderr.puts "mkdir -p #{dirname}" if verbose? return if no_harm? # does not check '/'... it's too abnormal case dirs = dirname.split(%r<(?=/)>) if /\A[a-z]:\z/i =~ dirs[0] disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless File.dir?(path) end end def rm_f(fname) $stderr.puts "rm -f #{fname}" if verbose? return if no_harm? if File.exist?(fname) or File.symlink?(fname) File.chmod 0777, fname File.unlink fname end end def rm_rf(dn) $stderr.puts "rm -rf #{dn}" if verbose? return if no_harm? Dir.chdir dn Dir.foreach('.') do |fn| next if fn == '.' next if fn == '..' if File.dir?(fn) verbose_off { rm_rf fn } else verbose_off { rm_f fn } end end Dir.chdir '..' Dir.rmdir dn end def move_file(src, dest) File.unlink dest if File.exist?(dest) begin File.rename src, dest rescue File.open(dest, 'wb') {|f| f.write File.binread(src) } File.chmod File.stat(src).mode, dest File.unlink src end end def install(from, dest, mode, prefix = nil) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix + dest if prefix realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) str = File.binread(from) if diff?(str, realdest) verbose_off { rm_f realdest if File.exist?(realdest) } File.open(realdest, 'wb') {|f| f.write str } File.chmod mode, realdest File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| if prefix f.puts realdest.sub(prefix, '') else f.puts realdest end } end end def diff?(new_content, path) return true unless File.exist?(path) new_content != File.binread(path) end def command(str) $stderr.puts str if verbose? system str or raise RuntimeError, "'system #{str}' failed" end def ruby(str) command config('ruby-prog') + ' ' + str end def make(task = '') command config('make-prog') + ' ' + task end def extdir?(dir) File.exist?(dir + '/MANIFEST') end def all_files_in(dirname) Dir.open(dirname) {|d| return d.select {|ent| File.file?("#{dirname}/#{ent}") } } end REJECT_DIRS = %w( CVS SCCS RCS CVS.adm ) def all_dirs_in(dirname) Dir.open(dirname) {|d| return d.select {|n| File.dir?("#{dirname}/#{n}") } - %w(. ..) - REJECT_DIRS } end end # # Main Installer # class InstallError < StandardError; end module HookUtils def run_hook(name) try_run_hook "#{curr_srcdir()}/#{name}" or try_run_hook "#{curr_srcdir()}/#{name}.rb" end def try_run_hook(fname) return false unless File.file?(fname) begin instance_eval File.read(fname), fname, 1 rescue raise InstallError, "hook #{fname} failed:\n" + $!.message end true end end module HookScriptAPI def get_config(key) @config[key] end alias config get_config def set_config(key, val) @config[key] = val end # # srcdir/objdir (works only in the package directory) # #abstract srcdir_root #abstract objdir_root #abstract relpath def curr_srcdir "#{srcdir_root()}/#{relpath()}" end def curr_objdir "#{objdir_root()}/#{relpath()}" end def srcfile(path) "#{curr_srcdir()}/#{path}" end def srcexist?(path) File.exist?(srcfile(path)) end def srcdirectory?(path) File.dir?(srcfile(path)) end def srcfile?(path) File.file? srcfile(path) end def srcentries(path = '.') Dir.open("#{curr_srcdir()}/#{path}") {|d| return d.to_a - %w(. ..) } end def srcfiles(path = '.') srcentries(path).select {|fname| File.file?(File.join(curr_srcdir(), path, fname)) } end def srcdirectories(path = '.') srcentries(path).select {|fname| File.dir?(File.join(curr_srcdir(), path, fname)) } end end class ToplevelInstaller Version = '3.2.4' Copyright = 'Copyright (c) 2000-2004 Minero Aoki' TASKS = [ [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles ruby extentions and others' ], [ 'install', 'installs files' ], [ 'clean', "does `make clean' for each extention" ], [ 'distclean',"does `make distclean' for each extention" ] ] def ToplevelInstaller.invoke instance().invoke end @singleton = nil def ToplevelInstaller.instance @singleton ||= new(File.dirname($0)) @singleton end include MetaConfigAPI def initialize(ardir_root) @config = nil @options = { 'verbose' => true } @ardir = File.expand_path(ardir_root) end def inspect "#<#{self.class} #{__id__()}>" end def invoke run_metaconfigs task = parsearg_global() @config = load_config(task) __send__ "parsearg_#{task}" init_installers __send__ "exec_#{task}" end def run_metaconfigs eval_file_ifexist "#{@ardir}/metaconfig" end def load_config(task) case task when 'config' ConfigTable.new when 'clean', 'distclean' if File.exist?('config.save') then ConfigTable.load else ConfigTable.new end else ConfigTable.load end end def init_installers @installer = Installer.new(@config, @options, @ardir, File.expand_path('.')) end # # Hook Script API bases # def srcdir_root @ardir end def objdir_root '.' end def relpath '.' end # # Option Parsing # def parsearg_global valid_task = /\A(?:#{TASKS.map {|task,desc| task }.join '|'})\z/ while arg = ARGV.shift case arg when /\A\w+\z/ raise InstallError, "invalid task: #{arg}" unless valid_task =~ arg return arg when '-q', '--quiet' @options['verbose'] = false when '--verbose' @options['verbose'] = true when '-h', '--help' print_usage $stdout exit 0 when '-v', '--version' puts "#{File.basename($0)} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else raise InstallError, "unknown global option '#{arg}'" end end raise InstallError, <<EOS No task or global option given. Typical installation procedure is: $ ruby #{File.basename($0)} config $ ruby #{File.basename($0)} setup # ruby #{File.basename($0)} install (may require root privilege) EOS end def parsearg_no_options raise InstallError, "#{task}: unknown options: #{ARGV.join ' '}"\ unless ARGV.empty? end alias parsearg_show parsearg_no_options alias parsearg_setup parsearg_no_options alias parsearg_clean parsearg_no_options alias parsearg_distclean parsearg_no_options def parsearg_config re = /\A--(#{ConfigTable.keys.join '|'})(?:=(.*))?\z/ @options['config-opt'] = [] while i = ARGV.shift if /\A--?\z/ =~ i @options['config-opt'] = ARGV.dup break end m = re.match(i) or raise InstallError, "config: unknown option #{i}" name, value = m.to_a[1,2] if value if ConfigTable.bool_config?(name) raise InstallError, "config: --#{name} allows only yes/no for argument"\ unless /\A(y(es)?|n(o)?|t(rue)?|f(alse))\z/i =~ value value = (/\Ay(es)?|\At(rue)/i =~ value) ? 'yes' : 'no' end else raise InstallError, "config: --#{name} requires argument"\ unless ConfigTable.bool_config?(name) value = 'yes' end @config[name] = value end end def parsearg_install @options['no-harm'] = false @options['install-prefix'] = '' while a = ARGV.shift case a when /\A--no-harm\z/ @options['no-harm'] = true when /\A--prefix=(.*)\z/ path = $1 path = File.expand_path(path) unless path[0,1] == '/' @options['install-prefix'] = path else raise InstallError, "install: unknown option #{a}" end end end def print_usage(out) out.puts 'Typical Installation Procedure:' out.puts " $ ruby #{File.basename $0} config" out.puts " $ ruby #{File.basename $0} setup" out.puts " # ruby #{File.basename $0} install (may require root privilege)" out.puts out.puts 'Detailed Usage:' out.puts " ruby #{File.basename $0} <global option>" out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" fmt = " %-20s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, '-h,--help', 'print this message' out.printf fmt, '-v,--version', 'print version and quit' out.printf fmt, ' --copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf " %-10s %s\n", name, desc end out.puts out.puts 'Options for config:' ConfigTable.each_definition do |name, (default, arg, desc, default2)| out.printf " %-20s %s [%s]\n", '--'+ name + (ConfigTable.bool_config?(name) ? '' : '='+arg), desc, default2 || default end out.printf " %-20s %s [%s]\n", '--rbconfig=path', 'your rbconfig.rb to load', "running ruby's" out.puts out.puts 'Options for install:' out.printf " %-20s %s [%s]\n", '--no-harm', 'only display what to do if given', 'off' out.printf " %-20s %s [%s]\n", '--prefix', 'install path prefix', '$prefix' out.puts end # # Task Handlers # def exec_config @installer.exec_config @config.save # must be final end def exec_setup @installer.exec_setup end def exec_install @installer.exec_install end def exec_show ConfigTable.each_name do |k| v = @config.get_raw(k) if not v or v.empty? v = '(not specified)' end printf "%-10s %s\n", k, v end end def exec_clean @installer.exec_clean end def exec_distclean @installer.exec_distclean end end class ToplevelInstallerMulti < ToplevelInstaller include HookUtils include HookScriptAPI include FileOperations def initialize(ardir) super @packages = all_dirs_in("#{@ardir}/packages") raise 'no package exists' if @packages.empty? end def run_metaconfigs eval_file_ifexist "#{@ardir}/metaconfig" @packages.each do |name| eval_file_ifexist "#{@ardir}/packages/#{name}/metaconfig" end end def init_installers @installers = {} @packages.each do |pack| @installers[pack] = Installer.new(@config, @options, "#{@ardir}/packages/#{pack}", "packages/#{pack}") end with = extract_selection(config('with')) without = extract_selection(config('without')) @selected = @installers.keys.select {|name| (with.empty? or with.include?(name)) \ and not without.include?(name) } end def extract_selection(list) a = list.split(/,/) a.each do |name| raise InstallError, "no such package: #{name}" \ unless @installers.key?(name) end a end def print_usage(f) super f.puts 'Inluded packages:' f.puts ' ' + @packages.sort.join(' ') f.puts end # # multi-package metaconfig API # attr_reader :packages def declare_packages(list) raise 'package list is empty' if list.empty? list.each do |name| raise "directory packages/#{name} does not exist"\ unless File.dir?("#{@ardir}/packages/#{name}") end @packages = list end # # Task Handlers # def exec_config run_hook 'pre-config' each_selected_installers {|inst| inst.exec_config } run_hook 'post-config' @config.save # must be final end def exec_setup run_hook 'pre-setup' each_selected_installers {|inst| inst.exec_setup } run_hook 'post-setup' end def exec_install run_hook 'pre-install' each_selected_installers {|inst| inst.exec_install } run_hook 'post-install' end def exec_clean rm_f 'config.save' run_hook 'pre-clean' each_selected_installers {|inst| inst.exec_clean } run_hook 'post-clean' end def exec_distclean rm_f 'config.save' run_hook 'pre-distclean' each_selected_installers {|inst| inst.exec_distclean } run_hook 'post-distclean' end # # lib # def each_selected_installers Dir.mkdir 'packages' unless File.dir?('packages') @selected.each do |pack| $stderr.puts "Processing the package `#{pack}' ..." if @options['verbose'] Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") Dir.chdir "packages/#{pack}" yield @installers[pack] Dir.chdir '../..' end end def verbose? @options['verbose'] end def no_harm? @options['no-harm'] end end class Installer FILETYPES = %w( bin lib ext data ) include HookScriptAPI include HookUtils include FileOperations def initialize(config, opt, srcroot, objroot) @config = config @options = opt @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{self.class} #{File.basename(@srcdir)}>" end # # Hook Script API bases # def srcdir_root @srcdir end def objdir_root @objdir end def relpath @currdir end # # configs/options # def no_harm? @options['no-harm'] end def verbose? @options['verbose'] end def verbose_off begin save, @options['verbose'] = @options['verbose'], false yield ensure @options['verbose'] = save end end # # TASK config # def exec_config exec_task_traverse 'config' end def config_dir_bin(rel) end def config_dir_lib(rel) end def config_dir_ext(rel) extconf if extdir?(curr_srcdir()) end def extconf opt = @options['config-opt'].join(' ') command "#{config('ruby-prog')} #{curr_srcdir()}/extconf.rb #{opt}" end def config_dir_data(rel) end # # TASK setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin(rel) all_files_in(curr_srcdir()).each do |fname| adjust_shebang "#{curr_srcdir()}/#{fname}" end end # modify: #!/usr/bin/ruby # modify: #! /usr/bin/ruby # modify: #!ruby # not modify: #!/usr/bin/env ruby SHEBANG_RE = /\A\#!\s*\S*ruby\S*/ def adjust_shebang(path) return if no_harm? tmpfile = File.basename(path) + '.tmp' begin File.open(path, 'rb') {|r| File.open(tmpfile, 'wb') {|w| first = r.gets return unless SHEBANG_RE =~ first $stderr.puts "adjusting shebang: #{File.basename path}" if verbose? w.print first.sub(SHEBANG_RE, '#!' + config('ruby-path')) w.write r.read } } move_file tmpfile, File.basename(path) ensure File.unlink tmpfile if File.exist?(tmpfile) end end def setup_dir_lib(rel) end def setup_dir_ext(rel) make if extdir?(curr_srcdir()) end def setup_dir_data(rel) end # # TASK install # def exec_install exec_task_traverse 'install' end def install_dir_bin(rel) install_files collect_filenames_auto(), "#{config('bin-dir')}/#{rel}", 0755 end def install_dir_lib(rel) install_files ruby_scripts(), "#{config('rb-dir')}/#{rel}", 0644 end def install_dir_ext(rel) return unless extdir?(curr_srcdir()) install_files ruby_extentions('.'), "#{config('so-dir')}/#{File.dirname(rel)}", 0555 end def install_dir_data(rel) install_files collect_filenames_auto(), "#{config('data-dir')}/#{rel}", 0644 end def install_files(list, dest, mode) mkdir_p dest, @options['install-prefix'] list.each do |fname| install fname, dest, mode, @options['install-prefix'] end end def ruby_scripts collect_filenames_auto().select {|n| /\.rb\z/ =~ n } end # picked up many entries from cvs-1.11.1/src/ignore.c reject_patterns = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ *.org *.in .* ) mapping = { '.' => '\.', '$' => '\$', '#' => '\#', '*' => '.*' } REJECT_PATTERNS = Regexp.new('\A(?:' + reject_patterns.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| mapping[ch] } }.join('|') + ')\z') def collect_filenames_auto mapdir((existfiles() - hookfiles()).reject {|fname| REJECT_PATTERNS =~ fname }) end def existfiles all_files_in(curr_srcdir()) | all_files_in('.') end def hookfiles %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| %w( config setup install clean ).map {|t| sprintf(fmt, t) } }.flatten end def mapdir(filelist) filelist.map {|fname| if File.exist?(fname) # objdir fname else # srcdir File.join(curr_srcdir(), fname) end } end def ruby_extentions(dir) _ruby_extentions(dir) or raise InstallError, "no ruby extention exists: 'ruby #{$0} setup' first" end DLEXT = /\.#{ ::Config::CONFIG['DLEXT'] }\z/ def _ruby_extentions(dir) Dir.open(dir) {|d| return d.select {|fname| DLEXT =~ fname } } end # # TASK clean # def exec_clean exec_task_traverse 'clean' rm_f 'config.save' rm_f 'InstalledFiles' end def clean_dir_bin(rel) end def clean_dir_lib(rel) end def clean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'clean' if File.file?('Makefile') end def clean_dir_data(rel) end # # TASK distclean # def exec_distclean exec_task_traverse 'distclean' rm_f 'config.save' rm_f 'InstalledFiles' end def distclean_dir_bin(rel) end def distclean_dir_lib(rel) end def distclean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'distclean' if File.file?('Makefile') end # # lib # def exec_task_traverse(task) run_hook "pre-#{task}" FILETYPES.each do |type| if config('without-ext') == 'yes' and type == 'ext' $stderr.puts 'skipping ext/* by user option' if verbose? next end traverse task, type, "#{task}_dir_#{type}" end run_hook "post-#{task}" end def traverse(task, rel, mid) dive_into(rel) { run_hook "pre-#{task}" __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') all_dirs_in(curr_srcdir()).each do |d| traverse task, "#{rel}/#{d}", mid end run_hook "post-#{task}" } end def dive_into(rel) return unless File.dir?("#{@srcdir}/#{rel}") dir = File.basename(rel) Dir.mkdir dir unless File.dir?(dir) prevdir = Dir.pwd Dir.chdir dir $stderr.puts '---> ' + rel if verbose? @currdir = rel yield Dir.chdir prevdir $stderr.puts '<--- ' + rel if verbose? @currdir = File.dirname(rel) end end if $0 == __FILE__ begin if multipackage_install? ToplevelInstallerMulti.invoke else ToplevelInstaller.invoke end rescue raise if $DEBUG $stderr.puts $!.message $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." exit 1 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/contrib/erubis-run.rb
gems/gems/erubis-2.6.0/contrib/erubis-run.rb
=begin = apache/erubis-run.rb Copyright (C) 2007 Andrew R Jackson <arjackson at acm dot org> Built from original by Shugo Maeda: Copyright (C) 2001 Shugo Maeda <shugo@modruby.net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WAreqANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WAreqANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTEreqUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. == Overview Apache::ErubisRun handles eRuby files with erubis == Example of httpd.conf RubyRequire apache/erubis-run <Location /eruby> SetHandler ruby-object RubyHandler Apache::ErubisRun.instance </Location> =end require "singleton" require "tempfile" require "eruby" # Still needed to bring in a couple useful helper methods require "erubis" module Erubis @@cgi = nil def self.cgi return @@cgi end def self.cgi=(cgi) @@cgi = cgi end end module Apache class ErubisRun include Singleton def handler(req) status = check_request(req) return status if(status != OK) filename = req.filename.dup filename.untaint erubis = compile(filename) prerun(req) begin run(erubis, filename) ensure postrun(req) end return OK end private def initialize @compiler = nil end def check_request(req) if(req.method_number == M_OPTIONS) req.allowed |= (1 << M_GET) req.allowed |= (1 << M_POST) return DECLINED end if(req.finfo.mode == 0) return NOT_FOUND end return OK end def compile(filename) @compiler = Erubis::Eruby.load_file(filename) # use caching version as much as possible return @compiler end def prerun(req) Erubis.cgi = nil req.setup_cgi_env Apache.chdir_file(req.filename) end def run(erubis, filename) binding = eval_string_wrap("binding") puts erubis.result(binding) # eval the code in the context of the same binding ERuby uses end def postrun(req) if(cgi = Erubis.cgi) # TODO: pull the content type header from the cgi object, if set there? elsif(req.sync_output or req.sync_header) # Do nothing: header has already been sent else unless(req.content_type) req.content_type = format("text/html;") end req.send_http_header 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/benchmark/bench.rb
gems/gems/erubis-2.6.0/benchmark/bench.rb
#!/usr/bin/env ruby ### ### $Rev: 101 $ ### $Release: 2.6.0 $ ### copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ### require 'erb' require 'erubis' require 'erubis/tiny' require 'erubis/engine/enhanced' require 'yaml' require 'cgi' include ERB::Util begin require 'eruby' rescue LoadError ERuby = nil end def File.write(filename, content) File.open(filename, 'w') { |f| f.write(content) } end ## change benchmark library to use $stderr instead of $stdout require 'benchmark' module Benchmark class Report def print(*args) $stderr.print(*args) end end module_function def print(*args) $stderr.print(*args) end end class BenchmarkApplication TARGETS = %w[eruby ERB ERB(cached) Erubis::Eruby Erubis::Eruby(cached) Erubis::FastEruby Erubis::FastEruby(cached) Erubis::TinyEruby Erubis::ArrayBufferEruby Erubis::PrintOutEruby Erubis::StdoutEruby ] def initialize(ntimes, context, targets=nil, params={}) @ntimes = ntimes @context = context @targets = targets && !targets.empty? ? targets : TARGETS.dup @testmode = params[:testmode] || 'execute' @erubyfile = params[:erubyfile] || 'erubybench.rhtml' @printout = params[:printout] || false end attr_accessor :ntimes, :targets attr_accessor :testmode, :erubyfile, :contextfile, :printout def context2code(context, varname='context') s = '' context.each { |k, | s << "#{k} = #{varname}[#{k.inspect}]; " } return s end def perform_benchmark width = 30 $stderr.puts "*** ntimes=#{@ntimes}, testmode=#{@testmode}" Benchmark.bm(width) do |job| for target in @targets do method = "#{@testmode}_#{target.gsub(/::|-|\(/, '_').gsub(/\)/, '').downcase}" #$stderr.puts "*** debug: method=#{method.inspect}" next unless self.respond_to?(method) filename = "bench_#{(target =~ /^(\w+)/) && $1.downcase}.rhtml" title = target output = nil job.report(title) do output = self.__send__(method, filename, @context) end File.write("output.#{target.gsub(/[^\w]/,'')}", output) if @printout && output && !output.empty? end end end ## def execute_eruby(filename, context) return unless ERuby #eval context2code(context) list = context['list'] @ntimes.times do ERuby.import(filename) end return nil end def execute_erb(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = ERB.new(File.read(filename)) output = eruby.result(binding()) print output end return output end def execute_erb_cached(filename, context) #eval context2code(context) list = context['list'] output = nil cachefile = filename + '.cache' File.unlink(cachefile) if test(?f, cachefile) @ntimes.times do if !test(?f, cachefile) || File.mtime(filename) > File.mtime(cachefile) eruby = ERB.new(File.read(filename)) File.write(cachefile, eruby.src) else eruby = ERB.new('') #eruby.src = File.read(cachefile) eruby.instance_variable_set("@src", File.read(cachefile)) end output = eruby.result(binding()) print output end return output end ## no cached for klass in %w[Eruby FastEruby TinyEruby ArrayBufferEruby PrintOutEruby StdoutEruby] do s = <<-END def execute_erubis_#{klass.downcase}(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = Erubis::#{klass}.new(File.read(filename)) output = eruby.result(binding()) print output end return output end END eval s end ## cached for klass in %w[Eruby FastEruby] do s = <<-END def execute_erubis_#{klass.downcase}_cached(filename, context) #eval context2code(context) list = context['list'] cachefile = filename + '.cache' File.unlink(cachefile) if test(?f, cachefile) output = nil @ntimes.times do eruby = Erubis::#{klass}.load_file(filename) output = eruby.result(binding()) print output end savefile = cachefile.sub(/\\.cache$/, '.#{klass.downcase}.cache') File.rename(cachefile, savefile) return output end END eval s end ## def convert_eruby(filename, context) return unless ERuby #eval context2code(context) list = context['list'] output = nil @ntimes.times do output = ERuby::Compiler.new.compile_string(File.read(filename)) end return output end def convert_erb(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = ERB.new(File.read(filename)) output = eruby.src end return output end for klass in %w[Eruby FastEruby TinyEruby] s = <<-END def convert_erubis_#{klass.downcase}(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = Erubis::#{klass}.new(File.read(filename)) output = eruby.src end return output end END eval s end end require 'optparse' class MainApplication def parse_argv(argv=ARGV) optparser = OptionParser.new options = {} ['-h', '-n N', '-t erubyfile', '-f contextfile', '-A', '-e', '-x exclude', '-m testmode', '-X', '-p', '-D'].each do |opt| optparser.on(opt) { |val| options[opt[1].chr] = val } end begin targets = optparser.parse!(argv) rescue => ex $stderr.puts "#{@script}: #{ex.to_s}" exit(1) end return options, targets end def execute @script = File.basename($0) ntimes = 1000 targets = BenchmarkApplication::TARGETS.dup testmode = 'execute' contextfile = 'bench_context.yaml' # options, args = parse_argv(ARGV) ntimes = options['n'].to_i if options['n'] targets = args if args && !args.empty? targets = targets - options['x'].split(/,/) if options['x'] testmode = options['m'] if options['m'] contextfile = options['f'] if options['f'] erubyfile = options['t'] if options['t'] # if options['h'] $stderr.puts "Usage: ruby #{@script} [..options..] [..targets..]" $stderr.puts " -h : help" $stderr.puts " -n N : loop N times" $stderr.puts " -f datafile : context data filename (*.yaml)" $stderr.puts " -x exclude : exclude target name" $stdout.puts " -m testmode : 'execute' or 'convert' (default 'execute')" $stderr.puts " -p : print output to file (filename: 'output.TARGETNAME')" return end # #if ! options['t'] for item in %w[eruby erb erubis] fname = "bench_#{item}.rhtml" header = File.read("templates/_header.html") #body = File.read("templates/#{erubyfile}") body = File.read("templates/#{fname}") footer = File.read("templates/_footer.html") content = header + body + footer File.write(fname, content) end # if options['e'] # escape tuples = [ [ 'bench_eruby.rhtml', '<%= CGI.escapeHTML((\1).to_s) %>' ], [ 'bench_erb.rhtml', '<%=h \1 %>' ], [ 'bench_erubis.rhtml', '<%== \1 %>' ], ] for fname, replace in tuples content = File.read(fname).gsub(/<%= ?(.*?) ?%>/, replace) File.write(fname, content) end targets.delete('Erubis::TinyEruby') ## because TinyEruby doesn't support '<%== =>' end # context = YAML.load_file(contextfile) # params = { :printout=>options['p'], :testmode=>testmode, } app = BenchmarkApplication.new(ntimes, context, targets, params) app.perform_benchmark() end end if __FILE__ == $0 ## open /dev/null $stdout = File.open('/dev/null', 'w') at_exit do $stdout.close() end ## start benchmark MainApplication.new().execute() 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/test/test.rb
gems/gems/erubis-2.6.0/test/test.rb
## ## $Rev: 77 $ ## $Release: 2.6.0 $ ## copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ## unless defined?(TESTDIR) TESTDIR = File.dirname(__FILE__) LIBDIR = TESTDIR == '.' ? '../lib' : File.dirname(TESTDIR) + '/lib' $: << TESTDIR $: << LIBDIR end require 'test/unit' #require 'test/unit/ui/console/testrunner' require 'assert-text-equal' require 'yaml' require 'testutil' require 'erubis' if $0 == __FILE__ require "#{TESTDIR}/test-erubis.rb" require "#{TESTDIR}/test-engines.rb" require "#{TESTDIR}/test-enhancers.rb" require "#{TESTDIR}/test-main.rb" require "#{TESTDIR}/test-users-guide.rb" 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/test/test-enhancers.rb
gems/gems/erubis-2.6.0/test/test-enhancers.rb
## ## $Rev: 93 $ ## $Release: 2.6.0 $ ## copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'stringio' require 'erubis' require 'erubis/engine/enhanced' require 'erubis/engine/optimized' class EnhancersTest < Test::Unit::TestCase testdata_list = load_yaml_datafile(__FILE__) define_testmethods(testdata_list) def _test() @src.gsub!(/\^/, ' ') @output.gsub!(/\^/, ' ') if @output.is_a?(String) if @class k = Erubis @class.split('::').each do |name| k = k.const_get(name) end @klass = k else @klass = Erubis::Eruby end @options ||= {} @chomp.each do |target| case target when 'src' ; @src.chomp! when 'input' ; @input.chomp! when 'expected' ; @expected.chomp! else raise "#{@name}: invalid chomp value: #{@chomp.inspect}" end end if @chomp if @testopt == 'load_file' filename = "tmp.#{@name}.eruby" begin File.open(filename, 'w') { |f| f.write(@input) } eruby = @klass.load_file(filename, @options) ensure cachename = filename + '.cache' File.unlink(cachename) if test(?f, cachename) File.unlink(filename) if test(?f, filename) end else #if @klass == Erubis::TinyEruby # eruby = @klass.new(@input) #else eruby = @klass.new(@input, @options) #end end assert_text_equal(@src, eruby.src) return if @testopt == 'skip_output' list = ['<aaa>', 'b&b', '"ccc"'] context = @testopt == 'context' ? Erubis::Context.new : {} context[:list] = list case @testopt when /\Aeval\(/ eval eruby.src actual = eval @testopt assert_text_equal(@output, actual) when 'stdout', 'print' begin orig = $stdout $stdout = stringio = StringIO.new #actual = eruby.evaluate(context) actual = eruby.result(context) ensure $stdout = orig end if @testopt == 'stdout' assert_equal("", actual) else assert_nil(actual) end assert_text_equal(@output, stringio.string) when 'evaluate', 'context' actual = eruby.evaluate(context) assert_text_equal(@output, actual) when 'binding' actual = eruby.result(binding()) assert_text_equal(@output, actual) else actual = eruby.result(context) assert_text_equal(@output, actual) end end end __END__ ## - name: basic1 class: Eruby input: &basic1_input| <ul> <% for item in list %> <li><%= item %></li> <% end %> </ul> src: &basic1_src| _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: &basic1_output| <ul> <li><aaa></li> <li>b&b</li> <li>"ccc"</li> </ul> - name: xml1 class: XmlEruby input: | <pre> <% for item in list %> <%= item %> <%== item %> <% end %> </pre> src: | _buf = ''; _buf << '<pre> '; for item in list _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' '; _buf << ' '; _buf << ( item ).to_s; _buf << ' '; end _buf << '</pre> '; _buf.to_s output: | <pre> &lt;aaa&gt; <aaa> b&amp;b b&b &quot;ccc&quot; "ccc" </pre> ## - name: xml2 class: XmlEruby testopt: skip_output input: | <% for item in list %> <%= item["var#{n}"] %> <%== item["var#{n}"] %> <%=== item["var#{n}"] %> <%==== item["var#{n}"] %> <% end %> src: | _buf = ''; for item in list _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item["var#{n}"] ); _buf << ' '; _buf << ' '; _buf << ( item["var#{n}"] ).to_s; _buf << ' '; _buf << ' '; $stderr.puts("*** debug: item[\"var\#{n}\"]=#{(item["var#{n}"]).inspect}"); _buf << ' '; _buf << ' '; _buf << ' '; end _buf.to_s output: | ## - name: printout1 class: PrintOutEruby testopt: print input: *basic1_input src: |4 print '<ul> '; for item in list print ' <li>'; print(( item ).to_s); print '</li> '; end print '</ul> '; output: *basic1_output ## - name: printenabled1 class: PrintEnabledEruby input: &printenabled1_input| <ul> <% for item in list %> <li><% print item %></li> <% end %> </ul> src: | @_buf = _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; print item ; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> ## - name: stdout1 class: StdoutEruby testopt: stdout input: *basic1_input # <ul> # <% for item in list %> # <li><%= item %></li> # <% end %> # </ul> src: | _buf = $stdout; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; '' output: *basic1_output # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> ## - name: array1 class: ArrayEruby input: | <ul> <% for item in list %> <li><%= item %></li> <% end %> </ul> src: | _buf = []; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf output: - "<ul>\n" - " <li>" - "<aaa>" - "</li>\n" - " <li>" - "b&b" - "</li>\n" - " <li>" - "\"ccc\"" - "</li>\n" - "</ul>\n" ## - name: arraybuffer1 class: ArrayBufferEruby input: *basic1_input src: | _buf = []; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.join output: *basic1_output - name: stringbuffer1 class: StringBufferEruby input: *basic1_input # <ul> # <% for item in list %> # <li><%= item %></li> # <% end %> # </ul> src: | _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> ## - name: erbout1 class: ErboutEruby input: *basic1_input src: | _erbout = _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output ## - name: stringio1 class: StringIOEruby input: *basic1_input src: | _buf = StringIO.new; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.string output: *basic1_output ## - name: notext1 class: NoTextEruby input: *basic1_input src: | _buf = ''; for item in list _buf << ( item ).to_s; end _buf.to_s output: '<aaa>b&b"ccc"' ## - name: nocode1 class: NoCodeEruby testopt: skip_output input: *basic1_input src: | <ul> <li></li> </ul> output: ## - name: simplified class: SimplifiedEruby input: | <ul> <% for item in list %> <li> <%= item %> </li> <% end %> </ul> src: | _buf = ''; _buf << '<ul> '; for item in list ; _buf << ' <li> '; _buf << ( item ).to_s; _buf << ' </li> '; end ; _buf << ' </ul> '; _buf.to_s output: | <ul> ^ <li> <aaa> </li> ^ <li> b&b </li> ^ <li> "ccc" </li> ^ </ul> ## - name: bipattern1 class: BiPatternEruby #options: { :bipattern : '\[= =\]' } input: | <% for item in list %> <%= item %> % <%== item %> [= item =] = [== item =] <% end %> src: | _buf = ''; for item in list _buf << ' '; _buf << ( item ).to_s; _buf << ' % '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' '; _buf << ' '; _buf << ( item ).to_s; _buf << ' = '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' '; end _buf.to_s output: |4 <aaa> % &lt;aaa&gt; <aaa> = &lt;aaa&gt; b&b % b&amp;b b&b = b&amp;b "ccc" % &quot;ccc&quot; "ccc" = &quot;ccc&quot; ## - name: bipattern2 class: BiPatternEruby options: { :bipattern: '\$\{ \}' } input: | <% for item in list %> <%=item%> % <%==item%> ${item} = ${=item} <% end %> src: | _buf = ''; for item in list _buf << ' '; _buf << (item).to_s; _buf << ' % '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' '; _buf << ' '; _buf << (item).to_s; _buf << ' = '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' '; end _buf.to_s output: |4 <aaa> % &lt;aaa&gt; <aaa> = &lt;aaa&gt; b&b % b&amp;b b&b = b&amp;b "ccc" % &quot;ccc&quot; "ccc" = &quot;ccc&quot; ## - name: percentline1 class: PercentLineEruby options: input: | <table> % for item in list <tr> <td><%= item %></td> <td><%== item %></td> </tr> % end </table> <pre> %% double percent % spaced percent </pre> src: | _buf = ''; _buf << '<table> '; for item in list _buf << ' <tr> <td>'; _buf << ( item ).to_s; _buf << '</td> <td>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</td> </tr> '; end _buf << '</table> <pre> % double percent % spaced percent </pre> '; _buf.to_s output: | <table> <tr> <td><aaa></td> <td>&lt;aaa&gt;</td> </tr> <tr> <td>b&b</td> <td>b&amp;b</td> </tr> <tr> <td>"ccc"</td> <td>&quot;ccc&quot;</td> </tr> </table> <pre> % double percent % spaced percent </pre> ## - name: headerfooter1 class: HeaderFooterEruby options: testopt: eval('ordered_list(list)') input: | <!--#header: def ordered_list(list) #--> <ol> <% for item in list %> <li><%==item%></li> <% end %> </ol> <!--#footer: end #--> src: |4 def ordered_list(list) _buf = ''; _buf << '<ol> '; for item in list _buf << ' <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '</li> '; end _buf << '</ol> '; _buf.to_s end output: | <ol> <li>&lt;aaa&gt;</li> <li>b&amp;b</li> <li>&quot;ccc&quot;</li> </ol> ## - name: deleteindent1 class: DeleteIndentEruby options: testopt: input: *basic1_input src: | _buf = ''; _buf << '<ul> '; for item in list _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: | <ul> <li><aaa></li> <li>b&b</li> <li>"ccc"</li> </ul> ## - name: interpolation1 class: InterpolationEruby options: testopt: input: *basic1_input src: | _buf = ''; _buf << %Q`<ul>\n` for item in list _buf << %Q` <li>#{ item }</li>\n` end _buf << %Q`</ul>\n` _buf.to_s output: *basic1_output
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/test-users-guide.rb
gems/gems/erubis-2.6.0/test/test-users-guide.rb
### ### $Rev: 77 $ ### $Release: 2.6.0 $ ### copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ### require "#{File.dirname(__FILE__)}/test.rb" class KwarkUsersGuideTest < Test::Unit::TestCase DIR = File.expand_path(File.dirname(__FILE__) + '/data/users-guide') CWD = Dir.pwd() def setup Dir.chdir DIR end def teardown Dir.chdir CWD end def _test @name = (caller()[0] =~ /`(.*?)'/) && $1 s = File.read(@filename) s =~ /\A\$ (.*?)\n/ command = $1 expected = $' result = `#{command}` assert_text_equal(expected, result) end Dir.chdir DIR do filenames = [] filenames += Dir.glob('*.result') filenames += Dir.glob('*.source') filenames.each do |filename| name = filename.gsub(/[^\w]/, '_') s = <<-END def test_#{name} # $stderr.puts "*** debug: test_#{name}" @name = '#{name}' @filename = '#{filename}' _test() end END eval s 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/test/assert-text-equal.rb
gems/gems/erubis-2.6.0/test/assert-text-equal.rb
### ### $Rev: 77 $ ### $Release: 2.6.0 $ ### copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ### require 'test/unit' require 'tempfile' module Test module Unit class TestCase def assert_text_equal(expected, actual, message=nil, diffopt='-u', flag_cut=true) if expected == actual assert(true) return end if expected[-1] != ?\n || actual[-1] != ?\n expected += "\n" actual += "\n" end begin expfile = Tempfile.new(".expected.") expfile.write(expected); expfile.flush() actfile = Tempfile.new(".actual.") actfile.write(actual); actfile.flush() diff = `diff #{diffopt} #{expfile.path} #{actfile.path}` ensure expfile.close(true) if expfile actfile.close(true) if actfile end # cut 1st & 2nd lines message = (flag_cut ? diff.gsub(/\A.*\n.*\n/, '') : diff) unless message #raise Test::Unit::AssertionFailedError.new(message) assert_block(message) { false } # or assert(false, message) end alias assert_equal_with_diff assert_text_equal # for compatibility alias assert_text_equals assert_text_equal # for typo 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/test/testutil.rb
gems/gems/erubis-2.6.0/test/testutil.rb
### ### $Rev: 77 $ ### $Release: 2.6.0 $ ### copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ### require 'yaml' require 'test/unit/testcase' class Test::Unit::TestCase def self.load_yaml_datafile(filename, options={}, &block) # :nodoc: # read datafile s = File.read(filename) if filename =~ /\.rb$/ s =~ /^__END__$/ or raise "*** error: __END__ is not found in '#{filename}'." s = $' end # untabify unless options[:tabify] == false s = s.inject('') do |sb, line| sb << line.gsub(/([^\t]{8})|([^\t]*)\t/n) { [$+].pack("A8") } end end # load yaml document testdata_list = [] YAML.load_documents(s) do |ydoc| if ydoc.is_a?(Hash) testdata_list << ydoc elsif ydoc.is_a?(Array) ydoc.each do |hash| raise "testdata should be a mapping." unless hash.is_a?(Hash) testdata_list << hash end else raise "testdata should be a mapping." end end # data check identkey = options[:identkey] || 'name' table = {} testdata_list.each do |hash| ident = hash[identkey] ident or raise "*** key '#{identkey}' is required but not found." table[ident] and raise "*** #{identkey} '#{ident}' is duplicated." table[ident] = hash yield(hash) if block end # return testdata_list end def self.define_testmethods(testdata_list, options={}, &block) identkey = options[:identkey] || 'name' testmethod = options[:testmethod] || '_test' testdata_list.each do |hash| yield(hash) if block ident = hash[identkey] s = "def test_#{ident}\n" hash.each do |key, val| s << " @#{key} = #{val.inspect}\n" end s << " #{testmethod}\n" s << "end\n" $stderr.puts "*** load_yaml_testdata(): eval_str=<<'END'\n#{s}END" if $DEBUG self.module_eval s 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/test/test-main.rb
gems/gems/erubis-2.6.0/test/test-main.rb
## ## $Rev: 87 $ ## $Release: 2.6.0 $ ## $Date: 2007-07-12 05:01:24 +0900 (Thu, 12 Jul 2007) $ ## require "#{File.dirname(__FILE__)}/test.rb" require 'tempfile' require 'erubis/main' $script = File.dirname(TESTDIR) + '/bin/erubis' #if test(?f, 'bin/erubis') # $script = 'bin/erubis' #elsif test(?f, '../bin/erubis') # $script = '../bin/erubis' #end class StringWriter < String def write(arg) self << arg end end class Erubis::Main public :usage public :show_properties public :show_enhancers end class MainTest < Test::Unit::TestCase INPUT = <<'END' list: <% list = ['<aaa>', 'b&b', '"ccc"'] for item in list %> - <%= item %> <% end %> user: <%= defined?(user) ? user : "(none)" %> END INPUT2 = INPUT.gsub(/\blist([^:])/, '@list\1').gsub(/\buser([^:])/, '@user\1') # SRC = <<'END' #_buf = ''; _buf << "list:\n" # list = ['<aaa>', 'b&b', '"ccc"'] # for item in list #_buf << " - "; _buf << ( item ).to_s; _buf << "\n" # end #_buf << "user: "; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << "\n" #_buf #END SRC = <<'END' _buf = ''; _buf << 'list: '; list = ['<aaa>', 'b&b', '"ccc"'] for item in list _buf << ' - '; _buf << ( item ).to_s; _buf << ' '; end _buf << 'user: '; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << ' '; _buf.to_s END # SRC2 = SRC.gsub(/\blist /, '@list ').gsub(/\buser /, '@user ') OUTPUT = <<'END' list: - <aaa> - b&b - "ccc" user: (none) END ESCAPED_OUTPUT = <<'END' list: - &lt;aaa&gt; - b&amp;b - &quot;ccc&quot; user: (none) END PI_INPUT = <<'END' <ul> <?rb @list = ['<aaa>', 'b&b', '"ccc"'] for item in @list ?> <li>@{item}@ / @!{item}@ <%= item %> / <%== item %></li> <?rb end ?> <ul> END PI_SRC = <<'END' _buf = ''; _buf << '<ul> '; @list = ['<aaa>', 'b&b', '"ccc"'] for item in @list _buf << ' <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' / '; _buf << (item).to_s; _buf << ' '; _buf << ( item ).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li> '; end _buf << '<ul> '; _buf.to_s END PI_ESCAPED_SRC = <<'END' _buf = ''; _buf << '<ul> '; @list = ['<aaa>', 'b&b', '"ccc"'] for item in @list _buf << ' <li>'; _buf << (item).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' / '; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '<ul> '; _buf.to_s END PI_OUTPUT = <<'END' <ul> <li>&lt;aaa&gt; / <aaa> <aaa> / &lt;aaa&gt;</li> <li>b&amp;b / b&b b&b / b&amp;b</li> <li>&quot;ccc&quot; / "ccc" "ccc" / &quot;ccc&quot;</li> <ul> END PI_ESCAPED_OUTPUT = <<'END' <ul> <li><aaa> / &lt;aaa&gt; &lt;aaa&gt; / <aaa></li> <li>b&b / b&amp;b b&amp;b / b&b</li> <li>"ccc" / &quot;ccc&quot; &quot;ccc&quot; / "ccc"</li> <ul> END def _test() if $target name = (caller()[0] =~ /in `test_(.*?)'/) && $1 return unless name == $target end if @filename.nil? method = (caller[0] =~ /in `(.*)'/) && $1 #' @filename = "tmp.#{method}" end File.open(@filename, 'w') { |f| f.write(@input) } if @filename begin #if @options.is_a?(Array) # command = "ruby #{$script} #{@options.join(' ')} #{@filename}" #else # command = "ruby #{$script} #{@options} #{@filename}" #end #output = `#{command}` if @options.is_a?(Array) argv = @options + [ @filename ] else argv = "#{@options} #{@filename}".split end $stdout = output = StringWriter.new Erubis::Main.new.execute(argv) ensure $stdout = STDOUT File.unlink(@filename) if @filename && test(?f, @filename) end assert_text_equal(@expected, output) end def test_help # -h @options = '-h' m = Erubis::Main.new @expected = m.usage() + "\n" + m.show_properties() + m.show_enhancers() @filename = false _test() end def test_version # -v @options = '-v' @expected = (("$Release: 2.6.0 $" =~ /[.\d]+/) && $&) + "\n" @filename = false _test() end def test_basic1 @input = INPUT @expected = OUTPUT @options = '' _test() end def test_source1 # -x @input = INPUT @expected = SRC @options = '-x' _test() end def test_syntax1 # -z (syntax ok) @input = INPUT @expected = "Syntax OK\n" @options = '-z' _test() end def test_syntax2 # -z (syntax error) inputs = [] inputs << <<'END' <ul> <% for item in list %> <li><%= item[:name]] %></li> <% end %> </ul> END inputs << <<'END' <ul> <% for item in list %> <li><%= item[:name] %></li> <% edn %> </ul> END basename = 'tmp.test_syntax2_%d.rhtml' filenames = [ basename % 0, basename % 1 ] errmsgs = [] errmsgs << <<'END' 3: syntax error, unexpected ']', expecting ')' _buf << ' <li>'; _buf << ( item[:name]] ).to_s; _buf << '</li> ^ -:4: syntax error, unexpected kEND, expecting ')' '; end ^ -:7: syntax error, unexpected $end, expecting ')' END errmsgs << <<'END' 7: syntax error, unexpected $end, expecting kEND END # max = inputs.length (0...max).each do |i| @input = inputs[i] @expected = "tmp.test_syntax2:#{errmsgs[i]}" @options = '-z' _test() end # begin (0...max).each do |i| File.open(filenames[i], 'w') { |f| f.write(inputs[i]) } end @input = '<ok/>' @expected = '' @options = '-z' (0...max).each do |i| @expected << "#{filenames[i]}:#{errmsgs[i]}" @options << " #{filenames[i]}" end _test() ensure (0...max).each do |i| File.unlink(filenames[i]) if test(?f, filenames[i]) end end end def test_pattern1 # -p @input = INPUT.gsub(/<%/, '<!--%').gsub(/%>/, '%-->') @expected = OUTPUT #@options = "-p '<!--% %-->'" @options = ["-p", "<!--% %-->"] _test() end # def test_class1 # -C # @input = INPUT # @expected = OUTPUT.gsub(/<aaa>/, '&lt;aaa&gt;').gsub(/b&b/, 'b&amp;b').gsub(/"ccc"/, '&quot;ccc&quot;') # @options = "-C XmlEruby" # _test() # end def test_notrim1 # --trim=false @input = INPUT @expected = <<'END' list: - <aaa> - b&b - "ccc" user: (none) END @options = "--trim=false" # -T _test() end def test_notrim2 # --trim=false @input = INPUT # @expected = <<'END' #_buf = ''; _buf << "list:\n" # list = ['<aaa>', 'b&b', '"ccc"'] # for item in list ; _buf << "\n" #_buf << " - "; _buf << ( item ).to_s; _buf << "\n" # end ; _buf << "\n" #_buf << "user: "; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << "\n" #_buf #END @expected = <<'END' _buf = ''; _buf << 'list: '; list = ['<aaa>', 'b&b', '"ccc"'] for item in list ; _buf << ' '; _buf << ' - '; _buf << ( item ).to_s; _buf << ' '; end ; _buf << ' '; _buf << 'user: '; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << ' '; _buf.to_s END @options = "-x --trim=false" # -xT _test() end #-- #def test_context1 # @input = INPUT # @expected = OUTPUT.gsub(/\(none\)/, 'Hello') # @options = '--user=Hello' # _test() #end #++ def test_datafile1 # -f data.yaml datafile = "test.context1.yaml" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-f #{datafile}" # str = <<-END user: Hello password: world END File.open(datafile, 'w') { |f| f.write(str) } begin _test() ensure File.unlink(datafile) if test(?f, datafile) end end def test_datafile2 # -f data.rb datafile = "test.context1.rb" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-f #{datafile}" # str = <<-END @user = 'Hello' @password = 'world' END File.open(datafile, 'w') { |f| f.write(str) } begin _test() ensure File.unlink(datafile) if test(?f, datafile) end end def test_untabify1 # -t (obsolete) yamlfile = "test.context2.yaml" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-tf #{yamlfile}" # yaml = <<-END user: Hello password: world END File.open(yamlfile, 'w') { |f| f.write(yaml) } begin _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end end def test_untabify2 # -T yamlfile = "test.context2.yaml" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-Tf #{yamlfile}" # yaml = <<-END user: Hello items: - aaa - bbb - ccc END File.open(yamlfile, 'w') { |f| f.write(yaml) } assert_raise(ArgumentError) do _test() end File.open(yamlfile, 'w') { |f| f.write(yaml.gsub(/\t/, ' '*8)) } _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end def test_symbolify1 # -S yamlfile = "test.context3.yaml" @input = <<END <% for h in @list %> <tr> <td><%= h[:name] %></td><td><%= h[:mail] %></td> </tr> <% end %> END @expected = <<END <tr> <td>foo</td><td>foo@mail.com</td> </tr> <tr> <td>bar</td><td>bar@mail.org</td> </tr> END @options = "-f #{yamlfile} -S" # yaml = <<-END list: - name: foo mail: foo@mail.com - name: bar mail: bar@mail.org END File.open(yamlfile, 'w') { |f| f.write(yaml) } begin _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end end def test_result1 # -B yamlfile = "test.context4.yaml" # @input = <<'END' user = <%= user %> <% for item in list %> - <%= item %> <% end %> END @expected = <<'END' user = World - aaa - bbb - ccc END @options = "-f #{yamlfile} -B " # yaml = <<-END user: World list: - aaa - bbb - ccc END File.open(yamlfile, 'w') { |f| f.write(yaml) } begin _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end end def test_context1 # -c @input = <<'END' user = <%= @user %> <% for item in @list %> - <%= item %> <% end %> END @expected = <<'END' user = World - aaa - bbb - ccc END # @options = ['-c', '{user: World, list: [aaa, bbb, ccc]}'] _test() @options = ['-c', '@user="World"; @list=%w[aaa bbb ccc]'] _test() end def test_include1 # -I dir = 'foo' lib = 'bar' Dir.mkdir dir unless test(?d, dir) filename = "#{dir}/#{lib}.rb" File.open(filename, 'w') do |f| f.write <<-'END' def escape(str) return "<#{str.upcase}>" end END end # @input = "<% require '#{lib}' %>\n" + INPUT.gsub(/<%= item %>/, '<%= escape(item) %>') @expected = OUTPUT.gsub(/<aaa>/, '<<AAA>>').gsub(/b\&b/, '<B&B>').gsub(/"ccc"/, '<"CCC">') @options = "-I #{dir}" # begin _test() ensure File.unlink filename if test(?f, filename) Dir.rmdir dir if test(?d, dir) end end def test_require1 # -r dir = 'foo' lib = 'bar' Dir.mkdir dir unless test(?d, dir) filename = "#{dir}/#{lib}.rb" File.open(filename, 'w') do |f| f.write <<-'END' def escape(str) return "<#{str.upcase}>" end END end # @input = INPUT.gsub(/<%= item %>/, '<%= escape(item) %>') @expected = OUTPUT.gsub(/<aaa>/, '<<AAA>>').gsub(/b\&b/, '<B&B>').gsub(/"ccc"/, '<"CCC">') @options = "-I #{dir} -r #{lib}" # begin _test() ensure File.unlink filename if test(?f, filename) Dir.rmdir dir if test(?d, dir) end end def test_enhancers1 # -E @input = <<END <% list = %w[<aaa> b&b "ccc"] %> % for item in list - <%= item %> : <%== item %> - [= item =] : [== item =] % end END @expected = <<END - &lt;aaa&gt; : <aaa> - &lt;aaa&gt; : <aaa> - b&amp;b : b&b - b&amp;b : b&b - &quot;ccc&quot; : "ccc" - &quot;ccc&quot; : "ccc" END @options = "-E Escape,PercentLine,HeaderFooter,BiPattern" _test() end def test_bodyonly1 # -b @input = INPUT @expected = SRC.sub(/\A_buf = '';/,'').sub(/\n_buf.to_s\n\z/,'') @options = '-b -x' _test() end def test_escape1 # -e @input = INPUT @expected = SRC.gsub(/<< \((.*?)\).to_s;/, '<< Erubis::XmlHelper.escape_xml(\1);') @options = '-ex' _test() end def test_pi1 # --pi -x @input = PI_INPUT @expected = PI_SRC @options = '-x --pi' _test() end def test_pi2 # --pi -x --escape=false @input = PI_INPUT @expected = PI_ESCAPED_SRC @options = '-x --pi --escape=false' _test() end def test_pi3 # --pi @input = PI_INPUT @expected = PI_OUTPUT @options = '--pi' _test() end def test_pi4 # --pi --escape=false @input = PI_INPUT @expected = PI_ESCAPED_OUTPUT @options = '--pi --escape=false' _test() end def test_pi5 # --pi=ruby -x @input = PI_INPUT.gsub(/<\?rb/, '<?ruby') @expected = PI_SRC @options = '--pi=ruby -x' _test() end def test_pi6 # --pi -xl java @input = <<'END' <?java for (int i = 0; i < arr.length; i++) { ?> - @{arr[i]}@ / @!{arr[i]}@ <?java } ?> END @expected = <<'END' StringBuffer _buf = new StringBuffer(); for (int i = 0; i < arr.length; i++) { _buf.append(" - "); _buf.append(escape(arr[i])); _buf.append(" / "); _buf.append(arr[i]); _buf.append("\n"); } return _buf.toString(); END @options = '--pi -xl java' _test() 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/test/test-engines.rb
gems/gems/erubis-2.6.0/test/test-engines.rb
## ## $Rev: 95 $ ## $Release: 2.6.0 $ ## copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'erubis' 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' class EnginesTest < Test::Unit::TestCase #load_yaml_documents(__FILE__) testdata_list = load_yaml_datafile(__FILE__) define_testmethods(testdata_list) def _test() klass = Erubis.const_get(@class) engine = klass.new(@input, @options || {}) actual = engine.src assert_text_equal(@expected, actual) end end __END__ - name: ruby1 lang: ruby class: Eruby options: input: | <table> <tbody> <% i = 0 list.each_with_index do |item, i| %> <tr> <td><%= i+1 %></td> <td><%== list %></td> </tr> <% end %> </tbody> </table> <%=== i+1 %> expected: | _buf = ''; _buf << '<table> <tbody> '; i = 0 list.each_with_index do |item, i| _buf << ' <tr> <td>'; _buf << ( i+1 ).to_s; _buf << '</td> <td>'; _buf << Erubis::XmlHelper.escape_xml( list ); _buf << '</td> </tr> '; end _buf << ' </tbody> </table> '; $stderr.puts("*** debug: i+1=#{(i+1).inspect}"); _buf << ' '; _buf.to_s ## - name: php1 lang: php class: Ephp options: input: | <table> <tbody> <% $i = 0; foreach ($list as $item) { $i++; %> <tr> <td><%= $i %></td> <td><%== $item %></td> </tr> <% } %> </tbody> </table> <%=== $i %> expected: | <table> <tbody> <?php $i = 0; foreach ($list as $item) { $i++; ?> <tr> <td><?php echo $i; ?></td> <td><?php echo htmlspecialchars($item); ?></td> </tr> <?php } ?> </tbody> </table> <?php error_log('*** debug: $i='.($i), 0); ?> ## - name: c1 lang: c class: Ec options: { :filename: foo.html, :indent: ' ' } input: |4 <table> <tbody> <% for (i = 0; i < list; i++) { %> <tr> <td><%= "%d", i %></td> <td><%== list[i] %></td> </tr> <% } %> </tbody> </table> <%=== "%d", i %> expected: | #line 1 "foo.html" fputs("<table>\n" " <tbody>\n", stdout); for (i = 0; i < list; i++) { fputs(" <tr>\n" " <td>", stdout); fprintf(stdout, "%d", i); fputs("</td>\n" " <td>", stdout); escape(list[i], stdout); fputs("</td>\n" " </tr>\n", stdout); } fputs(" </tbody>\n" "</table>\n", stdout); fprintf(stderr, "*** debug: i=" "%d", i); fputs("\n", stdout); ## - name: java1 lang: java class: Ejava options: { :buf: _buf, :bufclass: StringBuilder, :indent: ' ' } input: | <table> <tbody> <% int i = 0; for (Iterator it = list.iterator(); it.hasNext(); ) { String s = (String)it.next(); i++; %> <tr class="<%= i%2==0 ? "even" : "odd" %>"> <td><%= i %></td> <td><%== s %></td> </tr> <% } %> <tbody> </table> <%=== i %> expected: |4 StringBuilder _buf = new StringBuilder(); _buf.append("<table>\n" + " <tbody>\n"); int i = 0; for (Iterator it = list.iterator(); it.hasNext(); ) { String s = (String)it.next(); i++; _buf.append(" <tr class=\""); _buf.append(i%2==0 ? "even" : "odd"); _buf.append("\">\n" + " <td>"); _buf.append(i); _buf.append("</td>\n" + " <td>"); _buf.append(escape(s)); _buf.append("</td>\n" + " </tr>\n"); } _buf.append(" <tbody>\n" + "</table>\n"); System.err.println("*** debug: i="+(i)); _buf.append("\n"); return _buf.toString(); ## - name: scheme1 lang: scheme class: Escheme options: input: &scheme1_input| <% (let ((i 0)) %> <table> <tbody> <% (for-each (lambda (item) (set! i (+ i 1)) %> <tr> <td><%= i %></td> <td><%== item %></td> </tr> <% ); lambda end list); for-each end %> </tbody> </table> <%=== i %> <% ); let end %> expected: |4 (let ((_buf '())) (define (_add x) (set! _buf (cons x _buf))) (let ((i 0)) (_add "<table> <tbody>\n") (for-each (lambda (item) (set! i (+ i 1)) (_add " <tr> <td>")(_add i)(_add "</td> <td>")(_add (escape item))(_add "</td> </tr>\n") ); lambda end list); for-each end (_add " </tbody> </table>\n") (display "*** debug: i=")(display i)(display "\n")(_add "\n") ); let end (reverse _buf)) ## - name: scheme2 lang: scheme class: Escheme options: { :func: 'display' } input: *scheme1_input expected: |4 (let ((i 0)) (display "<table> <tbody>\n") (for-each (lambda (item) (set! i (+ i 1)) (display " <tr> <td>")(display i)(display "</td> <td>")(display (escape item))(display "</td> </tr>\n") ); lambda end list); for-each end (display " </tbody> </table>\n") (display "*** debug: i=")(display i)(display "\n")(display "\n") ); let end ## - name: perl1 lang: perl class: Eperl options: input: | <% my $user = 'Erubis'; my @list = ('<aaa>', 'b&b', '"ccc"'); %> <p>Hello <%= $user %>!</p> <table> <tbody> <% $i = 0; %> <% for $item (@list) { %> <tr bgcolor=<%= ++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>"> <td><%= $i %></td> <td><%== $item %></td> </tr> <% } %> </tbody> </table> <%=== $i %> expected: |4 use HTML::Entities; my $user = 'Erubis'; my @list = ('<aaa>', 'b&b', '"ccc"'); print('<p>Hello '); print($user); print('!</p> <table> <tbody> '); $i = 0; for $item (@list) { print(' <tr bgcolor='); print(++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); print('"> <td>'); print($i); print('</td> <td>'); print(encode_entities($item)); print('</td> </tr> '); } print(' </tbody> </table> '); print('*** debug: $i=', $i, "\n");print(' '); ## - name: javascript1 lang: javascript class: Ejavascript options: input: &javascript_input | <% var user = 'Erubis'; var list = ['<aaa>', 'b&b', '"ccc"']; %> <p>Hello <%= user %>!</p> <table> <tbody> <% var i; %> <% for (i = 0; i < list.length; i++) { %> <tr bgcolor=<%= ++i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>"> <td><%= i %></td> <td><%= list[i] %></td> </tr> <% } %> </tbody> </table> <%=== i %> expected: |4 var _buf = []; var user = 'Erubis'; var list = ['<aaa>', 'b&b', '"ccc"']; _buf.push("<p>Hello "); _buf.push(user); _buf.push("!</p>\n\ <table>\n\ <tbody>\n"); var i; for (i = 0; i < list.length; i++) { _buf.push(" <tr bgcolor="); _buf.push(++i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); _buf.push("\">\n\ <td>"); _buf.push(i); _buf.push("</td>\n\ <td>"); _buf.push(list[i]); _buf.push("</td>\n\ </tr>\n"); } _buf.push(" </tbody>\n\ </table>\n"); alert("*** debug: i="+(i)); _buf.push("\n"); document.write(_buf.join("")); ## - name: javascript2 lang: javascript class: Ejavascript options: { :docwrite: false } input: *javascript_input expected: |4 var _buf = []; var user = 'Erubis'; var list = ['<aaa>', 'b&b', '"ccc"']; _buf.push("<p>Hello "); _buf.push(user); _buf.push("!</p>\n\ <table>\n\ <tbody>\n"); var i; for (i = 0; i < list.length; i++) { _buf.push(" <tr bgcolor="); _buf.push(++i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); _buf.push("\">\n\ <td>"); _buf.push(i); _buf.push("</td>\n\ <td>"); _buf.push(list[i]); _buf.push("</td>\n\ </tr>\n"); } _buf.push(" </tbody>\n\ </table>\n"); alert("*** debug: i="+(i)); _buf.push("\n"); _buf.join(""); ##
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/test-erubis.rb
gems/gems/erubis-2.6.0/test/test-erubis.rb
## ## $Rev: 104 $ ## $Release: 2.6.0 $ ## copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'stringio' require 'erubis' require 'erubis/engine/enhanced' require 'erubis/engine/optimized' require 'erubis/tiny' class ErubisTest < Test::Unit::TestCase testdata_list = load_yaml_datafile(__FILE__) define_testmethods(testdata_list) def _test() @src.gsub!(/\^/, ' ') @output.gsub!(/\^/, ' ') if @output.is_a?(String) if @class k = Erubis @class.split('::').each do |name| k = k.const_get(name) end @klass = k else @klass = Erubis::Eruby end @options ||= {} @chomp.each do |target| case target when 'src' ; @src.chomp! when 'input' ; @input.chomp! when 'expected' ; @expected.chomp! else raise "#{@name}: invalid chomp value: #{@chomp.inspect}" end end if @chomp if @testopt == 'load_file' filename = "tmp.#{@name}.eruby" begin File.open(filename, 'w') { |f| f.write(@input) } eruby = @klass.load_file(filename, @options) ensure cachename = filename + '.cache' File.unlink(cachename) if test(?f, cachename) File.unlink(filename) if test(?f, filename) end else if @klass == Erubis::TinyEruby eruby = @klass.new(@input) else eruby = @klass.new(@input, @options) end end assert_text_equal(@src, eruby.src) return if @testopt == 'skip_output' list = ['<aaa>', 'b&b', '"ccc"'] context = @testopt == 'context' ? Erubis::Context.new : {} context[:list] = list case @testopt when /\Aeval\(/ eval eruby.src actual = eval @testopt assert_text_equal(@output, actual) when 'stdout', 'print' begin orig = $stdout $stdout = stringio = StringIO.new #actual = eruby.evaluate(context) actual = eruby.result(context) ensure $stdout = orig end if @testopt == 'stdout' assert_equal("", actual) else assert_nil(actual) end assert_text_equal(@output, stringio.string) when 'evaluate', 'context' actual = eruby.evaluate(context) assert_text_equal(@output, actual) when 'binding' actual = eruby.result(binding()) assert_text_equal(@output, actual) else actual = eruby.result(context) assert_text_equal(@output, actual) end end def test_load_file_cache1 @input = <<END <ul> <% for item in @list %> <li><%= item %></li> <% end %> </ul> END @src = <<END _buf = ''; _buf << '<ul> '; for item in @list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s END @klass = Erubis::Eruby filename = 'tmp.load_file_timestamp1' cachename = filename + '.cache' begin File.open(filename, 'w') { |f| f.write(@input) } assert_block() { !test(?f, cachename) } engine = @klass.load_file(filename) assert_block() { test(?f, cachename) } assert_block() { File.mtime(filename) <= File.mtime(cachename) } assert_text_equal(@src, engine.src) # input2 = @input.gsub(/ul>/, 'ol>') src2 = @src.gsub(/ul>/, 'ol>') mtime = File.mtime(filename) File.open(filename, 'w') { |f| f.write(input2) } t1 = Time.now() sleep(1) t2 = Time.now() File.utime(t1, t1, filename) File.utime(t2, t2, cachename) assert_block('cache should be newer') { File.mtime(filename) < File.mtime(cachename) } engine = @klass.load_file(filename) assert_block('cache should be newer') { File.mtime(filename) < File.mtime(cachename) } assert_text_equal(@src, engine.src) # File.utime(t2, t2, filename) File.utime(t1, t1, cachename) assert_block('cache should be older') { File.mtime(filename) > File.mtime(cachename) } engine = @klass.load_file(filename) assert_block('cache should be newer') { File.mtime(filename) <= File.mtime(cachename) } assert_text_equal(src2, engine.src) ensure File.unlink(cachename) if File.file?(cachename) File.unlink(filename) if File.file?(filename) end end class Dummy end def test_def_method1 s = "<%for i in list%>i=<%=i%>\n<%end%>" eruby = Erubis::Eruby.new(s) assert(! Dummy.instance_methods.include?('render')) eruby.def_method(Dummy, 'render(list)', 'foo.rhtml') assert(Dummy.instance_methods.include?('render')) actual = Dummy.new().render(%w[1 2 3]) assert_equal("i=1\ni=2\ni=3\n", actual) end def test_def_method2 s = "<%for i in list%>i=<%=i%>\n<%end%>" eruby = Erubis::Eruby.new(s) assert(! (eruby.respond_to? :render)) eruby.def_method(eruby, 'render(list)', 'foo.rhtml') assert eruby.respond_to?(:render) actual = eruby.render([1, 2, 3]) assert_equal("i=1\ni=2\ni=3\n", actual) assert !(eruby.class.instance_methods.include? :render) end def test_evaluate_creates_proc s = "hello <%= @name %>" eruby = Erubis::Eruby.new(s) assert_nil(eruby.instance_variable_get('@_proc')) actual1 = eruby.evaluate(:name=>'world') assert_not_nil(eruby.instance_variable_get('@_proc')) assert_instance_of(Proc, eruby.instance_variable_get('@_proc')) actual2 = eruby.evaluate(:name=>'world') assert_equal(actual1, actual2) # convert() must clear @_proc eruby.convert(s) assert_nil(eruby.instance_variable_get('@_proc')) end #def test_toplevel_binding # s = "locals = <%= local_variables().inspect %>\n<% x = 50 %>\n" # eruby = Erubis::Eruby.new(s) # _x = eval 'x', TOPLEVEL_BINDING # _y = eval 'y', TOPLEVEL_BINDING # actual = eruby.evaluate(:x=>_x, :y=>_y) # _x = eval 'x', TOPLEVEL_BINDING # _y = eval 'y', TOPLEVEL_BINDING # puts "*** actual=#{actual.inspect}, x=#{_x.inspect}, y=#{_y.inspect}" #end end x = 10 y = 20 __END__ - name: basic1 input: &basic1_input| <ul> <% for item in list %> <li><%= item %></li> <% end %> </ul> src: &basic1_src| _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: &basic1_output| <ul> <li><aaa></li> <li>b&b</li> <li>"ccc"</li> </ul> ## - name: basic2 input: | <ul> <% i = 0 for item in list i += 1 %> <li><%= item %></li> <% end %> </ul> src: | _buf = ''; _buf << '<ul> '; i = 0 for item in list i += 1 ^^^ _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> ## - name: basic3 input: | <ul><% i = 0 for item in list i += 1 %><li><%= item %></li><% end %> </ul> src: | _buf = ''; _buf << '<ul>'; i = 0 for item in list i += 1 ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>'; end ; _buf << ' '; _buf << '</ul> '; _buf.to_s output: | <ul><li><aaa></li><li>b&b</li><li>"ccc"</li> </ul> ## - name: context1 testopt: context input: | <ul> <% for item in @list %> <li><%= item %></li> <% end %> </ul> src: | _buf = ''; _buf << '<ul> '; for item in @list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output ## - name: ignore1 input: | <ul> <%# i = 0 %> <% for item in list %> <%# i += 1 color = i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %> <li> <%#= i %> : <%= item %> </li> <% end %> </ul> src: | _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li> ';; _buf << ' : '; _buf << ( item ).to_s; _buf << ' </li> '; end _buf << '</ul> '; _buf.to_s output: | <ul> <li> : <aaa> </li> <li> : b&b </li> <li> : "ccc" </li> </ul> ## - name: quotation1 desc: single quotation and backslash class: Eruby input: &quotation1_input| a = "'" b = "\"" c = '\'' src: | _buf = ''; _buf << 'a = "\'" b = "\\"" c = \'\\\'\' '; _buf.to_s output: *quotation1_input ## - name: minus1 desc: '<%- -%>' class: Eruby input: | <ul> <%- for item in list -%> <li><%= item -%></li> <% end -%> </ul> src: *basic1_src output: *basic1_output ## - name: pattern1 options: :pattern : '\[@ @\]' input: | <ul> [@ for item in list @] <li>[@= item @]</li> [@ end @] </ul> src: | _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> ## - name: pattern2 options: :pattern : '<(?:!--)?% %(?:--)?>' input: | <ul> <!--% for item in list %--> <li><%= item %></li> <!--% end %--> </ul> src: | _buf = ''; _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: *basic1_output # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> ## - name: trim1 options: :trim : false input: *basic1_input # <ul> # <% for item in list %> # <li><%= item %></li> # <% end %> # </ul> src: | _buf = ''; _buf << '<ul> '; _buf << ' '; for item in list ; _buf << ' '; _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; _buf << ' '; end ; _buf << ' '; _buf << '</ul> '; _buf.to_s output: | <ul> ^ <li><aaa></li> ^ <li>b&b</li> ^ <li>"ccc"</li> ^ </ul> ## - name: bodyonly1 testopt: skip_output options: { :preamble: no, :postamble: no } input: *basic1_input src: |4 _buf << '<ul> '; for item in list _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; chomp: [src] expected: null ## - name: loadfile1 testopt: load_file #input: | # <ul> # <% for item in list %> # <li><%= item %></li> # <% end %> # </ul> input: "<ul>\r\n <% for item in list %>\r\n <li><%= item %></li>\r\n <% end %>\r\n</ul>\r\n" #src: | # _buf = ''; _buf << "<ul>\n" # for item in list # _buf << " <li>"; _buf << ( item ).to_s; _buf << "</li>\n" # end # _buf << "</ul>\n" # _buf src: "_buf = ''; _buf << '<ul>\r\n'; for item in list \r\n _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li>\r\n'; end \r\n _buf << '</ul>\r\n';\n_buf.to_s\n" #output: | # <ul> # <li><aaa></li> # <li>b&b</li> # <li>"ccc"</li> # </ul> output: "<ul>\n <li><aaa></li>\n <li>b&b</li>\n <li>\"ccc\"</li>\n</ul>\n" # "<ul>\r\n <li><aaa></li>\r\n <li>b&b</li>\r\n <li>\"ccc\"</li>\r\n</ul>\r\n" ## - name: nomatch1 desc: bug input: &nomatch1| <ul> <li>foo</li> </ul> src: | _buf = ''; _buf << '<ul> <li>foo</li> </ul> '; _buf.to_s output: *nomatch1 ## - name: escape1 options: { :escape: true } input: | <% str = '<>&"' %> <%= str %> <%== str %> src: | _buf = ''; str = '<>&"' _buf << Erubis::XmlHelper.escape_xml( str ); _buf << ' '; _buf << ( str ).to_s; _buf << ' '; _buf.to_s output: | &lt;&gt;&amp;&quot; <>&" ## - name: tailch1 options: input: | <p> <% str = '<>&"' %> <%= str %> <%= str =%> <%= str -%> </p> src: | _buf = ''; _buf << '<p> '; str = '<>&"' _buf << ' '; _buf << ( str ).to_s; _buf << ' '; _buf << ' '; _buf << ( str ).to_s; _buf << ' '; _buf << ( str ).to_s; _buf << '</p> '; _buf.to_s output: | <p> <>&" <>&" <>&"</p> ## - name: doublepercent1 options: input: | <% x1 = 10 %> <%% x2 = 20 %> <%= x1 %> <%%= x2 %> src: | _buf = ''; x1 = 10 _buf << '<% x2 = 20 %> '; _buf << ( x1 ).to_s; _buf << ' '; _buf << '<%= x2 %> '; _buf.to_s output: | <% x2 = 20 %> 10 <%= x2 %> ## - name: optimized1 class: OptimizedEruby input: &optimized1_input| <table> <% for item in list %> <tr> <td><%= item %></td> <td><%== item %></td> </tr> <% end %> </table> <ul><% for item in list %><li><%= item %></li><% end %></ul> src: | _buf = '<table> '; for item in list _buf << ' <tr> <td>' << ( item ).to_s << '</td> <td>' << Erubis::XmlHelper.escape_xml( item ) << '</td> </tr> '; end _buf << '</table> <ul>'; for item in list ; _buf << '<li>' << ( item ).to_s << '</li>'; end ; _buf << '</ul> ' _buf output: | <table> <tr> <td><aaa></td> <td>&lt;aaa&gt;</td> </tr> <tr> <td>b&b</td> <td>b&amp;b</td> </tr> <tr> <td>"ccc"</td> <td>&quot;ccc&quot;</td> </tr> </table> <ul><li><aaa></li><li>b&b</li><li>"ccc"</li></ul> ## - name: optimized2 class: OptimizedXmlEruby input: *optimized1_input # <table> # <% for item in list %> # <tr> # <td><%= item %></td> # <td><%== item %></td> # </tr> # <% end %> # </table> # <ul><% for item in list %><li><%= item %></li><% end %></ul> src: | _buf = '<table> '; for item in list _buf << ' <tr> <td>' << Erubis::XmlHelper.escape_xml( item ) << '</td> <td>' << ( item ).to_s << '</td> </tr> '; end _buf << '</table> <ul>'; for item in list ; _buf << '<li>' << Erubis::XmlHelper.escape_xml( item ) << '</li>'; end ; _buf << '</ul> ' _buf output: | <table> <tr> <td>&lt;aaa&gt;</td> <td><aaa></td> </tr> <tr> <td>b&amp;b</td> <td>b&b</td> </tr> <tr> <td>&quot;ccc&quot;</td> <td>"ccc"</td> </tr> </table> <ul><li>&lt;aaa&gt;</li><li>b&amp;b</li><li>&quot;ccc&quot;</li></ul> ## - name: optimized3 desc: bug class: OptimizedEruby input: | user = <%= "Foo" %> <% for item in list %> <%= item %> <% end %> src: | _buf = 'user = '; _buf << ( "Foo" ).to_s << ' '; for item in list _buf << ' ' << ( item ).to_s << ' '; end _buf output: | user = Foo <aaa> b&b "ccc" ## - name: optimized4 desc: single quotation and backslash class: OptimizedEruby input: &optimized4_input| a = "'" b = "\"" c = '\'' src: | _buf = 'a = "\'" b = "\\"" c = \'\\\'\' '; _buf output: *optimized4_input ## - name: tiny1 class: TinyEruby testopt: binding input: | <ul> <% for item in list %> <li><%= item %></li> <% end %> </ul> src: | _buf = ''; _buf << '<ul> '; for item in list ; _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end ; _buf << ' </ul> '; _buf.to_s output: | <ul> ^ <li><aaa></li> ^ <li>b&b</li> ^ <li>"ccc"</li> ^ </ul> ## - name: tiny2 class: TinyEruby testopt: evaluate input: | <ul> <% for item in @list %> <li><%= item %></li> <% end %> </ul> src: | _buf = ''; _buf << '<ul> '; for item in @list ; _buf << ' <li>'; _buf << ( item ).to_s; _buf << '</li> '; end ; _buf << ' </ul> '; _buf.to_s output: | <ul> ^ <li><aaa></li> ^ <li>b&b</li> ^ <li>"ccc"</li> ^ </ul> ## - name: pi1 class: PI::Eruby testopt: evaluate input: &input_pi1| <ul> <?rb for item in @list ?> <li>@{item}@ / @!{item}@</li> <li><%= item %> / <%== item %></li> <?rb end ?> </ul> src: &src_pi1| _buf = ''; _buf << '<ul> '; for item in @list _buf << ' <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' / '; _buf << (item).to_s; _buf << '</li> <li>'; _buf << ( item ).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: &output_pi1| <ul> <li>&lt;aaa&gt; / <aaa></li> <li><aaa> / &lt;aaa&gt;</li> <li>b&amp;b / b&b</li> <li>b&b / b&amp;b</li> <li>&quot;ccc&quot; / "ccc"</li> <li>"ccc" / &quot;ccc&quot;</li> </ul> ## - name: pi2 class: PI::Eruby options: { :escape: false } testopt: evaluate input: *input_pi1 src: | _buf = ''; _buf << '<ul> '; for item in @list _buf << ' <li>'; _buf << (item).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '</li> <li>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' / '; _buf << ( item ).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: | <ul> <li><aaa> / &lt;aaa&gt;</li> <li>&lt;aaa&gt; / <aaa></li> <li>b&b / b&amp;b</li> <li>b&amp;b / b&b</li> <li>"ccc" / &quot;ccc&quot;</li> <li>&quot;ccc&quot; / "ccc"</li> </ul> ## - name: pi3 class: PI::Eruby options: { :pi: hoge, :embchar: '$' } testopt: evaluate input: | <ul> <?hoge for item in @list ?> <li>${item}$ / $!{item}$</li> <li><%= item %> / <%== item %></li> <?hoge end ?> </ul> src: *src_pi1 output: *output_pi1 - name: pi4 class: PI::Eruby testopt: evaluate input: | <?rb-header def show(list) ?> <ul> <?rb for item in list ?> <?rb-value item ?> <?rb end ?> <?rb-comment # comment # comment ?> </ul> <?rb-footer end show(@list) ?> src: |4 def show(list) _buf = ''; _buf << '<ul> '; for item in list _buf << ( item ).to_s; end _buf << '</ul> '; _buf.to_s end show(@list) output: | <ul> <aaa>b&b"ccc"</ul> - name: pitiny1 class: PI::TinyEruby testopt: evaluate input: | <ul> <?rb for item in @list ?> <li>@{item}@ / @!{item}@</li> <?rb end ?> </ul> src: | _buf = ''; _buf << '<ul> '; for item in @list _buf << ' <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' / '; _buf << (item).to_s; _buf << '</li> '; end _buf << '</ul> '; _buf.to_s output: | <ul> <li>&lt;aaa&gt; / <aaa></li> <li>b&amp;b / b&b</li> <li>&quot;ccc&quot; / "ccc"</li> </ul>
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/example3.rb
gems/gems/erubis-2.6.0/test/data/users-guide/example3.rb
require 'erubis' input = File.read('example3.eruby') eruby = Erubis::EscapedEruby.new(input) # or Erubis::XmlEruby puts "----- script source ---" puts eruby.src # print script source puts "----- result ----------" list = ['<aaa>', 'b&b', '"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/example10.rb
gems/gems/erubis-2.6.0/test/data/users-guide/example10.rb
require 'erubis' input = File.read('example10.xhtml') eruby = Erubis::PI::Eruby.new(input) print eruby.src
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/example9.rb
gems/gems/erubis-2.6.0/test/data/users-guide/example9.rb
require 'erubis' input = File.read('example9.eruby') eruby1 = Erubis::Eruby.new(input) eruby2 = Erubis::Eruby.new(input, :preamble=>false, :postamble=>false) puts eruby1.src # print preamble and postamble puts "--------------" puts eruby2.src # don't print preamble and postamble
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/fasteruby.rb
gems/gems/erubis-2.6.0/test/data/users-guide/fasteruby.rb
require 'erubis' input = File.read('fasteruby.rhtml') eruby = Erubis::FastEruby.new(input) # create Eruby object puts "---------- script source ---" puts eruby.src puts "---------- result ----------" context = { :title=>'Example', :list=>['aaa', 'bbb', 'ccc'] } output = eruby.evaluate(context) print output
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/example1.rb
gems/gems/erubis-2.6.0/test/data/users-guide/example1.rb
require 'erubis' input = File.read('example1.eruby') eruby = Erubis::Eruby.new(input) # create Eruby object puts "---------- script source ---" puts eruby.src # print script source puts "---------- result ----------" list = ['aaa', 'bbb', 'ccc'] puts eruby.result(binding()) # get result ## # or ## eruby = Erubis::Eruby.new ## input = File.read('example1.eruby') ## src = eruby.convert(input) ## eval src
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/example5.rb
gems/gems/erubis-2.6.0/test/data/users-guide/example5.rb
require 'erubis' input = File.read('example5.eruby') eruby = Erubis::Eruby.new(input) # create Eruby object ## create context object ## (key means var name, which may be string or symbol.) context = { :val => 'Erubis Example', 'list' => ['aaa', 'bbb', 'ccc'], } ## or # context = Erubis::Context.new() # context['val'] = 'Erubis Example' # context[:list] = ['aaa', 'bbb', 'ccc'], puts eruby.evaluate(context) # 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/example4.rb
gems/gems/erubis-2.6.0/test/data/users-guide/example4.rb
require 'erubis' input = File.read('example4.eruby') eruby = Erubis::Eruby.new(input, :pattern=>'<!--% %-->') # or '<(?:!--)?% %(?:--)?>' 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/headerfooter-example2.rb
gems/gems/erubis-2.6.0/test/data/users-guide/headerfooter-example2.rb
require 'erubis' class HeaderFooterEruby < Erubis::Eruby include Erubis::HeaderFooterEnhancer end input = File.read('headerfooter-example2.rhtml') eruby = HeaderFooterEruby.new(input) print eruby.src
ruby
MIT
8039b8a99883597deeb3d03f67216755f101f667
2026-01-04T17:49:41.524706Z
false