CombinedText stringlengths 4 3.42M |
|---|
require 'optparse'
module VagrantPlugins
module DevCommands
# Provides access to messages used by the plugin
class Messages
def self.no_help(&out)
out.call 'No detailed help for this command available.'
end
def self.no_commands(&out)
out.call 'No commands defined!'
end
def self.plugin_usage(&out)
out.call 'Usage: vagrant run [box] <command>'
out.call 'Help: vagrant run help <command>'
end
def self.plugin_usage_info(&out)
curdir = File.expand_path(File.dirname(__FILE__))
readme = File.expand_path(File.join(curdir, '../../../README.md'))
out.call ''
out.call 'For detailed usage please read the'
out.call 'README.md at the original source location:'
out.call '>>> https://github.com/mneudert/vagrant-devcommands'
out.call 'A copy of this file should be locally available at'
out.call ">>> #{readme}"
end
end
end
end
removes line break in help README block
require 'optparse'
module VagrantPlugins
module DevCommands
# Provides access to messages used by the plugin
class Messages
def self.no_help(&out)
out.call 'No detailed help for this command available.'
end
def self.no_commands(&out)
out.call 'No commands defined!'
end
def self.plugin_usage(&out)
out.call 'Usage: vagrant run [box] <command>'
out.call 'Help: vagrant run help <command>'
end
def self.plugin_usage_info(&out)
curdir = File.expand_path(File.dirname(__FILE__))
readme = File.expand_path(File.join(curdir, '../../../README.md'))
out.call ''
out.call 'For detailed usage please read the'\
' README.md at the original source location:'
out.call '>>> https://github.com/mneudert/vagrant-devcommands'
out.call 'A copy of this file should be locally available at'
out.call ">>> #{readme}"
end
end
end
end
|
module ValidatesTimeliness
class Railtie < Rails::Railtie
initializer "validates_timeliness.initialize_active_record", :after => 'active_record.initialize_timezone' do
ActiveSupport.on_load(:active_record) do
ValidatesTimeliness.default_timezone = ActiveRecord::Base.default_timezone
ValidatesTimeliness.extend_orms = [ :active_record ]
end
end
initializer "validates_timeliness.initialize_restriction_errors" do
ValidatesTimeliness.ignore_restriction_errors = !Rails.env.test?
end
end
end
Move AR railtie hook outside of initializer to avoid late inclusion of shim
module ValidatesTimeliness
class Railtie < Rails::Railtie
initializer "validates_timeliness.initialize_active_record", :after => 'active_record.initialize_timezone' do
ValidatesTimeliness.default_timezone = ActiveRecord::Base.default_timezone
end
initializer "validates_timeliness.initialize_restriction_errors" do
ValidatesTimeliness.ignore_restriction_errors = !Rails.env.test?
end
end
end
ActiveSupport.on_load(:active_record) do
ValidatesTimeliness.extend_orms = [ :active_record ]
end
|
module Vcloud
module Fog
class ServiceInterface
def initialize
@vcloud = ::Fog::Compute::VcloudDirector.new
end
def org
link = session[:Link].select { |l| l[:rel] == RELATION::CHILD }.detect do |l|
l[:type] == ContentTypes::ORG
end
@vcloud.get_organization(link[:href].split('/').last).body
end
def get_vapp_by_name_and_vdc_name name, vdc_name
response = @vcloud.get_vapps_in_lease_from_query({:filter => "name==#{name}"})
response.body[:VAppRecord].detect { |record| record[:vdcName] == vdc_name }
end
def catalog(name)
link = org[:Link].select { |l| l[:rel] == RELATION::CHILD }.detect do |l|
l[:type] == ContentTypes::CATALOG && l[:name] == name
end
@vcloud.get_catalog(extract_id(link)).body
end
def vdc(name)
link = org[:Link].select { |l| l[:rel] == RELATION::CHILD }.detect do |l|
l[:type] == ContentTypes::VDC && l[:name] == name
end
@vcloud.get_vdc(link[:href].split('/').last).body
end
def template(catalog_name, template_name)
link = catalog(catalog_name)[:CatalogItems][:CatalogItem].detect do |l|
l[:type] == ContentTypes::CATALOG_ITEM && l[:name].match(template_name)
end
if link.nil?
Vcloud.logger.warn("Template #{template_name} not found in catalog #{catalog_name}")
return nil
end
catalog_item = @vcloud.get_catalog_item(extract_id(link)).body
catalog_item[:Entity]
end
def session
@vcloud.get_current_session.body
end
def post_instantiate_vapp_template(vdc, template, name, params)
Vcloud.logger.info("instantiating #{name} vapp in #{vdc[:name]}")
vapp = @vcloud.post_instantiate_vapp_template(extract_id(vdc), template, name, params).body
@vcloud.process_task(vapp[:Tasks][:Task])
@vcloud.get_vapp(extract_id(vapp)).body
end
def put_memory(vm_id, memory)
Vcloud.logger.info("putting #{memory}MB memory into VM #{vm_id}")
task = @vcloud.put_memory(vm_id, memory).body
@vcloud.process_task(task)
end
def get_vapp(id)
@vcloud.get_vapp(id).body
end
def put_cpu(vm_id, cpu)
Vcloud.logger.info("putting #{cpu} CPU(s) into VM #{vm_id}")
task = @vcloud.put_cpu(vm_id, cpu).body
@vcloud.process_task(task)
end
def put_network_connection_system_section_vapp(vm_id, section)
begin
Vcloud.logger.info("adding NIC into VM #{vm_id}")
task = @vcloud.put_network_connection_system_section_vapp(vm_id, section).body
@vcloud.process_task(task)
rescue
Vcloud.logger.info("failed to put_network_connection_system_section_vapp for vm : #{vm_id} ")
Vcloud.logger.info("requested network section : #{section.inspect}")
raise
end
end
def organizations
@vcloud.organizations
end
def org_name
@vcloud.org_name
end
def delete_vapp(vapp_id)
task = @vcloud.delete_vapp(vapp_id).body
@vcloud.process_task(task)
end
def power_off_vapp(vapp_id)
task = @vcloud.post_power_off_vapp(vapp_id).body
@vcloud.process_task(task)
end
def power_on_vapp(vapp_id)
Vcloud.logger.info("Powering on vApp #{vapp_id}")
task = @vcloud.post_power_on_vapp(vapp_id).body
@vcloud.process_task(task)
end
def shutdown_vapp(vapp_id)
task = @vcloud.post_shutdown_vapp(vapp_id).body
@vcloud.process_task(task)
end
def find_networks(network_names, vdc_name)
network_names.collect do |network|
vdc(vdc_name)[:AvailableNetworks][:Network].detect do |l|
l[:type] == ContentTypes::NETWORK && l[:name] == network
end
end
end
def get_execute_query(type=nil, options={})
@vcloud.get_execute_query(type, options).body
end
def get_vapp_metadata(id)
@vcloud.get_vapp_metadata(id).body
end
def get_vapp_metadata_by_key(id, key)
@vcloud.get_vapp_metadata_item_metadata(id, key.to_s)
end
def put_vapp_metadata_value(id, k, v)
Vcloud.logger.info("putting metadata pair '#{k}'=>'#{v}' to #{id}")
# need to convert key to_s since Fog 0.17 borks on symbol key
task = @vcloud.put_vapp_metadata_item_metadata(id, k.to_s, v).body
@vcloud.process_task(task)
end
def put_guest_customization_section(vm_id, vm_name, script)
begin
Vcloud.logger.info("configuring guest customization section for vm : #{vm_id}")
customization_req = {
:Enabled => true,
:CustomizationScript => script,
:ComputerName => vm_name
}
task = @vcloud.put_guest_customization_section_vapp(vm_id, customization_req).body
@vcloud.process_task(task)
rescue
Vcloud.logger.info("=== interpolated preamble:")
Vcloud.logger.info(script)
raise
end
end
def put_vm id, name, options
Vcloud.logger.info("updating name : #{name}, :options => #{options} in vm : #{id}")
task = @vcloud.put_vm(id, name, options).body
@vcloud.process_task(task)
end
def vcloud_token
@vcloud.vcloud_token
end
def end_point
@vcloud.end_point
end
private
def extract_id(link)
link[:href].split('/').last
end
end
end
end
fix put_vm to allow just name to be specified
module Vcloud
module Fog
class ServiceInterface
def initialize
@vcloud = ::Fog::Compute::VcloudDirector.new
end
def org
link = session[:Link].select { |l| l[:rel] == RELATION::CHILD }.detect do |l|
l[:type] == ContentTypes::ORG
end
@vcloud.get_organization(link[:href].split('/').last).body
end
def get_vapp_by_name_and_vdc_name name, vdc_name
response = @vcloud.get_vapps_in_lease_from_query({:filter => "name==#{name}"})
response.body[:VAppRecord].detect { |record| record[:vdcName] == vdc_name }
end
def catalog(name)
link = org[:Link].select { |l| l[:rel] == RELATION::CHILD }.detect do |l|
l[:type] == ContentTypes::CATALOG && l[:name] == name
end
@vcloud.get_catalog(extract_id(link)).body
end
def vdc(name)
link = org[:Link].select { |l| l[:rel] == RELATION::CHILD }.detect do |l|
l[:type] == ContentTypes::VDC && l[:name] == name
end
@vcloud.get_vdc(link[:href].split('/').last).body
end
def template(catalog_name, template_name)
link = catalog(catalog_name)[:CatalogItems][:CatalogItem].detect do |l|
l[:type] == ContentTypes::CATALOG_ITEM && l[:name].match(template_name)
end
if link.nil?
Vcloud.logger.warn("Template #{template_name} not found in catalog #{catalog_name}")
return nil
end
catalog_item = @vcloud.get_catalog_item(extract_id(link)).body
catalog_item[:Entity]
end
def session
@vcloud.get_current_session.body
end
def post_instantiate_vapp_template(vdc, template, name, params)
Vcloud.logger.info("instantiating #{name} vapp in #{vdc[:name]}")
vapp = @vcloud.post_instantiate_vapp_template(extract_id(vdc), template, name, params).body
@vcloud.process_task(vapp[:Tasks][:Task])
@vcloud.get_vapp(extract_id(vapp)).body
end
def put_memory(vm_id, memory)
Vcloud.logger.info("putting #{memory}MB memory into VM #{vm_id}")
task = @vcloud.put_memory(vm_id, memory).body
@vcloud.process_task(task)
end
def get_vapp(id)
@vcloud.get_vapp(id).body
end
def put_cpu(vm_id, cpu)
Vcloud.logger.info("putting #{cpu} CPU(s) into VM #{vm_id}")
task = @vcloud.put_cpu(vm_id, cpu).body
@vcloud.process_task(task)
end
def put_network_connection_system_section_vapp(vm_id, section)
begin
Vcloud.logger.info("adding NIC into VM #{vm_id}")
task = @vcloud.put_network_connection_system_section_vapp(vm_id, section).body
@vcloud.process_task(task)
rescue
Vcloud.logger.info("failed to put_network_connection_system_section_vapp for vm : #{vm_id} ")
Vcloud.logger.info("requested network section : #{section.inspect}")
raise
end
end
def organizations
@vcloud.organizations
end
def org_name
@vcloud.org_name
end
def delete_vapp(vapp_id)
task = @vcloud.delete_vapp(vapp_id).body
@vcloud.process_task(task)
end
def power_off_vapp(vapp_id)
task = @vcloud.post_power_off_vapp(vapp_id).body
@vcloud.process_task(task)
end
def power_on_vapp(vapp_id)
Vcloud.logger.info("Powering on vApp #{vapp_id}")
task = @vcloud.post_power_on_vapp(vapp_id).body
@vcloud.process_task(task)
end
def shutdown_vapp(vapp_id)
task = @vcloud.post_shutdown_vapp(vapp_id).body
@vcloud.process_task(task)
end
def find_networks(network_names, vdc_name)
network_names.collect do |network|
vdc(vdc_name)[:AvailableNetworks][:Network].detect do |l|
l[:type] == ContentTypes::NETWORK && l[:name] == network
end
end
end
def get_execute_query(type=nil, options={})
@vcloud.get_execute_query(type, options).body
end
def get_vapp_metadata(id)
@vcloud.get_vapp_metadata(id).body
end
def get_vapp_metadata_by_key(id, key)
@vcloud.get_vapp_metadata_item_metadata(id, key.to_s)
end
def put_vapp_metadata_value(id, k, v)
Vcloud.logger.info("putting metadata pair '#{k}'=>'#{v}' to #{id}")
# need to convert key to_s since Fog 0.17 borks on symbol key
task = @vcloud.put_vapp_metadata_item_metadata(id, k.to_s, v).body
@vcloud.process_task(task)
end
def put_guest_customization_section(vm_id, vm_name, script)
begin
Vcloud.logger.info("configuring guest customization section for vm : #{vm_id}")
customization_req = {
:Enabled => true,
:CustomizationScript => script,
:ComputerName => vm_name
}
task = @vcloud.put_guest_customization_section_vapp(vm_id, customization_req).body
@vcloud.process_task(task)
rescue
Vcloud.logger.info("=== interpolated preamble:")
Vcloud.logger.info(script)
raise
end
end
def put_vm(id, name, options={})
Vcloud.logger.info("updating name : #{name}, :options => #{options} in vm : #{id}")
task = @vcloud.put_vm(id, name, options).body
@vcloud.process_task(task)
end
def vcloud_token
@vcloud.vcloud_token
end
def end_point
@vcloud.end_point
end
private
def extract_id(link)
link[:href].split('/').last
end
end
end
end
|
require 'vin/helpers/helper_methods'
class SubsciberAction
include Helpers
def add_sub (subscribers, sub)
errors = Validator.validate_sub(sub)
if (errors.length == 0)
new_sub = Subscriber.new sub.name, sub.email, sub.address, sub.phone, sub.facebook, sub.twitter
subscribers << new_sub
id = new_sub.id
else
id = ""
end
{ 'id' => id, 'errors' => errors }
end
def edit_sub (subscribers, id, sub)
found_it = false
errors = []
subscribers.each do |subscriber|
if subscriber.id == id
found_it = true
errors = Validator.validate_sub(sub)
if errors.length == 0
subscriber.name = sub.name
subscriber.email = sub.email
subscriber.address = sub.address
subscriber.phone = sub.phone
subscriber.facebook = sub.facebook
subscriber.twitter = sub.twitter
break;
end
end
end
if !found_it
errors = [(Error.new 8, "Could not locate the subscriber with the given id")]
end
{'errors' => errors}
end
def get_sub(subscribers, id)
subscribers.each do |sub|
if sub.id == id
return sub.to_h
end
end
{'errors' => [(Error.new 8, 'Could not locate the subscriber with the given id')]}
end
def get_sub_shipments(subscribers, sub_id)
shipments = []
found_it = false
subscribers.each do |sub|
if (sub.id == sub_id)
found_it = true
sub.shipments.each do |ship|
shipments << {'id' => ship.id, 'selection_month'=> ship.month.to_s + '/' + ship.year, 'status' => ship.status.to_s}
end
break
end
end
return nil unless found_it
{'shipments' => shipments }
end
def get_sub_shipment( subscribers, sub_id, ship_id)
shipment = nil
subscribers.each do |sub|
if (sub.id == sub_id)
sub.shipments.each do |ship|
if (ship.id == ship_id)
shipment = ship
break
end
end
end
end
shipment ? shipment.to_h : nil
end
def update_sub_ship(subscribers, sub_id, ship_id, ship_new_info)
found_it = false
sub = find_object_by_id(subscribers, sub_id)
if (sub)
ship = find_object_by_id(sub.shipments, ship_id)
if (ship)
ship.monthly_selection.day_of_week = ship_new_info.day_of_week
ship.monthly_selection.time_of_day = ship_new_info.time_of_day
ship.monthly_selection.selection_type = ship_new_info.selection_type
found_it = true
end
end
found_it ? {} : {'errors' => [(Error.new 9, "One of the resources does not exist")]}
end
def get_ship_notes(subscribers, sub_id, ship_id)
ship = nil
sub = find_object_by_id subscribers, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
end
ship ? {'notes' => ship.notes.map { |e| e.to_h }} : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def add_note_to_ship(subscribers, sub_id, ship_id, content)
ship = nil
sub = find_object_by_id subscribers, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
end
if ship
note = Note.new content
ship.add_note note
end
note ? {'id' => note.id} : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def get_note(subscribers, sub_id, ship_id, note_id)
note = nil
sub = find_object_by_id subscribers, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
if ship
note = find_object_by_id ship.notes, note_id
end
end
note ? note.to_h : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def update_note(subs, sub_id, ship_id, note_id, content)
note = nil
sub = find_object_by_id subs, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
if ship
note = find_object_by_id ship.notes, note_id
end
end
if note
note.content = content
return {}
end
{'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def delete_note(subs, sub_id, ship_id, note_id)
found_it = false
sub = find_object_by_id subs, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
if ship
found_it = ship.delete_note note_id
end
end
found_it ? {} : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def get_wines_shipped_to_sub(subs, sub_id)
wines = []
ids = Set.new
sub = find_object_by_id subs, sub_id
if sub
sub.shipments.each do |ship|
ship.wines.each do |wine|
if !ids.include? wine.id
wines << wine
ids.add wine.id
end
end
end
end
wines
end
def get_wine_shipped_to_sub(subs, sub_id, wine_id)
my_wine = nil
found_it = false
sub = find_object_by_id subs, sub_id
if sub
sub.shipments.each do |ship|
ship.wines.each do |wine|
if wine.id == wine_id
my_wine = wine
found_it = true
break
end
end
break unless !found_it
end
end
my_wine
end
def get_wine_notes(subs, sub_id, wine_id)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
wine.notes unless wine
end
def add_note_to_wine(subs, sub_id, wine_id, content)
notes = get_wine_notes subs, sub_id, wine_id
if notes
note = Note.new content
notes << note
end
notes ? true : false
end
def get_wine_note(subs, sub_id, wine_id, note_id)
note = nil
notes = get_wine_notes subs, sub_id, wine_id
if notes
note = find_object_by_id notes, note_id
end
note
end
def edit_wine_note (subs, sub_id, wine_id, note_id, content)
note = get_wine_note subs, sub_id, wine_id, note_id
if note
note.content = content
end
note ? true : false
end
def delete_wine_note(subs, sub_id, wine_id, note_id)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
if wine
wine.delete_note note_id
end
end
def get_wine_rating(subs, sub_id, wine_id)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
if wine
wine.rating
end
end
def add_wine_rating(subs, sub_id, wine_id, rating)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
if wine
wine.add_rating rating
end
end
def get_monthly_selection(subs, sub_id)
sub = find_object_by_id subs, sub_id
if sub
sub.monthly_selection
end
end
def update_monthly_selection(subs, sub_id, monthly_selection)
sub = find_object_by_id subs, sub_id
if sub
sub.monthly_selection.day_of_week = monthly_selection.day_of_week
sub.monthly_selection.time_of_day = monthly_selection.time_of_day
true
end
end
end
add get_wine method
require 'vin/helpers/helper_methods'
class SubsciberAction
include Helpers
def add_sub (subscribers, sub)
errors = Validator.validate_sub(sub)
if (errors.length == 0)
new_sub = Subscriber.new sub.name, sub.email, sub.address, sub.phone, sub.facebook, sub.twitter
subscribers << new_sub
id = new_sub.id
else
id = ""
end
{ 'id' => id, 'errors' => errors }
end
def edit_sub (subscribers, id, sub)
found_it = false
errors = []
subscribers.each do |subscriber|
if subscriber.id == id
found_it = true
errors = Validator.validate_sub(sub)
if errors.length == 0
subscriber.name = sub.name
subscriber.email = sub.email
subscriber.address = sub.address
subscriber.phone = sub.phone
subscriber.facebook = sub.facebook
subscriber.twitter = sub.twitter
break;
end
end
end
if !found_it
errors = [(Error.new 8, "Could not locate the subscriber with the given id")]
end
{'errors' => errors}
end
def get_sub(subscribers, id)
subscribers.each do |sub|
if sub.id == id
return sub.to_h
end
end
{'errors' => [(Error.new 8, 'Could not locate the subscriber with the given id')]}
end
def get_sub_shipments(subscribers, sub_id)
shipments = []
found_it = false
subscribers.each do |sub|
if (sub.id == sub_id)
found_it = true
sub.shipments.each do |ship|
shipments << {'id' => ship.id, 'selection_month'=> ship.month.to_s + '/' + ship.year, 'status' => ship.status.to_s}
end
break
end
end
return nil unless found_it
{'shipments' => shipments }
end
def get_sub_shipment( subscribers, sub_id, ship_id)
shipment = nil
subscribers.each do |sub|
if (sub.id == sub_id)
sub.shipments.each do |ship|
if (ship.id == ship_id)
shipment = ship
break
end
end
end
end
shipment ? shipment.to_h : nil
end
def update_sub_ship(subscribers, sub_id, ship_id, ship_new_info)
found_it = false
sub = find_object_by_id(subscribers, sub_id)
if (sub)
ship = find_object_by_id(sub.shipments, ship_id)
if (ship)
ship.monthly_selection.day_of_week = ship_new_info.day_of_week
ship.monthly_selection.time_of_day = ship_new_info.time_of_day
ship.monthly_selection.selection_type = ship_new_info.selection_type
found_it = true
end
end
found_it ? {} : {'errors' => [(Error.new 9, "One of the resources does not exist")]}
end
def get_ship_notes(subscribers, sub_id, ship_id)
ship = nil
sub = find_object_by_id subscribers, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
end
ship ? {'notes' => ship.notes.map { |e| e.to_h }} : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def add_note_to_ship(subscribers, sub_id, ship_id, content)
ship = nil
sub = find_object_by_id subscribers, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
end
if ship
note = Note.new content
ship.add_note note
end
note ? {'id' => note.id} : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def get_note(subscribers, sub_id, ship_id, note_id)
note = nil
sub = find_object_by_id subscribers, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
if ship
note = find_object_by_id ship.notes, note_id
end
end
note ? note.to_h : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def update_note(subs, sub_id, ship_id, note_id, content)
note = nil
sub = find_object_by_id subs, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
if ship
note = find_object_by_id ship.notes, note_id
end
end
if note
note.content = content
return {}
end
{'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def delete_note(subs, sub_id, ship_id, note_id)
found_it = false
sub = find_object_by_id subs, sub_id
if sub
ship = find_object_by_id sub.shipments, ship_id
if ship
found_it = ship.delete_note note_id
end
end
found_it ? {} : {'errors' => [(Error.new 9, "One of the resources does not exists")]}
end
def get_wines_shipped_to_sub(subs, sub_id)
wines = []
ids = Set.new
sub = find_object_by_id subs, sub_id
if sub
sub.shipments.each do |ship|
ship.wines.each do |wine|
if !ids.include? wine.id
wines << wine
ids.add wine.id
end
end
end
end
wines
end
def get_wine_shipped_to_sub(subs, sub_id, wine_id)
my_wine = nil
found_it = false
sub = find_object_by_id subs, sub_id
if sub
sub.shipments.each do |ship|
ship.wines.each do |wine|
if wine.id == wine_id
my_wine = wine
found_it = true
break
end
end
break unless !found_it
end
end
my_wine
end
def get_wine_notes(subs, sub_id, wine_id)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
wine.notes unless wine
end
def add_note_to_wine(subs, sub_id, wine_id, content)
notes = get_wine_notes subs, sub_id, wine_id
if notes
note = Note.new content
notes << note
end
notes ? true : false
end
def get_wine_note(subs, sub_id, wine_id, note_id)
note = nil
notes = get_wine_notes subs, sub_id, wine_id
if notes
note = find_object_by_id notes, note_id
end
note
end
def edit_wine_note (subs, sub_id, wine_id, note_id, content)
note = get_wine_note subs, sub_id, wine_id, note_id
if note
note.content = content
end
note ? true : false
end
def delete_wine_note(subs, sub_id, wine_id, note_id)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
if wine
wine.delete_note note_id
end
end
def get_wine_rating(subs, sub_id, wine_id)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
if wine
wine.rating
end
end
def add_wine_rating(subs, sub_id, wine_id, rating)
wine = get_wine_shipped_to_sub subs, sub_id, wine_id
if wine
wine.add_rating rating
end
end
def get_monthly_selection(subs, sub_id)
sub = find_object_by_id subs, sub_id
if sub
sub.monthly_selection
end
end
def update_monthly_selection(subs, sub_id, monthly_selection)
sub = find_object_by_id subs, sub_id
if sub
sub.monthly_selection.day_of_week = monthly_selection.day_of_week
sub.monthly_selection.time_of_day = monthly_selection.time_of_day
true
end
end
def get_wine(wines, wine_id)
find_object_by_id wines, wine_id
end
end
|
require_relative "block"
module Virtual
# the static info of a method (with its compiled code, argument names etc ) is part of the
# runtime, ie found in Parfait::Method
# the info we create here is injected int the method and used only at compile-time
# receiver
# return arg (usually mystery, but for coded ones can be more specific)
#
# Methods are one step up from to VM::Blocks. Where Blocks can be jumped to, Methods can be called.
# Methods also have arguments and a return. These are typed by subclass instances of Value
# They also have local variables.
# Code-wise Methods are made up from a list of Blocks, in a similar way blocks are made up of
# Instructions. The function starts with one block, and that has a start and end (return)
# Blocks can be linked in two ways:
# -linear: flow continues from one to the next as they are sequential both logically and
# "physically" use the block set_next for this.
# This "straight line", there must be a continuous sequence from body to return
# Linear blocks may be created from an existing block with new_block
# - branched: You create new blocks using function.new_block which gets added "after" return
# These (eg if/while) blocks may themselves have linear blocks ,but the last of these
# MUST have an uncoditional branch. And remember, all roads lead to return.
class CompiledMethodInfo
# create method does two things
# first it creates the parfait method, for the given class, with given argument names
# second, it creates CompiledMethodInfo and attaches it to the method
#
# compile code then works with the method, but adds code tot the info
def self.create_method( class_name , method_name , args)
raise "uups #{class_name}.#{class_name.class}" unless class_name.is_a? Symbol
raise "uups #{method_name}.#{method_name.class}" unless method_name.is_a? Symbol
clazz = Virtual.machine.space.get_class_by_name class_name
raise "No such class #{class_name}" unless clazz
method = clazz.create_instance_method( method_name , Virtual.new_list(args))
method.info = CompiledMethodInfo.new
method
end
def initialize return_type = Virtual::Unknown
# first block we have to create with .new , as new_block assumes a current
enter = Block.new( "enter" , self ).add_code(MethodEnter.new())
@return_type = return_type
@blocks = [enter]
@current = enter
new_block("return").add_code(MethodReturn.new)
@constants = []
end
attr_reader :blocks , :constants
attr_accessor :return_type , :current , :receiver
# add an instruction after the current (insertion point)
# the added instruction will become the new insertion point
def add_code instruction
unless (instruction.is_a?(Instruction) or instruction.is_a?(Register::Instruction))
raise instruction.inspect
end
@current.add_code(instruction) #insert after current
self
end
# return a list of registers that are still in use after the given block
# a call_site uses pushes and pops these to make them available for code after a call
def locals_at l_block
used =[]
# call assigns the return register, but as it is in l_block, it is not asked.
assigned = [ RegisterReference.new(Virtual::RegisterMachine.instance.return_register) ]
l_block.reachable.each do |b|
b.uses.each {|u|
(used << u) unless assigned.include?(u)
}
assigned += b.assigns
end
used.uniq
end
# control structures need to see blocks as a graph, but they are stored as a list with implict
# branches
# So when creating a new block (with new_block), it is only added to the list, but instructions
# still go to the current one
# With this function one can change the current block, to actually code it.
# This juggling is (unfortunately) neccessary, as all compile functions just keep puring their
# code into the method and don't care what other compiles (like if's) do.
# Example: while, needs 2 extra blocks
# 1 condition code, must be its own blockas we jump back to it
# - the body, can actually be after the condition as we don't need to jump there
# 2 after while block. Condition jumps here
# After block 2, the function is linear again and the calling code does not need to know what
# happened
# But subsequent statements are still using the original block (self) to add code to
# So the while expression creates the extra blocks, adds them and the code and then "moves"
# the insertion point along
def current block
@current = block
self
end
# create a new linear block after the current insertion block.
# Linear means there is no brach needed from that one to the new one.
# Usually the new one just serves as jump address for a control statement
# In code generation , the new_block is written after this one, ie zero runtime cost
# This does _not_ change the insertion point, that has do be done with insert_at(block)
def new_block new_name
new_b = Block.new( new_name , self )
index = @blocks.index( @current )
@blocks.insert( index + 1 , new_b ) # + one because we want the ne after the insert_at
return new_b
end
def get_tmp
name = "__tmp__#{@tmps.length}"
@tmps << name
Ast::NameExpression.new(name)
end
# sugar to create instructions easily.
# any method will be passed on to the RegisterMachine and the result added to the insertion block
# With this trick we can write what looks like assembler,
# Example func.instance_eval
# mov( r1 , r2 )
# add( r1 , r2 , 4)
# end
# mov and add will be called on Machine and generate Instructions that are then added
# to the current block
# also symbols are supported and wrapped as register usages (for bare metal programming)
def method_missing(meth, *arg_names, &block)
add_code ::Arm::ArmMachine.send(meth , *arg_names)
end
def byte_length
@blocks.inject(0) { |c , block| c += block.byte_length }
end
# position of the function is the position of the entry block, is where we call
def set_position at
at += 8 #for the 2 header words
@blocks.each do |block|
block.set_position at
at = at + block.byte_length
end
end
end
end
allowing for relinking to add more instructions
require_relative "block"
module Virtual
# the static info of a method (with its compiled code, argument names etc ) is part of the
# runtime, ie found in Parfait::Method
# the info we create here is injected int the method and used only at compile-time
# receiver
# return arg (usually mystery, but for coded ones can be more specific)
#
# Methods are one step up from to VM::Blocks. Where Blocks can be jumped to, Methods can be called.
# Methods also have arguments and a return. These are typed by subclass instances of Value
# They also have local variables.
# Code-wise Methods are made up from a list of Blocks, in a similar way blocks are made up of
# Instructions. The function starts with one block, and that has a start and end (return)
# Blocks can be linked in two ways:
# -linear: flow continues from one to the next as they are sequential both logically and
# "physically" use the block set_next for this.
# This "straight line", there must be a continuous sequence from body to return
# Linear blocks may be created from an existing block with new_block
# - branched: You create new blocks using function.new_block which gets added "after" return
# These (eg if/while) blocks may themselves have linear blocks ,but the last of these
# MUST have an uncoditional branch. And remember, all roads lead to return.
class CompiledMethodInfo
# create method does two things
# first it creates the parfait method, for the given class, with given argument names
# second, it creates CompiledMethodInfo and attaches it to the method
#
# compile code then works with the method, but adds code tot the info
def self.create_method( class_name , method_name , args)
raise "uups #{class_name}.#{class_name.class}" unless class_name.is_a? Symbol
raise "uups #{method_name}.#{method_name.class}" unless method_name.is_a? Symbol
clazz = Virtual.machine.space.get_class_by_name class_name
raise "No such class #{class_name}" unless clazz
method = clazz.create_instance_method( method_name , Virtual.new_list(args))
method.info = CompiledMethodInfo.new
method
end
def initialize return_type = Virtual::Unknown
# first block we have to create with .new , as new_block assumes a current
enter = Block.new( "enter" , self ).add_code(MethodEnter.new())
@return_type = return_type
@blocks = [enter]
@current = enter
new_block("return").add_code(MethodReturn.new)
@constants = []
end
attr_reader :blocks , :constants
attr_accessor :return_type , :current , :receiver
# add an instruction after the current (insertion point)
# the added instruction will become the new insertion point
def add_code instruction
unless (instruction.is_a?(Instruction) or instruction.is_a?(Register::Instruction))
raise instruction.inspect
end
@current.add_code(instruction) #insert after current
self
end
# return a list of registers that are still in use after the given block
# a call_site uses pushes and pops these to make them available for code after a call
def locals_at l_block
used =[]
# call assigns the return register, but as it is in l_block, it is not asked.
assigned = [ RegisterReference.new(Virtual::RegisterMachine.instance.return_register) ]
l_block.reachable.each do |b|
b.uses.each {|u|
(used << u) unless assigned.include?(u)
}
assigned += b.assigns
end
used.uniq
end
# control structures need to see blocks as a graph, but they are stored as a list with implict
# branches
# So when creating a new block (with new_block), it is only added to the list, but instructions
# still go to the current one
# With this function one can change the current block, to actually code it.
# This juggling is (unfortunately) neccessary, as all compile functions just keep puring their
# code into the method and don't care what other compiles (like if's) do.
# Example: while, needs 2 extra blocks
# 1 condition code, must be its own blockas we jump back to it
# - the body, can actually be after the condition as we don't need to jump there
# 2 after while block. Condition jumps here
# After block 2, the function is linear again and the calling code does not need to know what
# happened
# But subsequent statements are still using the original block (self) to add code to
# So the while expression creates the extra blocks, adds them and the code and then "moves"
# the insertion point along
def current block
@current = block
self
end
# create a new linear block after the current insertion block.
# Linear means there is no brach needed from that one to the new one.
# Usually the new one just serves as jump address for a control statement
# In code generation , the new_block is written after this one, ie zero runtime cost
# This does _not_ change the insertion point, that has do be done with insert_at(block)
def new_block new_name
new_b = Block.new( new_name , self )
index = @blocks.index( @current )
@blocks.insert( index + 1 , new_b ) # + one because we want the ne after the insert_at
return new_b
end
def get_tmp
name = "__tmp__#{@tmps.length}"
@tmps << name
Ast::NameExpression.new(name)
end
# sugar to create instructions easily.
# any method will be passed on to the RegisterMachine and the result added to the insertion block
# With this trick we can write what looks like assembler,
# Example func.instance_eval
# mov( r1 , r2 )
# add( r1 , r2 , 4)
# end
# mov and add will be called on Machine and generate Instructions that are then added
# to the current block
# also symbols are supported and wrapped as register usages (for bare metal programming)
def method_missing(meth, *arg_names, &block)
add_code ::Arm::ArmMachine.send(meth , *arg_names)
end
def byte_length
@blocks.inject(0) { |c , block| c += block.byte_length } + 8
end
# position of the function is the position of the entry block, is where we call
def set_position at
at += 8 #for the 2 header words
@blocks.each do |block|
block.set_position at
at = at + block.byte_length
end
end
end
end
|
#
# Cookbook Name:: paramount
# Recipe:: _web
#
# Copyright (C) 2015 Michael Burns
# License:: Apache License, Version 2.0
#
include_recipe 'paramount::default'
include_recipe 'chef_nginx'
# service 'nginx' do
# action %i(enable start)
# end
openssl_x509 "/etc/httpd/ssl/#{node['paramount']['domain']}.pem" do
common_name node['paramount']['domain']
org node['paramount']['organization']
org_unit node['paramount']['organization_unit']
country 'US'
end
include_recipe 'paramount::wallabag'
remove duplicate code, this is handled by ::_security
#
# Cookbook Name:: paramount
# Recipe:: _web
#
# Copyright (C) 2015 Michael Burns
# License:: Apache License, Version 2.0
#
include_recipe 'paramount::default'
include_recipe 'chef_nginx'
include_recipe 'paramount::wallabag'
|
#
# Cookbook Name:: cdap
# Recipe:: init
#
# Copyright © 2013-2016 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We also need the configuration, so we can run HDFS commands
# Retries allow for orchestration scenarios where HDFS is starting up
ns_path = node['cdap']['cdap_site']['hdfs.namespace']
hdfs_user = node['cdap']['cdap_site']['hdfs.user']
# Workaround for CDAP-3817, by pre-creating the transaction service snapshot directory
tx_snapshot_dir =
if node['cdap']['cdap_site'].key?('data.tx.snapshot.dir')
node['cdap']['cdap_site']['data.tx.snapshot.dir']
else
"#{ns_path}/tx.snapshot"
end
user_path = "/user/#{hdfs_user}"
%W(#{ns_path} #{tx_snapshot_dir} #{user_path}).each do |path|
execute "initaction-create-hdfs-path#{path.tr('/', '-')}" do
command "hadoop fs -mkdir -p #{path} && hadoop fs -chown #{hdfs_user} #{path}"
not_if "hadoop fs -test -d #{path}", :user => hdfs_user
timeout 300
user node['cdap']['fs_superuser']
retries 3
retry_delay 10
end
end
%w(cdap yarn mapr).each do |u|
%w(done done_intermediate).each do |dir|
execute "initaction-create-hdfs-mr-jhs-staging-#{dir.tr('_', '-')}-#{u}" do
only_if "getent passwd #{u}"
not_if "hadoop fs -test -d /tmp/hadoop-yarn/staging/history/#{dir}/#{u}", :user => u
command "hadoop fs -mkdir -p /tmp/hadoop-yarn/staging/history/#{dir}/#{u} && hadoop fs -chown #{u} /tmp/hadoop-yarn/staging/history/#{dir}/#{u} && hadoop fs -chmod 770 /tmp/hadoop-yarn/staging/history/#{dir}/#{u}"
timeout 300
user node['cdap']['fs_superuser']
retries 3
retry_delay 10
end
end
end
include_recipe 'krb5' if hadoop_kerberos?
princ =
if node['cdap']['cdap_site'].key?('cdap.master.kerberos.principal')
node['cdap']['cdap_site']['cdap.master.kerberos.principal']
else
"#{hdfs_user}/_HOST"
end
# Set principal with _HOST in config, so configs match across cluster
node.default['cdap']['cdap_site']['cdap.master.kerberos.principal'] = princ
# Substitite _HOST with FQDN, for creating actual principals
princ.gsub!('_HOST', node['fqdn'])
krb5_principal princ do
randkey true
action :create
only_if { hadoop_kerberos? }
end
keytab =
if node['cdap']['cdap_site'].key?('cdap.master.kerberos.keytab')
node['cdap']['cdap_site']['cdap.master.kerberos.keytab']
else
"#{node['krb5']['keytabs_dir']}/cdap.service.keytab"
end
node.default['cdap']['cdap_site']['cdap.master.kerberos.keytab'] = keytab
krb5_keytab keytab do
principals [princ]
owner 'cdap'
group 'cdap'
mode '0640'
action :create
only_if { hadoop_kerberos? }
end
Install rkerberos gem during init
#
# Cookbook Name:: cdap
# Recipe:: init
#
# Copyright © 2013-2017 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We also need the configuration, so we can run HDFS commands
# Retries allow for orchestration scenarios where HDFS is starting up
ns_path = node['cdap']['cdap_site']['hdfs.namespace']
hdfs_user = node['cdap']['cdap_site']['hdfs.user']
# Workaround for CDAP-3817, by pre-creating the transaction service snapshot directory
tx_snapshot_dir =
if node['cdap']['cdap_site'].key?('data.tx.snapshot.dir')
node['cdap']['cdap_site']['data.tx.snapshot.dir']
else
"#{ns_path}/tx.snapshot"
end
user_path = "/user/#{hdfs_user}"
%W(#{ns_path} #{tx_snapshot_dir} #{user_path}).each do |path|
execute "initaction-create-hdfs-path#{path.tr('/', '-')}" do
command "hadoop fs -mkdir -p #{path} && hadoop fs -chown #{hdfs_user} #{path}"
not_if "hadoop fs -test -d #{path}", :user => hdfs_user
timeout 300
user node['cdap']['fs_superuser']
retries 3
retry_delay 10
end
end
%w(cdap yarn mapr).each do |u|
%w(done done_intermediate).each do |dir|
execute "initaction-create-hdfs-mr-jhs-staging-#{dir.tr('_', '-')}-#{u}" do
only_if "getent passwd #{u}"
not_if "hadoop fs -test -d /tmp/hadoop-yarn/staging/history/#{dir}/#{u}", :user => u
command "hadoop fs -mkdir -p /tmp/hadoop-yarn/staging/history/#{dir}/#{u} && hadoop fs -chown #{u} /tmp/hadoop-yarn/staging/history/#{dir}/#{u} && hadoop fs -chmod 770 /tmp/hadoop-yarn/staging/history/#{dir}/#{u}"
timeout 300
user node['cdap']['fs_superuser']
retries 3
retry_delay 10
end
end
end
if hadoop_kerberos?
include_recipe 'krb5'
include_recipe 'krb5::rkerberos_gem'
end
princ =
if node['cdap']['cdap_site'].key?('cdap.master.kerberos.principal')
node['cdap']['cdap_site']['cdap.master.kerberos.principal']
else
"#{hdfs_user}/_HOST"
end
# Set principal with _HOST in config, so configs match across cluster
node.default['cdap']['cdap_site']['cdap.master.kerberos.principal'] = princ
# Substitite _HOST with FQDN, for creating actual principals
princ.gsub!('_HOST', node['fqdn'])
krb5_principal princ do
randkey true
action :create
only_if { hadoop_kerberos? }
end
keytab =
if node['cdap']['cdap_site'].key?('cdap.master.kerberos.keytab')
node['cdap']['cdap_site']['cdap.master.kerberos.keytab']
else
"#{node['krb5']['keytabs_dir']}/cdap.service.keytab"
end
node.default['cdap']['cdap_site']['cdap.master.kerberos.keytab'] = keytab
krb5_keytab keytab do
principals [princ]
owner 'cdap'
group 'cdap'
mode '0640'
action :create
only_if { hadoop_kerberos? }
end
|
=begin
The internals of a recipe are up to you, but a recipe should do at least the
following:
First, require 'kindlefodder' and subclass Kindlefodder.
Second, contain a #get_source_files method that does two things:
1. Save a sections.yml to the path returned by the superclass's #output_dir
method with the following format:
---
- :title: Getting Started
:articles:
- :title: Getting Started with Heroku
:path: articles/quickstart
- :title: Platform Basics
:articles:
- :title: Architecture Overview
:path: articles/architecture-overview
- :title: Dyno Isolation
:path: articles/dyno-isolation
[etc.]
2. Save HTML fragments of the article content at the path values (relative to
#output_dir) indicated in the sections.yml above
The recipe class should also contain a #document method that returns a metadata
hash as shown below. The masthead and cover values seem optional. But if you fill
them in, use paths relative to output_dir.
=end
require 'kindlefodder'
class Node < Kindlefodder
# These next two methods must be implemented.
def get_source_files
@node_version = ARGV[0] ? "v#{ARGV[0]}" : "latest"
# The start_url is any webpage that will contain the navigation structure
# of the documentaion
@start_url = "http://nodejs.org/docs/#{@node_version}/api/"
# @start_doc = Nokogiri::HTML run_shell_command("curl -s #{@start_url}")
File.open("#{output_dir}/sections.yml", 'w') {|f|
# extract_sections() is defined below. It gets the sections of the ebook
# out of the webpage docs navigation sidebar.
f.puts extract_sections.to_yaml
}
end
# This method is for the ebook metadata.
def document
{
# 'title' => 'Node.js v#{node_version} Manual & Documentation',
'title' => 'Node.js Manual & Documentation',
'cover' => nil,
'masthead' => nil,
}
end
# The methods below are not required methods. They are this recipe's
# implementation for generating the required sections.yml and article
# fragment files.
# This method extracts the sections from the html sidebar at start_url
# This method returns an Array of elements with the Hash structure you
# see at the end.
def extract_sections
articles_list = run_shell_command "curl -s #{@start_url}"
[{
title: "Main",
articles: get_articles(articles_list)
}]
end
# For each section, this method saves the HTML fragment of each article's
# content to a path and returns an Array containing hashes with each article's
# metadata.
def get_articles html
FileUtils::mkdir_p "#{output_dir}/articles"
category_page = Nokogiri::HTML html
xs = category_page.search("#apicontent a").map {|x|
title = x.inner_text.strip
href = x[:href] =~ /^https?:/ ? x[:href] : "#{@start_url}#{x[:href]}"
$stderr.puts "- #{title}"
# Article content will be saved to path articles/filename
path = "articles/" + x[:href]
# Save just the HTML fragment that contains the article text. Throw out everything else.
html = run_shell_command "curl -s #{href}"
article_doc = Nokogiri::HTML html
content = article_doc.at('#toc').inner_html + article_doc.at('#apicontent').inner_html
File.open("#{output_dir}/#{path}", 'w') {|f| f.puts(content)}
# Return the article metadata hash for putting into the section's articles array
{
title: title,
path: path
}
}
end
end
# RUN IT! This pulls down the documentation and turns it into the Kindle ebook.
Node.generate
Cleaning up output
=begin
The internals of a recipe are up to you, but a recipe should do at least the
following:
First, require 'kindlefodder' and subclass Kindlefodder.
Second, contain a #get_source_files method that does two things:
1. Save a sections.yml to the path returned by the superclass's #output_dir
method with the following format:
---
- :title: Getting Started
:articles:
- :title: Getting Started with Heroku
:path: articles/quickstart
- :title: Platform Basics
:articles:
- :title: Architecture Overview
:path: articles/architecture-overview
- :title: Dyno Isolation
:path: articles/dyno-isolation
[etc.]
2. Save HTML fragments of the article content at the path values (relative to
#output_dir) indicated in the sections.yml above
The recipe class should also contain a #document method that returns a metadata
hash as shown below. The masthead and cover values seem optional. But if you fill
them in, use paths relative to output_dir.
=end
require 'kindlefodder'
class Node < Kindlefodder
# These next two methods must be implemented.
def get_source_files
@node_version = ARGV[0] ? "v#{ARGV[0]}" : "latest"
# The start_url is any webpage that will contain the navigation structure
# of the documentaion
@start_url = "http://nodejs.org/docs/#{@node_version}/api/"
File.open("#{output_dir}/sections.yml", 'w') {|f|
# extract_sections() is defined below. It gets the sections of the ebook
# out of the webpage docs navigation sidebar.
f.puts extract_sections.to_yaml
}
end
# This method is for the ebook metadata.
def document
{
'title' => "Node.js (#{@node_version}) Manual & Documentation",
'cover' => nil,
'masthead' => nil,
}
end
# The methods below are not required methods. They are this recipe's
# implementation for generating the required sections.yml and article
# fragment files.
# This method extracts the sections from the html sidebar at start_url
# This method returns an Array of elements with the Hash structure you
# see at the end.
def extract_sections
articles_list = run_shell_command "curl -s #{@start_url}"
[{
title: "API Documentation",
articles: get_articles(articles_list)
}]
end
# For each section, this method saves the HTML fragment of each article's
# content to a path and returns an Array containing hashes with each article's
# metadata.
def get_articles html
FileUtils::mkdir_p "#{output_dir}/articles"
category_page = Nokogiri::HTML html
xs = category_page.search("#apicontent a").map {|x|
title = x.inner_text.strip
href = x[:href] =~ /^https?:/ ? x[:href] : "#{@start_url}#{x[:href]}"
$stderr.puts "- #{title}"
# Article content will be saved to path articles/filename
path = "articles/" + x[:href]
# Save just the HTML fragment that contains the article text. Throw out everything else.
html = run_shell_command "curl -s #{href}"
article_doc = Nokogiri::HTML html
article_doc.search("a.mark").remove()
content = article_doc.at('#apicontent').inner_html
File.open("#{output_dir}/#{path}", 'w') {|f| f.puts(content)}
# Return the article metadata hash for putting into the section's articles array
{
title: title,
path: path
}
}
end
end
# RUN IT! This pulls down the documentation and turns it into the Kindle ebook.
Node.generate
|
if node['php']['version'] >= '7'
apt_repository 'ondrej-php' do
uri 'ppa:ondrej/php'
distribution node['lsb']['codename']
end
end
Fixed FC023
apt_repository 'ondrej-php' do
uri 'ppa:ondrej/php'
distribution node['lsb']['codename']
only_if node['php']['version'] >= '7'
end |
require 'fileutils'
# remove file so we can test sending notification on its creation
if ::File.exist? "/tmp/foobarbaz/foo1.txt"
FileUtils.rm_f "/tmp/foobarbaz/foo1.txt"
end
ruby_block "test_notification" do
block do
if ::File.exist? "/tmp/foobarbaz/foo1.txt"
FileUtils.touch "/tmp/foobarbaz/notification_successful.txt"
end
end
action :nothing
end
user 'foobarbaz'
directory "/opt/bin" do
recursive true
end
ark 'test_put' do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
owner 'foobarbaz'
group 'foobarbaz'
action :put
end
ark "test_dump" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.zip'
checksum 'deea3a324115c9ca0f3078362f807250080bf1b27516f7eca9d34aad863a11e0'
path '/usr/local/foo_dump'
creates 'foo1.txt'
action :dump
owner 'foobarbaz'
group 'foobarbaz'
end
ark 'cherry_pick_test' do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
path '/usr/local/foo_cherry_pick'
owner 'foobarbaz'
group 'foobarbaz'
creates "foo1.txt"
action :cherry_pick
end
ark "foo" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
version '2'
prefix_root "/usr/local"
owner "foobarbaz"
group 'foobarbaz'
has_binaries [ 'bin/do_foo', 'bin/do_more_foo' ]
action :install
end
ark "foo_append_env" do
version "7.0.26"
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
append_env_path true
action :install
end
ark "foo_dont_strip" do
version "2"
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
strip_leading_dir false
action :install
end
ark "foo_zip_strip" do
version "2"
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.zip'
checksum 'deea3a324115c9ca0f3078362f807250080bf1b27516f7eca9d34aad863a11e0'
action :install
end
ark "haproxy" do
url "http://haproxy.1wt.eu/download/1.5/src/snapshot/haproxy-ss-20120403.tar.gz"
version "1.5"
checksum 'ba0424bf7d23b3a607ee24bbb855bb0ea347d7ffde0bec0cb12a89623cbaf911'
make_opts [ 'TARGET=linux26' ]
action :install_with_make
end unless platform?("freebsd")
ark "foo_alt_bin" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
version '3'
prefix_root "/opt"
prefix_home "/opt"
prefix_bin "/opt/bin"
owner "foobarbaz"
group 'foobarbaz'
has_binaries [ 'bin/do_foo' ]
action :install
end
ark "foo_tbz" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tbz'
version '3'
end
ark "foo_tgz" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tgz'
version '3'
end
ark "test notification" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.zip'
path "/tmp/foobarbaz"
creates "foo1.txt"
action :dump
notifies :create, "ruby_block[test_notification]", :immediately
end
ark "test_autogen" do
url 'https://github.com/zeromq/libzmq/tarball/master'
extension "tar.gz"
action :configure
end
Fix cherry_pick_test.
require 'fileutils'
# remove file so we can test sending notification on its creation
if ::File.exist? "/tmp/foobarbaz/foo1.txt"
FileUtils.rm_f "/tmp/foobarbaz/foo1.txt"
end
ruby_block "test_notification" do
block do
if ::File.exist? "/tmp/foobarbaz/foo1.txt"
FileUtils.touch "/tmp/foobarbaz/notification_successful.txt"
end
end
action :nothing
end
user 'foobarbaz'
directory "/opt/bin" do
recursive true
end
ark 'test_put' do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
owner 'foobarbaz'
group 'foobarbaz'
action :put
end
ark "test_dump" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.zip'
checksum 'deea3a324115c9ca0f3078362f807250080bf1b27516f7eca9d34aad863a11e0'
path '/usr/local/foo_dump'
creates 'foo1.txt'
action :dump
owner 'foobarbaz'
group 'foobarbaz'
end
ark 'cherry_pick_test' do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
path '/usr/local/foo_cherry_pick'
owner 'foobarbaz'
group 'foobarbaz'
creates "foo_sub/foo1.txt"
action :cherry_pick
end
ark "foo" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
version '2'
prefix_root "/usr/local"
owner "foobarbaz"
group 'foobarbaz'
has_binaries [ 'bin/do_foo', 'bin/do_more_foo' ]
action :install
end
ark "foo_append_env" do
version "7.0.26"
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
append_env_path true
action :install
end
ark "foo_dont_strip" do
version "2"
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
strip_leading_dir false
action :install
end
ark "foo_zip_strip" do
version "2"
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.zip'
checksum 'deea3a324115c9ca0f3078362f807250080bf1b27516f7eca9d34aad863a11e0'
action :install
end
ark "haproxy" do
url "http://haproxy.1wt.eu/download/1.5/src/snapshot/haproxy-ss-20120403.tar.gz"
version "1.5"
checksum 'ba0424bf7d23b3a607ee24bbb855bb0ea347d7ffde0bec0cb12a89623cbaf911'
make_opts [ 'TARGET=linux26' ]
action :install_with_make
end unless platform?("freebsd")
ark "foo_alt_bin" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tar.gz'
checksum '5996e676f17457c823d86f1605eaa44ca8a81e70d6a0e5f8e45b51e62e0c52e8'
version '3'
prefix_root "/opt"
prefix_home "/opt"
prefix_bin "/opt/bin"
owner "foobarbaz"
group 'foobarbaz'
has_binaries [ 'bin/do_foo' ]
action :install
end
ark "foo_tbz" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tbz'
version '3'
end
ark "foo_tgz" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.tgz'
version '3'
end
ark "test notification" do
url 'https://github.com/bryanwb/chef-ark/raw/master/files/default/foo.zip'
path "/tmp/foobarbaz"
creates "foo1.txt"
action :dump
notifies :create, "ruby_block[test_notification]", :immediately
end
ark "test_autogen" do
url 'https://github.com/zeromq/libzmq/tarball/master'
extension "tar.gz"
action :configure
end
|
require "rack"
require "rack/auth_proxy/authenticate"
require "rack/auth_proxy/authorize"
require "rack/auth_proxy/formatted_error_response"
require "rack/auth_proxy/log"
require "rack/auth_proxy/throttle"
require "redis"
module AuthProxy
class RackApp
def self.redis_cache
@@redis_cache ||= Redis.new(self.redis_config)
end
@@redis_config = nil
def self.redis_config
unless @@redis_config
config_path = ::File.join(AUTH_PROXY_ROOT, "config", "redis.yml")
@@redis_config = YAML.load(ERB.new(File.read(config_path)).result)[ENV["RACK_ENV"]]
@@redis_config ||= {}
@@redis_config.symbolize_keys!
end
@@redis_config
end
def self.instance
@@instance ||= Rack::Builder.app do
use Rack::AuthProxy::Log
use Rack::AuthProxy::FormattedErrorResponse
use Rack::AuthProxy::Authenticate
use Rack::AuthProxy::Authorize
use Rack::AuthProxy::Throttle::Daily,
:cache => AuthProxy::RackApp.redis_cache,
:max => 30000,
:code => 503
use Rack::AuthProxy::Throttle::Hourly,
:cache => AuthProxy::RackApp.redis_cache,
:max => 2000,
:code => 503
# Return a 200 OK status if all the middlewares pass through
# successfully. This indicates to the calling AuthProxy::RequestHandler
# that no errors have occurred processing the headers, and the
# application can continue with a instruction to proxymachine.
run lambda { |env| [200, {}, ["OK"]] }
end
end
end
end
Lower the default thottling limits for now.
require "rack"
require "rack/auth_proxy/authenticate"
require "rack/auth_proxy/authorize"
require "rack/auth_proxy/formatted_error_response"
require "rack/auth_proxy/log"
require "rack/auth_proxy/throttle"
require "redis"
module AuthProxy
class RackApp
def self.redis_cache
@@redis_cache ||= Redis.new(self.redis_config)
end
@@redis_config = nil
def self.redis_config
unless @@redis_config
config_path = ::File.join(AUTH_PROXY_ROOT, "config", "redis.yml")
@@redis_config = YAML.load(ERB.new(File.read(config_path)).result)[ENV["RACK_ENV"]]
@@redis_config ||= {}
@@redis_config.symbolize_keys!
end
@@redis_config
end
def self.instance
@@instance ||= Rack::Builder.app do
use Rack::AuthProxy::Log
use Rack::AuthProxy::FormattedErrorResponse
use Rack::AuthProxy::Authenticate
use Rack::AuthProxy::Authorize
use Rack::AuthProxy::Throttle::Daily,
:cache => AuthProxy::RackApp.redis_cache,
:max => 10000,
:code => 503
use Rack::AuthProxy::Throttle::Hourly,
:cache => AuthProxy::RackApp.redis_cache,
:max => 1000,
:code => 503
# Return a 200 OK status if all the middlewares pass through
# successfully. This indicates to the calling AuthProxy::RequestHandler
# that no errors have occurred processing the headers, and the
# application can continue with a instruction to proxymachine.
run lambda { |env| [200, {}, ["OK"]] }
end
end
end
end
|
# -*- encoding: utf-8 -*-
require_relative "./version"
Gem::Specification.new do |s|
s.name = "regxing"
s.version = RegXing.version
s.authors = ["Dana Scheider"]
s.description = "Regex in, string out"
s.summary = "rambo-#{s.version}"
s.email = "dana.scheider@gmail.com"
s.license = "MIT"
s.platform = Gem::Platform::RUBY
s.required_ruby_version = ">= 2.1.0"
s.add_development_dependency "rspec", "~> 3.3"
s.add_development_dependency "coveralls", "~> 0.7"
s.add_development_dependency "rake", "~> 10.4"
s.rubygems_version = ">= 1.6.1"
s.files = `git ls-files`.split("\n").reject {|path| path =~ /\.gitignore$/ }
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.rdoc_options = ["--charset=UTF-8"]
s.require_path = "lib"
end
Update Rake
# -*- encoding: utf-8 -*-
require_relative "./version"
Gem::Specification.new do |s|
s.name = "regxing"
s.version = RegXing.version
s.authors = ["Dana Scheider"]
s.description = "Regex in, string out"
s.summary = "rambo-#{s.version}"
s.email = "dana.scheider@gmail.com"
s.license = "MIT"
s.platform = Gem::Platform::RUBY
s.required_ruby_version = ">= 2.1.0"
s.add_development_dependency "rspec", "~> 3.3"
s.add_development_dependency "coveralls", "~> 0.7"
s.add_development_dependency "rake", "~> 11.0"
s.rubygems_version = ">= 1.6.1"
s.files = `git ls-files`.split("\n").reject {|path| path =~ /\.gitignore$/ }
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.rdoc_options = ["--charset=UTF-8"]
s.require_path = "lib"
end
|
#!/usr/bin/env ruby
require 'eventmachine'
require 'date'
require 'ffi'
require 'yaml'
require 'trollop'
require 'daemons'
require_relative 'em-simplerepl'
module Xname
extend FFI::Library
ffi_lib 'xname'
attach_function :xname, [ :string ], :int
end
class ObservableArray < Array
def initialize(&callback)
@callback = callback
end
def []=(index, value)
@callback.call
super(index, value)
end
end
class DSD
attr_accessor :values
attr_accessor :timers
def initialize(h = {})
@values = ObservableArray.new { Xname.xname @values.reverse.join " | " }
@timers = []
h["items"].each.with_index do |item, index|
@timers << EM.add_periodic_timer(item["period"]) do
@values[index] = case item["type"]
when "time"
time item["format"]
when "file"
file item["path"], item["unit"]
when "array_from_file"
array_from_file item["path"], item["range"]
end
end
end
end
def time(format = "%Y-%m-%d %H:%M:%S")
DateTime.now.strftime format
end
def file(path, unit = "")
File.read(path).strip + unit
end
def array_from_file(path, range)
ends = range.split('..').map { |s| Integer(s) }
File.read(path).strip.split[ends[0]..ends[1]]
end
end
def initialize_statusbar(h)
$a = eval("ObservableArray.new { #{h["statusbar"]["update_code"]} }")
h["statusbar"]["items"].each.with_index do |item, index|
eval("EM.add_periodic_timer(#{item["item"]["period"]}) { $a[#{index}] = #{item["item"]["code"]} }")
end
end
opts = Trollop::options do
opt :config, "Configuration file", :type => :io, :default => File.open("#{ENV["HOME"]}/.dsd.conf")
opt :daemon, "Daemonize on startup", :type => :flag, :default => true
opt :debug, "Save debug log at dsd.log", :type => :flag, :default => false
opt :repl, "Start a repl", :type => :flag, :default => true
end
h = YAML.parse(opts[:config].read).to_ruby
Daemons.daemonize({:app_name => "dsd", :backtrace => opts[:debug], :ontop => not(opts[:daemon])})
EM.run do
initialize_statusbar(h)
EventMachine::start_server '127.0.0.1', h["repl"]["port"], SimpleRepl if opts[:repl]
end
The code is, somewhat, working now. Still needs some refinements, though
#!/usr/bin/env ruby
require 'eventmachine'
require 'date'
require 'ffi'
require 'yaml'
require 'trollop'
require 'daemons'
require_relative 'em-simplerepl'
module Xname
extend FFI::Library
ffi_lib 'xname'
attach_function :xname, [ :string ], :int
end
class ObservableArray < Array
def initialize(&callback)
@callback = callback
end
def []=(index, value)
@callback.call
super(index, value)
end
end
class DSD < ObservableArray
attr_accessor :timers
def initialize(configuration, &callback)
@callback = callback
@timers = {}
configuration["items"].each.with_index do |item, index|
item = item["item"]
@timers.merge!({
item["name"].to_sym => EM.add_periodic_timer(item["period"]) do
case item["type"]
when "time"
self[index] = time item["format"]
when "file"
self[index] = file item["path"], item["unit"]
when "array_from_file"
self[index] = array_from_file item["path"], item["range"]
end
end
})
end
end
def time(format = "%Y-%m-%d %H:%M:%S")
DateTime.now.strftime format
end
def file(path, unit = "")
File.read(path).strip + unit
end
def array_from_file(path, range)
ends = range.split('..').map { |s| Integer(s) }
File.read(path).strip.split[ends[0]..ends[1]].join " "
end
end
def initialize_statusbar(h)
$a = eval("ObservableArray.new { #{h["statusbar"]["update_code"]} }")
h["statusbar"]["items"].each.with_index do |item, index|
eval("EM.add_periodic_timer(#{item["item"]["period"]}) { $a[#{index}] = #{item["item"]["code"]} }")
end
end
opts = Trollop::options do
opt :config, "Configuration file", :type => :io, :default => File.open("#{ENV["HOME"]}/.dsd.conf")
opt :daemon, "Daemonize on startup", :type => :flag, :default => true
opt :debug, "Save debug log at dsd.log", :type => :flag, :default => false
opt :repl, "Start a repl", :type => :flag, :default => true
end
h = YAML.parse(opts[:config].read).to_ruby
Daemons.daemonize({:app_name => "dsd", :backtrace => opts[:debug], :ontop => not(opts[:daemon])})
EM.run do
initialize_statusbar(h)
EventMachine::start_server '127.0.0.1', h["repl"]["port"], SimpleRepl if opts[:repl]
end
|
Pod::Spec.new do |s|
s.name = 'DBCamera'
s.version = '0.8'
s.license = 'MIT'
s.summary = 'DBCamera is a simple custom camera with AVFoundation'
s.homepage = 'https://github.com/danielebogo/DBCamera'
s.author = { 'Daniele Bogo' => 'daniele@paperstreetsoapdesign.com' }
s.source = { :git => 'https://github.com/danielebogo/DBCamera.git', :tag => '0.8' }
s.platform = :ios, '6.0'
s.requires_arc = true
s.source_files = 'DBCamera/*.{h,m}'
s.resource = ['DBCamera/Resources/*.{xib,xcassets}', 'DBCamera/Localizations/**']
s.framework = 'AVFoundation'
end
Update podspec
Pod::Spec.new do |s|
s.name = 'DBCamera'
s.version = '0.9'
s.license = 'MIT'
s.summary = 'DBCamera is a simple custom camera with AVFoundation'
s.homepage = 'https://github.com/danielebogo/DBCamera'
s.author = { 'Daniele Bogo' => 'daniele@paperstreetsoapdesign.com' }
s.source = { :git => 'https://github.com/danielebogo/DBCamera.git', :tag => '0.9' }
s.platform = :ios, '6.0'
s.requires_arc = true
s.source_files = 'DBCamera/*.{h,m}'
s.resource = ['DBCamera/Resources/*.{xib,xcassets}', 'DBCamera/Localizations/**']
s.framework = 'AVFoundation'
end |
require '../lib/rambutan'
Dir[File.join(".", "controllers/*.rb")].each do |f|
require f
end
app = Rambutan::RoutesSet.new do
get '/posts' => 'posts#index'
end
run app.router
Fixing load path in config.ru
lib = File.expand_path('../../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rambutan'
Dir[File.join(".", "controllers/*.rb")].each do |f|
require f
end
app = Rambutan::RoutesSet.new do
get '/posts' => 'posts#index'
end
run app.router
|
require 'rails_helper'
describe AlertsController do
describe '#destroy' do
let!(:course) { create(:course) }
let!(:user) { create(:test_user) }
let!(:target_user) { create(:test_user) }
let!(:courses_users) { create(:courses_user, course_id: course.id, user_id: user.id) }
before do
allow(controller).to receive(:current_user).and_return(user)
allow(controller).to receive(:user_signed_in?).and_return(true)
controller.instance_variable_set(:@course, course)
end
it "should work" do
target_user.email = "email@email.com"
target_user.save
alert_params = { message: 'hello?', target_user_id: target_user.id, course_id: course.id }
post :create, alert_params, format: :json
expect(ActionMailer::Base.deliveries).not_to be_empty
expect(ActionMailer::Base.deliveries.last.to).to include(target_user.email)
expect(ActionMailer::Base.deliveries.last.subject).to include("#{user.username} / #{course.slug}")
expect(ActionMailer::Base.deliveries.last.body).to include(alert_params[:message])
expect(NeedHelpAlert.last.email_sent_at).not_to be_nil
expect(response.status).to eq(200)
end
end
end
Alert controller spec tweaks
require 'rails_helper'
describe AlertsController do
describe '#create' do
let!(:course) { create(:course) }
let!(:user) { create(:test_user) }
let!(:target_user) { create(:test_user) }
let!(:courses_users) { create(:courses_user, course_id: course.id, user_id: user.id) }
before do
allow(controller).to receive(:current_user).and_return(user)
allow(controller).to receive(:user_signed_in?).and_return(true)
controller.instance_variable_set(:@course, course)
end
it "should create Need Help alert and send email" do
target_user.email = "email@email.com"
target_user.save
alert_params = { message: 'hello?', target_user_id: target_user.id, course_id: course.id }
post :create, alert_params, format: :json
expect(ActionMailer::Base.deliveries.last.to).to include(target_user.email)
expect(ActionMailer::Base.deliveries.last.subject).to include("#{user.username} / #{course.slug}")
expect(ActionMailer::Base.deliveries.last.body).to include(alert_params[:message])
expect(NeedHelpAlert.last.email_sent_at).not_to be_nil
expect(response.status).to eq(200)
end
end
end
|
require 'spec_helper'
describe AssetsController do
render_views # for json responses
describe "POST create" do
context "a valid asset" do
before do
@atts = { :file => load_fixture_file("asset.png") }
end
it "is uploaded" do
post :create, asset: @atts
assigns(:asset).should be_persisted
assigns(:asset).file.current_path.should =~ /asset\.png$/
end
it "returns a created status" do
post :create, asset: @atts
response.status.should == 201
end
it "returns the location of the new asset" do
post :create, asset: @atts
asset = assigns(:asset)
body = JSON.parse(response.body)
body['asset']['id'].should == "http://test.host/assets/#{asset.id}"
end
end
context "an invalid asset" do
it "is not uploaded"
it "returns an unprocessable status"
end
end
end
Add specs for creating an invalid asset
require 'spec_helper'
describe AssetsController do
render_views # for json responses
describe "POST create" do
context "a valid asset" do
before do
@atts = { :file => load_fixture_file("asset.png") }
end
it "is persisted" do
post :create, asset: @atts
assigns(:asset).should be_persisted
assigns(:asset).file.current_path.should =~ /asset\.png$/
end
it "returns a created status" do
post :create, asset: @atts
response.status.should == 201
end
it "returns the location of the new asset" do
post :create, asset: @atts
asset = assigns(:asset)
body = JSON.parse(response.body)
body['asset']['id'].should == "http://test.host/assets/#{asset.id}"
end
end
context "an invalid asset" do
before do
@atts = { :file => nil }
end
it "is not persisted" do
post :create, asset: @atts
assigns(:asset).should_not be_persisted
assigns(:asset).file.current_path.should be_nil
end
it "returns an unprocessable status" do
post :create, asset: @atts
response.status.should == 422
end
end
end
end
|
require 'spec_helper'; require 'controller_spec_helper'
describe OrdersController do
render_views
before(:all) { create_users }
it "should route" do
{ :get => "/orders/cart" }.should route_to(:controller => "orders", :action => "cart")
{ :get => "/orders/1" }.should route_to(:controller => "orders", :action => "show", :id => "1")
{ :put => "/orders/1" }.should route_to(:controller => "orders", :action => "update", :id => "1")
{ :put => "/orders/1/add" }.should route_to(:controller => "orders", :action => "add", :id => "1")
{ :put => "/orders/1/remove/3" }.should route_to(:controller => "orders", :action => "remove", :id => "1", :order_detail_id => "3")
{ :put => "/orders/1" }.should route_to(:controller => "orders", :action => "update", :id => "1")
{ :put => "/orders/1/clear" }.should route_to(:controller => "orders", :action => "clear", :id => "1")
{ :put => "/orders/1/purchase" }.should route_to(:controller => "orders", :action => "purchase", :id => "1")
{ :get => "/orders/1/receipt" }.should route_to(:controller => "orders", :action => "receipt", :id => "1")
{ :get => "/orders/1/choose_account" }.should route_to(:controller => "orders", :action => "choose_account", :id => "1")
end
before :each do
@authable = Factory.create(:facility)
@facility_account = @authable.facility_accounts.create(Factory.attributes_for(:facility_account))
@price_group = @authable.price_groups.create(Factory.attributes_for(:price_group))
@account = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @staff, :created_by => @staff, :user_role => AccountUser::ACCOUNT_OWNER]])
@order = @staff.orders.create(Factory.attributes_for(:order, :created_by => @staff.id, :account => @account))
@item = @authable.items.create(Factory.attributes_for(:item, :facility_account_id => @facility_account.id))
Factory.create(:user_price_group_member, :user => @staff, :price_group => @price_group)
@item_pp=@item.item_price_policies.create(Factory.attributes_for(:item_price_policy, :price_group_id => @price_group.id))
@item_pp.reload.restrict_purchase=false
@params={ :id => @order.id, :order_id => @order.id }
end
context 'cart' do
before :each do
@method=:get
@action=:cart
end
it_should_require_login
it_should_allow :staff do
assert_redirected_to order_url(@order)
end
it 'should test more than auth'
end
context 'choose_account' do
before :each do
@order.add(@item, 1)
@order.order_details.size.should == 1
@method=:get
@action=:choose_account
@params.merge!(:account_id => @account.id)
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order).with_kind_of Order
assigns(:order).should == @order
should render_template 'choose_account'
end
it 'should test more than auth'
end
context 'purchase' do
before :each do
@method=:put
@action=:purchase
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order).with_kind_of Order
assigns(:order).should == @order
should respond_with :redirect
end
it 'should test more than auth'
end
context 'receipt' do
before :each do
# for receipt to work, order needs to have order_details
@complete_order = place_and_complete_item_order(@staff, @authable, @account).order.reload
@method=:get
@action=:receipt
@params={:id => @complete_order.id}
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order).with_kind_of Order
assigns(:order).should == @complete_order
should render_template 'receipt'
end
end
context 'index' do
before :each do
@method=:get
@action=:index
@params={:status => 'pending'}
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order_details).with_kind_of ActiveRecord::Relation
should render_template 'index'
end
end
context "add to cart" do
before(:each) do
@method=:put
@action=:add
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item.id}]})
@order.clear_cart?
end
it_should_require_login
context "with account (having already gone through choose_account)" do
before :each do
@order.account = @account
assert @order.save
session[:add_to_cart] = nil
do_request
end
it_should_allow :staff, "to add a product with quantity to cart" do
assigns(:order).id.should == @order.id
@order.reload.order_details.count.should == 1
flash[:error].should be_nil
should set_the_flash
response.should redirect_to "/orders/#{@order.id}"
end
end
context 'instrument' do
before :each do
@options=Factory.attributes_for(:instrument, :facility_account => @facility_account, :min_reserve_mins => 60, :max_reserve_mins => 60)
@order.clear_cart?
@instrument=@authable.instruments.create(@options)
@params[:id]=@order.id
@params[:order][:order_details].first[:product_id] = @instrument.id
end
it_should_allow :staff, "with empty cart (will use same order)" do
assigns(:order).id.should == @order.id
flash[:error].should be_nil
assert_redirected_to new_order_order_detail_reservation_path(@order.id, @order.reload.order_details.first.id)
end
context "quantity = 2" do
before :each do
@params[:order][:order_details].first[:quantity] = 2
end
it_should_allow :staff, "with empty cart (will use same order) redirect to choose account" do
assigns(:order).id.should == @order.id
flash[:error].should be_nil
assert_redirected_to choose_account_order_url(@order)
end
end
context "with non-empty cart" do
before :each do
@order.add(@item, 1)
end
it_should_allow :staff, "with non-empty cart (will create new order)" do
assigns(:order).should_not == @order
flash[:error].should be_nil
assert_redirected_to new_order_order_detail_reservation_path(assigns(:order), assigns(:order).order_details.first)
end
end
end
context "add is called and cart doesn't have an account" do
before :each do
@order.account = nil
@order.save
maybe_grant_always_sign_in :staff
do_request
end
it "should redirect to choose account" do
response.should redirect_to("/orders/#{@order.id}/choose_account")
end
it "should set session with contents of params[:order][:order_details]" do
session[:add_to_cart].should_not be_empty
session[:add_to_cart].should == [{"product_id" => @item.id, "quantity" => 1}]
end
end
context "w/ account" do
before :each do
@order.account = @account
@order.save!
end
context "mixed facility" do
it "should flash error message containing another" do
@facility2 = Factory.create(:facility)
@facility_account2 = @facility2.facility_accounts.create!(Factory.attributes_for(:facility_account))
@account2 = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @staff, :created_by => @staff, :user_role => AccountUser::ACCOUNT_OWNER]])
@item2 = @facility2.items.create!(Factory.attributes_for(:item, :facility_account_id => @facility_account2.id))
# add first item to cart
maybe_grant_always_sign_in :staff
do_request
# add second item to cart
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item2.id}]})
do_request
should set_the_flash.to(/can not/)
should set_the_flash.to(/another/)
response.should redirect_to "/orders/#{@order.id}"
end
end
end
context "acting_as" do
before :each do
@order.account = @account
@order.save!
@facility2 = Factory.create(:facility)
@facility_account2 = @facility2.facility_accounts.create!(Factory.attributes_for(:facility_account))
@account2 = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @staff, :created_by => @staff, :user_role => AccountUser::ACCOUNT_OWNER]])
@item2 = @facility2.items.create!(Factory.attributes_for(:item, :facility_account_id => @facility_account2.id))
end
context "in the right facility" do
before :each do
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item.id}]})
end
facility_operators.each do |role|
it "should allow #{role} to purchase" do
maybe_grant_always_sign_in role
switch_to @guest
do_request
should_not set_the_flash
@order.reload.order_details.should_not be_empty
response.should redirect_to "/orders/#{@order.id}"
end
end
it "should not allow guest" do
maybe_grant_always_sign_in :guest
@guest2 = Factory.create(:user)
switch_to @guest2
do_request
should set_the_flash
@order.reload.order_details.should be_empty
end
end
context "in the another facility" do
before :each do
maybe_grant_always_sign_in :director
switch_to @guest
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item2.id}]})
end
it "should not allow ordering" do
do_request
@order.reload.order_details.should be_empty
should set_the_flash.to(/You are not authorized to place an order on behalf of another user for the facility/)
end
end
it "should show a warning if the user doesn't have access to the product to be added"
end
end
context "remove from cart" do
before(:each) do
@order.add(@item, 1)
@order.order_details.size.should == 1
@order_detail = @order.order_details[0]
@method=:put
@action=:remove
@params.merge!(:order_detail_id => @order_detail.id)
end
it_should_require_login
it_should_allow :staff, "should delete an order_detail when /remove/:order_detail_id is called" do
@order.reload.order_details.size.should == 0
response.should redirect_to "/orders/#{@order.id}"
end
it "should 404 it the order_detail to be removed is not in the current cart" do
@account2 = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @director, :created_by => @director, :user_role => 'Owner']])
@order2 = @director.orders.create(Factory.attributes_for(:order, :user => @director, :created_by => @director, :account => @account2))
@order2.add(@item)
@order_detail2 = @order2.order_details[0]
@params[:order_detail_id]=@order_detail2.id
maybe_grant_always_sign_in :staff
do_request
response.response_code.should == 404
end
context "removing last item in cart" do
it "should nil out the payment source in the order/session" do
maybe_grant_always_sign_in :staff
do_request
response.should redirect_to "/orders/#{@order.id}"
should set_the_flash.to /removed/
@order.reload.order_details.size.should == 0
@order.reload.account.should == nil
end
end
it "should redirect to the value of the redirect_to param if available" do
maybe_grant_always_sign_in :staff
overridden_redirect = facility_url(@item.facility)
@params.merge!(:redirect_to => overridden_redirect)
do_request
response.should redirect_to overridden_redirect
should set_the_flash.to /removed/
end
end
context "update order_detail quantities" do
before(:each) do
@method=:put
@action=:update
@order_detail = @order.add(@item, 1).first
@params.merge!("quantity#{@order_detail.id}" => "6")
end
it_should_require_login
it_should_allow :staff, "to update the quantities of order_details" do
@order_detail.reload.quantity.should == 6
end
context "bad input" do
it "should show an error on not an integer" do
@params.merge!("quantity#{@order_detail.id}" => "1.5")
maybe_grant_always_sign_in :guest
do_request
should set_the_flash.to(/quantity/i)
should set_the_flash.to(/integer/i)
should render_template :show
end
end
it "should not allow updates of quantities for instruments"
end
context "update order_detail notes" do
before(:each) do
@method=:put
@action=:update
@order_detail = @order.add(@item, 1).first
@params.merge!(
"quantity#{@order_detail.id}" => "6",
"note#{@order_detail.id}" => "new note"
)
end
it_should_require_login
it_should_allow :staff, "to update the note field of order_details" do
@order_detail.reload.note.should == 'new note'
end
end
context "cart meta data" do
before(:each) do
@instrument = @authable.instruments.create(Factory.attributes_for(:instrument, :facility_account_id => @facility_account.id))
@instrument.schedule_rules.create(Factory.attributes_for(:schedule_rule, :start_hour => 0, :end_hour => 24))
@instrument_pp = @instrument.instrument_price_policies.create(Factory.attributes_for(:instrument_price_policy, :price_group_id => @price_group.id, :restrict_purchase => false))
@service = @authable.services.create(Factory.attributes_for(:service, :facility_account_id => @facility_account.id))
@method=:get
@action=:show
end
it_should_require_login
context 'staff' do
before :each do
@order.add(@instrument)
@order_detail = @order.order_details.first
end
it_should_allow :staff, "to show links for making a reservation for instruments" do
response.should be_success
end
end
it "should show links for uploading files for services where required by service"
it "should show links for submitting survey for services where required by service"
context "restricted instrument" do
before :each do
@instrument.update_attributes(:requires_approval => true)
maybe_grant_always_sign_in :director
@order.update_attributes(:created_by_user => @director)
@order.add(@instrument)
@order.order_details.size.should == 1
switch_to @guest
end
it "should allow purchasing a restricted item the user isn't authorized for" do
place_reservation(@authable, @order.order_details.first, Time.zone.now)
do_request
assigns[:order].should be_validated
end
it "should not be validated if there is no reservation" do
do_request
assigns[:order].should_not be_validated
assigns[:order].order_details.first.validate_for_purchase.should == "Please make a reservation"
end
end
end
context "clear" do
before(:each) do
@method=:put
@action=:clear
end
it_should_require_login
it_should_allow :staff, "to clear the cart and redirect back to cart" do
@order.order_details.size == 0
assert_redirected_to order_path(@order)
end
end
context "checkout" do
before(:each) do
#@item_pp = Factory.create(:item_price_policy, :item => @item, :price_group => @price_group)
#@pg_member = Factory.create(:user_price_group_member, :user => @staff, :price_group => @price_group)
@order.add(@item, 10)
@method=:get
@action=:show
end
it_should_require_login
it "should disallow viewing of cart that is purchased" do
Factory.create(:price_group_product, :product => @item, :price_group =>@price_group, :reservation_window => nil)
define_open_account(@item.account, @account.account_number)
@order.validate_order!
@order.purchase!
maybe_grant_always_sign_in :staff
do_request
response.should redirect_to "/orders/#{@order.id}/receipt"
@action=:choose_account
do_request
response.should redirect_to "/orders/#{@order.id}/receipt"
@method=:put
@action=:purchase
do_request
response.should redirect_to "/orders/#{@order.id}/receipt"
# TODO: add, etc.
end
it "should validate and transition to validated"
it "should only allow checkout if the cart has at least one order_detail"
end
context "receipt /receipt/:order_id" do
it "should 404 unless :order_id exists and is related to the current user"
end
end
define open account in spec
require 'spec_helper'; require 'controller_spec_helper'
describe OrdersController do
render_views
before(:all) { create_users }
it "should route" do
{ :get => "/orders/cart" }.should route_to(:controller => "orders", :action => "cart")
{ :get => "/orders/1" }.should route_to(:controller => "orders", :action => "show", :id => "1")
{ :put => "/orders/1" }.should route_to(:controller => "orders", :action => "update", :id => "1")
{ :put => "/orders/1/add" }.should route_to(:controller => "orders", :action => "add", :id => "1")
{ :put => "/orders/1/remove/3" }.should route_to(:controller => "orders", :action => "remove", :id => "1", :order_detail_id => "3")
{ :put => "/orders/1" }.should route_to(:controller => "orders", :action => "update", :id => "1")
{ :put => "/orders/1/clear" }.should route_to(:controller => "orders", :action => "clear", :id => "1")
{ :put => "/orders/1/purchase" }.should route_to(:controller => "orders", :action => "purchase", :id => "1")
{ :get => "/orders/1/receipt" }.should route_to(:controller => "orders", :action => "receipt", :id => "1")
{ :get => "/orders/1/choose_account" }.should route_to(:controller => "orders", :action => "choose_account", :id => "1")
end
before :each do
@authable = Factory.create(:facility)
@facility_account = @authable.facility_accounts.create(Factory.attributes_for(:facility_account))
@price_group = @authable.price_groups.create(Factory.attributes_for(:price_group))
@account = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @staff, :created_by => @staff, :user_role => AccountUser::ACCOUNT_OWNER]])
@order = @staff.orders.create(Factory.attributes_for(:order, :created_by => @staff.id, :account => @account))
@item = @authable.items.create(Factory.attributes_for(:item, :facility_account_id => @facility_account.id))
Factory.create(:user_price_group_member, :user => @staff, :price_group => @price_group)
@item_pp=@item.item_price_policies.create(Factory.attributes_for(:item_price_policy, :price_group_id => @price_group.id))
@item_pp.reload.restrict_purchase=false
@params={ :id => @order.id, :order_id => @order.id }
end
context 'cart' do
before :each do
@method=:get
@action=:cart
end
it_should_require_login
it_should_allow :staff do
assert_redirected_to order_url(@order)
end
it 'should test more than auth'
end
context 'choose_account' do
before :each do
@order.add(@item, 1)
@order.order_details.size.should == 1
@method=:get
@action=:choose_account
@params.merge!(:account_id => @account.id)
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order).with_kind_of Order
assigns(:order).should == @order
should render_template 'choose_account'
end
it 'should test more than auth'
end
context 'purchase' do
before :each do
@method=:put
@action=:purchase
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order).with_kind_of Order
assigns(:order).should == @order
should respond_with :redirect
end
it 'should test more than auth'
end
context 'receipt' do
before :each do
# for receipt to work, order needs to have order_details
@complete_order = place_and_complete_item_order(@staff, @authable, @account).order.reload
@method=:get
@action=:receipt
@params={:id => @complete_order.id}
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order).with_kind_of Order
assigns(:order).should == @complete_order
should render_template 'receipt'
end
end
context 'index' do
before :each do
@method=:get
@action=:index
@params={:status => 'pending'}
end
it_should_require_login
it_should_allow :staff do
should assign_to(:order_details).with_kind_of ActiveRecord::Relation
should render_template 'index'
end
end
context "add to cart" do
before(:each) do
@method=:put
@action=:add
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item.id}]})
@order.clear_cart?
end
it_should_require_login
context "with account (having already gone through choose_account)" do
before :each do
@order.account = @account
assert @order.save
session[:add_to_cart] = nil
do_request
end
it_should_allow :staff, "to add a product with quantity to cart" do
assigns(:order).id.should == @order.id
@order.reload.order_details.count.should == 1
flash[:error].should be_nil
should set_the_flash
response.should redirect_to "/orders/#{@order.id}"
end
end
context 'instrument' do
before :each do
@options=Factory.attributes_for(:instrument, :facility_account => @facility_account, :min_reserve_mins => 60, :max_reserve_mins => 60)
@order.clear_cart?
@instrument=@authable.instruments.create(@options)
@params[:id]=@order.id
@params[:order][:order_details].first[:product_id] = @instrument.id
end
it_should_allow :staff, "with empty cart (will use same order)" do
assigns(:order).id.should == @order.id
flash[:error].should be_nil
assert_redirected_to new_order_order_detail_reservation_path(@order.id, @order.reload.order_details.first.id)
end
context "quantity = 2" do
before :each do
@params[:order][:order_details].first[:quantity] = 2
end
it_should_allow :staff, "with empty cart (will use same order) redirect to choose account" do
assigns(:order).id.should == @order.id
flash[:error].should be_nil
assert_redirected_to choose_account_order_url(@order)
end
end
context "with non-empty cart" do
before :each do
@order.add(@item, 1)
end
it_should_allow :staff, "with non-empty cart (will create new order)" do
assigns(:order).should_not == @order
flash[:error].should be_nil
assert_redirected_to new_order_order_detail_reservation_path(assigns(:order), assigns(:order).order_details.first)
end
end
end
context "add is called and cart doesn't have an account" do
before :each do
@order.account = nil
@order.save
maybe_grant_always_sign_in :staff
do_request
end
it "should redirect to choose account" do
response.should redirect_to("/orders/#{@order.id}/choose_account")
end
it "should set session with contents of params[:order][:order_details]" do
session[:add_to_cart].should_not be_empty
session[:add_to_cart].should == [{"product_id" => @item.id, "quantity" => 1}]
end
end
context "w/ account" do
before :each do
@order.account = @account
@order.save!
end
context "mixed facility" do
it "should flash error message containing another" do
@facility2 = Factory.create(:facility)
@facility_account2 = @facility2.facility_accounts.create!(Factory.attributes_for(:facility_account))
@account2 = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @staff, :created_by => @staff, :user_role => AccountUser::ACCOUNT_OWNER]])
@item2 = @facility2.items.create!(Factory.attributes_for(:item, :facility_account_id => @facility_account2.id))
# add first item to cart
maybe_grant_always_sign_in :staff
do_request
# add second item to cart
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item2.id}]})
do_request
should set_the_flash.to(/can not/)
should set_the_flash.to(/another/)
response.should redirect_to "/orders/#{@order.id}"
end
end
end
context "acting_as" do
before :each do
@order.account = @account
@order.save!
@facility2 = Factory.create(:facility)
@facility_account2 = @facility2.facility_accounts.create!(Factory.attributes_for(:facility_account))
@account2 = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @staff, :created_by => @staff, :user_role => AccountUser::ACCOUNT_OWNER]])
@item2 = @facility2.items.create!(Factory.attributes_for(:item, :facility_account_id => @facility_account2.id))
end
context "in the right facility" do
before :each do
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item.id}]})
end
facility_operators.each do |role|
it "should allow #{role} to purchase" do
maybe_grant_always_sign_in role
switch_to @guest
do_request
should_not set_the_flash
@order.reload.order_details.should_not be_empty
response.should redirect_to "/orders/#{@order.id}"
end
end
it "should not allow guest" do
maybe_grant_always_sign_in :guest
@guest2 = Factory.create(:user)
switch_to @guest2
do_request
should set_the_flash
@order.reload.order_details.should be_empty
end
end
context "in the another facility" do
before :each do
maybe_grant_always_sign_in :director
switch_to @guest
@params.merge!(:order => {:order_details => [{:quantity => 1, :product_id => @item2.id}]})
end
it "should not allow ordering" do
do_request
@order.reload.order_details.should be_empty
should set_the_flash.to(/You are not authorized to place an order on behalf of another user for the facility/)
end
end
it "should show a warning if the user doesn't have access to the product to be added"
end
end
context "remove from cart" do
before(:each) do
@order.add(@item, 1)
@order.order_details.size.should == 1
@order_detail = @order.order_details[0]
@method=:put
@action=:remove
@params.merge!(:order_detail_id => @order_detail.id)
end
it_should_require_login
it_should_allow :staff, "should delete an order_detail when /remove/:order_detail_id is called" do
@order.reload.order_details.size.should == 0
response.should redirect_to "/orders/#{@order.id}"
end
it "should 404 it the order_detail to be removed is not in the current cart" do
@account2 = Factory.create(:nufs_account, :account_users_attributes => [Hash[:user => @director, :created_by => @director, :user_role => 'Owner']])
@order2 = @director.orders.create(Factory.attributes_for(:order, :user => @director, :created_by => @director, :account => @account2))
@order2.add(@item)
@order_detail2 = @order2.order_details[0]
@params[:order_detail_id]=@order_detail2.id
maybe_grant_always_sign_in :staff
do_request
response.response_code.should == 404
end
context "removing last item in cart" do
it "should nil out the payment source in the order/session" do
maybe_grant_always_sign_in :staff
do_request
response.should redirect_to "/orders/#{@order.id}"
should set_the_flash.to /removed/
@order.reload.order_details.size.should == 0
@order.reload.account.should == nil
end
end
it "should redirect to the value of the redirect_to param if available" do
maybe_grant_always_sign_in :staff
overridden_redirect = facility_url(@item.facility)
@params.merge!(:redirect_to => overridden_redirect)
do_request
response.should redirect_to overridden_redirect
should set_the_flash.to /removed/
end
end
context "update order_detail quantities" do
before(:each) do
@method=:put
@action=:update
@order_detail = @order.add(@item, 1).first
@params.merge!("quantity#{@order_detail.id}" => "6")
end
it_should_require_login
it_should_allow :staff, "to update the quantities of order_details" do
@order_detail.reload.quantity.should == 6
end
context "bad input" do
it "should show an error on not an integer" do
@params.merge!("quantity#{@order_detail.id}" => "1.5")
maybe_grant_always_sign_in :guest
do_request
should set_the_flash.to(/quantity/i)
should set_the_flash.to(/integer/i)
should render_template :show
end
end
it "should not allow updates of quantities for instruments"
end
context "update order_detail notes" do
before(:each) do
@method=:put
@action=:update
@order_detail = @order.add(@item, 1).first
@params.merge!(
"quantity#{@order_detail.id}" => "6",
"note#{@order_detail.id}" => "new note"
)
end
it_should_require_login
it_should_allow :staff, "to update the note field of order_details" do
@order_detail.reload.note.should == 'new note'
end
end
context "cart meta data" do
before(:each) do
@instrument = @authable.instruments.create(Factory.attributes_for(:instrument, :facility_account_id => @facility_account.id))
@instrument.schedule_rules.create(Factory.attributes_for(:schedule_rule, :start_hour => 0, :end_hour => 24))
@instrument_pp = @instrument.instrument_price_policies.create(Factory.attributes_for(:instrument_price_policy, :price_group_id => @price_group.id))
@instrument_pp.restrict_purchase = false
define_open_account(@instrument.account, @account.account_number)
@service = @authable.services.create(Factory.attributes_for(:service, :facility_account_id => @facility_account.id))
@method=:get
@action=:show
end
it_should_require_login
context 'staff' do
before :each do
@order.add(@instrument)
@order_detail = @order.order_details.first
end
it_should_allow :staff, "to show links for making a reservation for instruments" do
response.should be_success
end
end
it "should show links for uploading files for services where required by service"
it "should show links for submitting survey for services where required by service"
context "restricted instrument" do
before :each do
@instrument.update_attributes(:requires_approval => true)
maybe_grant_always_sign_in :director
@order.update_attributes(:created_by_user => @director)
@order.add(@instrument)
@order.order_details.size.should == 1
switch_to @guest
end
it "should allow purchasing a restricted item the user isn't authorized for" do
place_reservation(@authable, @order.order_details.first, Time.zone.now)
do_request
assigns[:order].should be_validated
end
it "should not be validated if there is no reservation" do
do_request
assigns[:order].should_not be_validated
assigns[:order].order_details.first.validate_for_purchase.should == "Please make a reservation"
end
end
end
context "clear" do
before(:each) do
@method=:put
@action=:clear
end
it_should_require_login
it_should_allow :staff, "to clear the cart and redirect back to cart" do
@order.order_details.size == 0
assert_redirected_to order_path(@order)
end
end
context "checkout" do
before(:each) do
#@item_pp = Factory.create(:item_price_policy, :item => @item, :price_group => @price_group)
#@pg_member = Factory.create(:user_price_group_member, :user => @staff, :price_group => @price_group)
@order.add(@item, 10)
@method=:get
@action=:show
end
it_should_require_login
it "should disallow viewing of cart that is purchased" do
Factory.create(:price_group_product, :product => @item, :price_group =>@price_group, :reservation_window => nil)
define_open_account(@item.account, @account.account_number)
@order.validate_order!
@order.purchase!
maybe_grant_always_sign_in :staff
do_request
response.should redirect_to "/orders/#{@order.id}/receipt"
@action=:choose_account
do_request
response.should redirect_to "/orders/#{@order.id}/receipt"
@method=:put
@action=:purchase
do_request
response.should redirect_to "/orders/#{@order.id}/receipt"
# TODO: add, etc.
end
it "should validate and transition to validated"
it "should only allow checkout if the cart has at least one order_detail"
end
context "receipt /receipt/:order_id" do
it "should 404 unless :order_id exists and is related to the current user"
end
end
|
# Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
require 'spec_helper'
describe PeopleController do
render_views
let(:user) { Factory(:user) }
let!(:aspect) { user.aspects.create(:name => "lame-os") }
before do
sign_in :user, user
end
describe '#share_with' do
before do
@person = Factory.create(:person)
end
it 'succeeds' do
get :share_with, :id => @person.id
response.should be_success
end
end
describe '#hashes_from_people' do
before do
@everyone = []
10.times do
@everyone << Factory.create(:person)
end
user.send_contact_request_to(@everyone[3], aspect)
user.send_contact_request_to(@everyone[2], aspect)
user.activate_contact(@everyone[4], aspect)
user.activate_contact(@everyone[5], aspect)
user.reload
user.aspects.reload
@people = @everyone
@people.length.should == 10
@hashes = @controller.hashes_for_people(@people, user.aspects)
end
it 'has the correct result for no relationship' do
hash = @hashes.first
hash[:person].should == @people.first
hash[:contact].should be_false
hash[:request].should be_false
hash[:aspects].should == user.aspects
end
it 'has the correct result for a connected person' do
hash = @hashes[4]
hash[:person].should == @people[4]
hash[:contact].should be_true
hash[:contact].should_not be_pending
hash[:aspects].should == user.aspects
end
it 'has the correct result for a requested person' do
hash = @hashes[2]
hash[:person].should == @people[2]
hash[:contact].should be_true
hash[:contact].should be_pending
hash[:aspects].should == user.aspects
end
end
describe '#index' do
before do
@eugene = Factory.create(:person, :profile => {:first_name => "Eugene", :last_name => "w"})
@korth = Factory.create(:person, :profile => {:first_name => "Evan", :last_name => "Korth"})
end
it "assigns hashes" do
eugene2 = Factory.create(:person, :profile => {:first_name => "Eugene", :last_name => "w"})
get :index, :q => "Eu"
people = assigns[:hashes].map{|h| h[:person]}
people.should include @eugene
people.should include eugene2
end
it "assigns people" do
eugene2 = Factory.create(:person, :profile => {:first_name => "Eugene", :last_name => "w"})
get :index, :q => "Eu"
assigns[:people].should == [@eugene, eugene2]
end
it 'shows a contact' do
user2 = make_user
connect_users(user, aspect, user2, user2.aspects.create(:name => 'Neuroscience'))
get :index, :q => user2.person.profile.first_name.to_s
response.should redirect_to user2.person
end
it 'shows a non-contact' do
user2 = make_user
user2.person.profile.searchable = true
user2.save
get :index, :q => user2.person.profile.first_name.to_s
response.should redirect_to user2.person
end
it "redirects to person page if there is exactly one match" do
get :index, :q => "Korth"
response.should redirect_to @korth
end
it "does not redirect if there are no matches" do
get :index, :q => "Korthsauce"
response.should_not be_redirect
end
end
describe '#show' do
it 'should go to the current_user show page' do
get :show, :id => user.person.id
response.should be_success
end
it 'renders with a post' do
user.post :status_message, :message => 'test more', :to => aspect.id
get :show, :id => user.person.id
response.should be_success
end
it 'renders with a post' do
message = user.post :status_message, :message => 'test more', :to => aspect.id
user.comment 'I mean it', :on => message
get :show, :id => user.person.id
response.should be_success
end
it "redirects on an invalid id" do
get :show, :id => 'delicious'
response.should redirect_to people_path
end
it "redirects on a nonexistent person" do
get :show, :id => user.id
response.should redirect_to people_path
end
it "renders the show page of a contact" do
user2 = make_user
connect_users(user, aspect, user2, user2.aspects.create(:name => 'Neuroscience'))
get :show, :id => user2.person.id
response.should be_success
end
it "renders the show page of a non-contact" do
user2 = make_user
get :show, :id => user2.person.id
response.should be_success
end
it "renders with public posts of a non-contact" do
user2 = make_user
status_message = user2.post(:status_message, :message => "hey there", :to => 'all', :public => true)
get :show, :id => user2.person.id
response.body.should include status_message.message
end
end
describe '#webfinger' do
it 'enqueues a webfinger job' do
Resque.should_receive(:enqueue).with(Jobs::SocketWebfinger, user.id, user.diaspora_handle, anything).once
get :retrieve_remote, :diaspora_handle => user.diaspora_handle
end
end
describe '#update' do
it "sets the flash" do
put :update, :id => user.person.id,
:profile => {
:image_url => "",
:first_name => "Will",
:last_name => "Smith"
}
flash[:notice].should_not be_empty
end
context 'with a profile photo set' do
before do
@params = { :id => user.person.id,
:profile =>
{:image_url => "",
:last_name => user.person.profile.last_name,
:first_name => user.person.profile.first_name }}
user.person.profile.image_url = "http://tom.joindiaspora.com/images/user/tom.jpg"
user.person.profile.save
end
it "doesn't overwrite the profile photo when an empty string is passed in" do
image_url = user.person.profile.image_url
put :update, @params
user.person.reload
user.person.profile.image_url.should == image_url
end
end
it 'does not allow mass assignment' do
new_user = make_user
put :update, :id => user.person.id, :owner_id => new_user.id
user.person.reload.owner_id.should_not == new_user.id
end
it 'does not overwrite the profile diaspora handle' do
handle_params = {:id => user.person.id, :profile => {:diaspora_handle => 'abc@a.com'}}
put :update, handle_params
user.person.reload.profile[:diaspora_handle].should_not == 'abc@a.com'
end
end
end
Fix spec in peoplecontroller
# Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
require 'spec_helper'
describe PeopleController do
render_views
let(:user) { Factory(:user) }
let!(:aspect) { user.aspects.create(:name => "lame-os") }
before do
sign_in :user, user
end
describe '#share_with' do
before do
@person = Factory.create(:person)
end
it 'succeeds' do
get :share_with, :id => @person.id
response.should be_success
end
end
describe '#hashes_from_people' do
before do
@everyone = []
10.times do
@everyone << Factory.create(:person)
end
user.send_contact_request_to(@everyone[3], aspect)
user.send_contact_request_to(@everyone[2], aspect)
user.activate_contact(@everyone[4], aspect)
user.activate_contact(@everyone[5], aspect)
user.reload
user.aspects.reload
@people = @everyone
@people.length.should == 10
@hashes = @controller.hashes_for_people(@people, user.aspects)
end
it 'has the correct result for no relationship' do
hash = @hashes.first
hash[:person].should == @people.first
hash[:contact].should be_false
hash[:request].should be_false
hash[:aspects].should == user.aspects
end
it 'has the correct result for a connected person' do
hash = @hashes[4]
hash[:person].should == @people[4]
hash[:contact].should be_true
hash[:contact].should_not be_pending
hash[:aspects].should == user.aspects
end
it 'has the correct result for a requested person' do
hash = @hashes[2]
hash[:person].should == @people[2]
hash[:contact].should be_true
hash[:contact].should be_pending
hash[:aspects].should == user.aspects
end
end
describe '#index' do
before do
@eugene = Factory.create(:person, :profile => {:first_name => "Eugene", :last_name => "w"})
@korth = Factory.create(:person, :profile => {:first_name => "Evan", :last_name => "Korth"})
end
it "assigns hashes" do
eugene2 = Factory.create(:person, :profile => {:first_name => "Eugene", :last_name => "w"})
get :index, :q => "Eu"
people = assigns[:hashes].map{|h| h[:person]}
people.should include @eugene
people.should include eugene2
end
it "assigns people" do
eugene2 = Factory.create(:person, :profile => {:first_name => "Eugene", :last_name => "w"})
get :index, :q => "Eu"
assigns[:people].should =~ [@eugene, eugene2]
end
it 'shows a contact' do
user2 = make_user
connect_users(user, aspect, user2, user2.aspects.create(:name => 'Neuroscience'))
get :index, :q => user2.person.profile.first_name.to_s
response.should redirect_to user2.person
end
it 'shows a non-contact' do
user2 = make_user
user2.person.profile.searchable = true
user2.save
get :index, :q => user2.person.profile.first_name.to_s
response.should redirect_to user2.person
end
it "redirects to person page if there is exactly one match" do
get :index, :q => "Korth"
response.should redirect_to @korth
end
it "does not redirect if there are no matches" do
get :index, :q => "Korthsauce"
response.should_not be_redirect
end
end
describe '#show' do
it 'should go to the current_user show page' do
get :show, :id => user.person.id
response.should be_success
end
it 'renders with a post' do
user.post :status_message, :message => 'test more', :to => aspect.id
get :show, :id => user.person.id
response.should be_success
end
it 'renders with a post' do
message = user.post :status_message, :message => 'test more', :to => aspect.id
user.comment 'I mean it', :on => message
get :show, :id => user.person.id
response.should be_success
end
it "redirects on an invalid id" do
get :show, :id => 'delicious'
response.should redirect_to people_path
end
it "redirects on a nonexistent person" do
get :show, :id => user.id
response.should redirect_to people_path
end
it "renders the show page of a contact" do
user2 = make_user
connect_users(user, aspect, user2, user2.aspects.create(:name => 'Neuroscience'))
get :show, :id => user2.person.id
response.should be_success
end
it "renders the show page of a non-contact" do
user2 = make_user
get :show, :id => user2.person.id
response.should be_success
end
it "renders with public posts of a non-contact" do
user2 = make_user
status_message = user2.post(:status_message, :message => "hey there", :to => 'all', :public => true)
get :show, :id => user2.person.id
response.body.should include status_message.message
end
end
describe '#webfinger' do
it 'enqueues a webfinger job' do
Resque.should_receive(:enqueue).with(Jobs::SocketWebfinger, user.id, user.diaspora_handle, anything).once
get :retrieve_remote, :diaspora_handle => user.diaspora_handle
end
end
describe '#update' do
it "sets the flash" do
put :update, :id => user.person.id,
:profile => {
:image_url => "",
:first_name => "Will",
:last_name => "Smith"
}
flash[:notice].should_not be_empty
end
context 'with a profile photo set' do
before do
@params = { :id => user.person.id,
:profile =>
{:image_url => "",
:last_name => user.person.profile.last_name,
:first_name => user.person.profile.first_name }}
user.person.profile.image_url = "http://tom.joindiaspora.com/images/user/tom.jpg"
user.person.profile.save
end
it "doesn't overwrite the profile photo when an empty string is passed in" do
image_url = user.person.profile.image_url
put :update, @params
user.person.reload
user.person.profile.image_url.should == image_url
end
end
it 'does not allow mass assignment' do
new_user = make_user
put :update, :id => user.person.id, :owner_id => new_user.id
user.person.reload.owner_id.should_not == new_user.id
end
it 'does not overwrite the profile diaspora handle' do
handle_params = {:id => user.person.id, :profile => {:diaspora_handle => 'abc@a.com'}}
put :update, handle_params
user.person.reload.profile[:diaspora_handle].should_not == 'abc@a.com'
end
end
end
|
## DEPRECATION NOTICE: Do not add new tests to this file!
##
## View and controller tests are deprecated in the Growstuff project.
## We no longer write new view and controller tests, but instead write
## feature tests (in spec/features) using Capybara (https://github.com/jnicklas/capybara).
## These test the full stack, behaving as a browser, and require less complicated setup
## to run. Please feel free to delete old view/controller tests as they are reimplemented
## in feature tests.
##
## If you submit a pull request containing new view or controller tests, it will not be
## merged.
require 'rails_helper'
describe PhotosController do
login_member
def valid_attributes
member = FactoryGirl.create(:member)
{
"owner_id" => member.id,
"flickr_photo_id" => 1,
"title" => "Photo",
"license_name" => "CC-BY",
"thumbnail_url" => 'http://example.com/thumb.jpg',
"fullsize_url" => 'http://example.com/full.jpg',
"link_url" => 'http://example.com'
}
end
def valid_session
{}
end
describe "GET new" do
before(:each) do
@member = FactoryGirl.create(:member)
sign_in @member
@member.stub(:flickr_photos) { [[], 0] }
@member.stub(:flickr_sets) { { "foo" => "bar" } }
controller.stub(:current_member) { @member }
end
it "assigns the flickr auth as @flickr_auth" do
@auth = FactoryGirl.create(:flickr_authentication, member: @member)
get :new, {}
assigns(:flickr_auth).should be_an_instance_of(Authentication)
end
it "assigns a planting id" do
get :new, type: "planting", id: 5
assigns(:id).should eq "5"
assigns(:type).should eq "planting"
expect(flash[:alert]).not_to be_present
end
it "assigns a harvest id" do
get :new, type: "harvest", id: 5
assigns(:id).should eq "5"
assigns(:type).should eq "harvest"
expect(flash[:alert]).not_to be_present
end
it "assigns a garden id" do
get :new, type: "garden", id: 5
assigns(:id).should eq "5"
assigns(:type).should eq "garden"
expect(flash[:alert]).not_to be_present
end
it "assigns the current set as @current_set" do
get :new, set: 'foo'
assigns(:current_set).should eq "foo"
expect(flash[:alert]).not_to be_present
end
end
describe "POST create" do
before(:each) do
Photo.any_instance.stub(:flickr_metadata).and_return(title: "A Heartbreaking work of staggering genius",
license_name: "CC-BY",
license_url: "http://example.com/aybpl",
thumbnail_url: "http://example.com/thumb.jpg",
fullsize_url: "http://example.com/full.jpg",
link_url: "http://example.com")
end
describe "with valid params" do
let(:member) { FactoryGirl.create(:member) }
let(:garden) { FactoryGirl.create(:garden, owner: member) }
let(:planting) { FactoryGirl.create(:planting, garden: garden, owner: member) }
let(:harvest) { FactoryGirl.create(:harvest, owner: member) }
let(:photo) { FactoryGirl.create(:photo, owner: member) }
before { controller.stub(:current_member) { member } }
it "attaches the photo to a planting" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).not_to be_present
Photo.last.plantings.first.should eq planting
end
it "doesn't attach a photo to a planting twice" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).not_to be_present
Photo.last.plantings.size.should eq 1
end
it "attaches the photo to a harvest" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).not_to be_present
Photo.last.harvests.first.should eq harvest
end
it "doesn't attach a photo to a harvest twice" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).not_to be_present
Photo.last.harvests.size.should eq 1
end
it "doesn't attach photo to a comment" do
comment = FactoryGirl.create(:comment)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "comment", id: comment.id
expect(flash[:alert]).to be_present
end
end
describe "for the second time" do
it "does not add a photo twice" do
expect do
post :create, photo: { flickr_photo_id: 1 }
end.to change(Photo, :count).by(1)
expect do
post :create, photo: { flickr_photo_id: 1 }
end.to change(Photo, :count).by(0)
end
end
describe "with matching owners" do
it "creates the planting/photo link" do
member = FactoryGirl.create(:member)
controller.stub(:current_member) { member }
garden = FactoryGirl.create(:garden, owner: member)
planting = FactoryGirl.create(:planting, garden: garden, owner: member)
photo = FactoryGirl.create(:photo, owner: member)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).not_to be_present
Photo.last.plantings.first.should eq planting
end
it "creates the harvest/photo link" do
member = FactoryGirl.create(:member)
controller.stub(:current_member) { member }
harvest = FactoryGirl.create(:harvest, owner: member)
photo = FactoryGirl.create(:photo, owner: member)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).not_to be_present
Photo.last.harvests.first.should eq harvest
end
end
describe "with mismatched owners" do
it "creates the planting/photo link" do
# members will be auto-created, and different
planting = FactoryGirl.create(:planting)
photo = FactoryGirl.create(:photo)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).to be_present
Photo.last.plantings.first.should_not eq planting
end
it "creates the harvest/photo link" do
# members will be auto-created, and different
harvest = FactoryGirl.create(:harvest)
photo = FactoryGirl.create(:photo)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).to be_present
Photo.last.harvests.first.should_not eq harvest
end
end
end
end
Corrected description in spec
## DEPRECATION NOTICE: Do not add new tests to this file!
##
## View and controller tests are deprecated in the Growstuff project.
## We no longer write new view and controller tests, but instead write
## feature tests (in spec/features) using Capybara (https://github.com/jnicklas/capybara).
## These test the full stack, behaving as a browser, and require less complicated setup
## to run. Please feel free to delete old view/controller tests as they are reimplemented
## in feature tests.
##
## If you submit a pull request containing new view or controller tests, it will not be
## merged.
require 'rails_helper'
describe PhotosController do
login_member
def valid_attributes
member = FactoryGirl.create(:member)
{
"owner_id" => member.id,
"flickr_photo_id" => 1,
"title" => "Photo",
"license_name" => "CC-BY",
"thumbnail_url" => 'http://example.com/thumb.jpg',
"fullsize_url" => 'http://example.com/full.jpg',
"link_url" => 'http://example.com'
}
end
def valid_session
{}
end
describe "GET new" do
before(:each) do
@member = FactoryGirl.create(:member)
sign_in @member
@member.stub(:flickr_photos) { [[], 0] }
@member.stub(:flickr_sets) { { "foo" => "bar" } }
controller.stub(:current_member) { @member }
end
it "assigns the flickr auth as @flickr_auth" do
@auth = FactoryGirl.create(:flickr_authentication, member: @member)
get :new, {}
assigns(:flickr_auth).should be_an_instance_of(Authentication)
end
it "assigns a planting id" do
get :new, type: "planting", id: 5
assigns(:id).should eq "5"
assigns(:type).should eq "planting"
expect(flash[:alert]).not_to be_present
end
it "assigns a harvest id" do
get :new, type: "harvest", id: 5
assigns(:id).should eq "5"
assigns(:type).should eq "harvest"
expect(flash[:alert]).not_to be_present
end
it "assigns a garden id" do
get :new, type: "garden", id: 5
assigns(:id).should eq "5"
assigns(:type).should eq "garden"
expect(flash[:alert]).not_to be_present
end
it "assigns the current set as @current_set" do
get :new, set: 'foo'
assigns(:current_set).should eq "foo"
expect(flash[:alert]).not_to be_present
end
end
describe "POST create" do
before(:each) do
Photo.any_instance.stub(:flickr_metadata).and_return(title: "A Heartbreaking work of staggering genius",
license_name: "CC-BY",
license_url: "http://example.com/aybpl",
thumbnail_url: "http://example.com/thumb.jpg",
fullsize_url: "http://example.com/full.jpg",
link_url: "http://example.com")
end
describe "with valid params" do
let(:member) { FactoryGirl.create(:member) }
let(:garden) { FactoryGirl.create(:garden, owner: member) }
let(:planting) { FactoryGirl.create(:planting, garden: garden, owner: member) }
let(:harvest) { FactoryGirl.create(:harvest, owner: member) }
let(:photo) { FactoryGirl.create(:photo, owner: member) }
before { controller.stub(:current_member) { member } }
it "attaches the photo to a planting" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).not_to be_present
Photo.last.plantings.first.should eq planting
end
it "doesn't attach a photo to a planting twice" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).not_to be_present
Photo.last.plantings.size.should eq 1
end
it "attaches the photo to a harvest" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).not_to be_present
Photo.last.harvests.first.should eq harvest
end
it "doesn't attach a photo to a harvest twice" do
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).not_to be_present
Photo.last.harvests.size.should eq 1
end
it "doesn't attach photo to a comment" do
comment = FactoryGirl.create(:comment)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "comment", id: comment.id
expect(flash[:alert]).to be_present
end
end
describe "for the second time" do
it "does not add a photo twice" do
expect do
post :create, photo: { flickr_photo_id: 1 }
end.to change(Photo, :count).by(1)
expect do
post :create, photo: { flickr_photo_id: 1 }
end.to change(Photo, :count).by(0)
end
end
describe "with matching owners" do
it "creates the planting/photo link" do
member = FactoryGirl.create(:member)
controller.stub(:current_member) { member }
garden = FactoryGirl.create(:garden, owner: member)
planting = FactoryGirl.create(:planting, garden: garden, owner: member)
photo = FactoryGirl.create(:photo, owner: member)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).not_to be_present
Photo.last.plantings.first.should eq planting
end
it "creates the harvest/photo link" do
member = FactoryGirl.create(:member)
controller.stub(:current_member) { member }
harvest = FactoryGirl.create(:harvest, owner: member)
photo = FactoryGirl.create(:photo, owner: member)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).not_to be_present
Photo.last.harvests.first.should eq harvest
end
end
describe "with mismatched owners" do
it "does not create the planting/photo link" do
# members will be auto-created, and different
planting = FactoryGirl.create(:planting)
photo = FactoryGirl.create(:photo)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "planting", id: planting.id
expect(flash[:alert]).to be_present
Photo.last.plantings.first.should_not eq planting
end
it "does not create the harvest/photo link" do
# members will be auto-created, and different
harvest = FactoryGirl.create(:harvest)
photo = FactoryGirl.create(:photo)
post :create, photo: { flickr_photo_id: photo.flickr_photo_id }, type: "harvest", id: harvest.id
expect(flash[:alert]).to be_present
Photo.last.harvests.first.should_not eq harvest
end
end
end
end
|
require File.expand_path('../../spec_helper', __FILE__)
describe SearchController do
include SolrSpecHelper
let(:admin_project) { Factory.create(:admin_project_no_jnlps, :include_external_activities => false) }
let(:mock_semester) { Factory.create(:portal_semester, :name => "Fall") }
let(:mock_school) { Factory.create(:portal_school, :semesters => [mock_semester]) }
let(:teacher_user) { Factory.create(:confirmed_user, :login => "teacher_user") }
let(:teacher) { Factory.create(:portal_teacher, :user => teacher_user, :schools => [mock_school]) }
let(:admin_user) { Factory.next(:admin_user) }
let(:author_user) { Factory.next(:author_user) }
let(:manager_user) { Factory.next(:manager_user) }
let(:researcher_user) { Factory.next(:researcher_user) }
let(:student_user) { Factory.create(:confirmed_user, :login => "authorized_student") }
let(:student) { Factory.create(:portal_student, :user_id => student_user.id) }
let(:physics_investigation) { Factory.create(:investigation, :name => 'physics_inv', :user => author_user, :publication_status => 'published') }
let(:chemistry_investigation) { Factory.create(:investigation, :name => 'chemistry_inv', :user => author_user, :publication_status => 'published') }
let(:biology_investigation) { Factory.create(:investigation, :name => 'mathematics_inv', :user => author_user, :publication_status => 'published') }
let(:mathematics_investigation) { Factory.create(:investigation, :name => 'biology_inv', :user => author_user, :publication_status => 'published') }
let(:lines) { Factory.create(:investigation, :name => 'lines_inv', :user => author_user, :publication_status => 'published') }
let(:laws_of_motion_activity) { Factory.create(:activity, :name => 'laws_of_motion_activity' ,:investigation_id => physics_investigation.id, :user => author_user) }
let(:fluid_mechanics_activity) { Factory.create(:activity, :name => 'fluid_mechanics_activity' , :investigation_id => physics_investigation.id, :user => author_user) }
let(:thermodynamics_activity) { Factory.create(:activity, :name => 'thermodynamics_activity' , :investigation_id => physics_investigation.id, :user => author_user) }
let(:parallel_lines) { Factory.create(:activity, :name => 'parallel_lines' , :investigation_id => lines.id, :user => author_user) }
let(:external_activity1) { Factory.create(:external_activity, :name => 'external_1', :url => "http://concord.org", :publication_status => 'published', :is_official => true) }
let(:external_activity2) { Factory.create(:external_activity, :name => 'a_study_in_lines_and_curves', :url => "http://github.com", :publication_status => 'published', :is_official => true) }
let(:external_activity3) { Factory.create(:external_activity, :name => "Copy of external_1", :url => "http://concord.org", :publication_status => 'published', :is_official => false) }
before(:each) do
admin_project
sign_in teacher_user
solr_setup
clean_solar_index
end
describe "GET index" do
it "should redirect to root for students" do
student # Ensure student_user has a PortalStudent
controller.stub!(:current_visitor).and_return(student_user)
post :index
response.should redirect_to("/")
end
it "should show all study materials materials" do
all_investigations = [physics_investigation, chemistry_investigation, biology_investigation, mathematics_investigation, lines]
all_activities = [laws_of_motion_activity, fluid_mechanics_activity, thermodynamics_activity, parallel_lines]
external_activities = [external_activity1, external_activity2, external_activity3]
post :index
assert_response :success
assert_template 'index'
assigns[:investigations].should_not be_nil
assigns[:investigations_count].should be(5)
assigns[:investigations].each do |investigation|
all_investigations.should include(investigation)
end
assigns[:activities].should_not be_nil
assigns[:activities_count].should be(4)
assigns[:activities].each do |activity|
all_activities.should include(activity)
end
assigns[:external_activities].should be_nil
assigns[:external_activities_count].should be(0)
end
it "should show all study materials materials including external activities" do
all_external_activities = [external_activity1, external_activity2, external_activity3]
admin_project.include_external_activities = true
admin_project.save
post :index
assigns[:external_activities].should_not be_nil
assigns[:external_activities_count].should == 2
assigns[:external_activities].each do |ext_activity|
all_external_activities.should include(ext_activity)
end
end
it "should search investigations" do
all_investigations = [physics_investigation, chemistry_investigation, biology_investigation, mathematics_investigation, lines]
post_params = {
:material => ['investigation']
}
post :index, post_params
assigns[:investigations].should_not be_nil
assigns[:investigations_count].should be(5)
assigns[:investigations].each do |investigation|
all_investigations.should include(investigation)
end
assigns[:activities].should be_nil
assigns[:activities_count].should be(0)
end
it "should search activities" do
all_activities = [laws_of_motion_activity, fluid_mechanics_activity, thermodynamics_activity, parallel_lines]
post_params = {
:material => ['activity']
}
post :index, post_params
assigns[:investigations].should be_nil
assigns[:investigations_count].should be(0)
assigns[:activities].should_not be_nil
assigns[:activities_count].should be(4)
assigns[:activities].each do |activity|
all_activities.should include(activity)
end
end
it "should search external activities" do
all_activities = [external_activity1, external_activity2, external_activity3]
post_params = {
:material => ['external_activity']
}
post :index, post_params
assigns[:investigations].should be_nil
assigns[:investigations_count].should be(0)
assigns[:activities].should be_nil
assigns[:activities_count].should be(0)
assigns[:external_activities].should_not be_nil
assigns[:external_activities_count].should be(2)
assigns[:external_activities].each do |activity|
all_activities.should include(activity)
end
end
it 'should include contributed activities if requested' do
all_external_activities = [external_activity1, external_activity2, external_activity3]
post_params = {
:material => ['external_activity'],
:include_contributed => 1
}
post :index, post_params
assigns[:external_activities_count].should == 3
assigns[:external_activities].should include(external_activity3)
end
end
describe "POST show" do
it "should redirect to root for all the users other than teacher" do
student # Ensure student_user has a PortalStudent
controller.stub!(:current_visitor).and_return(student_user)
post_params = {
:search_term => laws_of_motion_activity.name,
:activity => 'true',
:investigation => nil
}
xhr :post, :show, post_params
response.should redirect_to(:root)
post :show, post_params
response.should redirect_to(:root)
end
it "should search all study materials materials matching the search term" do
lines
parallel_lines
external_activity2
post_params = {
:search_term => 'lines',
:material => ['activity', 'investigation', 'external_activity']
}
xhr :post, :show, post_params
assigns[:investigations_count].should be(1)
assigns[:activities_count].should be(1)
assigns[:external_activities_count].should be(1)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
end
it "should search activities matching the search term" do
post_params = {
:search_term => laws_of_motion_activity.name,
:material => ['activity']
}
xhr :post, :show, post_params
assigns(:activities_count).should be(1)
assigns(:investigations_count).should be(0)
assigns(:external_activities_count).should be(0)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
post :show, post_params
assert_template "index"
end
it "should search investigations matching the search term" do
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:investigation => 'true'
}
xhr :post, :show, post_params
assigns(:investigations_count).should be(1)
assigns(:activities_count).should be(0)
assigns(:external_activities_count).should be(0)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
post :show, post_params
assert_template "index"
end
it "should search external activities matching the search term" do
post_params = {
:search_term => external_activity1.name,
:material => ['external_activity']
}
xhr :post, :show, post_params
assigns(:investigations_count).should be(0)
assigns(:activities_count).should be(0)
assigns(:external_activities_count).should be(1)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
post :show, post_params
assert_template "index"
end
it "should wrap domain_id params into an array" do
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => "1",
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => 1,
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => ["1","2"],
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => [1,2],
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
end
end
describe "Post get_current_material_unassigned_clazzes" do
let(:physics_clazz) { Factory.create(:portal_clazz, :name => 'Physics Clazz', :course => @mock_course,:teachers => [teacher]) }
let(:chemistry_clazz) { Factory.create(:portal_clazz, :name => 'Chemistry Clazz', :course => @mock_course,:teachers => [teacher]) }
let(:mathematics_clazz) { Factory.create(:portal_clazz, :name => 'Mathematics Clazz', :course => @mock_course,:teachers => [teacher]) }
let(:investigations_for_all_clazz) do
inv = Factory.create(:investigation, :name => 'investigations_for_all_clazz', :user => author_user, :publication_status => 'published')
#assign investigations_for_all_clazz to physics class
Portal::Offering.find_or_create_by_clazz_id_and_runnable_type_and_runnable_id(physics_clazz.id,'Investigation',inv.id)
inv
end
let(:activity_for_all_clazz) do
act = Factory.create(:activity, :name => 'activity_for_all_clazz' ,:investigation_id => physics_investigation.id, :user => author_user)
#assign activity_for_all_clazz to physics class
Portal::Offering.find_or_create_by_clazz_id_and_runnable_type_and_runnable_id(physics_clazz.id,'Activity',act.id)
act
end
before(:each) do
#remove all the classes assigned to the teacher
# FIXME: This is slow, and it seems like rspec must provide a more elegant way to set this up than to reset these every time.
teacher.teacher_clazzes.each { |tc| tc.destroy }
all_classes = [physics_clazz, chemistry_clazz, mathematics_clazz]
end
it "should get all the classes to which the activity is not assigned. Material to be assigned is a single activity" do
post_params = {
:material_type => 'Activity',
:material_id => activity_for_all_clazz.id
}
xhr :post, :get_current_material_unassigned_clazzes, post_params
should render_template('_material_unassigned_clazzes')
assigns[:material].should eq [activity_for_all_clazz]
assigns[:assigned_clazzes].should eq [physics_clazz]
assigns[:unassigned_clazzes].should eq [chemistry_clazz, mathematics_clazz]
end
it "should get all the classes to which the investigation is not assigned. Material to be assigned is a single investigation" do
post_params = {
:material_type => 'Investigation',
:material_id => investigations_for_all_clazz.id
}
xhr :post, :get_current_material_unassigned_clazzes, post_params
assigns[:material].should eq [investigations_for_all_clazz]
assigns[:assigned_clazzes].should eq [physics_clazz]
assigns[:unassigned_clazzes].should eq [chemistry_clazz, mathematics_clazz]
end
it "should get all the classes to which the activity is not assigned. Material to be assigned is a multiple activity" do
another_activity_for_all_clazz = Factory.create(:activity, :name => 'another_activity_for_all_clazz' ,:investigation_id => physics_investigation.id, :user => author_user)
post_params = {
:material_type => 'Activity',
:material_id => "#{activity_for_all_clazz.id},#{another_activity_for_all_clazz.id}"
}
xhr :post, :get_current_material_unassigned_clazzes, post_params
assigns[:material].should eq [activity_for_all_clazz, another_activity_for_all_clazz]
assigns[:assigned_clazzes].should eq []
assigns[:unassigned_clazzes].should eq [physics_clazz, chemistry_clazz, mathematics_clazz]
end
end
describe "POST add_material_to_clazzes" do
let(:clazz) { Factory.create(:portal_clazz,:course => @mock_course,:teachers => [teacher]) }
let(:another_clazz) { Factory.create(:portal_clazz,:course => @mock_course,:teachers => [teacher]) }
let(:already_assigned_offering) { Factory.create(:portal_offering, :clazz_id=> clazz.id, :runnable_id=> chemistry_investigation.id, :runnable_type => 'Investigation'.classify) }
let(:another_assigned_offering) { Factory.create(:portal_offering, :clazz_id=> clazz.id, :runnable_id=> laws_of_motion_activity.id, :runnable_type => 'Investigation'.classify) }
it "should assign only unassigned investigations to the classes" do
already_assigned_offering
post_params = {
:clazz_id => [clazz.id, another_clazz.id],
:material_id => chemistry_investigation.id,
:material_type => 'Investigation'
}
xhr :post, :add_material_to_clazzes, post_params
runnable_id = post_params[:material_id]
runnable_type = post_params[:material_type].classify
offering_for_clazz = Portal::Offering.find_all_by_clazz_id_and_runnable_type_and_runnable_id(clazz.id, runnable_type, runnable_id)
offering_for_another_clazz = Portal::Offering.find_all_by_clazz_id_and_runnable_type_and_runnable_id(another_clazz.id, runnable_type, runnable_id)
offering_for_clazz.length.should be(1)
offering_for_clazz.first.should == already_assigned_offering
offering_for_another_clazz.length.should be(1)
offering_for_another_clazz.first.runnable_id.should be(chemistry_investigation.id)
offering_for_another_clazz.first.clazz_id.should be(another_clazz.id)
end
it "should assign activities to the classes" do
another_assigned_offering
post_params = {
:clazz_id => [clazz.id, another_clazz.id],
:material_id => "#{laws_of_motion_activity.id},#{fluid_mechanics_activity.id}",
:material_type => 'Activity'
}
xhr :post, :add_material_to_clazzes, post_params
runnable_ids = post_params[:material_id].split(',')
runnable_type = post_params[:material_type].classify
post_params[:clazz_id].each do |clazz_id|
runnable_ids.each do |runnable_id|
offering = Portal::Offering.find_all_by_clazz_id_and_runnable_type_and_runnable_id(clazz_id, runnable_type, runnable_id)
offering.length.should be(1)
end
end
end
end
end
(sip - failing) search_controller_spec using solr (specs running)
require File.expand_path('../../spec_helper', __FILE__)
describe SearchController do
include SolrSpecHelper
def make(let); end
let(:admin_project) { Factory.create(:admin_project_no_jnlps, :include_external_activities => false) }
let(:mock_semester) { Factory.create(:portal_semester, :name => "Fall") }
let(:mock_school) { Factory.create(:portal_school, :semesters => [mock_semester]) }
let(:teacher_user) { Factory.create(:confirmed_user, :login => "teacher_user") }
let(:teacher) { Factory.create(:portal_teacher, :user => teacher_user, :schools => [mock_school]) }
let(:admin_user) { Factory.next(:admin_user) }
let(:author_user) { Factory.next(:author_user) }
let(:manager_user) { Factory.next(:manager_user) }
let(:researcher_user) { Factory.next(:researcher_user) }
let(:student_user) { Factory.create(:confirmed_user, :login => "authorized_student") }
let(:student) { Factory.create(:portal_student, :user_id => student_user.id) }
let(:physics_investigation) { Factory.create(:investigation, :name => 'physics_inv', :user => author_user, :publication_status => 'published') }
let(:chemistry_investigation) { Factory.create(:investigation, :name => 'chemistry_inv', :user => author_user, :publication_status => 'published') }
let(:biology_investigation) { Factory.create(:investigation, :name => 'mathematics_inv', :user => author_user, :publication_status => 'published') }
let(:mathematics_investigation) { Factory.create(:investigation, :name => 'biology_inv', :user => author_user, :publication_status => 'published') }
let(:lines) { Factory.create(:investigation, :name => 'lines_inv', :user => author_user, :publication_status => 'published') }
let(:laws_of_motion_activity) { Factory.create(:activity, :name => 'laws_of_motion_activity' ,:investigation_id => physics_investigation.id, :user => author_user) }
let(:fluid_mechanics_activity) { Factory.create(:activity, :name => 'fluid_mechanics_activity' , :investigation_id => physics_investigation.id, :user => author_user) }
let(:thermodynamics_activity) { Factory.create(:activity, :name => 'thermodynamics_activity' , :investigation_id => physics_investigation.id, :user => author_user) }
let(:parallel_lines) { Factory.create(:activity, :name => 'parallel_lines' , :investigation_id => lines.id, :user => author_user) }
let(:external_activity1) { Factory.create(:external_activity, :name => 'external_1', :url => "http://concord.org", :publication_status => 'published', :is_official => true) }
let(:external_activity2) { Factory.create(:external_activity, :name => 'a_study_in_lines_and_curves', :url => "http://github.com", :publication_status => 'published', :is_official => true) }
let(:contributed_activity) { Factory.create(:external_activity, :name => "Copy of external_1", :url => "http://concord.org", :publication_status => 'published', :is_official => false) }
let(:all_investigations) { [physics_investigation, chemistry_investigation, biology_investigation, mathematics_investigation, lines]}
let(:all_activities) { [laws_of_motion_activity, fluid_mechanics_activity, thermodynamics_activity, parallel_lines, external_activity1, external_activity2]}
let(:contributed_activities){ [contributed_activity] }
let(:investigation_results) { [] }
let(:activity_results) { [] }
let(:search_results) {{ Investigation => investigation_results, Activity => activity_results }}
let(:mock_search) { mock('results', {:results => search_results})}
before(:all) do
solr_setup
clean_solar_index
end
after(:each) do
clean_solar_index
end
before(:each) do
admin_project
sign_in teacher_user
make all_investigations
make all_activities
Sunspot.commit_if_dirty
end
describe "GET index" do
describe "when its a student visiting" do
it "should redirect to root" do
student # Ensure student_user has a PortalStudent
controller.stub!(:current_visitor).and_return(student_user)
post :index
response.should redirect_to("/")
end
end
describe "searching for materials" do
let(:post_params) {{}}
before(:each) do
post :index, post_params
assert_response :success
assert_template 'index'
end
describe "with no filter parameters" do
it "should show all study materials materials" do
assigns[:investigations].should_not be_nil
assigns[:investigations_count].should be(5)
assigns[:investigations].each do |investigation|
all_investigations.should include(investigation)
end
assigns[:activities].should_not be_nil
assigns[:activities_count].should be(6)
assigns[:activities].each do |activity|
all_activities.should include(activity)
end
end
end
describe "searching only investigations" do
let(:post_params) {{:material => ['investigation']}}
let(:activity_results) {[]}
it "should return all investigations" do
assigns[:investigations].should_not be_nil
assigns[:investigations_count].should be(5)
end
it "should not return any activities" do
controller.should_receive(:new_search).and_return(mock_search)
post :index, post_params
assigns[:activities].should be_empty
assigns[:activities_count].should be(0)
end
end
describe "searching only activities" do
let(:post_params) {{:material_types => ['Activity']}}
it "should not include investigations" do
assigns[:investigations].should be_empty
assigns[:investigations_count].should be(0)
end
it "should return all activities" do
assigns[:activities].should_not be_nil
assigns[:activities_count].should be(6)
assigns[:activities].each do |activity|
all_activities.should include(activity)
end
end
describe "including contributed activities" do
let(:activity_results) {all_activities + contributed_activities}
let(:post_params) {{ :material_types => ['Activity'], :include_contributed => 1 }}
it "should include contributed activities" do
assigns[:activities_count].should == 7
assigns[:activities].should include(contributed_activity)
end
end
end
end
end
describe "POST show" do
it "should redirect to root for all the users other than teacher" do
student # Ensure student_user has a PortalStudent
controller.stub!(:current_visitor).and_return(student_user)
post_params = {
:search_term => laws_of_motion_activity.name,
:activity => 'true',
:investigation => nil
}
xhr :post, :show, post_params
response.should redirect_to(:root)
post :show, post_params
response.should redirect_to(:root)
end
it "should search all study materials materials matching the search term" do
lines
parallel_lines
external_activity2
post_params = {
:search_term => 'lines',
:material_types => ['Activity', 'Investigation']
}
xhr :post, :show, post_params
assigns[:investigations_count].should be(1)
assigns[:activities_count].should be(2)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
end
it "should search activities matching the search term" do
post_params = {
:search_term => laws_of_motion_activity.name,
:material => ['activity']
}
xhr :post, :show, post_params
assigns(:activities_count).should be(1)
assigns(:investigations_count).should be(0)
assigns(:external_activities_count).should be(0)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
post :show, post_params
assert_template "index"
end
it "should search investigations matching the search term" do
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:investigation => 'true'
}
xhr :post, :show, post_params
assigns(:investigations_count).should be(1)
assigns(:activities_count).should be(0)
assigns(:external_activities_count).should be(0)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
post :show, post_params
assert_template "index"
end
it "should search external activities matching the search term" do
post_params = {
:search_term => external_activity1.name,
:material => ['external_activity']
}
xhr :post, :show, post_params
assigns(:investigations_count).should be(0)
assigns(:activities_count).should be(0)
assigns(:external_activities_count).should be(1)
assert_select_rjs :replace_html, 'offering_list'
assert_select 'suggestions' , false
post :show, post_params
assert_template "index"
end
it "should wrap domain_id params into an array" do
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => "1",
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => 1,
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => ["1","2"],
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
post_params = {
:search_term => physics_investigation.name,
:activity => nil,
:domain_id => [1,2],
:investigation => 'true'
}
xhr :post, :show, post_params
assigns[:domain_id].should be_a_kind_of(Enumerable)
end
end
describe "Post get_current_material_unassigned_clazzes" do
let(:physics_clazz) { Factory.create(:portal_clazz, :name => 'Physics Clazz', :course => @mock_course,:teachers => [teacher]) }
let(:chemistry_clazz) { Factory.create(:portal_clazz, :name => 'Chemistry Clazz', :course => @mock_course,:teachers => [teacher]) }
let(:mathematics_clazz) { Factory.create(:portal_clazz, :name => 'Mathematics Clazz', :course => @mock_course,:teachers => [teacher]) }
let(:investigations_for_all_clazz) do
inv = Factory.create(:investigation, :name => 'investigations_for_all_clazz', :user => author_user, :publication_status => 'published')
#assign investigations_for_all_clazz to physics class
Portal::Offering.find_or_create_by_clazz_id_and_runnable_type_and_runnable_id(physics_clazz.id,'Investigation',inv.id)
inv
end
let(:activity_for_all_clazz) do
act = Factory.create(:activity, :name => 'activity_for_all_clazz' ,:investigation_id => physics_investigation.id, :user => author_user)
#assign activity_for_all_clazz to physics class
Portal::Offering.find_or_create_by_clazz_id_and_runnable_type_and_runnable_id(physics_clazz.id,'Activity',act.id)
act
end
before(:each) do
#remove all the classes assigned to the teacher
# FIXME: This is slow, and it seems like rspec must provide a more elegant way to set this up than to reset these every time.
teacher.teacher_clazzes.each { |tc| tc.destroy }
all_classes = [physics_clazz, chemistry_clazz, mathematics_clazz]
end
it "should get all the classes to which the activity is not assigned. Material to be assigned is a single activity" do
post_params = {
:material_type => 'Activity',
:material_id => activity_for_all_clazz.id
}
xhr :post, :get_current_material_unassigned_clazzes, post_params
should render_template('_material_unassigned_clazzes')
assigns[:material].should eq [activity_for_all_clazz]
assigns[:assigned_clazzes].should eq [physics_clazz]
assigns[:unassigned_clazzes].should eq [chemistry_clazz, mathematics_clazz]
end
it "should get all the classes to which the investigation is not assigned. Material to be assigned is a single investigation" do
post_params = {
:material_type => 'Investigation',
:material_id => investigations_for_all_clazz.id
}
xhr :post, :get_current_material_unassigned_clazzes, post_params
assigns[:material].should eq [investigations_for_all_clazz]
assigns[:assigned_clazzes].should eq [physics_clazz]
assigns[:unassigned_clazzes].should eq [chemistry_clazz, mathematics_clazz]
end
it "should get all the classes to which the activity is not assigned. Material to be assigned is a multiple activity" do
another_activity_for_all_clazz = Factory.create(:activity, :name => 'another_activity_for_all_clazz' ,:investigation_id => physics_investigation.id, :user => author_user)
post_params = {
:material_type => 'Activity',
:material_id => "#{activity_for_all_clazz.id},#{another_activity_for_all_clazz.id}"
}
xhr :post, :get_current_material_unassigned_clazzes, post_params
assigns[:material].should eq [activity_for_all_clazz, another_activity_for_all_clazz]
assigns[:assigned_clazzes].should eq []
assigns[:unassigned_clazzes].should eq [physics_clazz, chemistry_clazz, mathematics_clazz]
end
end
describe "POST add_material_to_clazzes" do
let(:clazz) { Factory.create(:portal_clazz,:course => @mock_course,:teachers => [teacher]) }
let(:another_clazz) { Factory.create(:portal_clazz,:course => @mock_course,:teachers => [teacher]) }
let(:already_assigned_offering) { Factory.create(:portal_offering, :clazz_id=> clazz.id, :runnable_id=> chemistry_investigation.id, :runnable_type => 'Investigation'.classify) }
let(:another_assigned_offering) { Factory.create(:portal_offering, :clazz_id=> clazz.id, :runnable_id=> laws_of_motion_activity.id, :runnable_type => 'Investigation'.classify) }
it "should assign only unassigned investigations to the classes" do
already_assigned_offering
post_params = {
:clazz_id => [clazz.id, another_clazz.id],
:material_id => chemistry_investigation.id,
:material_type => 'Investigation'
}
xhr :post, :add_material_to_clazzes, post_params
runnable_id = post_params[:material_id]
runnable_type = post_params[:material_type].classify
offering_for_clazz = Portal::Offering.find_all_by_clazz_id_and_runnable_type_and_runnable_id(clazz.id, runnable_type, runnable_id)
offering_for_another_clazz = Portal::Offering.find_all_by_clazz_id_and_runnable_type_and_runnable_id(another_clazz.id, runnable_type, runnable_id)
offering_for_clazz.length.should be(1)
offering_for_clazz.first.should == already_assigned_offering
offering_for_another_clazz.length.should be(1)
offering_for_another_clazz.first.runnable_id.should be(chemistry_investigation.id)
offering_for_another_clazz.first.clazz_id.should be(another_clazz.id)
end
it "should assign activities to the classes" do
another_assigned_offering
post_params = {
:clazz_id => [clazz.id, another_clazz.id],
:material_id => "#{laws_of_motion_activity.id},#{fluid_mechanics_activity.id}",
:material_type => 'Activity'
}
xhr :post, :add_material_to_clazzes, post_params
runnable_ids = post_params[:material_id].split(',')
runnable_type = post_params[:material_type].classify
post_params[:clazz_id].each do |clazz_id|
runnable_ids.each do |runnable_id|
offering = Portal::Offering.find_all_by_clazz_id_and_runnable_type_and_runnable_id(clazz_id, runnable_type, runnable_id)
offering.length.should be(1)
end
end
end
end
end
|
# frozen_string_literal: true
require 'faraday'
module Twilio
module HTTP
class Client
attr_accessor :adapter
attr_reader :timeout, :last_response, :last_request
def initialize(proxy_addr = nil, proxy_port = nil, proxy_user = nil, proxy_pass = nil, ssl_ca_file = nil,
timeout: nil)
@proxy_addr = proxy_addr
@proxy_port = proxy_port
@proxy_user = proxy_user
@proxy_pass = proxy_pass
@ssl_ca_file = ssl_ca_file
@timeout = timeout
@adapter = Faraday.default_adapter
end
def _request(request)
@connection = Faraday.new(url: request.host + ':' + request.port.to_s, ssl: { verify: true }) do |f|
f.options.params_encoder = Faraday::FlatParamsEncoder
f.request :url_encoded
f.adapter @adapter
f.headers = request.headers
f.basic_auth(request.auth[0], request.auth[1])
if @proxy_addr
f.proxy "#{@proxy_user}:#{@proxy_pass}@#{@proxy_addr}:#{@proxy_port}"
end
f.options.open_timeout = request.timeout || @timeout
f.options.timeout = request.timeout || @timeout
end
@last_request = request
@last_response = nil
response = @connection.send(request.method.downcase.to_sym,
request.url,
request.method == 'GET' ? request.params : request.data)
if response.body && !response.body.empty?
object = response.body
elsif response.status == 400
object = { message: 'Bad request', code: 400 }.to_json
end
twilio_response = Twilio::Response.new(response.status, object, headers: response.headers)
@last_response = twilio_response
twilio_response
end
def request(host, port, method, url, params = {}, data = {}, headers = {}, auth = nil, timeout = nil)
request = Twilio::Request.new(host, port, method, url, params, data, headers, auth, timeout)
_request(request)
end
end
end
end
breaking: Added proxy protocol to HTTP Client constructor (#399)
# frozen_string_literal: true
require 'faraday'
module Twilio
module HTTP
class Client
attr_accessor :adapter
attr_reader :timeout, :last_response, :last_request
def initialize(proxy_prot = nil, proxy_addr = nil, proxy_port = nil, proxy_user = nil, proxy_pass = nil, ssl_ca_file = nil,
timeout: nil)
@proxy_prot = proxy_prot
@proxy_addr = proxy_addr
@proxy_port = proxy_port
@proxy_user = proxy_user
@proxy_pass = proxy_pass
@ssl_ca_file = ssl_ca_file
@timeout = timeout
@adapter = Faraday.default_adapter
end
def _request(request)
@connection = Faraday.new(url: request.host + ':' + request.port.to_s, ssl: { verify: true }) do |f|
f.options.params_encoder = Faraday::FlatParamsEncoder
f.request :url_encoded
f.adapter @adapter
f.headers = request.headers
f.basic_auth(request.auth[0], request.auth[1])
if @proxy_addr
f.proxy = "#{@proxy_prot}://#{@proxy_user}:#{@proxy_pass}@#{@proxy_addr}:#{@proxy_port}"
end
f.options.open_timeout = request.timeout || @timeout
f.options.timeout = request.timeout || @timeout
end
@last_request = request
@last_response = nil
response = @connection.send(request.method.downcase.to_sym,
request.url,
request.method == 'GET' ? request.params : request.data)
if response.body && !response.body.empty?
object = response.body
elsif response.status == 400
object = { message: 'Bad request', code: 400 }.to_json
end
twilio_response = Twilio::Response.new(response.status, object, headers: response.headers)
@last_response = twilio_response
twilio_response
end
def request(host, port, method, url, params = {}, data = {}, headers = {}, auth = nil, timeout = nil)
request = Twilio::Request.new(host, port, method, url, params, data, headers, auth, timeout)
_request(request)
end
end
end
end
|
module Twostroke::Runtime
Lib.register do |scope|
obj = Types::StringObject.constructor_function
scope.set_var "String", obj
proto = Types::Object.new
# String.prototype.toString
proto.proto_put "toString", Types::Function.new(->(scope, this, args) {
if this.is_a?(Types::StringObject)
Types::String.new(this.string)
else
Lib.throw_type_error "String.prototype.toString is not generic"
end
}, nil, "toString", [])
# String.prototype.valueOf
proto.proto_put "valueOf", Types::Function.new(->(scope, this, args) { this.is_a?(Types::StringObject) ? Types::String.new(this.string) : Types.to_primitive(this) }, nil, "valueOf", [])
# String.prototype.split
proto.proto_put "split", Types::Function.new(->(scope, this, args) {
sep = Types.to_string(args[0] || Types::Undefined.new).string
str = Types.to_string(this).string
Types::Array.new (if args[1]
str.split sep, Types.to_uint32(args[1])
else
str.split sep
end).map { |s| Types::String.new s }
}, nil, "split", [])
# String.prototype.length
proto.define_own_property "length", get: ->(this) { Types::Number.new this.string.size }, writable: false, enumerable: false
# String.prototype.replace
proto.proto_put "replace", Types::Function.new(->(scope, this, args) {
sobj = Types.to_string(this)
s = sobj.string
find = args[0] || Types::Undefined.new
re = find.is_a?(Types::RegExp) ? find.regexp : Regexp.new(Regexp.escape Types.to_string(find).string)
global = find.is_a?(Types::RegExp) && find.global
replace = args[1] || Types::Undefined.new
callback = replace.respond_to?(:call) ? replace : ->(*_) { replace }
retn = ""
offset = 0
loop do
md = re.match s, offset
break unless md && (offset.zero? || global)
retn << md.pre_match[offset..-1]
retn << Types.to_string(callback.(scope, nil, [*md.to_a.map { |c| Types::String.new(c || "") }, Types::Number.new(md.begin 0), sobj])).string
offset = md.end 0
end
retn << s[offset..-1]
Types::String.new retn
}, nil, "replace", [])
# String.prototype.substring
proto.proto_put "substring", Types::Function.new(->(scope, this, args) {
indexA = args[0] && Types.to_int32(args[0])
indexB = args[1] && Types.to_int32(args[1])
str = Types.to_string(this).string
return Types::String.new(str) unless indexA
return Types::String.new(str[indexA..-1] || "") unless indexB
indexA, indexB = indexB, indexA if indexB < indexA
Types::String.new(str[indexA...indexB] || "")
}, nil, "substring", [])
# String.prototype.substr
proto.proto_put "substr", Types::Function.new(->(scope, this, args) {
index = args[0] && Types.to_int32(args[0])
len = args[1] && Types.to_uint32(args[1])
str = Types.to_string(this).string
return Types::String.new(str) unless index
return Types::String.new(str[index..-1] || "") unless len
Types::String.new(str[index, len] || "")
}, nil, "substr", [])
# String.prototype.slice
proto.proto_put "slice", Types::Function.new(->(scope, this, args) {
sobj = Types.to_string(this)
s = sobj.string
if args[0].nil?
sobj
else
start = Types.to_int32 args[0]
if args[1]
fin = Types.to_int32 args[1]
Types::String.new s[start...fin]
else
Types::String.new s[start..-1]
end
end
}, nil, "slice", [])
# String.prototype.indexOf
proto.proto_put "indexOf", Types::Function.new(->(scope, this, args) {
idx = args[1] ? Types.to_int32(args[1]) : 0
Types::Number.new(Types.to_string(this).string.index(Types.to_string(args[0] || Types::Undefined.new).string, idx) || -1)
}, nil, "indexOf", [])
# String.prototype.lastIndexOf
proto.proto_put "lastIndexOf", Types::Function.new(->(scope, this, args) {
idx = args[1] ? Types.to_int32(args[1]) : -1
Types::Number.new(Types.to_string(this).string.rindex(Types.to_string(args[0] || Types::Undefined.new).string, idx) || -1)
}, nil, "lastIndexOf", [])
# String.prototype.charAt
proto.proto_put "charAt", Types::Function.new(->(scope, this, args) {
idx = args[0] ? Types.to_int32(args[0]) : 0
str = Types.to_string(this).string
if idx < 0 or idx >= str.length
Types::String.new ""
else
Types::String.new str[idx]
end
}, nil, "charAt", [])
# String.prototype.charAt
proto.proto_put "charCodeAt", Types::Function.new(->(scope, this, args) {
idx = args[0] ? Types.to_int32(args[0]) : 0
str = Types.to_string(this).string
if idx < 0 or idx >= str.length
Types::Number.new Float::NAN
else
Types::Number.new str[idx].ord
end
}, nil, "charCodeAt", [])
# String.prototype.match
proto.proto_put "match", Types::Function.new(->(scope, this, args) {
re = args[0] || Types::Undefined.new
re = Types::RegExp.constructor_function.(nil, nil, re) unless re.is_a?(Types::RegExp)
unless re.global
# same as re.exec(str) in this case
Types::RegExp.exec(nil, re, [this])
else
Types::RegExp.all_matches(nil, re, [this])
end
}, nil, "match", [])
# String.prototype.toUpperCase
proto.proto_put "toUpperCase", Types::Function.new(->(scope, this, args) {
Types::String.new Types.to_string(this).string.upcase
}, nil, "toUpperCase", [])
# String.prototype.toUpperCase
proto.proto_put "toLowerCase", Types::Function.new(->(scope, this, args) {
Types::String.new Types.to_string(this).string.downcase
}, nil, "toLowerCase", [])
obj.proto_put "prototype", proto
obj.proto_put "fromCharCode", Types::Function.new(->(scope, this, args) {
Types::String.new args.map { |a| Types.to_number(a).number.to_i.chr "utf-8" }.join
}, nil, "fromCharCode", [])
end
end
TIL about anonymous splat syntax
module Twostroke::Runtime
Lib.register do |scope|
obj = Types::StringObject.constructor_function
scope.set_var "String", obj
proto = Types::Object.new
# String.prototype.toString
proto.proto_put "toString", Types::Function.new(->(scope, this, args) {
if this.is_a?(Types::StringObject)
Types::String.new(this.string)
else
Lib.throw_type_error "String.prototype.toString is not generic"
end
}, nil, "toString", [])
# String.prototype.valueOf
proto.proto_put "valueOf", Types::Function.new(->(scope, this, args) { this.is_a?(Types::StringObject) ? Types::String.new(this.string) : Types.to_primitive(this) }, nil, "valueOf", [])
# String.prototype.split
proto.proto_put "split", Types::Function.new(->(scope, this, args) {
sep = Types.to_string(args[0] || Types::Undefined.new).string
str = Types.to_string(this).string
Types::Array.new (if args[1]
str.split sep, Types.to_uint32(args[1])
else
str.split sep
end).map { |s| Types::String.new s }
}, nil, "split", [])
# String.prototype.length
proto.define_own_property "length", get: ->(this) { Types::Number.new this.string.size }, writable: false, enumerable: false
# String.prototype.replace
proto.proto_put "replace", Types::Function.new(->(scope, this, args) {
sobj = Types.to_string(this)
s = sobj.string
find = args[0] || Types::Undefined.new
re = find.is_a?(Types::RegExp) ? find.regexp : Regexp.new(Regexp.escape Types.to_string(find).string)
global = find.is_a?(Types::RegExp) && find.global
replace = args[1] || Types::Undefined.new
callback = replace.respond_to?(:call) ? replace : ->* { replace }
retn = ""
offset = 0
loop do
md = re.match s, offset
break unless md && (offset.zero? || global)
retn << md.pre_match[offset..-1]
retn << Types.to_string(callback.(scope, nil, [*md.to_a.map { |c| Types::String.new(c || "") }, Types::Number.new(md.begin 0), sobj])).string
offset = md.end 0
end
retn << s[offset..-1]
Types::String.new retn
}, nil, "replace", [])
# String.prototype.substring
proto.proto_put "substring", Types::Function.new(->(scope, this, args) {
indexA = args[0] && Types.to_int32(args[0])
indexB = args[1] && Types.to_int32(args[1])
str = Types.to_string(this).string
return Types::String.new(str) unless indexA
return Types::String.new(str[indexA..-1] || "") unless indexB
indexA, indexB = indexB, indexA if indexB < indexA
Types::String.new(str[indexA...indexB] || "")
}, nil, "substring", [])
# String.prototype.substr
proto.proto_put "substr", Types::Function.new(->(scope, this, args) {
index = args[0] && Types.to_int32(args[0])
len = args[1] && Types.to_uint32(args[1])
str = Types.to_string(this).string
return Types::String.new(str) unless index
return Types::String.new(str[index..-1] || "") unless len
Types::String.new(str[index, len] || "")
}, nil, "substr", [])
# String.prototype.slice
proto.proto_put "slice", Types::Function.new(->(scope, this, args) {
sobj = Types.to_string(this)
s = sobj.string
if args[0].nil?
sobj
else
start = Types.to_int32 args[0]
if args[1]
fin = Types.to_int32 args[1]
Types::String.new s[start...fin]
else
Types::String.new s[start..-1]
end
end
}, nil, "slice", [])
# String.prototype.indexOf
proto.proto_put "indexOf", Types::Function.new(->(scope, this, args) {
idx = args[1] ? Types.to_int32(args[1]) : 0
Types::Number.new(Types.to_string(this).string.index(Types.to_string(args[0] || Types::Undefined.new).string, idx) || -1)
}, nil, "indexOf", [])
# String.prototype.lastIndexOf
proto.proto_put "lastIndexOf", Types::Function.new(->(scope, this, args) {
idx = args[1] ? Types.to_int32(args[1]) : -1
Types::Number.new(Types.to_string(this).string.rindex(Types.to_string(args[0] || Types::Undefined.new).string, idx) || -1)
}, nil, "lastIndexOf", [])
# String.prototype.charAt
proto.proto_put "charAt", Types::Function.new(->(scope, this, args) {
idx = args[0] ? Types.to_int32(args[0]) : 0
str = Types.to_string(this).string
if idx < 0 or idx >= str.length
Types::String.new ""
else
Types::String.new str[idx]
end
}, nil, "charAt", [])
# String.prototype.charAt
proto.proto_put "charCodeAt", Types::Function.new(->(scope, this, args) {
idx = args[0] ? Types.to_int32(args[0]) : 0
str = Types.to_string(this).string
if idx < 0 or idx >= str.length
Types::Number.new Float::NAN
else
Types::Number.new str[idx].ord
end
}, nil, "charCodeAt", [])
# String.prototype.match
proto.proto_put "match", Types::Function.new(->(scope, this, args) {
re = args[0] || Types::Undefined.new
re = Types::RegExp.constructor_function.(nil, nil, re) unless re.is_a?(Types::RegExp)
unless re.global
# same as re.exec(str) in this case
Types::RegExp.exec(nil, re, [this])
else
Types::RegExp.all_matches(nil, re, [this])
end
}, nil, "match", [])
# String.prototype.toUpperCase
proto.proto_put "toUpperCase", Types::Function.new(->(scope, this, args) {
Types::String.new Types.to_string(this).string.upcase
}, nil, "toUpperCase", [])
# String.prototype.toUpperCase
proto.proto_put "toLowerCase", Types::Function.new(->(scope, this, args) {
Types::String.new Types.to_string(this).string.downcase
}, nil, "toLowerCase", [])
obj.proto_put "prototype", proto
obj.proto_put "fromCharCode", Types::Function.new(->(scope, this, args) {
Types::String.new args.map { |a| Types.to_number(a).number.to_i.chr "utf-8" }.join
}, nil, "fromCharCode", [])
end
end |
# -*- coding: utf-8 -*-
require "zlib"
class Commit
attr_accessor :oid, :parents, :msg, :committer, :author
def initialize
@parents = []
end
def to_hash
{
:oid => @oid,
:parents => @parents,
:msg => @msg,
:committer => @committer,
:author => @author
}
end
def self.parse str
c = Commit.new
str.each_line{|line|
case line
when /^parent (.+)/ ; c.parents << $1
when /^committer (.+)/ ; c.committer = $1
when /^author (.+)/ ; c.author = $1
end
}
msg = str.split("\n\n")[1]
c.msg = msg
c
end
end
class Git
def initialize dir
@dir = File.expand_path(dir)
@branches = []
@tags = []
@commits = []
end
def read_file path
File.read(File.join(@dir, ".git", path))
end
def read_file_bin path
File.binread File.join(@dir, ".git", path)
end
def file_path path
File.join(@dir, ".git", path)
end
def get_br_cid br_name
if File.exist?(file_path("/refs/heads/#{br_name}"))
return read_file("/refs/heads/#{br_name}").chomp
end
# fallback
# see:
# Git - メインテナンスとデータリカバリ
# https://git-scm.com/book/ja/v1/Git%E3%81%AE%E5%86%85%E5%81%B4-%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%86%E3%83%8A%E3%83%B3%E3%82%B9%E3%81%A8%E3%83%87%E3%83%BC%E3%82%BF%E3%83%AA%E3%82%AB%E3%83%90%E3%83%AA
str = read_file("packed-refs");
cid = nil
str.each_line {|line|
if %r{.+/(.+)$} =~ line
name = $1
if name == br_name
/^(.+) / =~ line
cid = $1
break
end
end
}
raise "cid for (#{br_name}) not found" if cid.nil?
cid
end
def get_tag_cid br_name
read_file("/refs/tags/#{br_name}").chomp
end
def get_branches
Dir.glob(@dir + "/.git/refs/heads/*").map{|path|
name = File.basename(path)
{
:name => name,
:cid => get_br_cid(name)
}
}
end
def get_tags
Dir.glob(@dir + "/.git/refs/tags/*").map{|path|
name = File.basename(path)
{
:name => name,
:cid => get_tag_cid(name)
}
}
end
def to_hash
{
:dir => @dir,
:branches => @branches,
:tags => @tags,
:commits => @commits,
:head => @head
}
end
def read_object_bin oid
/^(..)(.+)$/ =~ oid
index, name = $1, $2
compressed = read_file_bin("objects/#{index}/#{name}")
Zlib::Inflate.inflate compressed
end
def read_head_oid
br_name = File.basename(read_file("HEAD").chomp)
read_file("refs/heads/#{br_name}").chomp
end
def load_commit commits, oid
if oid.nil? || commits.has_key?(oid)
return commits
end
bin = read_object_bin(oid)
/\A(.+?)\x00(.+)\Z/m =~ bin
head, body = $1, $2
c = Commit.parse(body)
c.oid = oid
commits[oid] = c
commits = load_commit(commits, c.parents[0])
commits = load_commit(commits, c.parents[1])
commits
end
def load_commits_br commits, br_name
br_head_oid = read_file("refs/heads/#{br_name}").chomp
load_commit(commits, br_head_oid)
end
def load_commits_tag commits, tag_name
tag_head_oid = read_file("refs/tags/#{tag_name}").chomp
load_commit(commits, tag_head_oid)
end
def load
@branches = get_branches()
@tags = get_tags()
_commits = {}
@branches.each do |br|
_commits = load_commits_br(_commits, br[:name])
end
@tags.each do |tag|
_commits = load_commits_tag(_commits, tag[:name])
end
@commits = _commits.values.map{|commit|
commit.to_hash
}
@head = read_head_oid()
end
end
if __FILE__ == $0
require "pp"
dir = ARGV[0]
git = Git.new(dir)
git.load
pp git.to_hash
end
rename: oid => cid
# -*- coding: utf-8 -*-
require "zlib"
class Commit
attr_accessor :cid, :parents, :msg, :committer, :author
def initialize
@parents = []
end
def to_hash
{
:cid => @cid,
:parents => @parents,
:msg => @msg,
:committer => @committer,
:author => @author
}
end
def self.parse str
c = Commit.new
str.each_line{|line|
case line
when /^parent (.+)/ ; c.parents << $1
when /^committer (.+)/ ; c.committer = $1
when /^author (.+)/ ; c.author = $1
end
}
msg = str.split("\n\n")[1]
c.msg = msg
c
end
end
class Git
def initialize dir
@dir = File.expand_path(dir)
@branches = []
@tags = []
@commits = []
end
def read_file path
File.read(File.join(@dir, ".git", path))
end
def read_file_bin path
File.binread File.join(@dir, ".git", path)
end
def file_path path
File.join(@dir, ".git", path)
end
def get_br_cid br_name
if File.exist?(file_path("/refs/heads/#{br_name}"))
return read_file("/refs/heads/#{br_name}").chomp
end
# fallback
# see:
# Git - メインテナンスとデータリカバリ
# https://git-scm.com/book/ja/v1/Git%E3%81%AE%E5%86%85%E5%81%B4-%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%86%E3%83%8A%E3%83%B3%E3%82%B9%E3%81%A8%E3%83%87%E3%83%BC%E3%82%BF%E3%83%AA%E3%82%AB%E3%83%90%E3%83%AA
str = read_file("packed-refs");
cid = nil
str.each_line {|line|
if %r{.+/(.+)$} =~ line
name = $1
if name == br_name
/^(.+) / =~ line
cid = $1
break
end
end
}
raise "cid for (#{br_name}) not found" if cid.nil?
cid
end
def get_tag_cid br_name
read_file("/refs/tags/#{br_name}").chomp
end
def get_branches
Dir.glob(@dir + "/.git/refs/heads/*").map{|path|
name = File.basename(path)
{
:name => name,
:cid => get_br_cid(name)
}
}
end
def get_tags
Dir.glob(@dir + "/.git/refs/tags/*").map{|path|
name = File.basename(path)
{
:name => name,
:cid => get_tag_cid(name)
}
}
end
def to_hash
{
:dir => @dir,
:branches => @branches,
:tags => @tags,
:commits => @commits,
:head => @head
}
end
def read_object_bin oid
/^(..)(.+)$/ =~ oid
index, name = $1, $2
compressed = read_file_bin("objects/#{index}/#{name}")
Zlib::Inflate.inflate compressed
end
def read_head_oid
br_name = File.basename(read_file("HEAD").chomp)
read_file("refs/heads/#{br_name}").chomp
end
def load_commit commits, oid
if oid.nil? || commits.has_key?(oid)
return commits
end
bin = read_object_bin(oid)
/\A(.+?)\x00(.+)\Z/m =~ bin
head, body = $1, $2
c = Commit.parse(body)
c.cid = oid
commits[oid] = c
commits = load_commit(commits, c.parents[0])
commits = load_commit(commits, c.parents[1])
commits
end
def load_commits_br commits, br_name
br_head_oid = read_file("refs/heads/#{br_name}").chomp
load_commit(commits, br_head_oid)
end
def load_commits_tag commits, tag_name
tag_head_oid = read_file("refs/tags/#{tag_name}").chomp
load_commit(commits, tag_head_oid)
end
def load
@branches = get_branches()
@tags = get_tags()
_commits = {}
@branches.each do |br|
_commits = load_commits_br(_commits, br[:name])
end
@tags.each do |tag|
_commits = load_commits_tag(_commits, tag[:name])
end
@commits = _commits.values.map{|commit|
commit.to_hash
}
@head = read_head_oid()
end
end
if __FILE__ == $0
require "pp"
dir = ARGV[0]
git = Git.new(dir)
git.load
pp git.to_hash
end
|
module UkAccountValidator
VERSION = '0.0.5'
end
Bump version
module UkAccountValidator
VERSION = '0.0.6'
end
|
# frozen_string_literal: true
module VagrantPlugins
module AnsibleAuto
VERSION = '0.2.1'.freeze
end
end
Bump version to 0.2.2
# frozen_string_literal: true
module VagrantPlugins
module AnsibleAuto
VERSION = '0.2.2'.freeze
end
end
|
module VagrantPlugins
module Mountaineer
# Vagrant project registry
class Registry
I18N_KEY = 'vagrant_mountaineer.registry'.freeze
attr_accessor :projects
def initialize(env)
@projects = {}
@env = env
end
def read_projectfile(projectfile)
instance_eval(projectfile.path.read)
end
private
def options_warning(name)
@env.ui.warn I18n.t("#{I18N_KEY}.err_configuration", name: name)
@env.ui.warn I18n.t("#{I18N_KEY}.def_ignored")
@env.ui.warn ''
end
def project(name, options = nil)
options = {} unless options.is_a?(Hash)
return options_warning(name) unless valid_options?(options)
options[:name] = name
@projects[name] = options
end
def valid_options?(options)
return false unless options[:guestpath].is_a?(String)
return false unless options[:hostpath].is_a?(String)
return false if options[:guestpath].empty?
return false if options[:hostpath].empty?
true
end
end
end
end
improves method/variable naming
module VagrantPlugins
module Mountaineer
# Vagrant project registry
class Registry
I18N_KEY = 'vagrant_mountaineer.registry'.freeze
attr_accessor :projects
def initialize(env)
@projects = {}
@env = env
end
def read_projectfile(projectfile)
instance_eval(projectfile.path.read)
end
private
def config_warning(name)
@env.ui.warn I18n.t("#{I18N_KEY}.err_configuration", name: name)
@env.ui.warn I18n.t("#{I18N_KEY}.def_ignored")
@env.ui.warn ''
end
def project(name, config = nil)
config = {} unless config.is_a?(Hash)
return config_warning(name) unless valid_config?(config)
config[:name] = name
@projects[name] = config
end
def valid_config?(config)
return false unless config[:guestpath].is_a?(String)
return false unless config[:hostpath].is_a?(String)
return false if config[:guestpath].empty?
return false if config[:hostpath].empty?
true
end
end
end
end
|
require 'vcloud'
require 'hashdiff'
module Vcloud
class EdgeGatewayServices
def initialize
@config_loader = Vcloud::ConfigLoader.new
end
def self.edge_gateway_services
[
:FirewallService,
:NatService,
]
end
def update(config_file = nil, options = {})
config = translate_yaml_input(config_file)
edge_gateway = Core::EdgeGateway.get_by_name config[:gateway]
diff_output = diff(config_file)
skipped_service_count = 0
EdgeGatewayServices.edge_gateway_services.each do |service|
# Skip services whose configuration has not changed, or that
# are not specified in our source configuration.
if diff_output[service].empty? or not config.key?(service)
skipped_service_count += 1
config.delete(service)
end
end
if skipped_service_count == EdgeGatewayServices.edge_gateway_services.size
Vcloud.logger.info("EdgeGatewayServices.update: Configuration is already up to date. Skipping.")
else
edge_gateway.update_configuration config
end
end
def diff(config_file)
local_config = translate_yaml_input config_file
edge_gateway = Core::EdgeGateway.get_by_name local_config[:gateway]
remote_config = edge_gateway.vcloud_attributes[:Configuration][:EdgeGatewayServiceConfiguration]
diff = {}
EdgeGatewayServices.edge_gateway_services.each do |service|
local = local_config[service]
remote = remote_config[service]
differ = EdgeGateway::ConfigurationDiffer.new(local, remote)
diff[service] = differ.diff
end
diff
end
private
def translate_yaml_input(config_file)
config = @config_loader.load_config(config_file, Vcloud::Schema::EDGE_GATEWAY_SERVICES)
nat_service_config = EdgeGateway::ConfigurationGenerator::NatService.new(config[:gateway], config[:nat_service]).generate_fog_config
firewall_service_config = EdgeGateway::ConfigurationGenerator::FirewallService.new.generate_fog_config(config[:firewall_service])
out = { gateway: config[:gateway] }
out[:FirewallService] = firewall_service_config unless firewall_service_config.nil?
out[:NatService] = nat_service_config unless nat_service_config.nil?
out
end
end
end
Call Differ directly instead of via diff
We want to use the Differ class instead of the diff method so this small change means no code calls it.
We had to comment out the unit test because they are tied very closely to the implementation - they expect the object to call certain methods etc, which is exactly what we are changing. We are using the integration test to check our refactor - that is green after this change.
require 'vcloud'
require 'hashdiff'
module Vcloud
class EdgeGatewayServices
def initialize
@config_loader = Vcloud::ConfigLoader.new
end
def self.edge_gateway_services
[
:FirewallService,
:NatService,
]
end
def update(config_file = nil, options = {})
config = translate_yaml_input(config_file)
edge_gateway = Core::EdgeGateway.get_by_name config[:gateway]
remote_config = edge_gateway.vcloud_attributes[:Configuration][:EdgeGatewayServiceConfiguration]
diff_output = {}
EdgeGatewayServices.edge_gateway_services.each do |service|
local = config[service]
remote = remote_config[service]
differ = EdgeGateway::ConfigurationDiffer.new(local, remote)
diff_output[service] = differ.diff
end
skipped_service_count = 0
EdgeGatewayServices.edge_gateway_services.each do |service|
# Skip services whose configuration has not changed, or that
# are not specified in our source configuration.
if diff_output[service].empty? or not config.key?(service)
skipped_service_count += 1
config.delete(service)
end
end
if skipped_service_count == EdgeGatewayServices.edge_gateway_services.size
Vcloud.logger.info("EdgeGatewayServices.update: Configuration is already up to date. Skipping.")
else
edge_gateway.update_configuration config
end
end
def diff(config_file)
local_config = translate_yaml_input config_file
edge_gateway = Core::EdgeGateway.get_by_name local_config[:gateway]
remote_config = edge_gateway.vcloud_attributes[:Configuration][:EdgeGatewayServiceConfiguration]
diff = {}
EdgeGatewayServices.edge_gateway_services.each do |service|
local = local_config[service]
remote = remote_config[service]
differ = EdgeGateway::ConfigurationDiffer.new(local, remote)
diff[service] = differ.diff
end
diff
end
private
def translate_yaml_input(config_file)
config = @config_loader.load_config(config_file, Vcloud::Schema::EDGE_GATEWAY_SERVICES)
nat_service_config = EdgeGateway::ConfigurationGenerator::NatService.new(config[:gateway], config[:nat_service]).generate_fog_config
firewall_service_config = EdgeGateway::ConfigurationGenerator::FirewallService.new.generate_fog_config(config[:firewall_service])
out = { gateway: config[:gateway] }
out[:FirewallService] = firewall_service_config unless firewall_service_config.nil?
out[:NatService] = nat_service_config unless nat_service_config.nil?
out
end
end
end
|
class Wakame::Command::ActionStatus
include Wakame::Command
def run
walk_subactions = proc { |a, level|
res = a.dump_attrs
unless a.subactions.empty?
res[:subactions] = a.subactions.collect { |s|
walk_subactions.call(s, level + 1)
}
end
res
}
StatusDB.barrier {
result = {}
master.action_manager.active_jobs.each { |id, v|
result[id]={}
(v.keys - [:root_action]).each { |k|
result[id][k]=v[k]
}
result[id][:root_action] = walk_subactions.call(v[:root_action], 0)
}
@status = result
@status
}
end
end
Fix the class reference.
class Wakame::Command::ActionStatus
include Wakame::Command
def run
walk_subactions = proc { |a, level|
res = a.dump_attrs
unless a.subactions.empty?
res[:subactions] = a.subactions.collect { |s|
walk_subactions.call(s, level + 1)
}
end
res
}
Wakame::StatusDB.barrier {
result = {}
master.action_manager.active_jobs.each { |id, v|
result[id]={}
(v.keys - [:root_action]).each { |k|
result[id][k]=v[k]
}
result[id][:root_action] = walk_subactions.call(v[:root_action], 0)
}
@status = result
@status
}
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "foma"
s.version = "0.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Marius L. J\u{f8}hndal"]
s.date = "2012-01-26"
s.description = "A wrapper for the FOMA finite state library"
s.email = "mariuslj (at) ifi [dot] uio (dot) no"
s.extensions = ["ext/extconf.rb"]
s.extra_rdoc_files = [
"README.rdoc"
]
s.files = [
"CHANGELOG",
"README.rdoc",
"Rakefile",
"VERSION",
"ext/extconf.rb",
"ext/foma.c",
"foma.gemspec",
"test/.gitignore",
"test/test_foma.bin",
"test/test_foma.rb"
]
s.homepage = "http://github.com/mlj/ruby-foma"
s.require_paths = ["lib"]
s.rubyforge_project = "foma"
s.rubygems_version = "1.8.11"
s.summary = "FOMA finite state library interface"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
Regenerate gemspec for version 0.2.1
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "foma"
s.version = "0.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Marius L. J\u{f8}hndal"]
s.date = "2012-08-16"
s.description = "A wrapper for the FOMA finite state library"
s.email = "mariuslj (at) ifi [dot] uio (dot) no"
s.extensions = ["ext/extconf.rb"]
s.extra_rdoc_files = [
"README.rdoc"
]
s.files = [
"CHANGELOG",
"README.rdoc",
"Rakefile",
"VERSION",
"ext/extconf.rb",
"ext/foma.c",
"foma.gemspec",
"test/.gitignore",
"test/test_foma.bin",
"test/test_foma.rb"
]
s.homepage = "http://github.com/mlj/ruby-foma"
s.require_paths = ["lib"]
s.rubyforge_project = "foma"
s.rubygems_version = "1.8.11"
s.summary = "FOMA finite state library interface"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
# frozen_string_literal: true
require 'forwardable'
require_relative 'api_error'
module WCC::API
class RestClient
class AbstractResponse
extend ::Forwardable
attr_reader :raw_response
attr_reader :raw_body
attr_reader :client
attr_reader :request
def_delegators :raw_response, :status, :headers
alias_method :code, :status
def body
@body ||= ::JSON.parse(raw_body)
end
alias_method :to_json, :body
def initialize(client, request, raw_response)
@client = client
@request = request
@raw_response = raw_response
@raw_body = raw_response.body.to_s
end
def skip
throw new NotImplementedError, 'Please implement "skip" parsing in response class'
end
def count
throw new NotImplementedError, 'Please implement "count" parsing in response class'
end
def collection_response?
page_items.nil? ? false : true
end
def page_items
throw new NotImplementedError, 'Please implement "page_items" parsing in response class'
end
def error_message
parsed_message =
begin
body.dig('error', 'message') || body.dig('message')
rescue ::JSON::ParserError
nil
end
parsed_message || "#{code}: #{raw_response.body}"
end
def next_page?
return false unless collection_response?
return false if count.nil?
page_items.length + skip < count
end
def next_page
return unless next_page?
next_page ||= @client.get(
@request[:url],
(@request[:query] || {}).merge(next_page_query)
)
next_page.assert_ok!
end
def assert_ok!
return self if code >= 200 && code < 300
raise ApiError[code], self
end
# This method has a bit of complexity that is better kept in one location
def each_page(&block)
raise ArgumentError, 'Not a collection response' unless collection_response?
ret = PaginatingEnumerable.new(self)
if block_given?
ret.map(&block)
else
ret.lazy
end
end
def items
return unless collection_response?
each_page.flat_map(&:page_items)
end
def first
raise ArgumentError, 'Not a collection response' unless collection_response?
page_items.first
end
def next_page_query
return unless collection_response?
{
skip: page_items.length + skip
}
end
end
class DefaultResponse < AbstractResponse
def skip
body['skip']
end
def count
body['total']
end
def page_items
body['items']
end
end
class PaginatingEnumerable
include Enumerable
def initialize(initial_page)
raise ArgumentError, 'Must provide initial page' unless initial_page.present?
@initial_page = initial_page
end
def each
page = @initial_page
yield page
while page.next_page?
page = page.next_page
yield page
end
end
end
end
end
We don't have activesupport in here
# frozen_string_literal: true
require 'forwardable'
require_relative 'api_error'
module WCC::API
class RestClient
class AbstractResponse
extend ::Forwardable
attr_reader :raw_response
attr_reader :raw_body
attr_reader :client
attr_reader :request
def_delegators :raw_response, :status, :headers
alias_method :code, :status
def body
@body ||= ::JSON.parse(raw_body)
end
alias_method :to_json, :body
def initialize(client, request, raw_response)
@client = client
@request = request
@raw_response = raw_response
@raw_body = raw_response.body.to_s
end
def skip
throw new NotImplementedError, 'Please implement "skip" parsing in response class'
end
def count
throw new NotImplementedError, 'Please implement "count" parsing in response class'
end
def collection_response?
page_items.nil? ? false : true
end
def page_items
throw new NotImplementedError, 'Please implement "page_items" parsing in response class'
end
def error_message
parsed_message =
begin
body.dig('error', 'message') || body.dig('message')
rescue ::JSON::ParserError
nil
end
parsed_message || "#{code}: #{raw_response.body}"
end
def next_page?
return false unless collection_response?
return false if count.nil?
page_items.length + skip < count
end
def next_page
return unless next_page?
next_page ||= @client.get(
@request[:url],
(@request[:query] || {}).merge(next_page_query)
)
next_page.assert_ok!
end
def assert_ok!
return self if code >= 200 && code < 300
raise ApiError[code], self
end
# This method has a bit of complexity that is better kept in one location
def each_page(&block)
raise ArgumentError, 'Not a collection response' unless collection_response?
ret = PaginatingEnumerable.new(self)
if block_given?
ret.map(&block)
else
ret.lazy
end
end
def items
return unless collection_response?
each_page.flat_map(&:page_items)
end
def first
raise ArgumentError, 'Not a collection response' unless collection_response?
page_items.first
end
def next_page_query
return unless collection_response?
{
skip: page_items.length + skip
}
end
end
class DefaultResponse < AbstractResponse
def skip
body['skip']
end
def count
body['total']
end
def page_items
body['items']
end
end
class PaginatingEnumerable
include Enumerable
def initialize(initial_page)
raise ArgumentError, 'Must provide initial page' unless initial_page
@initial_page = initial_page
end
def each
page = @initial_page
yield page
while page.next_page?
page = page.next_page
yield page
end
end
end
end
end
|
module XNGemReleaseTasks
VERSION = "0.1.8.pre"
end
Version 0.1.8
module XNGemReleaseTasks
VERSION = "0.1.8"
end
|
require 'formula'
class Gmp < Formula
homepage 'http://gmplib.org/'
url 'ftp://ftp.gmplib.org/pub/gmp-5.1.2/gmp-5.1.2.tar.bz2'
mirror 'http://ftp.gnu.org/gnu/gmp/gmp-5.1.2.tar.bz2'
sha1 '2cb498322b9be4713829d94dee944259c017d615'
bottle do
root_url 'http://archive.org/download/julialang/bottles'
cellar :any
revision 2
sha1 'a55c253064287d96f9d8d6b064f1e415e3dd02ed' => :mountain_lion
sha1 'a55c253064287d96f9d8d6b064f1e415e3dd02ed' => :lion
sha1 'a55c253064287d96f9d8d6b064f1e415e3dd02ed' => :snow_leopard
end
option '32-bit'
def install
args = ["--prefix=#{prefix}", "--enable-cxx"]
if build.build_32_bit?
ENV.m32
ENV.append 'ABI', '32'
# https://github.com/mxcl/homebrew/issues/20693
args << "--disable-assembly"
end
system "./configure", *args
system "make"
system "make check"
ENV.deparallelize
system "make install"
end
end
Bump gmp version number
require 'formula'
class Gmp < Formula
homepage 'http://gmplib.org/'
url 'ftp://ftp.gmplib.org/pub/gmp/gmp-5.1.3.tar.bz2'
mirror 'http://ftp.gnu.org/gnu/gmp/gmp-5.1.3.tar.bz2'
sha1 'b35928e2927b272711fdfbf71b7cfd5f86a6b165'
bottle do
root_url 'http://archive.org/download/julialang/bottles'
cellar :any
revision 2
sha1 'a55c253064287d96f9d8d6b064f1e415e3dd02ed' => :mountain_lion
sha1 'a55c253064287d96f9d8d6b064f1e415e3dd02ed' => :lion
sha1 'a55c253064287d96f9d8d6b064f1e415e3dd02ed' => :snow_leopard
end
option '32-bit'
def install
args = ["--prefix=#{prefix}", "--enable-cxx"]
if build.build_32_bit?
ENV.m32
ENV.append 'ABI', '32'
# https://github.com/mxcl/homebrew/issues/20693
args << "--disable-assembly"
end
system "./configure", *args
system "make"
system "make check"
ENV.deparallelize
system "make install"
end
end
|
require "spec_helper"
require "sidekiq/testing"
RSpec.describe "Republishing manuals", type: :feature do
before do
Sidekiq::Testing.inline!
login_as(:generic_editor)
stub_organisation_details(GDS::SSO.test_user.organisation_slug)
end
let(:original_publish_time) { DateTime.now - 1.day }
let(:manual_fields) { { title: "Example manual title", summary: "A summary" } }
let(:edited_manual_fields) { { title: "Editted manual title", summary: "A changed summary" } }
def edited_section_fields(section)
{
title: "I've changed this section: #{section.title}",
summary: "And its summary: #{section.summary}",
}
end
def create_manual_with_sections(published: true)
manual = create_manual_without_ui(manual_fields)
@documents = create_documents_for_manual_without_ui(manual: manual, count: 2)
# Re-fetch manual to include documents
@manual = manual_repository.fetch(manual.id)
if published
Timecop.freeze(original_publish_time) do
publish_manual_without_ui(@manual)
end
end
if published
check_manual_is_drafted_to_publishing_api(@manual.id, number_of_drafts: 4)
check_manual_is_published_to_publishing_api(@manual.id)
else
check_manual_is_drafted_to_publishing_api(@manual.id, number_of_drafts: 3)
end
WebMock::RequestRegistry.instance.reset!
end
def edit_manual_and_sections
@edited_manual = edit_manual_without_ui(@manual, edited_manual_fields)
@edited_documents = @documents.map do |document|
edit_section_without_ui(@manual, document, edited_section_fields(document))
end
WebMock::RequestRegistry.instance.reset!
end
def republish_manuals
republish_manuals_without_ui
end
def manual_repository
RepositoryRegistry.create.manual_repository
end
describe "republishing a published manual with sections" do
before do
create_manual_with_sections(published: true)
republish_manuals
end
it "sends the manual and the sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: manual_fields[:title],
description: manual_fields[:summary],
})
check_manual_is_published_to_publishing_api(@manual.id)
check_manual_is_published_to_rummager(@manual.slug, manual_fields)
@documents.each do |document|
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: document.attributes[:title],
description: document.attributes[:summary],
})
check_section_is_published_to_publishing_api(document.id)
check_section_is_published_to_rummager(document.slug, document_fields(document), manual_fields)
end
end
it "does not change the exported timestamp" do
expect(@documents.first.latest_edition.reload.exported_at).to be_within(1.second).of original_publish_time
end
end
describe "republishing a draft manual with sections" do
before do
create_manual_with_sections(published: false)
republish_manuals
end
it "sends the manual and the sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: manual_fields[:title],
description: manual_fields[:summary],
})
check_manual_is_not_published_to_publishing_api(@manual.id)
check_manual_is_not_published_to_rummager(@manual.slug)
@documents.each do |document|
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: document.attributes[:title],
description: document.attributes[:summary],
})
check_section_is_not_published_to_publishing_api(document.id)
check_section_is_not_published_to_rummager(document.slug)
end
end
it "does not change the exported timestamp" do
expect(@documents.first.latest_edition.reload.exported_at).to be_nil
end
end
describe "republishing a published manual with sections and a new draft waiting" do
before do
create_manual_with_sections(published: true)
@edited_document = edit_manual_and_sections
republish_manuals
end
it "sends the published versions of the manual and its sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: manual_fields[:title],
description: manual_fields[:summary],
})
check_manual_is_published_to_publishing_api(@manual.id)
check_manual_is_published_to_rummager(@manual.slug, manual_fields)
@documents.each do |document|
edited_fields = edited_section_fields(document)
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: edited_fields[:title],
description: edited_fields[:summary],
})
check_section_is_published_to_publishing_api(document.id)
check_section_is_published_to_rummager(document.slug, document_fields(document), manual_fields)
end
end
it "sends the draft versions of the manual and its sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: edited_manual_fields[:title],
description: edited_manual_fields[:summary],
})
# we can't check that it's not published (because one version will be)
# all we can check is that it was only published once
check_manual_is_published_to_publishing_api(@manual.id, times: 1)
check_manual_is_not_published_to_rummager_with_attrs(@manual.slug, edited_manual_fields)
@edited_documents.each do |document|
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: document.title,
description: document.summary,
})
# we can't check that it's not published (because one version will be)
# all we can check is that it was only published once
check_section_is_published_to_publishing_api(document.id, times: 1)
check_section_is_not_published_to_rummager_with_attrs(document.slug, document_fields(document), edited_manual_fields)
end
end
it "does not set the exported timestamp of the draft version of the section" do
expect(@edited_documents.first.latest_edition.reload.exported_at).to be_nil
end
it "does not set the exported timestamp of the previously published version of the section" do
expect(@documents.first.latest_edition.reload.exported_at).to be_within(1.second).of original_publish_time
end
end
end
Inline #republish_manuals in republishing manuals spec
require "spec_helper"
require "sidekiq/testing"
RSpec.describe "Republishing manuals", type: :feature do
before do
Sidekiq::Testing.inline!
login_as(:generic_editor)
stub_organisation_details(GDS::SSO.test_user.organisation_slug)
end
let(:original_publish_time) { DateTime.now - 1.day }
let(:manual_fields) { { title: "Example manual title", summary: "A summary" } }
let(:edited_manual_fields) { { title: "Editted manual title", summary: "A changed summary" } }
def edited_section_fields(section)
{
title: "I've changed this section: #{section.title}",
summary: "And its summary: #{section.summary}",
}
end
def create_manual_with_sections(published: true)
manual = create_manual_without_ui(manual_fields)
@documents = create_documents_for_manual_without_ui(manual: manual, count: 2)
# Re-fetch manual to include documents
@manual = manual_repository.fetch(manual.id)
if published
Timecop.freeze(original_publish_time) do
publish_manual_without_ui(@manual)
end
end
if published
check_manual_is_drafted_to_publishing_api(@manual.id, number_of_drafts: 4)
check_manual_is_published_to_publishing_api(@manual.id)
else
check_manual_is_drafted_to_publishing_api(@manual.id, number_of_drafts: 3)
end
WebMock::RequestRegistry.instance.reset!
end
def edit_manual_and_sections
@edited_manual = edit_manual_without_ui(@manual, edited_manual_fields)
@edited_documents = @documents.map do |document|
edit_section_without_ui(@manual, document, edited_section_fields(document))
end
WebMock::RequestRegistry.instance.reset!
end
def manual_repository
RepositoryRegistry.create.manual_repository
end
describe "republishing a published manual with sections" do
before do
create_manual_with_sections(published: true)
republish_manuals_without_ui
end
it "sends the manual and the sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: manual_fields[:title],
description: manual_fields[:summary],
})
check_manual_is_published_to_publishing_api(@manual.id)
check_manual_is_published_to_rummager(@manual.slug, manual_fields)
@documents.each do |document|
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: document.attributes[:title],
description: document.attributes[:summary],
})
check_section_is_published_to_publishing_api(document.id)
check_section_is_published_to_rummager(document.slug, document_fields(document), manual_fields)
end
end
it "does not change the exported timestamp" do
expect(@documents.first.latest_edition.reload.exported_at).to be_within(1.second).of original_publish_time
end
end
describe "republishing a draft manual with sections" do
before do
create_manual_with_sections(published: false)
republish_manuals_without_ui
end
it "sends the manual and the sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: manual_fields[:title],
description: manual_fields[:summary],
})
check_manual_is_not_published_to_publishing_api(@manual.id)
check_manual_is_not_published_to_rummager(@manual.slug)
@documents.each do |document|
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: document.attributes[:title],
description: document.attributes[:summary],
})
check_section_is_not_published_to_publishing_api(document.id)
check_section_is_not_published_to_rummager(document.slug)
end
end
it "does not change the exported timestamp" do
expect(@documents.first.latest_edition.reload.exported_at).to be_nil
end
end
describe "republishing a published manual with sections and a new draft waiting" do
before do
create_manual_with_sections(published: true)
@edited_document = edit_manual_and_sections
republish_manuals_without_ui
end
it "sends the published versions of the manual and its sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: manual_fields[:title],
description: manual_fields[:summary],
})
check_manual_is_published_to_publishing_api(@manual.id)
check_manual_is_published_to_rummager(@manual.slug, manual_fields)
@documents.each do |document|
edited_fields = edited_section_fields(document)
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: edited_fields[:title],
description: edited_fields[:summary],
})
check_section_is_published_to_publishing_api(document.id)
check_section_is_published_to_rummager(document.slug, document_fields(document), manual_fields)
end
end
it "sends the draft versions of the manual and its sections to the Publishing API" do
check_manual_is_drafted_to_publishing_api(@manual.id, extra_attributes: {
title: edited_manual_fields[:title],
description: edited_manual_fields[:summary],
})
# we can't check that it's not published (because one version will be)
# all we can check is that it was only published once
check_manual_is_published_to_publishing_api(@manual.id, times: 1)
check_manual_is_not_published_to_rummager_with_attrs(@manual.slug, edited_manual_fields)
@edited_documents.each do |document|
check_section_is_drafted_to_publishing_api(document.id, extra_attributes: {
title: document.title,
description: document.summary,
})
# we can't check that it's not published (because one version will be)
# all we can check is that it was only published once
check_section_is_published_to_publishing_api(document.id, times: 1)
check_section_is_not_published_to_rummager_with_attrs(document.slug, document_fields(document), edited_manual_fields)
end
end
it "does not set the exported timestamp of the draft version of the section" do
expect(@edited_documents.first.latest_edition.reload.exported_at).to be_nil
end
it "does not set the exported timestamp of the previously published version of the section" do
expect(@documents.first.latest_edition.reload.exported_at).to be_within(1.second).of original_publish_time
end
end
end
|
require 'spec_helper'
module Dough
module Helpers
class TestInsetBlockController < AbstractController::Base
include AbstractController::Helpers
include AbstractController::Rendering
include ActionView::Rendering
helper Dough::Helpers
def index
render inline: "<%= inset_block 'hello' %>"
end
private
def lookup_context
ActionView::LookupContext.new(ActionController::Base.view_paths)
end
end
describe InsetBlock do
it 'renders text' do
controller = TestInsetBlockController.new
controller.process(:index)
expect(controller.response_body).to include('hello')
end
end
end
end
Leverage rspec-rails controller specs
require 'spec_helper'
module Dough
module Helpers
describe InsetBlock, type: 'controller' do
render_views
controller do
helper Dough::Helpers
def index
render inline: "<%= inset_block 'hello' %>"
end
end
it 'renders "text"' do
get :index
expect(response.body).to include('hello')
end
end
end
end
|
require 'spec_helper'
describe Isbm::ConsumerPublication, :external_service => true do
context "with invalid arguments" do
describe "#open_session" do
let(:uri) { "Test#{Time.now.to_i}" }
let(:topics) { ["topics"] }
it "raises error with no URI" do
expect { Isbm::ConsumerPublication.open_session(nil, topics) }.to raise_error
end
it "raises error with no topics" do
expect { Isbm::ConsumerPublication.open_session(uri, nil) }.to raise_error
end
end
describe "#read_publication" do
it "raises error with no session id" do
expect { Isbm::ConsumerPublication.read_publication(nil, nil) }.to raise_error
end
end
describe "#close_session" do
it "raises error with no session id" do
expect { Isbm::ConsumerPublication.close_session(nil) }.to raise_error
end
end
end
context "with valid arguments" do
let(:uri) { "Test#{Time.now.to_i}" }
let(:type) { :publication }
let(:topics) { ["topic"] }
let(:content) { '<CCOMData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.mimosa.org/osa-eai/v3-2-3/xml/CCOM-ML"><Entity xsi:type="Asset"><GUID>C013C740-19F5-11E1-92B7-6B8E4824019B</GUID></Entity></CCOMData>' }
before(:all) { Isbm::ChannelManagement.create_channel(uri, type) }
let(:provider_session_id) { Isbm::ProviderPublication.open_session(uri) }
let(:consumer_session_id) { Isbm::ConsumerPublication.open_session(uri, topics) }
describe "#open_session" do
it "returns a session id" do
consumer_session_id.should_not be_nil
end
end
describe "#read_publication" do
before(:all) { Isbm::ProviderPublication.post_publication(provider_session_id, content, topics) }
let(:message) { Isbm::ConsumerPublication.read_publication(consumer_session_id, nil) }
it "returns a valid message" do
message.id.should_not be_nil
message.topics.should_not be_nil
message.topics.empty?.should be_false
message.content.name.should eq "CCOMData"
end
end
after(:all) do
Isbm::ProviderPublication.close_session(provider_session_id)
Isbm::ChannelManagement.delete_channel(uri)
end
end
end
Update test for read_publication to expect an array
require 'spec_helper'
describe Isbm::ConsumerPublication, :external_service => true do
context "with invalid arguments" do
describe "#open_session" do
let(:uri) { "Test#{Time.now.to_i}" }
let(:topics) { ["topics"] }
it "raises error with no URI" do
expect { Isbm::ConsumerPublication.open_session(nil, topics) }.to raise_error
end
it "raises error with no topics" do
expect { Isbm::ConsumerPublication.open_session(uri, nil) }.to raise_error
end
end
describe "#read_publication" do
it "raises error with no session id" do
expect { Isbm::ConsumerPublication.read_publication(nil, nil) }.to raise_error
end
end
describe "#close_session" do
it "raises error with no session id" do
expect { Isbm::ConsumerPublication.close_session(nil) }.to raise_error
end
end
end
context "with valid arguments" do
let(:uri) { "Test#{Time.now.to_i}" }
let(:type) { :publication }
let(:topics) { ["topic"] }
let(:content) { '<CCOMData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.mimosa.org/osa-eai/v3-2-3/xml/CCOM-ML"><Entity xsi:type="Asset"><GUID>C013C740-19F5-11E1-92B7-6B8E4824019B</GUID></Entity></CCOMData>' }
before(:all) { Isbm::ChannelManagement.create_channel(uri, type) }
let(:provider_session_id) { Isbm::ProviderPublication.open_session(uri) }
let(:consumer_session_id) { Isbm::ConsumerPublication.open_session(uri, topics) }
describe "#open_session" do
it "returns a session id" do
consumer_session_id.should_not be_nil
end
end
describe "#read_publication" do
before(:all) { Isbm::ProviderPublication.post_publication(provider_session_id, content, topics) }
let(:message) { Isbm::ConsumerPublication.read_publication(consumer_session_id, nil) }
it "returns a valid message" do
message.id.should_not be_nil
message.topics.first.should eq topics.first
message.content.name.should eq "CCOMData"
end
end
after(:all) do
Isbm::ProviderPublication.close_session(provider_session_id)
Isbm::ChannelManagement.delete_channel(uri)
end
end
end
|
require_relative '../../spec_helper'
require 'message_bus'
describe PUB_SUB_CLASS do
def self.error!
@error = true
end
def self.error?
defined?(@error)
end
def new_bus
PUB_SUB_CLASS.new(MESSAGE_BUS_REDIS_CONFIG.merge(:db => 10))
end
def work_it
bus = new_bus
$stdout.reopen("/dev/null", "w")
$stderr.reopen("/dev/null", "w")
# subscribe blocks, so we need a new bus to transmit
new_bus.subscribe("/echo", 0) do |msg|
bus.publish("/response", Process.pid.to_s)
end
ensure
exit!(0)
end
def spawn_child
r = fork
if r.nil?
work_it
else
r
end
end
n = ENV['MULTI_PROCESS_TIMES'].to_i
n = 1 if n < 1
n.times do
it 'gets every response from child processes' do
skip("previous error") if self.class.error?
GC.start
new_bus.reset!
begin
pids = (1..10).map{spawn_child}
responses = []
bus = new_bus
t = Thread.new do
bus.subscribe("/response", 0) do |msg|
responses << msg if pids.include? msg.data.to_i
end
end
10.times{bus.publish("/echo", Process.pid.to_s)}
wait_for 4000 do
responses.count == 100
end
bus.global_unsubscribe
t.join
# p responses.group_by(&:data).map{|k,v|[k, v.count]}
# p responses.group_by(&:global_id).map{|k,v|[k, v.count]}
responses.count.must_equal 100
rescue Exception
self.class.error!
raise
ensure
if pids
pids.each do |pid|
begin
Process.kill("KILL", pid)
rescue SystemCallError
end
Process.wait(pid)
end
end
bus.global_unsubscribe
end
end
end
end
Better testing in multi_process_spec
Keep track of all responses. If an expected response was not
received, post which one, and if an unexpected or duplicate
response was received, also post that.
require_relative '../../spec_helper'
require 'message_bus'
describe PUB_SUB_CLASS do
def self.error!
@error = true
end
def self.error?
defined?(@error)
end
def new_bus
PUB_SUB_CLASS.new(MESSAGE_BUS_REDIS_CONFIG.merge(:db => 10))
end
def work_it
bus = new_bus
$stdout.reopen("/dev/null", "w")
$stderr.reopen("/dev/null", "w")
# subscribe blocks, so we need a new bus to transmit
new_bus.subscribe("/echo", 0) do |msg|
bus.publish("/response", "#{msg.data}-#{Process.pid.to_s}")
end
ensure
exit!(0)
end
def spawn_child
r = fork
if r.nil?
work_it
else
r
end
end
n = ENV['MULTI_PROCESS_TIMES'].to_i
n = 1 if n < 1
n.times do
it 'gets every response from child processes' do
skip("previous error") if self.class.error?
GC.start
new_bus.reset!
begin
pids = (1..10).map{spawn_child}
expected_responses = pids.map{|x| (0...10).map{|i| "#{i}-#{x}"}}.flatten
unexpected_responses = []
responses = []
bus = new_bus
t = Thread.new do
bus.subscribe("/response", 0) do |msg|
if expected_responses.include?(msg.data)
expected_responses.delete(msg.data)
else
unexpected_responses << msg.data
end
end
end
10.times{|i| bus.publish("/echo", i.to_s)}
wait_for 4000 do
expected_responses.empty?
end
bus.global_unsubscribe
t.join
expected_responses.must_be :empty?
unexpected_responses.must_be :empty?
rescue Exception
self.class.error!
raise
ensure
if pids
pids.each do |pid|
begin
Process.kill("KILL", pid)
rescue SystemCallError
end
Process.wait(pid)
end
end
bus.global_unsubscribe
end
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper')
describe Reports::Financial::Backers do
context "project with some backers" do
before do
@project = create(:project)
4.times do |n|
user = create(:user)
create(:backer, :project => @project, :user => user)
end
end
it 'should have all backers' do
report = Reports::Financial::Backers.report(@project.to_param)
report.should have(4).itens
end
end
end
verify backers information into csv string
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper')
describe Reports::Financial::Backers do
context "project with some backers" do
before do
@project = create(:project)
4.times do |n|
user = create(:user)
create(:backer, :value => (10.00+n),:project => @project, :user => user)
end
end
it 'should have the backers information' do
report = Reports::Financial::Backers.report(@project.to_param)
report.should =~ /R\$ 10/
report.should =~ /R\$ 11/
report.should =~ /R\$ 12/
report.should =~ /person[\d]\@example\.com/
end
end
end |
require 'rails_helper'
describe ClinicalTrials::Client do
let(:search_term) { 'duke lupus rheumatoid arthritis' }
let(:expected_url) { 'https://clinicaltrials.gov/search?term=duke+lupus+rheumatoid+arthritis&resultsxml=true' }
let(:stub_request_headers) { {'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'User-Agent'=>'Ruby'} }
subject { described_class.new(search_term: search_term) }
let(:zipped_studies) { File.read(Rails.root.join('spec','support','xml_data','download_xml_files.zip')) }
let(:raw_study_xml_1) { File.read(Rails.root.join('spec','support','xml_data','NCT00513591.xml')) }
let(:official_study_title_1) { 'Duke Autoimmunity in Pregnancy Registry' }
let(:raw_study_xml_1_mod) { File.read(Rails.root.join('spec','support','xml_data','NCT00513591_mod.xml')) }
let(:official_study_title_1_mod) { 'This Is An Updated Title' }
let(:raw_study_xml_1_mod_date) { 'June 15, 2016' }
let(:study_xml_nct_ids) { ["NCT00513591", "NCT00482794"] }
let(:study_xml_official_title) { [official_study_title_1, official_study_title_2] }
let(:study_xml_official_title_mod) { [official_study_title_1_mod, official_study_title_2] }
let(:study_xml_official_title) { ["Duke Autoimmunity in Pregnancy Registry", "Genetics of Antiphospholipid Antibody Syndrome"] }
let(:study_xml_record) { StudyXmlRecord.create(content: raw_study_xml_1, nct_id: "NCT00513591") }
let(:raw_study_xml_2) { File.read(Rails.root.join('spec','support','xml_data','NCT00482794.xml')) }
let(:official_study_title_2) { 'Genetics of Antiphospholipid Antibody Syndrome' }
context 'initialization' do
it 'should set the url based on the provided search term' do
expect(subject.url).to eq(expected_url)
end
it 'should set the processed_studies' do
expect(subject.url).to eq(expected_url)
end
end
describe '#download_xml_files' do
before do
stub_request(:get, expected_url).
with(:headers => stub_request_headers).
to_return(:status => 200, :body => zipped_studies, :headers => {})
end
it 'should create a study xml record and load event' do
expect {
expect {
subject.download_xml_files
}.to change{StudyXmlRecord.count}.by(2)
}.to change{ClinicalTrials::LoadEvent.count}.by(1)
study_xml_record_1 = StudyXmlRecord.find_by(nct_id:'NCT00513591')
Nokogiri::XML(study_xml_record_1.content).xpath('//clinical_study').xpath('lastchanged_date').text
expect(study_xml_record_1).to be
raw_xml_content = Nokogiri::XML(raw_study_xml_1).child.to_xml
existing_xml_content = Nokogiri::XML(study_xml_record_1.content).child.to_xml
expect(existing_xml_content).to eq(raw_xml_content)
load_event = ClinicalTrials::LoadEvent.first
expect(load_event.event_type).to eq('get_studies')
end
end
describe '#create_study_xml_record(xml)' do
it 'should create a study xml record' do
subject.create_study_xml_record(raw_study_xml_1)
study_xml_record_1 = StudyXmlRecord.find_by(nct_id:'NCT00513591')
expect(study_xml_record_1).to be
processed_studies = {
updated_studies: [],
new_studies: ["NCT00513591"]
}
expect(subject.processed_studies).to eq(processed_studies)
subject.create_study_xml_record(raw_study_xml_1_mod)
processed_studies = {
updated_studies: ["NCT00513591"],
new_studies: ["NCT00513591"]
}
expect(subject.processed_studies).to eq(processed_studies)
expect(StudyXmlRecord.count).to eq(1)
study_xml_record_1_mod = StudyXmlRecord.find_by(nct_id:'NCT00513591')
official_title = Nokogiri::XML(study_xml_record_1_mod.content)
.xpath('//clinical_study')
.xpath('official_title').text
expect(official_study_title_1_mod).to eq(official_title)
subject.create_study_xml_record(raw_study_xml_2)
processed_studies = {
updated_studies: ["NCT00513591"],
new_studies: ["NCT00513591", "NCT00482794"]
}
expect(subject.processed_studies).to eq(processed_studies)
subject.create_study_xml_record(raw_study_xml_1_mod)
expect(subject.processed_studies).to eq(processed_studies)
expect(StudyXmlRecord.count).to eq(2)
end
end
end
ClinicalTrials::Client populate_studies spec test, failing/incomplete
require 'rails_helper'
describe ClinicalTrials::Client do
let(:search_term) { 'duke lupus rheumatoid arthritis' }
let(:expected_url) { 'https://clinicaltrials.gov/search?term=duke+lupus+rheumatoid+arthritis&resultsxml=true' }
let(:stub_request_headers) { {'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'User-Agent'=>'Ruby'} }
subject { described_class.new(search_term: search_term) }
let(:zipped_studies) { File.read(Rails.root.join('spec','support','xml_data','download_xml_files.zip')) }
let(:raw_study_xml_1) { File.read(Rails.root.join('spec','support','xml_data','NCT00513591.xml')) }
let(:official_study_title_1) { 'Duke Autoimmunity in Pregnancy Registry' }
let(:raw_study_xml_1_mod) { File.read(Rails.root.join('spec','support','xml_data','NCT00513591_mod.xml')) }
let(:official_study_title_1_mod) { 'This Is An Updated Title' }
let(:raw_study_xml_1_mod_date) { 'June 15, 2016' }
let(:study_xml_nct_ids) { ["NCT00513591", "NCT00482794"] }
let(:study_xml_official_title) { [official_study_title_1, official_study_title_2] }
let(:study_xml_official_title_mod) { [official_study_title_1_mod, official_study_title_2] }
let(:study_xml_official_title) { ["Duke Autoimmunity in Pregnancy Registry", "Genetics of Antiphospholipid Antibody Syndrome"] }
let(:study_xml_record) { StudyXmlRecord.create(content: raw_study_xml_1, nct_id: "NCT00513591") }
let(:raw_study_xml_2) { File.read(Rails.root.join('spec','support','xml_data','NCT00482794.xml')) }
let(:official_study_title_2) { 'Genetics of Antiphospholipid Antibody Syndrome' }
context 'initialization' do
it 'should set the url based on the provided search term' do
expect(subject.url).to eq(expected_url)
end
it 'should set the processed_studies' do
expect(subject.url).to eq(expected_url)
end
end
describe '#download_xml_files' do
before do
stub_request(:get, expected_url).
with(:headers => stub_request_headers).
to_return(:status => 200, :body => zipped_studies, :headers => {})
end
it 'should create a study xml record and load event' do
expect {
expect {
subject.download_xml_files
}.to change{StudyXmlRecord.count}.by(2)
}.to change{ClinicalTrials::LoadEvent.count}.by(1)
study_xml_record_1 = StudyXmlRecord.find_by(nct_id:'NCT00513591')
Nokogiri::XML(study_xml_record_1.content).xpath('//clinical_study').xpath('lastchanged_date').text
expect(study_xml_record_1).to be
raw_xml_content = Nokogiri::XML(raw_study_xml_1).child.to_xml
existing_xml_content = Nokogiri::XML(study_xml_record_1.content).child.to_xml
expect(existing_xml_content).to eq(raw_xml_content)
load_event = ClinicalTrials::LoadEvent.first
expect(load_event.event_type).to eq('get_studies')
end
end
describe '#create_study_xml_record(xml)' do
it 'should create a study xml record' do
subject.create_study_xml_record(raw_study_xml_1)
study_xml_record_1 = StudyXmlRecord.find_by(nct_id:'NCT00513591')
expect(study_xml_record_1).to be
processed_studies = {
updated_studies: [],
new_studies: ["NCT00513591"]
}
expect(subject.processed_studies).to eq(processed_studies)
subject.create_study_xml_record(raw_study_xml_1_mod)
processed_studies = {
updated_studies: ["NCT00513591"],
new_studies: ["NCT00513591"]
}
expect(subject.processed_studies).to eq(processed_studies)
expect(StudyXmlRecord.count).to eq(1)
study_xml_record_1_mod = StudyXmlRecord.find_by(nct_id:'NCT00513591')
official_title = Nokogiri::XML(study_xml_record_1_mod.content)
.xpath('//clinical_study')
.xpath('official_title').text
expect(official_study_title_1_mod).to eq(official_title)
subject.create_study_xml_record(raw_study_xml_2)
processed_studies = {
updated_studies: ["NCT00513591"],
new_studies: ["NCT00513591", "NCT00482794"]
}
expect(subject.processed_studies).to eq(processed_studies)
subject.create_study_xml_record(raw_study_xml_1_mod)
expect(subject.processed_studies).to eq(processed_studies)
expect(StudyXmlRecord.count).to eq(2)
end
end
describe '#populate_studies' do
before do
stub_request(:get, expected_url).
with(:headers => stub_request_headers).
to_return(:status => 200, :body => zipped_studies, :headers => {})
subject.download_xml_files
end
it 'should create a study from an existing study xml record' do
subject.populate_studies
expect(Study.pluck(:nct_id)).to eq(study_xml_nct_ids)
expect(StudyXmlRecord.pluck(:nct_id)).to eq(study_xml_nct_ids)
expect(Study.pluck(:official_title)).to eq(study_xml_official_title)
subject.create_study_xml_record(raw_study_xml_1_mod)
expect(Study.pluck(:official_title)).to eq(study_xml_official_title_mod)
# binding.pry
# expect(Study.pluck(:official_title)).to eq(study_xml_official_title)
# expect(StudyXmlRecord.pluck(:nct_id)).to eq(study_xml_nct_ids)
#
# subject.create_study_xml_record(raw_study_xml_1_mod)
# expect(Study.pluck(:nct_id)).to eq(study_xml_nct_ids)
# subject.download_xml_files
# raw_study_xml_1_mod
# binding.pry
# study_xml_record_1 = StudyXmlRecord.find_by(nct_id:'NCT00513591')
# study_xml_record_1
# load_event = ClinicalTrials::LoadEvent.first
# expect(load_event.event_type).to eq('get_studies')
end
end
# describe '#import_xml_file' do
#
# context 'success' do
# context 'new study' do
# before do
# client.import_xml_file(raw_study_xml)
# @new_study = Study.last
# end
#
# # it 'should create study from the study xml record' do
# # expect(Study.count).to eq(1)
# # binding.pry
# # expect(@new_study.nct_id).to eq(study_id)
# # # xml: study,
# # # nct_id: nct_id
# # expect(@new_study.xml).to eq(study_id)
# # @new_study
# # binding.pry
# # end
# end
#
# context 'study has changed' do
# before do
# client.import_xml_file(raw_study_xml)
# binding.pry
# doc = Nokogiri::XML(raw_study_xml)
# @new_title = 'Testing File For Import Differences'
# doc.xpath('//clinical_study').xpath('//official_title').children.first.content = @new_title
# doc.xpath('//clinical_study').xpath('lastchanged_date').children.first.content = 'Jan 1, 2016'
# @updated_study = doc.to_xml
# client.import_xml_file(@updated_study)
# end
#
# it 'should update study' do
# expect(Study.all.count).to eq(1)
# expect(Study.last.last_changed_date.to_s).to eq('2016-01-01')
# expect(Study.last.official_title).to eq(@new_title)
# expect(Study.last.updated_at).not_to eq(Study.last.created_at)
# end
#
# it 'should update the study xml record' do
# expect(StudyXmlRecord.count).to eq(1)
#
# updated_content = StudyXmlRecord.last.content
# imported_content = Nokogiri::XML(@updated_study).xpath("//clinical_study").to_xml
# expect(updated_content.chomp).to eq(imported_content)
# end
# end
# end
#
# context 'failure' do
# context 'duplicate study' do
# let!(:xml_record) { StudyXmlRecord.create(content: raw_study_xml, nct_id: study_id) }
#
# it 'should not create new study' do
# client.import_xml_file(study)
# client.import_xml_file(study)
#
# expect(Study.all.count).to eq(1)
# expect(Study.last.updated_at).to eq(Study.last.created_at)
# end
# end
# end
#
# end
end |
# encoding: utf-8
require_relative '../../spec_helper'
require_relative '../../../services/data-repository/backend/sequel'
require_relative '../../../services/data-repository/repository'
require_relative '../../../app/models/synchronization/member'
include CartoDB
describe Synchronization::Member do
before do
Synchronization.repository = DataRepository.new
end
describe 'Basic actions' do
it 'assigns an id by default' do
member = Synchronization::Member.new
member.should be_an_instance_of Synchronization::Member
member.id.should_not be_nil
end
it 'persists attributes to the repository' do
attributes = random_attributes
member = Synchronization::Member.new(attributes)
member.store
member = Synchronization::Member.new(id: member.id)
member.name.should be_nil
member.fetch
member.name .should == attributes.fetch(:name)
end
it 'fetches attributes from the repository' do
attributes = random_attributes
member = Synchronization::Member.new(attributes).store
member = Synchronization::Member.new(id: member.id)
member.name = 'changed'
member.fetch
member.name.should == attributes.fetch(:name)
end
it 'deletes this member from the repository' do
member = Synchronization::Member.new(random_attributes).store
member.fetch
member.name.should_not be_nil
member.delete
member.name.should be_nil
lambda { member.fetch }.should raise_error KeyError
end
end
describe "External sources" do
it "Authorizes to sync always if from an external source" do
member = Synchronization::Member.new(random_attributes({user_id: $user_1.id})).store
member.fetch
member.expects(:from_external_source?)
.returns(true)
$user_1.sync_tables_enabled = true
$user_2.sync_tables_enabled = true
member.authorize?($user_1).should eq true
member.authorize?($user_2).should eq false
$user_1.sync_tables_enabled = false
$user_2.sync_tables_enabled = false
member.authorize?($user_1).should eq true
end
end
private
def random_attributes(attributes={})
random = rand(999)
{
name: attributes.fetch(:name, "name #{random}"),
interval: attributes.fetch(:interval, 15 * 60 + random),
state: attributes.fetch(:state, 'enabled'),
user_id: attributes.fetch(:user_id, nil)
}
end
end
refactors synchronization/member_spec.rb
# encoding: utf-8
require_relative '../../spec_helper'
require_relative '../../../services/data-repository/backend/sequel'
require_relative '../../../services/data-repository/repository'
require_relative '../../../app/models/synchronization/member'
include CartoDB
describe Synchronization::Member do
before do
Synchronization.repository = DataRepository.new
end
describe 'Basic actions' do
it 'assigns an id by default' do
member = Synchronization::Member.new
member.should be_an_instance_of Synchronization::Member
member.id.should_not be_nil
end
it 'persists attributes to the repository' do
attributes = random_attributes
member = Synchronization::Member.new(attributes)
member.store
member = Synchronization::Member.new(id: member.id)
member.name.should be_nil
member.fetch
member.name .should == attributes.fetch(:name)
end
it 'fetches attributes from the repository' do
attributes = random_attributes
member = Synchronization::Member.new(attributes).store
member = Synchronization::Member.new(id: member.id)
member.name = 'changed'
member.fetch
member.name.should == attributes.fetch(:name)
end
it 'deletes this member from the repository' do
member = Synchronization::Member.new(random_attributes).store
member.fetch
member.name.should_not be_nil
member.delete
member.name.should be_nil
lambda { member.fetch }.should raise_error KeyError
end
end
describe "External sources" do
before(:each) do
@user_1 = FactoryGirl.create(:valid_user)
@user_2 = FactoryGirl.create(:valid_user)
end
after(:each) do
@user_1.destroy
@user_2.destroy
end
it "Authorizes to sync always if from an external source" do
member = Synchronization::Member.new(random_attributes({user_id: @user_1.id})).store
member.fetch
member.expects(:from_external_source?)
.returns(true)
@user_1.sync_tables_enabled = true
@user_2.sync_tables_enabled = true
member.authorize?(@user_1).should eq true
member.authorize?(@user_2).should eq false
@user_1.sync_tables_enabled = false
@user_2.sync_tables_enabled = false
member.authorize?(@user_1).should eq true
end
end
private
def random_attributes(attributes={})
random = rand(999)
{
name: attributes.fetch(:name, "name #{random}"),
interval: attributes.fetch(:interval, 15 * 60 + random),
state: attributes.fetch(:state, 'enabled'),
user_id: attributes.fetch(:user_id, nil)
}
end
end
|
require 'rails_helper'
describe Suscribir::Suscribible do
subject { Tematica.create }
let(:dominio_de_alta) { 'es' }
let(:suscriptor) { FactoryGirl.create(:usuario) }
describe "#busca_suscripcion" do
context "sin ninguna suscripción" do
it "debe devolver nil" do
expect(subject.busca_suscripcion(suscriptor, dominio_de_alta)).to be_nil
end
end
context "con una suscripción" do
before { create(:suscripcion_con_suscriptor, suscriptor: suscriptor, suscribible: subject) }
it "debe devolver una suscripcion" do
expect(subject.busca_suscripcion(suscriptor, dominio_de_alta)).to be_present
end
end
end
describe "#busca_suscripciones" do
context "sin ninguna suscripción" do
it "debe devolver vacío" do
expect(subject.busca_suscripciones(dominio_de_alta)).to be_empty
end
end
context "con dos suscripciones" do
before { 2.times { FactoryGirl.create(:suscripcion, suscribible: subject, dominio_de_alta: dominio_de_alta) } }
it "debe devolver dos suscripciones" do
expect(subject.busca_suscripciones(dominio_de_alta).size).to eq(2)
end
end
end
describe "#nombre_lista" do
context "con un suscribible sin nombre" do
it "da un nombre identificativo para la lista de suscriptores" do
expect(subject.nombre_lista).to include subject.id.to_s
expect(subject.nombre_lista).to include subject.class.name
end
end
context "con un suscribible con nombre" do
before { allow(subject).to receive(:nombre).and_return(Faker::Lorem.sentence) }
it "da un nombre identificativo para la lista de suscriptores" do
expect(subject.nombre_lista).to include subject.id.to_s
expect(subject.nombre_lista).to include subject.class.name
expect(subject.nombre_lista).to include subject.nombre
end
end
end
end
unit tests moved from @Rankia.Respuesta to @Suscribir.Suscripciones_a_notificar
require 'rails_helper'
describe Suscribir::Suscribible do
subject { Tematica.create }
let(:dominio_de_alta) { 'es' }
let(:suscriptor) { FactoryGirl.create(:usuario) }
describe 'suscripciones_a_notificar' do
let!(:suscripcion) { create(:suscripcion_con_suscriptor, suscriptor: suscriptor, suscribible: subject) }
it 'devuelve las suscripciones a un suscribible' do
expect(subject.suscripciones_a_notificar).to eq([suscripcion])
end
it 'permite excluir ciertos id de usuario' do
expect(subject.suscripciones_a_notificar(excepto: suscriptor.id)).to eq([])
end
it 'no devuelve suscripciones de usuarios baneados' do
allow_any_instance_of(Usuario).to receive(:emailable?).and_return(false)
expect(subject.suscripciones_a_notificar).to eq([])
end
it 'devuelve suscripciones de usuarios no suscritos a alertas del foro' do
allow_any_instance_of(Usuario).to receive(:foro_alertas).and_return(false)
expect(subject.suscripciones_a_notificar).to eq([suscripcion])
end
end
describe "#busca_suscripcion" do
context "sin ninguna suscripción" do
it "debe devolver nil" do
expect(subject.busca_suscripcion(suscriptor, dominio_de_alta)).to be_nil
end
end
context "con una suscripción" do
before { create(:suscripcion_con_suscriptor, suscriptor: suscriptor, suscribible: subject) }
it "debe devolver una suscripcion" do
expect(subject.busca_suscripcion(suscriptor, dominio_de_alta)).to be_present
end
end
end
describe "#busca_suscripciones" do
context "sin ninguna suscripción" do
it "debe devolver vacío" do
expect(subject.busca_suscripciones(dominio_de_alta)).to be_empty
end
end
context "con dos suscripciones" do
before { 2.times { FactoryGirl.create(:suscripcion, suscribible: subject, dominio_de_alta: dominio_de_alta) } }
it "debe devolver dos suscripciones" do
expect(subject.busca_suscripciones(dominio_de_alta).size).to eq(2)
end
end
end
describe "#nombre_lista" do
context "con un suscribible sin nombre" do
it "da un nombre identificativo para la lista de suscriptores" do
expect(subject.nombre_lista).to include subject.id.to_s
expect(subject.nombre_lista).to include subject.class.name
end
end
context "con un suscribible con nombre" do
before { allow(subject).to receive(:nombre).and_return(Faker::Lorem.sentence) }
it "da un nombre identificativo para la lista de suscriptores" do
expect(subject.nombre_lista).to include subject.id.to_s
expect(subject.nombre_lista).to include subject.class.name
expect(subject.nombre_lista).to include subject.nombre
end
end
end
end
|
added a proof-of-concept for how loggers attach
# def log
# puts "global, self is #{ self }"
# [:global, 'main']
# end
class Logger
def self.create obj
puts "creating for #{ obj }"
name = obj.respond_to?(:name) ? obj.name : obj.to_s
logger = Logger.new(name)
obj.instance_variable_set :@logger, logger
body = ->(msg) {
puts "calling log for #{ self }"
logger.log msg
}
if obj.is_a? Class
puts "#{ obj } is a class"
obj.define_singleton_method :log, &body
obj.send :define_method, :log, &body
elsif obj.is_a? Module
puts "#{ obj } is a module"
obj.define_singleton_method :log, &body
else
puts "#{ obj } is an instance"
obj.send :define_method, :log, &body
end
end
def self.reference obj, from
puts "referencing for #{ obj }"
logger = from.instance_variable_get :@logger
body = ->(msg) {
puts "calling log for #{ self }"
logger.log msg
}
if obj.is_a? Class
puts "#{ obj } is a class"
obj.define_singleton_method :log, &body
obj.send :define_method, :log, &body
elsif obj.is_a? Module
puts "#{ obj } is a module"
obj.define_singleton_method :log, &body
else
puts "#{ obj } is an instance"
obj.send :define_method, :log, &body
end
end
attr_reader :name
def initialize name
@name = name
end
def log msg
puts "logging from Logger #{ @name }: #{ msg }"
@name
end
end
Logger.create self
module M1
def self.f msg
log msg
end
end
module M2
Logger.create self
def self.f msg
log msg
end
end
class C1
Logger.create self
def self.f msg
log msg
end
def g msg
self.class.log msg
end
def h msg
log msg
end
end
class C2 < C1
def self.f msg
log msg
end
end
module M3
Logger.create self
module M4
Logger.reference self, M3
def self.f msg
log msg
end
end
end
describe "playing around with globals and modules and includes and stuff" do
specify do
expect(log 'hey').to eq 'main'
expect(M1.f 'ho').to eq 'main'
expect(M2.log "let's go!").to eq 'M2'
expect(C1.f 'sdfsd').to eq 'C1'
c1 = C1.new
expect(c1.g 'blah').to eq 'C1'
expect(c1.h 'ex').to eq 'C1'
expect(C2.f 'eff').to eq 'C1'
expect(M3::M4.f 'lay').to eq 'M3'
end
end |
share_examples_for 'A public Resource' do
before :all do
@no_join = defined?(DataMapper::Adapters::InMemoryAdapter) && @adapter.kind_of?(DataMapper::Adapters::InMemoryAdapter) ||
defined?(DataMapper::Adapters::YamlAdapter) && @adapter.kind_of?(DataMapper::Adapters::YamlAdapter)
relationship = @user_model.relationships[:referrer]
@one_to_one_through = relationship.kind_of?(DataMapper::Associations::OneToOne::Relationship) && relationship.respond_to?(:through)
@skip = @no_join && @one_to_one_through
end
before :all do
unless @skip
%w[ @user_model @user @comment_model ].each do |ivar|
raise "+#{ivar}+ should be defined in before block" unless instance_variable_get(ivar)
end
end
end
before do
pending if @skip
end
[ :==, :=== ].each do |method|
it { @user.should respond_to(method) }
describe "##{method}" do
describe 'when comparing to the same resource' do
before :all do
@other = @user
@return = @user.__send__(method, @other)
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to an resource that does not respond to resource methods' do
before :all do
@other = Object.new
@return = @user.__send__(method, @other)
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties, but the model is a subclass' do
before :all do
rescue_if @skip do
@other = @author_model.new(@user.attributes)
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to a resource with the same repository, key and neither self or the other resource is dirty' do
before :all do
rescue_if @skip do
@other = @user_model.get(*@user.key)
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to a resource with the same repository, key but either self or the other resource is dirty' do
before :all do
rescue_if @skip do
@user.age = 20
@other = @user_model.get(*@user.key)
@return = @user.__send__(method, @other)
end
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties' do
before :all do
rescue_if @skip do
@other = @user_model.new(@user.attributes)
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
with_alternate_adapter do
describe 'when comparing to a resource with a different repository, but the same properties' do
before :all do
rescue_if @skip do
@other = @alternate_repository.scope { @user_model.create(@user.attributes) }
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
end
end
end
it { @user.should respond_to(:<=>) }
describe '#<=>' do
describe 'when the default order properties are equal with another resource' do
before :all do
rescue_if @skip do
@other = @user_model.new(:name => 'dbussink')
@return = @user <=> @other
end
end
it 'should return 0' do
@return.should == 0
end
end
describe 'when the default order property values are sorted before another resource' do
before :all do
rescue_if @skip do
@other = @user_model.new(:name => 'c')
@return = @user <=> @other
end
end
it 'should return 1' do
@return.should == 1
end
end
describe 'when the default order property values are sorted after another resource' do
before :all do
rescue_if @skip do
@other = @user_model.new(:name => 'e')
@return = @user <=> @other
end
end
it 'should return -1' do
@return.should == -1
end
end
describe 'when comparing an unrelated type of Object' do
it 'should raise an exception' do
lambda { @user <=> @comment_model.new }.should raise_error(ArgumentError, "Cannot compare a #{@comment_model} instance with a #{@user_model} instance")
end
end
end
it { @user.should respond_to(:attribute_get) }
describe '#attribute_get' do
it { @user.attribute_get(:name).should == 'dbussink' }
end
it { @user.should respond_to(:attribute_set) }
describe '#attribute_set' do
before { @user.attribute_set(:name, 'dkubb') }
it { @user.name.should == 'dkubb' }
end
it { @user.should respond_to(:attributes) }
describe '#attributes' do
describe 'with a new resource' do
before :all do
rescue_if @skip do
@user = @user.model.new
end
end
it 'should return the expected values' do
@user.attributes.should == {}
end
end
describe 'with a new resource with a property set' do
before :all do
rescue_if @skip do
@user = @user.model.new
@user.name = 'dbussink'
end
end
it 'should return the expected values' do
@user.attributes.should == {:name => 'dbussink'}
end
end
describe 'with a saved resource' do
it 'should return the expected values' do
@user.attributes.only(:name, :description, :age).should == { :name => 'dbussink', :description => 'Test', :age => 25 }
end
end
end
it { @user.should respond_to(:attributes=) }
describe '#attributes=' do
describe 'when a public mutator is specified' do
before :all do
rescue_if @skip do
@user.attributes = { :name => 'dkubb' }
end
end
it 'should set the value' do
@user.name.should eql('dkubb')
end
end
describe 'when a non-public mutator is specified' do
it 'should raise an exception' do
lambda {
@user.attributes = { :admin => true }
}.should raise_error(ArgumentError, "The attribute \'admin\' is not accessible in #{@user_model}")
end
end
end
[ :destroy, :destroy! ].each do |method|
it { @user.should respond_to(:destroy) }
describe "##{method}" do
describe 'on a single resource' do
before :all do
@resource = @user_model.create(:name => 'hacker', :age => 20, :comment => @comment)
@return = @resource.__send__(method)
end
it 'should successfully remove a resource' do
@return.should be_true
end
it 'should mark the destroyed resource as readonly' do
@resource.should be_readonly
end
it "should return true when calling #{method} on a destroyed resource" do
@resource.__send__(method).should be_true
end
it 'should remove resource from persistent storage' do
@user_model.get(*@resource.key).should be_nil
end
end
describe 'with has relationship resources' do
it 'should raise an exception'
end
end
end
it { @user.should respond_to(:dirty?) }
describe '#dirty?' do
describe 'on a record, with dirty attributes' do
before { @user.age = 100 }
it { @user.should be_dirty }
end
describe 'on a record, with no dirty attributes, and dirty parents' do
before :all do
rescue_if @skip do
@user.should_not be_dirty
parent = @user.parent = @user_model.new(:name => 'Parent')
parent.should be_dirty
end
end
it { @user.should be_dirty }
end
describe 'on a record, with no dirty attributes, and dirty children' do
before :all do
rescue_if @skip do
@user.should_not be_dirty
child = @user.children.new(:name => 'Child')
child.should be_dirty
end
end
it { @user.should be_dirty }
end
describe 'on a record, with no dirty attributes, and dirty siblings' do
before :all do
rescue_if @skip do
@user.should_not be_dirty
parent = @user_model.create(:name => 'Parent', :comment => @comment)
parent.should_not be_dirty
@user.update(:parent => parent)
@user.should_not be_dirty
sibling = parent.children.new(:name => 'Sibling')
sibling.should be_dirty
parent.should be_dirty
end
end
it { @user.should_not be_dirty }
end
describe 'on a saved record, with no dirty attributes' do
it { @user.should_not be_dirty }
end
describe 'on a new record, with no dirty attributes, no default attributes, and no identity field' do
before { @user = @user_model.new }
it { @user.should_not be_dirty }
end
describe 'on a new record, with no dirty attributes, no default attributes, and an identity field' do
before { @comment = @comment_model.new }
it { @comment.should be_dirty }
end
describe 'on a new record, with no dirty attributes, default attributes, and no identity field' do
before { @default = Default.new }
it { @default.should be_dirty }
end
describe 'on a record with itself as a parent (circular dependency)' do
before :all do
rescue_if @skip do
@user.parent = @user
end
end
it 'should not raise an exception' do
lambda {
@user.dirty?.should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with itself as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user ]
end
end
it 'should not raise an exception' do
lambda {
@user.dirty?.should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with a parent as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user.parent = @user_model.new(:name => 'Parent', :comment => @comment) ]
@user.save.should be_true
end
end
it 'should not raise an exception' do
lambda {
@user.dirty?.should be_true
}.should_not raise_error(SystemStackError)
end
end
end
it { @user.should respond_to(:eql?) }
describe '#eql?' do
describe 'when comparing to the same resource' do
before :all do
@other = @user
@return = @user.eql?(@other)
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to an resource that does not respond to model' do
before :all do
@other = Object.new
@return = @user.eql?(@other)
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties, but the model is a subclass' do
before :all do
rescue_if @skip do
@other = @author_model.new(@user.attributes)
@return = @user.eql?(@other)
end
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with a different key' do
before :all do
@other = @user_model.create(:name => 'dkubb', :age => 33, :comment => @comment)
@return = @user.eql?(@other)
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same repository, key and neither self or the other resource is dirty' do
before :all do
rescue_if @skip do
@other = @user_model.get(*@user.key)
@return = @user.eql?(@other)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to a resource with the same repository, key but either self or the other resource is dirty' do
before :all do
rescue_if @skip do
@user.age = 20
@other = @user_model.get(*@user.key)
@return = @user.eql?(@other)
end
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties' do
before :all do
rescue_if @skip do
@other = @user_model.new(@user.attributes)
@return = @user.eql?(@other)
end
end
it 'should return true' do
@return.should be_true
end
end
with_alternate_adapter do
describe 'when comparing to a resource with a different repository, but the same properties' do
before :all do
rescue_if @skip do
@other = @alternate_repository.scope { @user_model.create(@user.attributes) }
@return = @user.eql?(@other)
end
end
it 'should return true' do
@return.should be_true
end
end
end
end
it { @user.should respond_to(:inspect) }
describe '#inspect' do
before :all do
rescue_if @skip do
@user = @user_model.get(*@user.key)
@inspected = @user.inspect
end
end
it { @inspected.should match(/^#<#{@user_model}/) }
it { @inspected.should match(/name="dbussink"/) }
it { @inspected.should match(/age=25/) }
it { @inspected.should match(/description=<not loaded>/) }
end
it { @user.should respond_to(:key) }
describe '#key' do
before :all do
rescue_if @skip do
@key = @user.key
@user.name = 'dkubb'
end
end
it { @key.should be_kind_of(Array) }
it 'should always return the key value persisted in the back end' do
@key.first.should eql("dbussink")
end
it { @user.key.should eql(@key) }
end
it { @user.should respond_to(:new?) }
describe '#new?' do
describe 'on an existing record' do
it { @user.should_not be_new }
end
describe 'on a new record' do
before { @user = @user_model.new }
it { @user.should be_new }
end
end
it { @user.should respond_to(:reload) }
describe '#reload' do
before do
# reset the user for each spec
rescue_if(@skip) do
@user.update(:name => 'dbussink', :age => 25, :description => 'Test')
end
end
subject { rescue_if(@skip) { @user.reload } }
describe 'on a resource not persisted' do
before do
@user.attributes = { :description => 'Changed' }
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'reset the changed attributes' do
method(:subject).should change(@user, :description).from('Changed').to('Test')
end
end
describe 'on a resource where the key is changed, but not persisted' do
before do
@user.attributes = { :name => 'dkubb' }
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'reset the changed attributes' do
method(:subject).should change(@user, :name).from('dkubb').to('dbussink')
end
end
describe 'on a resource that is changed outside another resource' do
before do
rescue_if @skip do
@user.dup.update(:description => 'Changed')
end
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'should reload the resource from the data store' do
method(:subject).should change(@user, :description).from('Test').to('Changed')
end
end
describe 'on an anonymous resource' do
before do
rescue_if @skip do
@user = @user.class.first(:fields => [ :description ])
@user.description.should == 'Test'
end
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'should not reload any attributes' do
method(:subject).should_not change(@user, :attributes)
end
end
end
it { @user.should respond_to(:readonly?) }
describe '#readonly?' do
describe 'on a new resource' do
before :all do
rescue_if @skip do
@user = @user.model.new
end
end
it 'should return false' do
@user.readonly?.should be_false
end
end
describe 'on a saved resource' do
before :all do
rescue_if @skip do
@user.should be_saved
end
end
it 'should return false' do
@user.readonly?.should be_false
end
end
describe 'on a destroyed resource' do
before :all do
rescue_if @skip do
@user.destroy.should be_true
end
end
it 'should return true' do
@user.readonly?.should be_true
end
end
describe 'on an anonymous resource' do
before :all do
rescue_if @skip do
# load the user without a key
@user = @user.model.first(:fields => @user_model.properties - @user_model.key)
end
end
it 'should return true' do
@user.readonly?.should be_true
end
end
end
[ :save, :save! ].each do |method|
it { @user.should respond_to(method) }
describe "##{method}" do
before :all do
@user_model.class_eval do
attr_accessor :save_hook_call_count
before :save do
@save_hook_call_count ||= 0
@save_hook_call_count += 1
end
end
end
describe 'on a new, not dirty resource' do
before :all do
@user = @user_model.new
@return = @user.__send__(method)
end
it 'should return false' do
@return.should be_false
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should be_nil
end
end
describe 'on a not new, not dirty resource' do
before :all do
@return = @user.__send__(method)
end
it 'should return true even when resource is not dirty' do
@return.should be_true
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should be_nil
end
end
describe 'on a not new, dirty resource' do
before :all do
rescue_if @skip do
@user.age = 26
@return = @user.__send__(method)
end
end
it 'should save a resource succesfully when dirty' do
@return.should be_true
end
it 'should actually store the changes to persistent storage' do
@user.attributes.should == @user.reload.attributes
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should == (method == :save ? 1 : nil)
end
end
describe 'on a dirty invalid resource' do
before :all do
rescue_if @skip do
@user.name = nil
end
end
it 'should not save an invalid resource' do
@user.__send__(method).should be_false
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should == (method == :save ? 1 : nil)
end
end
describe 'with new resources in a has relationship' do
before do
rescue_if 'TODO: fix for one to one association', !@user.respond_to?(:comments) do
@initial_comments = @user.comments.size
@first_comment = @user.comments.new(:body => "DM is great!")
@second_comment = @comment_model.new(:user => @user, :body => "is it really?")
@return = @user.__send__(method)
end
end
it 'should save resource' do
pending_if !@user.respond_to?(:comments) do
@return.should be_true
end
end
it 'should save the first resource created through new' do
pending_if !@user.respond_to?(:comments) do
@first_comment.new?.should be_false
end
end
it 'should save the correct foreign key for the first resource' do
pending_if !@user.respond_to?(:comments) do
@first_comment.user.should eql(@user)
end
end
it 'should save the second resource created through the constructor' do
pending "Changing a belongs_to parent should add the resource to the correct association" do
@second_comment.new?.should be_false
end
end
it 'should save the correct foreign key for the second resource' do
pending_if !@user.respond_to?(:comments) do
@second_comment.user.should eql(@user)
end
end
it 'should create 2 extra resources in persistent storage' do
pending "Changing a belongs_to parent should add the resource to the correct association" do
@user.comments.size.should == @initial_comments + 2
end
end
end
describe 'with dirty resources in a has relationship' do
before :all do
rescue_if 'TODO: fix for one to one association', !@user.respond_to?(:comments) do
@first_comment = @user.comments.create(:body => 'DM is great!')
@second_comment = @comment_model.create(:user => @user, :body => 'is it really?')
@first_comment.body = 'It still has rough edges'
@second_comment.body = 'But these cool specs help fixing that'
@second_comment.user = @user_model.create(:name => 'dkubb')
@return = @user.__send__(method)
end
end
it 'should return true' do
pending_if !@user.respond_to?(:comments) do
@return.should be_true
end
end
it 'should not be dirty' do
@user.should_not be_dirty
end
it 'should have saved the first child resource' do
pending_if !@user.respond_to?(:comments) do
@first_comment.model.get(*@first_comment.key).body.should == 'It still has rough edges'
end
end
it 'should not have saved the second child resource' do
pending_if !@user.respond_to?(:comments) do
@second_comment.model.get(*@second_comment.key).body.should == 'is it really?'
end
end
end
describe 'with a new dependency' do
before :all do
@first_comment = @comment_model.new(:body => "DM is great!")
@first_comment.user = @user_model.new(:name => 'dkubb')
end
it 'should not raise an exception when saving the resource' do
pending do
lambda { @first_comment.send(method).should be_false }.should_not raise_error
end
end
end
describe 'with a dirty dependency' do
before :all do
rescue_if @skip do
@user.name = 'dbussink-the-second'
@first_comment = @comment_model.new(:body => 'DM is great!')
@first_comment.user = @user
@return = @first_comment.__send__(method)
end
end
it 'should succesfully save the resource' do
@return.should be_true
end
it 'should not have a dirty dependency' do
@user.should_not be_dirty
end
it 'should succesfully save the dependency' do
@user.attributes.should == @user_model.get(*@user.key).attributes
end
end
describe 'with a new resource and new relations' do
before :all do
@article = @article_model.new(:body => "Main")
rescue_if 'TODO: fix for one to one association', (!@article.respond_to?(:paragraphs)) do
@paragraph = @article.paragraphs.new(:text => 'Content')
@article.__send__(method)
end
end
it 'should not be dirty' do
pending_if !@article.respond_to?(:paragraphs) do
@article.should_not be_dirty
end
end
it 'should not be dirty' do
pending_if !@article.respond_to?(:paragraphs) do
@paragraph.should_not be_dirty
end
end
it 'should set the related resource' do
pending_if !@article.respond_to?(:paragraphs) do
@paragraph.article.should == @article
end
end
it 'should set the foreign key properly' do
pending_if !@article.respond_to?(:paragraphs) do
@paragraph.article_id.should == @article.id
end
end
end
describe 'with a dirty resource with a changed key' do
before :all do
rescue_if @skip do
@original_key = @user.key
@user.name = 'dkubb'
@return = @user.__send__(method)
end
end
it 'should save a resource succesfully when dirty' do
@return.should be_true
end
it 'should actually store the changes to persistent storage' do
@user.name.should == @user.reload.name
end
it 'should update the identity map' do
@user.repository.identity_map(@user_model).should have_key(%w[ dkubb ])
end
it 'should remove the old entry from the identity map' do
@user.repository.identity_map(@user_model).should_not have_key(@original_key)
end
end
describe 'on a new resource with unsaved parent and grandparent' do
before :all do
@grandparent = @user_model.new(:name => 'dkubb', :comment => @comment)
@parent = @user_model.new(:name => 'ashleymoran', :comment => @comment, :referrer => @grandparent)
@child = @user_model.new(:name => 'mrship', :comment => @comment, :referrer => @parent)
@response = @child.__send__(method)
end
it 'should return true' do
@response.should be_true
end
it 'should save the child' do
@child.should be_saved
end
it 'should save the parent' do
@parent.should be_saved
end
it 'should save the grandparent' do
@grandparent.should be_saved
end
it 'should relate the child to the parent' do
@child.model.get(*@child.key).referrer.should == @parent
end
it 'should relate the parent to the grandparent' do
@parent.model.get(*@parent.key).referrer.should == @grandparent
end
it 'should relate the grandparent to nothing' do
@grandparent.model.get(*@grandparent.key).referrer.should be_nil
end
end
describe 'on a destroyed resource' do
before :all do
rescue_if @skip do
@user.destroy
end
end
it 'should raise an exception' do
lambda {
@user.__send__(method)
}.should raise_error(DataMapper::PersistenceError, "#{@user.model}##{method} cannot be called on a destroyed resource")
end
end
describe 'on a record with itself as a parent (circular dependency)' do
before :all do
rescue_if @skip do
@user.parent = @user
end
end
it 'should not raise an exception' do
lambda {
@user.__send__(method).should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with itself as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user ]
end
end
it 'should not raise an exception' do
lambda {
@user.__send__(method).should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with a parent as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user.parent = @user_model.new(:name => 'Parent', :comment => @comment) ]
end
end
it 'should not raise an exception' do
lambda {
@user.__send__(method).should be_true
}.should_not raise_error(SystemStackError)
end
end
end
end
it { @user.should respond_to(:saved?) }
describe '#saved?' do
describe 'on an existing record' do
it { @user.should be_saved }
end
describe 'on a new record' do
before { @user = @user_model.new }
it { @user.should_not be_saved }
end
end
[ :update, :update! ].each do |method|
it { @user.should respond_to(method) }
describe "##{method}" do
describe 'with no arguments' do
before :all do
rescue_if @skip do
@return = @user.__send__(method)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'with attributes' do
before :all do
rescue_if @skip do
@attributes = { :description => 'Changed' }
@return = @user.__send__(method, @attributes)
end
end
it 'should return true' do
@return.should be_true
end
it 'should update attributes of Resource' do
@attributes.each { |key, value| @user.__send__(key).should == value }
end
it 'should persist the changes' do
resource = @user_model.get(*@user.key)
@attributes.each { |key, value| resource.__send__(key).should == value }
end
end
describe 'with attributes where one is a parent association' do
before :all do
rescue_if @skip do
@attributes = { :referrer => @user_model.create(:name => 'dkubb', :age => 33, :comment => @comment) }
@return = @user.__send__(method, @attributes)
end
end
it 'should return true' do
@return.should be_true
end
it 'should update attributes of Resource' do
@attributes.each { |key, value| @user.__send__(key).should == value }
end
it 'should persist the changes' do
resource = @user_model.get(*@user.key)
@attributes.each { |key, value| resource.__send__(key).should == value }
end
end
describe 'with attributes where a value is nil for a property that does not allow nil' do
before :all do
rescue_if @skip do
@return = @user.__send__(method, :name => nil)
end
end
it 'should return false' do
@return.should be_false
end
it 'should not persist the changes' do
@user.reload.name.should_not be_nil
end
end
describe 'on a dirty resource' do
before :all do
rescue_if @skip do
@user.age = 99
end
end
it 'should raise an exception' do
lambda {
@user.__send__(method, :admin => true)
}.should raise_error(DataMapper::UpdateConflictError, "#{@user.model}##{method} cannot be called on a dirty resource")
end
end
end
end
describe 'invalid resources' do
before do
class ::EmptyObject
include DataMapper::Resource
end
class ::KeylessObject
include DataMapper::Resource
property :name, String
end
end
it 'should raise an error for a resource without attributes' do
lambda { EmptyObject.new }.should raise_error
end
it 'should raise an error for a resource without a key' do
lambda { KeylessObject.new }.should raise_error
end
after do
# clean out invalid models so that global model cleanup
# does not throw an exception when working with models
# in an invalid state
[ EmptyObject, KeylessObject ].each do |model|
Object.send(:remove_const, model.name.to_sym)
DataMapper::Model.descendants.delete(model)
end
end
end
describe 'lazy loading' do
before :all do
rescue_if @skip do
@user.name = 'dkubb'
@user.age = 33
@user.summary = 'Programmer'
# lazy load the description
@user.description
end
end
it 'should not overwrite dirty attribute' do
@user.age.should == 33
end
it 'should not overwrite dirty lazy attribute' do
@user.summary.should == 'Programmer'
end
it 'should not overwrite dirty key' do
pending do
@user.name.should == 'dkubb'
end
end
end
end
Minor fix to spec for in-memory adapter
share_examples_for 'A public Resource' do
before :all do
@no_join = defined?(DataMapper::Adapters::InMemoryAdapter) && @adapter.kind_of?(DataMapper::Adapters::InMemoryAdapter) ||
defined?(DataMapper::Adapters::YamlAdapter) && @adapter.kind_of?(DataMapper::Adapters::YamlAdapter)
relationship = @user_model.relationships[:referrer]
@one_to_one_through = relationship.kind_of?(DataMapper::Associations::OneToOne::Relationship) && relationship.respond_to?(:through)
@skip = @no_join && @one_to_one_through
end
before :all do
unless @skip
%w[ @user_model @user @comment_model ].each do |ivar|
raise "+#{ivar}+ should be defined in before block" unless instance_variable_get(ivar)
end
end
end
before do
pending if @skip
end
[ :==, :=== ].each do |method|
it { @user.should respond_to(method) }
describe "##{method}" do
describe 'when comparing to the same resource' do
before :all do
@other = @user
@return = @user.__send__(method, @other)
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to an resource that does not respond to resource methods' do
before :all do
@other = Object.new
@return = @user.__send__(method, @other)
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties, but the model is a subclass' do
before :all do
rescue_if @skip do
@other = @author_model.new(@user.attributes)
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to a resource with the same repository, key and neither self or the other resource is dirty' do
before :all do
rescue_if @skip do
@other = @user_model.get(*@user.key)
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to a resource with the same repository, key but either self or the other resource is dirty' do
before :all do
rescue_if @skip do
@user.age = 20
@other = @user_model.get(*@user.key)
@return = @user.__send__(method, @other)
end
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties' do
before :all do
rescue_if @skip do
@other = @user_model.new(@user.attributes)
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
with_alternate_adapter do
describe 'when comparing to a resource with a different repository, but the same properties' do
before :all do
rescue_if @skip do
@other = @alternate_repository.scope { @user_model.create(@user.attributes) }
@return = @user.__send__(method, @other)
end
end
it 'should return true' do
@return.should be_true
end
end
end
end
end
it { @user.should respond_to(:<=>) }
describe '#<=>' do
describe 'when the default order properties are equal with another resource' do
before :all do
rescue_if @skip do
@other = @user_model.new(:name => 'dbussink')
@return = @user <=> @other
end
end
it 'should return 0' do
@return.should == 0
end
end
describe 'when the default order property values are sorted before another resource' do
before :all do
rescue_if @skip do
@other = @user_model.new(:name => 'c')
@return = @user <=> @other
end
end
it 'should return 1' do
@return.should == 1
end
end
describe 'when the default order property values are sorted after another resource' do
before :all do
rescue_if @skip do
@other = @user_model.new(:name => 'e')
@return = @user <=> @other
end
end
it 'should return -1' do
@return.should == -1
end
end
describe 'when comparing an unrelated type of Object' do
it 'should raise an exception' do
lambda { @user <=> @comment_model.new }.should raise_error(ArgumentError, "Cannot compare a #{@comment_model} instance with a #{@user_model} instance")
end
end
end
it { @user.should respond_to(:attribute_get) }
describe '#attribute_get' do
it { @user.attribute_get(:name).should == 'dbussink' }
end
it { @user.should respond_to(:attribute_set) }
describe '#attribute_set' do
before { @user.attribute_set(:name, 'dkubb') }
it { @user.name.should == 'dkubb' }
end
it { @user.should respond_to(:attributes) }
describe '#attributes' do
describe 'with a new resource' do
before :all do
rescue_if @skip do
@user = @user.model.new
end
end
it 'should return the expected values' do
@user.attributes.should == {}
end
end
describe 'with a new resource with a property set' do
before :all do
rescue_if @skip do
@user = @user.model.new
@user.name = 'dbussink'
end
end
it 'should return the expected values' do
@user.attributes.should == {:name => 'dbussink'}
end
end
describe 'with a saved resource' do
it 'should return the expected values' do
@user.attributes.only(:name, :description, :age).should == { :name => 'dbussink', :description => 'Test', :age => 25 }
end
end
end
it { @user.should respond_to(:attributes=) }
describe '#attributes=' do
describe 'when a public mutator is specified' do
before :all do
rescue_if @skip do
@user.attributes = { :name => 'dkubb' }
end
end
it 'should set the value' do
@user.name.should eql('dkubb')
end
end
describe 'when a non-public mutator is specified' do
it 'should raise an exception' do
lambda {
@user.attributes = { :admin => true }
}.should raise_error(ArgumentError, "The attribute \'admin\' is not accessible in #{@user_model}")
end
end
end
[ :destroy, :destroy! ].each do |method|
it { @user.should respond_to(:destroy) }
describe "##{method}" do
describe 'on a single resource' do
before :all do
@resource = @user_model.create(:name => 'hacker', :age => 20, :comment => @comment)
@return = @resource.__send__(method)
end
it 'should successfully remove a resource' do
@return.should be_true
end
it 'should mark the destroyed resource as readonly' do
@resource.should be_readonly
end
it "should return true when calling #{method} on a destroyed resource" do
@resource.__send__(method).should be_true
end
it 'should remove resource from persistent storage' do
@user_model.get(*@resource.key).should be_nil
end
end
describe 'with has relationship resources' do
it 'should raise an exception'
end
end
end
it { @user.should respond_to(:dirty?) }
describe '#dirty?' do
describe 'on a record, with dirty attributes' do
before { @user.age = 100 }
it { @user.should be_dirty }
end
describe 'on a record, with no dirty attributes, and dirty parents' do
before :all do
rescue_if @skip do
@user.should_not be_dirty
parent = @user.parent = @user_model.new(:name => 'Parent')
parent.should be_dirty
end
end
it { @user.should be_dirty }
end
describe 'on a record, with no dirty attributes, and dirty children' do
before :all do
rescue_if @skip do
@user.should_not be_dirty
child = @user.children.new(:name => 'Child')
child.should be_dirty
end
end
it { @user.should be_dirty }
end
describe 'on a record, with no dirty attributes, and dirty siblings' do
before :all do
rescue_if @skip do
@user.should_not be_dirty
parent = @user_model.create(:name => 'Parent', :comment => @comment)
parent.should_not be_dirty
@user.update(:parent => parent)
@user.should_not be_dirty
sibling = parent.children.new(:name => 'Sibling')
sibling.should be_dirty
parent.should be_dirty
end
end
it { @user.should_not be_dirty }
end
describe 'on a saved record, with no dirty attributes' do
it { @user.should_not be_dirty }
end
describe 'on a new record, with no dirty attributes, no default attributes, and no identity field' do
before { @user = @user_model.new }
it { @user.should_not be_dirty }
end
describe 'on a new record, with no dirty attributes, no default attributes, and an identity field' do
before { @comment = @comment_model.new }
it { @comment.should be_dirty }
end
describe 'on a new record, with no dirty attributes, default attributes, and no identity field' do
before { @default = Default.new }
it { @default.should be_dirty }
end
describe 'on a record with itself as a parent (circular dependency)' do
before :all do
rescue_if @skip do
@user.parent = @user
end
end
it 'should not raise an exception' do
lambda {
@user.dirty?.should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with itself as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user ]
end
end
it 'should not raise an exception' do
lambda {
@user.dirty?.should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with a parent as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user.parent = @user_model.new(:name => 'Parent', :comment => @comment) ]
@user.save.should be_true
end
end
it 'should not raise an exception' do
lambda {
@user.dirty?.should be_true
}.should_not raise_error(SystemStackError)
end
end
end
it { @user.should respond_to(:eql?) }
describe '#eql?' do
describe 'when comparing to the same resource' do
before :all do
@other = @user
@return = @user.eql?(@other)
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to an resource that does not respond to model' do
before :all do
@other = Object.new
@return = @user.eql?(@other)
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties, but the model is a subclass' do
before :all do
rescue_if @skip do
@other = @author_model.new(@user.attributes)
@return = @user.eql?(@other)
end
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with a different key' do
before :all do
@other = @user_model.create(:name => 'dkubb', :age => 33, :comment => @comment)
@return = @user.eql?(@other)
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same repository, key and neither self or the other resource is dirty' do
before :all do
rescue_if @skip do
@other = @user_model.get(*@user.key)
@return = @user.eql?(@other)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'when comparing to a resource with the same repository, key but either self or the other resource is dirty' do
before :all do
rescue_if @skip do
@user.age = 20
@other = @user_model.get(*@user.key)
@return = @user.eql?(@other)
end
end
it 'should return false' do
@return.should be_false
end
end
describe 'when comparing to a resource with the same properties' do
before :all do
rescue_if @skip do
@other = @user_model.new(@user.attributes)
@return = @user.eql?(@other)
end
end
it 'should return true' do
@return.should be_true
end
end
with_alternate_adapter do
describe 'when comparing to a resource with a different repository, but the same properties' do
before :all do
rescue_if @skip do
@other = @alternate_repository.scope { @user_model.create(@user.attributes) }
@return = @user.eql?(@other)
end
end
it 'should return true' do
@return.should be_true
end
end
end
end
it { @user.should respond_to(:inspect) }
describe '#inspect' do
before :all do
rescue_if @skip do
@user = @user_model.get(*@user.key)
@inspected = @user.inspect
end
end
it { @inspected.should match(/^#<#{@user_model}/) }
it { @inspected.should match(/name="dbussink"/) }
it { @inspected.should match(/age=25/) }
it { @inspected.should match(/description=<not loaded>/) }
end
it { @user.should respond_to(:key) }
describe '#key' do
before :all do
rescue_if @skip do
@key = @user.key
@user.name = 'dkubb'
end
end
it { @key.should be_kind_of(Array) }
it 'should always return the key value persisted in the back end' do
@key.first.should eql("dbussink")
end
it { @user.key.should eql(@key) }
end
it { @user.should respond_to(:new?) }
describe '#new?' do
describe 'on an existing record' do
it { @user.should_not be_new }
end
describe 'on a new record' do
before { @user = @user_model.new }
it { @user.should be_new }
end
end
it { @user.should respond_to(:reload) }
describe '#reload' do
before do
# reset the user for each spec
rescue_if(@skip) do
@user.update(:name => 'dbussink', :age => 25, :description => 'Test')
end
end
subject { rescue_if(@skip) { @user.reload } }
describe 'on a resource not persisted' do
before do
@user.attributes = { :description => 'Changed' }
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'reset the changed attributes' do
method(:subject).should change(@user, :description).from('Changed').to('Test')
end
end
describe 'on a resource where the key is changed, but not persisted' do
before do
@user.attributes = { :name => 'dkubb' }
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'reset the changed attributes' do
method(:subject).should change(@user, :name).from('dkubb').to('dbussink')
end
end
describe 'on a resource that is changed outside another resource' do
before do
rescue_if @skip do
@user.dup.update(:description => 'Changed')
end
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'should reload the resource from the data store' do
method(:subject).should change(@user, :description).from('Test').to('Changed')
end
end
describe 'on an anonymous resource' do
before do
rescue_if @skip do
@user = @user.class.first(:fields => [ :description ])
@user.description.should == 'Test'
end
end
it { should be_kind_of(DataMapper::Resource) }
it { should equal(@user) }
it { should be_clean }
it 'should not reload any attributes' do
method(:subject).should_not change(@user, :attributes)
end
end
end
it { @user.should respond_to(:readonly?) }
describe '#readonly?' do
describe 'on a new resource' do
before :all do
rescue_if @skip do
@user = @user.model.new
end
end
it 'should return false' do
@user.readonly?.should be_false
end
end
describe 'on a saved resource' do
before :all do
rescue_if @skip do
@user.should be_saved
end
end
it 'should return false' do
@user.readonly?.should be_false
end
end
describe 'on a destroyed resource' do
before :all do
rescue_if @skip do
@user.destroy.should be_true
end
end
it 'should return true' do
@user.readonly?.should be_true
end
end
describe 'on an anonymous resource' do
before :all do
rescue_if @skip do
# load the user without a key
@user = @user.model.first(:fields => @user_model.properties - @user_model.key)
end
end
it 'should return true' do
@user.readonly?.should be_true
end
end
end
[ :save, :save! ].each do |method|
it { @user.should respond_to(method) }
describe "##{method}" do
before :all do
@user_model.class_eval do
attr_accessor :save_hook_call_count
before :save do
@save_hook_call_count ||= 0
@save_hook_call_count += 1
end
end
end
describe 'on a new, not dirty resource' do
before :all do
@user = @user_model.new
@return = @user.__send__(method)
end
it 'should return false' do
@return.should be_false
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should be_nil
end
end
describe 'on a not new, not dirty resource' do
before :all do
rescue_if @skip do
@return = @user.__send__(method)
end
end
it 'should return true even when resource is not dirty' do
@return.should be_true
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should be_nil
end
end
describe 'on a not new, dirty resource' do
before :all do
rescue_if @skip do
@user.age = 26
@return = @user.__send__(method)
end
end
it 'should save a resource succesfully when dirty' do
@return.should be_true
end
it 'should actually store the changes to persistent storage' do
@user.attributes.should == @user.reload.attributes
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should == (method == :save ? 1 : nil)
end
end
describe 'on a dirty invalid resource' do
before :all do
rescue_if @skip do
@user.name = nil
end
end
it 'should not save an invalid resource' do
@user.__send__(method).should be_false
end
it 'should call save hook expected number of times' do
@user.save_hook_call_count.should == (method == :save ? 1 : nil)
end
end
describe 'with new resources in a has relationship' do
before do
rescue_if 'TODO: fix for one to one association', !@user.respond_to?(:comments) do
@initial_comments = @user.comments.size
@first_comment = @user.comments.new(:body => "DM is great!")
@second_comment = @comment_model.new(:user => @user, :body => "is it really?")
@return = @user.__send__(method)
end
end
it 'should save resource' do
pending_if !@user.respond_to?(:comments) do
@return.should be_true
end
end
it 'should save the first resource created through new' do
pending_if !@user.respond_to?(:comments) do
@first_comment.new?.should be_false
end
end
it 'should save the correct foreign key for the first resource' do
pending_if !@user.respond_to?(:comments) do
@first_comment.user.should eql(@user)
end
end
it 'should save the second resource created through the constructor' do
pending "Changing a belongs_to parent should add the resource to the correct association" do
@second_comment.new?.should be_false
end
end
it 'should save the correct foreign key for the second resource' do
pending_if !@user.respond_to?(:comments) do
@second_comment.user.should eql(@user)
end
end
it 'should create 2 extra resources in persistent storage' do
pending "Changing a belongs_to parent should add the resource to the correct association" do
@user.comments.size.should == @initial_comments + 2
end
end
end
describe 'with dirty resources in a has relationship' do
before :all do
rescue_if 'TODO: fix for one to one association', !@user.respond_to?(:comments) do
@first_comment = @user.comments.create(:body => 'DM is great!')
@second_comment = @comment_model.create(:user => @user, :body => 'is it really?')
@first_comment.body = 'It still has rough edges'
@second_comment.body = 'But these cool specs help fixing that'
@second_comment.user = @user_model.create(:name => 'dkubb')
@return = @user.__send__(method)
end
end
it 'should return true' do
pending_if !@user.respond_to?(:comments) do
@return.should be_true
end
end
it 'should not be dirty' do
@user.should_not be_dirty
end
it 'should have saved the first child resource' do
pending_if !@user.respond_to?(:comments) do
@first_comment.model.get(*@first_comment.key).body.should == 'It still has rough edges'
end
end
it 'should not have saved the second child resource' do
pending_if !@user.respond_to?(:comments) do
@second_comment.model.get(*@second_comment.key).body.should == 'is it really?'
end
end
end
describe 'with a new dependency' do
before :all do
@first_comment = @comment_model.new(:body => "DM is great!")
@first_comment.user = @user_model.new(:name => 'dkubb')
end
it 'should not raise an exception when saving the resource' do
pending do
lambda { @first_comment.send(method).should be_false }.should_not raise_error
end
end
end
describe 'with a dirty dependency' do
before :all do
rescue_if @skip do
@user.name = 'dbussink-the-second'
@first_comment = @comment_model.new(:body => 'DM is great!')
@first_comment.user = @user
@return = @first_comment.__send__(method)
end
end
it 'should succesfully save the resource' do
@return.should be_true
end
it 'should not have a dirty dependency' do
@user.should_not be_dirty
end
it 'should succesfully save the dependency' do
@user.attributes.should == @user_model.get(*@user.key).attributes
end
end
describe 'with a new resource and new relations' do
before :all do
@article = @article_model.new(:body => "Main")
rescue_if 'TODO: fix for one to one association', (!@article.respond_to?(:paragraphs)) do
@paragraph = @article.paragraphs.new(:text => 'Content')
@article.__send__(method)
end
end
it 'should not be dirty' do
pending_if !@article.respond_to?(:paragraphs) do
@article.should_not be_dirty
end
end
it 'should not be dirty' do
pending_if !@article.respond_to?(:paragraphs) do
@paragraph.should_not be_dirty
end
end
it 'should set the related resource' do
pending_if !@article.respond_to?(:paragraphs) do
@paragraph.article.should == @article
end
end
it 'should set the foreign key properly' do
pending_if !@article.respond_to?(:paragraphs) do
@paragraph.article_id.should == @article.id
end
end
end
describe 'with a dirty resource with a changed key' do
before :all do
rescue_if @skip do
@original_key = @user.key
@user.name = 'dkubb'
@return = @user.__send__(method)
end
end
it 'should save a resource succesfully when dirty' do
@return.should be_true
end
it 'should actually store the changes to persistent storage' do
@user.name.should == @user.reload.name
end
it 'should update the identity map' do
@user.repository.identity_map(@user_model).should have_key(%w[ dkubb ])
end
it 'should remove the old entry from the identity map' do
@user.repository.identity_map(@user_model).should_not have_key(@original_key)
end
end
describe 'on a new resource with unsaved parent and grandparent' do
before :all do
@grandparent = @user_model.new(:name => 'dkubb', :comment => @comment)
@parent = @user_model.new(:name => 'ashleymoran', :comment => @comment, :referrer => @grandparent)
@child = @user_model.new(:name => 'mrship', :comment => @comment, :referrer => @parent)
@response = @child.__send__(method)
end
it 'should return true' do
@response.should be_true
end
it 'should save the child' do
@child.should be_saved
end
it 'should save the parent' do
@parent.should be_saved
end
it 'should save the grandparent' do
@grandparent.should be_saved
end
it 'should relate the child to the parent' do
@child.model.get(*@child.key).referrer.should == @parent
end
it 'should relate the parent to the grandparent' do
@parent.model.get(*@parent.key).referrer.should == @grandparent
end
it 'should relate the grandparent to nothing' do
@grandparent.model.get(*@grandparent.key).referrer.should be_nil
end
end
describe 'on a destroyed resource' do
before :all do
rescue_if @skip do
@user.destroy
end
end
it 'should raise an exception' do
lambda {
@user.__send__(method)
}.should raise_error(DataMapper::PersistenceError, "#{@user.model}##{method} cannot be called on a destroyed resource")
end
end
describe 'on a record with itself as a parent (circular dependency)' do
before :all do
rescue_if @skip do
@user.parent = @user
end
end
it 'should not raise an exception' do
lambda {
@user.__send__(method).should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with itself as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user ]
end
end
it 'should not raise an exception' do
lambda {
@user.__send__(method).should be_true
}.should_not raise_error(SystemStackError)
end
end
describe 'on a record with a parent as a child (circular dependency)' do
before :all do
rescue_if @skip do
@user.children = [ @user.parent = @user_model.new(:name => 'Parent', :comment => @comment) ]
end
end
it 'should not raise an exception' do
lambda {
@user.__send__(method).should be_true
}.should_not raise_error(SystemStackError)
end
end
end
end
it { @user.should respond_to(:saved?) }
describe '#saved?' do
describe 'on an existing record' do
it { @user.should be_saved }
end
describe 'on a new record' do
before { @user = @user_model.new }
it { @user.should_not be_saved }
end
end
[ :update, :update! ].each do |method|
it { @user.should respond_to(method) }
describe "##{method}" do
describe 'with no arguments' do
before :all do
rescue_if @skip do
@return = @user.__send__(method)
end
end
it 'should return true' do
@return.should be_true
end
end
describe 'with attributes' do
before :all do
rescue_if @skip do
@attributes = { :description => 'Changed' }
@return = @user.__send__(method, @attributes)
end
end
it 'should return true' do
@return.should be_true
end
it 'should update attributes of Resource' do
@attributes.each { |key, value| @user.__send__(key).should == value }
end
it 'should persist the changes' do
resource = @user_model.get(*@user.key)
@attributes.each { |key, value| resource.__send__(key).should == value }
end
end
describe 'with attributes where one is a parent association' do
before :all do
rescue_if @skip do
@attributes = { :referrer => @user_model.create(:name => 'dkubb', :age => 33, :comment => @comment) }
@return = @user.__send__(method, @attributes)
end
end
it 'should return true' do
@return.should be_true
end
it 'should update attributes of Resource' do
@attributes.each { |key, value| @user.__send__(key).should == value }
end
it 'should persist the changes' do
resource = @user_model.get(*@user.key)
@attributes.each { |key, value| resource.__send__(key).should == value }
end
end
describe 'with attributes where a value is nil for a property that does not allow nil' do
before :all do
rescue_if @skip do
@return = @user.__send__(method, :name => nil)
end
end
it 'should return false' do
@return.should be_false
end
it 'should not persist the changes' do
@user.reload.name.should_not be_nil
end
end
describe 'on a dirty resource' do
before :all do
rescue_if @skip do
@user.age = 99
end
end
it 'should raise an exception' do
lambda {
@user.__send__(method, :admin => true)
}.should raise_error(DataMapper::UpdateConflictError, "#{@user.model}##{method} cannot be called on a dirty resource")
end
end
end
end
describe 'invalid resources' do
before do
class ::EmptyObject
include DataMapper::Resource
end
class ::KeylessObject
include DataMapper::Resource
property :name, String
end
end
it 'should raise an error for a resource without attributes' do
lambda { EmptyObject.new }.should raise_error
end
it 'should raise an error for a resource without a key' do
lambda { KeylessObject.new }.should raise_error
end
after do
# clean out invalid models so that global model cleanup
# does not throw an exception when working with models
# in an invalid state
[ EmptyObject, KeylessObject ].each do |model|
Object.send(:remove_const, model.name.to_sym)
DataMapper::Model.descendants.delete(model)
end
end
end
describe 'lazy loading' do
before :all do
rescue_if @skip do
@user.name = 'dkubb'
@user.age = 33
@user.summary = 'Programmer'
# lazy load the description
@user.description
end
end
it 'should not overwrite dirty attribute' do
@user.age.should == 33
end
it 'should not overwrite dirty lazy attribute' do
@user.summary.should == 'Programmer'
end
it 'should not overwrite dirty key' do
pending do
@user.name.should == 'dkubb'
end
end
end
end
|
require "spec_helper"
app_require "repositories/story_repository"
describe StoryRepository do
klass = described_class
describe ".urls_to_absolute" do
it "preserves existing absolute urls" do
content = '<a href="http://foo">bar</a>'
expect(klass.urls_to_absolute(content, nil)).to eq(content)
end
it "replaces relative urls in a, img and video tags" do
content = <<-EOS
<div>
<img src="https://foo">
<a href="/bar/baz">tee</a>
<img src="bar/bar">
<video src="/tee"></video>
</div>
EOS
expect(klass.urls_to_absolute(content, "http://oodl.io/d/")).to eq(<<-EOS)
<div>
<img src="https://foo">
<a href="http://oodl.io/bar/baz">tee</a>
<img src="http://oodl.io/d/bar/bar">
<video src="http://oodl.io/tee"></video>
</div>
EOS
end
end
end
urls_to_absolute spec: remove newlines before comparing
require "spec_helper"
app_require "repositories/story_repository"
describe StoryRepository do
klass = described_class
describe ".urls_to_absolute" do
it "preserves existing absolute urls" do
content = '<a href="http://foo">bar</a>'
expect(klass.urls_to_absolute(content, nil)).to eq(content)
end
it "replaces relative urls in a, img and video tags" do
content = <<-EOS
<div>
<img src="https://foo">
<a href="/bar/baz">tee</a><img src="bar/bar">
<video src="/tee"></video>
</div>
EOS
expect(klass.urls_to_absolute(content, "http://oodl.io/d/").gsub(/\n/, ""))
.to eq((<<-EOS).gsub(/\n/, ""))
<div>
<img src="https://foo">
<a href="http://oodl.io/bar/baz">tee</a>
<img src="http://oodl.io/d/bar/bar">
<video src="http://oodl.io/tee"></video>
</div>
EOS
end
end
end
|
require 'rails_helper'
RSpec.describe Api::DropsController, :vcr, type: :request do
context 'with several drops present' do
let!(:drops) { FactoryGirl.create_list(:drop, 3) }
describe "GET /drops" do
it "displays list of drops in database" do
get api_drops_path(format: :json)
expect(response.status).to eq(200)
end
it "defines JSON as format in headers" do
get "/api/drops"
expect(response.headers["Content-Type"]).to include 'application/json'
end
it "delivers valid JSON" do
get "/api/drops"
parsed_response = ActiveSupport::JSON.decode(response.body)
puts parsed_response
expect(parsed_response).to be_a Enumerable
end
it "contains a place sub-structure" do
get "/api/drops"
parsed_response = ActiveSupport::JSON.decode(response.body)
expect(parsed_response[0]["place"].keys).to eq(["id", "name", "latitude", "longitude"])
end
end
#let!(:drops) { FactoryGirl.create_list(:drop, 3) }
describe "GET /api/drops" do
context 'with latitude and longitude given' do
let!(:place_near_soundcloud) { FactoryGirl.create :place, :place_near_soundcloud}
let!(:place_australia) { FactoryGirl.create :place, :place_australia }
let!(:drop_at_Bernauer) { FactoryGirl.create :drop, :drop_at_Bernauer}
let!(:drop_in_sydney) { FactoryGirl.create :drop, :drop_in_sydney}
it "does not return drops outside of radius" do
expect(place_near_soundcloud).to be_geocoded
puts "Near soundcloud:"
puts place_near_soundcloud.to_coordinates
puts "Australia"
expect(place_australia).to be_geocoded
puts place_australia.to_coordinates
puts "Drop bernauer"
expect(drop_at_Bernauer.place).to be_geocoded
puts drop_at_Bernauer.place.to_coordinates
#
puts "Drop syndey"
expect(drop_in_sydney.place).to be_geocoded
puts drop_in_sydney.place.to_coordinates
puts "Distance"
class ANiceClass
include Geocoder::Calculations
end
distance = ANiceClass.new.distance_between(drop_at_Bernauer.place.to_coordinates, place_near_soundcloud.to_coordinates)
puts distance.to_s
get "/api/drops?latitude=52.537016&longitude=13.394861"
parsed_response = ActiveSupport::JSON.decode(response.body)
#puts parsed_response
expect(parsed_response[0].keys).to include("id")
end
it "returns empty array if there are no drops within the radius" do
end
end
end
end
end
refactor factories, reduce scope of list factory, make radius test more specific
require 'rails_helper'
RSpec.describe Api::DropsController, :vcr, type: :request do
context 'with several drops present' do
describe "GET /drops" do
let!(:drops) { FactoryGirl.create_list(:drop, 3) }
it "displays list of drops in database" do
get api_drops_path(format: :json)
expect(response.status).to eq(200)
end
it "defines JSON as format in headers" do
get "/api/drops"
expect(response.headers["Content-Type"]).to include 'application/json'
end
it "delivers valid JSON" do
get "/api/drops"
parsed_response = ActiveSupport::JSON.decode(response.body)
expect(parsed_response).to be_a Enumerable
end
it "contains a place sub-structure" do
get "/api/drops"
parsed_response = ActiveSupport::JSON.decode(response.body)
expect(parsed_response[0]["place"].keys).to eq(["id", "name", "latitude", "longitude"])
end
end
describe "GET /api/drops" do
context 'with latitude and longitude given' do
let!(:drop_in_berlin) { FactoryGirl.create :drop, :drop_at_Bernauer}
let!(:drop_in_sydney) { FactoryGirl.create :drop, :drop_in_sydney}
it "returns drop in Berlin" do
get "/api/drops?latitude=52.537016&longitude=13.394861" # Somewhere in the middle of Berlin
parsed_response = ActiveSupport::JSON.decode(response.body)
expect(parsed_response.length).to eq(1)
expect(parsed_response[0]["place"].values[2]).to eql drop_in_berlin.place.latitude.to_s
end
it "" do
end
end
end
end
end
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'dirtiness_validator/version'
Gem::Specification.new do |spec|
spec.name = 'dirtiness_validator'
spec.version = DirtinessValidator::VERSION
spec.authors = ['tyamagu2']
spec.email = ['tyamagu2@gmail.com']
spec.summary = %q{Dirtiness Validator validates attributes against their previous values.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_runtime_dependency 'activemodel'
spec.add_development_dependency 'bundler', '~> 1.10'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec'
end
Set homepage in gemspec
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'dirtiness_validator/version'
Gem::Specification.new do |spec|
spec.name = 'dirtiness_validator'
spec.version = DirtinessValidator::VERSION
spec.authors = ['tyamagu2']
spec.email = ['tyamagu2@gmail.com']
spec.summary = %q{Dirtiness Validator validates attributes against their previous values.}
spec.homepage = 'https://github.com/tyamagu2/dirtiness_validator'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_runtime_dependency 'activemodel'
spec.add_development_dependency 'bundler', '~> 1.10'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec'
end
|
# frozen_string_literal: true
shared_examples "a multiton" do
let(:args) { [123, :symbol, "String"] }
def expect_class_to_be_a_multiton(klass)
expect(klass).to be_a(Multiton)
expect(klass.instance(*args)).to be(klass.instance(*args))
end
def expect_generated_instances_to_be_the_same(klass_1, klass_2)
[klass_1, klass_2].each {|klass| expect_class_to_be_a_multiton(klass) }
expect(klass_1.instance(*args)).to be(klass_2.instance(*args))
end
def expect_generated_instances_to_be_different(klass_1, klass_2)
[klass_1, klass_2].each {|klass| expect_class_to_be_a_multiton(klass) }
expect(klass_1.instance(*args)).not_to be(klass_2.instance(*args))
end
describe Multiton::Mixin do
it "is an ancestor" do
expect(subject.ancestors).to include(described_class)
end
end
describe ".allocate" do
it "is not accesible" do
expect { subject.allocate }.to raise_error(NoMethodError)
end
end
describe ".clone" do
let(:clone) { subject.clone }
context "when passing the same arguments" do
it "generates a different instance than the original class" do
expect_generated_instances_to_be_different(subject, clone)
end
end
end
describe ".dup" do
let(:duplicate) { subject.dup }
context "when passing the same arguments" do
it "generates a different instance than the original class" do
expect_generated_instances_to_be_different(subject, duplicate)
end
end
end
describe ".new" do
it "is not accesible" do
expect { subject.new }.to raise_error(NoMethodError)
end
end
describe "instance" do
let(:object) { subject.instance(*args) }
let(:other_args) { [456, :other_symbol, "other string"] }
let(:other_object) { subject.instance(*other_args) }
context "when passing the same arguments" do
it "generates the same instances" do
expect(object).to be(subject.instance(*args))
expect(other_object).to be(subject.instance(*other_args))
end
end
context "when passing different arguments" do
it "generates different instances" do
expect(object).not_to be(other_object)
end
end
describe "marshalling" do
let(:marshalled_object) { Marshal.load(Marshal.dump(object)) }
let(:other_marshalled_object) { Marshal.load(Marshal.dump(other_object)) }
it "generates the same instances" do
# We need to give the anonymous class a name so it can be marshalled.
stub_const("Klass", subject)
expect(object).to be(marshalled_object)
expect(other_object).to be(other_marshalled_object)
expect(marshalled_object).not_to be(other_marshalled_object)
end
end
end
describe "marshalling" do
let(:marshalled_class) { Marshal.load(Marshal.dump(subject)) }
context "when passing the same arguments" do
it "generates the same instance than the original class" do
# We need to give the anonymous class a name so it can be marshalled.
stub_const("Klass", subject)
expect_generated_instances_to_be_the_same(Klass, marshalled_class)
end
end
end
describe "subclass" do
let(:subclass) { Class.new(subject) }
context "when passing the same arguments" do
it "generates a different instance than the original class" do
expect_generated_instances_to_be_different(subject, subclass)
end
end
end
end
Refactor `a_multiton.rb` shared examples.
# frozen_string_literal: true
shared_examples "a multiton" do
let(:args) { [123, :symbol, "String"] }
def expect_classes_to_be_multitons(*klasses)
expect(klasses).to all(be_a(Multiton))
klasses.each {|klass| expect(klass.instance(*args)).to be(klass.instance(*args)) }
end
def expect_generated_instances_to_be_the_same(klass_1, klass_2)
expect_classes_to_be_multitons(klass_1, klass_2)
expect(klass_1.instance(*args)).to be(klass_2.instance(*args))
end
def expect_generated_instances_to_be_different(klass_1, klass_2)
expect_classes_to_be_multitons(klass_1, klass_2)
expect(klass_1.instance(*args)).not_to be(klass_2.instance(*args))
end
describe Multiton::Mixin do
it "is an ancestor" do
expect(subject.ancestors).to include(described_class)
end
end
describe ".allocate" do
it "is not accesible" do
expect { subject.allocate }.to raise_error(NoMethodError)
end
end
describe ".clone" do
let(:clone) { subject.clone }
context "when passing the same arguments" do
it "generates a different instance than the original class" do
expect_generated_instances_to_be_different(subject, clone)
end
end
end
describe ".dup" do
let(:duplicate) { subject.dup }
context "when passing the same arguments" do
it "generates a different instance than the original class" do
expect_generated_instances_to_be_different(subject, duplicate)
end
end
end
describe ".new" do
it "is not accesible" do
expect { subject.new }.to raise_error(NoMethodError)
end
end
describe "instance" do
let(:object) { subject.instance(*args) }
let(:other_args) { [456, :other_symbol, "other string"] }
let(:other_object) { subject.instance(*other_args) }
context "when passing the same arguments" do
it "generates the same instances" do
expect(object).to be(subject.instance(*args))
expect(other_object).to be(subject.instance(*other_args))
end
end
context "when passing different arguments" do
it "generates different instances" do
expect(object).not_to be(other_object)
end
end
describe "marshalling" do
let(:marshalled_object) { Marshal.load(Marshal.dump(object)) }
let(:other_marshalled_object) { Marshal.load(Marshal.dump(other_object)) }
it "generates the same instances" do
# We need to give the anonymous class a name so it can be marshalled.
stub_const("Klass", subject)
expect(object).to be(marshalled_object)
expect(other_object).to be(other_marshalled_object)
expect(marshalled_object).not_to be(other_marshalled_object)
end
end
end
describe "marshalling" do
let(:marshalled_class) { Marshal.load(Marshal.dump(subject)) }
context "when passing the same arguments" do
it "generates the same instance than the original class" do
# We need to give the anonymous class a name so it can be marshalled.
stub_const("Klass", subject)
expect_generated_instances_to_be_the_same(Klass, marshalled_class)
end
end
end
describe "subclass" do
let(:subclass) { Class.new(subject) }
context "when passing the same arguments" do
it "generates a different instance than the original class" do
expect_generated_instances_to_be_different(subject, subclass)
end
end
end
end
|
require 'test_process_automator/runner'
RSpec.describe TestProcessAutomator::Runner do
let(:automator) { described_class.new(init_options) }
let(:init_options) { { name: name } }
describe 'initalised with a name' do
let(:name) { 'a_name' }
describe '#name' do
subject { automator.name }
specify { expect(subject).to be(name) }
end
context 'and with a :frontend process injected' do
let(:the_frontend_kill_command) { 'kill_that_frontend' }
let(:the_frontend) do
double('the frontend',
kill_command: the_frontend_kill_command
)
end
before do
automator.add_process(frontend: the_frontend)
end
describe '#kill!(:frontend)' do
subject { automator.kill!(:frontend) }
it 'runs shell command specified for frontend' do
expect(automator).to receive(:system).with(the_frontend_kill_command)
subject
end
end
context 'and with a :worker process injected' do
let(:the_worker_kill_command) { 'kill_that_worker' }
let(:the_worker) do
double('the worker',
kill_command: the_worker_kill_command
)
end
before do
automator.add_process(worker: the_worker)
end
describe '#kill!(:worker)' do
subject { automator.kill!(:worker) }
it 'runs shell command specified for worker' do
expect(automator).to receive(:system).with(the_worker_kill_command)
subject
end
it 'does not runs shell command specified for frontend' do
expect(automator).to_not receive(:system).with(the_frontend_kill_command)
subject
end
end
describe '#kill!(:worker, :frontend)' do
subject { automator.kill!(:worker, :frontend) }
before { allow(automator).to receive(:system).with(anything) }
it 'runs shell command specified for worker' do
expect(automator).to receive(:system).with(the_worker_kill_command)
subject
end
it 'runs shell command specified for frontend' do
expect(automator).to receive(:system).with(the_frontend_kill_command)
subject
end
end
end
end
end
end
refactor specs
require 'test_process_automator/runner'
RSpec.describe TestProcessAutomator::Runner do
let(:automator) { described_class.new(init_options) }
let(:init_options) { { name: name } }
let(:the_frontend_kill) { 'kill_that_frontend' }
let(:the_frontend) do
double('the frontend',
kill_command: the_frontend_kill
)
end
let(:the_worker_kill) { 'kill_that_worker' }
let(:the_worker) do
double('the worker',
kill_command: the_worker_kill
)
end
describe 'initalised with a name' do
let(:name) { 'a_name' }
describe '#name' do
subject { automator.name }
specify { expect(subject).to be(name) }
end
context 'and with a :frontend process injected' do
before { automator.add_process(frontend: the_frontend) }
describe '#kill!(:frontend)' do
subject { automator.kill!(:frontend) }
it 'runs shell command specified for frontend' do
expect(automator).to receive(:system).with(the_frontend_kill)
subject
end
end
context 'and with a :worker process injected' do
before { automator.add_process(worker: the_worker) }
describe '#kill!(:worker)' do
subject { automator.kill!(:worker) }
it 'runs shell command specified for worker' do
expect(automator).to receive(:system).with(the_worker_kill)
subject
end
it 'does not runs shell command specified for frontend' do
expect(automator).to_not receive(:system).with(the_frontend_kill)
subject
end
end
describe '#kill!(:worker, :frontend)' do
subject { automator.kill!(:worker, :frontend) }
before { allow(automator).to receive(:system).with(anything) }
it 'runs shell command specified for worker' do
expect(automator).to receive(:system).with(the_worker_kill)
subject
end
it 'runs shell command specified for frontend' do
expect(automator).to receive(:system).with(the_frontend_kill)
subject
end
end
end
end
end
end
|
require 'spec_helper'
describe 'test::recursor_install' do
context 'on ubuntu platform' do
let(:ubuntu_runner) do
ChefSpec::SoloRunner.new(
platform: 'ubuntu',
version: '14.04',
step_into: ['pdns_recursor'])
end
let(:chef_run) { ubuntu_runner.converge(described_recipe) }
let(:version) { '3.7.4' }
# Chef gets node['lsb']['codename'] even if it is not set as an attribute
it 'adds apt repository' do
expect(chef_run).to add_apt_repository('powerdns-recursor')
.with(uri: 'http://repo.powerdns.com/ubuntu', distribution: 'trusty-rec-40')
end
it 'creates apt pin for pdns' do
expect(chef_run).to add_apt_preference('pdns-*')
.with(pin: 'origin repo.powerdns.com', pin_priority: '600')
end
it 'installs pdns recursor package' do
expect(chef_run).to install_apt_package('pdns-recursor').with(version: version)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
context 'on rhel platform' do
let(:rhel_runner) do
ChefSpec::SoloRunner.new(
platform: 'centos',
version: '6.8',
step_into: ['pdns_recursor'])
end
let(:chef_run) { rhel_runner.converge(described_recipe) }
let(:version) { '3.7.4' }
it 'adds yum repository powerdns-rec-40' do
expect(chef_run).to create_yum_repository('powerdns-rec-40')
end
it 'adds yum repository powerdns-rec-40-debuginfo' do
expect(chef_run).to create_yum_repository('powerdns-rec-40-debuginfo')
end
it 'installs pdns recursor package' do
expect(chef_run).to install_yum_package('pdns-recursor').with(version: version)
end
end
end
Set correct package versions and add epel test
require 'spec_helper'
describe 'test::recursor_install' do
context 'on ubuntu platform' do
let(:ubuntu_runner) do
ChefSpec::SoloRunner.new(
platform: 'ubuntu',
version: '14.04',
step_into: ['pdns_recursor'])
end
let(:chef_run) { ubuntu_runner.converge(described_recipe) }
let(:version) { '4.0.4-1pdns.trusty' }
# Chef gets node['lsb']['codename'] even if it is not set as an attribute
it 'adds apt repository' do
expect(chef_run).to add_apt_repository('powerdns-recursor')
.with(uri: 'http://repo.powerdns.com/ubuntu', distribution: 'trusty-rec-40')
end
it 'creates apt pin for pdns' do
expect(chef_run).to add_apt_preference('pdns-*')
.with(pin: 'origin repo.powerdns.com', pin_priority: '600')
end
it 'installs pdns recursor package' do
expect(chef_run).to install_apt_package('pdns-recursor').with(version: version)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
context 'on rhel platform' do
let(:rhel_runner) do
ChefSpec::SoloRunner.new(
platform: 'centos',
version: '6.8',
step_into: ['pdns_recursor']) do |node|
node.automatic['centos-release']['version'] = '6'
end
end
let(:chef_run) { rhel_runner.converge(described_recipe) }
let(:version) { '4.0.4-1pdns.el6' }
it 'installs epel-release package' do
expect(chef_run).to install_yum_package('epel-release')
end
it 'adds yum repository powerdns-rec-40' do
expect(chef_run).to create_yum_repository('powerdns-rec-40')
end
it 'adds yum repository powerdns-rec-40-debuginfo' do
expect(chef_run).to create_yum_repository('powerdns-rec-40-debuginfo')
end
it 'installs pdns recursor package' do
expect(chef_run).to install_yum_package('pdns-recursor').with(version: version)
end
end
end
|
# coding: utf-8
require 'spec_helper'
RSpec.describe TTY::Table::Renderer::Basic, 'multiline content' do
context 'with escaping' do
it "renders multiline as single line" do
rows = [ ["First", '1'], ["Multiline\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: false)
expect(renderer.render).to eq <<-EOS.normalize
First 1
Multiline\\nContent 2
Third 3
EOS
end
it "truncates multiline content" do
rows = [ ["First", '1'], ["Multiline\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: false, column_widths: [8,1])
expect(renderer.render).to eq <<-EOS.normalize
First 1
Multil… 2
Third 3
EOS
end
end
context 'without escaping' do
it "renders every line" do
rows = [["First", '1'], ["Multi\nLine\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: true)
expect(renderer.render).to eq <<-EOS.normalize
First 1
Multi 2
Line
Content
Third 3
EOS
end
it "renders multiline with column widths" do
rows = [["First", '1'], ["Multi\nLine\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: true, column_widths: [8,1])
expect(renderer.render).to eq <<-EOS.normalize
First 1
Multi 2
Line
Content
Third 3
EOS
end
it 'wraps multi line' do
rows = [["First", '1'], ["Multi\nLine\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: true, column_widths: [5,1])
expect(renderer.render).to eq <<-EOS.normalize
First 1
Multi 2
Line
Conte
nt
Third 3
EOS
end
end
end
Ensure multiline content.
# coding: utf-8
require 'spec_helper'
RSpec.describe TTY::Table::Renderer::Basic, 'multiline content' do
context 'with escaping' do
it "renders multiline as single line" do
rows = [ ["First", '1'], ["Multiline\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: false)
expect(renderer.render).to eq unindent(<<-EOS)
First 1
Multiline\\nContent 2
Third 3
EOS
end
it "truncates multiline content" do
rows = [ ["First", '1'], ["Multiline\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: false, column_widths: [8,1])
expect(renderer.render).to eq unindent(<<-EOS)
First 1
Multil… 2
Third 3
EOS
end
end
context 'without escaping' do
it "renders every line" do
rows = [["First", '1'],
["Multi\nLine\nContent", '2'],
["Third", "Multi\nLine"]]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: true)
expect(renderer.render).to eq unindent(<<-EOS)
First 1
Multi 2
Line
Content
Third Multi
Line
EOS
end
it "renders multiline with column widths" do
rows = [["First", '1'], ["Multi\nLine\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: true, column_widths: [8,1])
expect(renderer.render).to eq unindent(<<-EOS)
First 1
Multi 2
Line
Content
Third 3
EOS
end
it 'wraps multi line' do
rows = [["First", '1'], ["Multi\nLine\nContent", '2'], ["Third", '3']]
table = TTY::Table.new rows
renderer = described_class.new(table, multiline: true, column_widths: [5,1])
expect(renderer.render).to eq unindent(<<-EOS)
First 1
Multi 2
Line
Conte
nt
Third 3
EOS
end
end
end
|
require 'json'
require 'logger'
require 'citysdk'
require 'trollop'
DATA_TYPES = [
'json',
'kml',
'zip'
]
def main
opts = parse_options()
logger = Logger.new(STDOUT)
url = opts.fetch(:url)
email = opts.fetch(:email)
password = opts.fetch(:password)
api = CitySDK::API.new(url)
api.set_credentials(email, password)
layer = opts.fetch(:layer)
unless api.layer?(layer)
logger.info("Creating layer: #{layer}, as it does not exist")
api.create_layer(
name: layer,
description: opts.fetch(:description),
organization: opts.fetch(:organization),
category: opts.fetch(:category)
)
end # unless
logger.info("Loading nodes from #{opts.fetch(:input)}")
builder = CitySDK::NodeBuilder.new
case opts[:type]
when 'json'
builder.load_data_set_from_json!(opts.fetch(:input))
builder.set_geometry_from_lat_lon!('lat', 'lon')
when 'zip'
builder.load_data_set_from_zip!(opts.fetch(:input))
when 'kml'
builder.load_data_set_from_kml!(opts.fetch(:input))
end
unless opts[:id].nil?
builder.set_node_id_from_value!(opts.fetch(:id))
end
unless opts[:name].nil?
name = opts.fetch(:name)
builder.set_node_name_from_value!(name)
builder.set_node_data_from_key_value!('name', name)
end
unless opts[:id_field].nil?
builder.set_node_id_from_data_field!(opts[:id_field])
end
unless opts[:name_field].nil?
builder.set_node_name_from_data_field!(opts[:name_field])
end
logger.info('Building nodes')
nodes = builder.build
logger.info('Creating nodes through the CitySDK API')
api.create_nodes(layer, nodes)
return 0
end
def parse_options
opts = Trollop::options do
opt(:type , "One of: #{DATA_TYPES.join(', ')}", type: :string)
opt(:category , 'Layer category' , type: :string)
opt(:config , 'Configuration file' , type: :string)
opt(:description , 'Layer description' , type: :string)
opt(:input , 'Input file to import', type: :string, required: true)
opt(:layer , 'Layer name' , type: :string)
opt(:organization, 'Layer organization' , type: :string)
opt(:password , 'CitySDK password' , type: :string)
opt(:url , 'CitySDK API base URL', type: :string)
opt(:email , 'CitySDK email' , type: :string)
opt(:id_field , 'Field for id' , type: :string)
opt(:name_field , 'Field for name' , type: :string)
opt(:id , 'Id to use' , type: :string)
opt(:name , 'Name to user' , type: :string)
end
unless opts[:config].nil?
config = open(opts.fetch(:config)) do |config_file|
JSON.load(config_file, nil, symbolize_names: true)
end # do
opts = opts.merge(config)
end # unless
required = [
:category,
:description,
:layer,
:organization,
:password,
:url,
:email,
:type
]
required.each do |opt|
Trollop::die(opt, 'must be specified.') if opts[opt].nil?
end # do
unless DATA_TYPES.include? opts[:type]
Trollop::die(:type, "must be one of #{DATA_TYPES.join(', ')}")
end # unless
opts
end
if __FILE__ == $0
exit main
end
Catch connection error so as not scare people
require 'json'
require 'logger'
require 'citysdk'
require 'trollop'
DATA_TYPES = [
'json',
'kml',
'zip'
]
def main
opts = parse_options()
logger = Logger.new(STDOUT)
url = opts.fetch(:url)
email = opts.fetch(:email)
password = opts.fetch(:password)
api = CitySDK::API.new(url)
api.set_credentials(email, password)
layer = opts.fetch(:layer)
unless api.layer?(layer)
logger.info("Creating layer: #{layer}, as it does not exist")
api.create_layer(
name: layer,
description: opts.fetch(:description),
organization: opts.fetch(:organization),
category: opts.fetch(:category)
)
end # unless
logger.info("Loading nodes from #{opts.fetch(:input)}")
builder = CitySDK::NodeBuilder.new
case opts[:type]
when 'json'
builder.load_data_set_from_json!(opts.fetch(:input))
builder.set_geometry_from_lat_lon!('lat', 'lon')
when 'zip'
builder.load_data_set_from_zip!(opts.fetch(:input))
when 'kml'
builder.load_data_set_from_kml!(opts.fetch(:input))
end
unless opts[:id].nil?
builder.set_node_id_from_value!(opts.fetch(:id))
end
unless opts[:name].nil?
name = opts.fetch(:name)
builder.set_node_name_from_value!(name)
builder.set_node_data_from_key_value!('name', name)
end
unless opts[:id_field].nil?
builder.set_node_id_from_data_field!(opts[:id_field])
end
unless opts[:name_field].nil?
builder.set_node_name_from_data_field!(opts[:name_field])
end
logger.info('Building nodes')
nodes = builder.build
logger.info('Creating nodes through the CitySDK API')
api.create_nodes(layer, nodes)
return 0
rescue Faraday::Error::ConnectionFailed => connection_error
puts "Could not connect to the API: #{connection_error.message}"
return 1
end
def parse_options
opts = Trollop::options do
opt(:type , "One of: #{DATA_TYPES.join(', ')}", type: :string)
opt(:category , 'Layer category' , type: :string)
opt(:config , 'Configuration file' , type: :string)
opt(:description , 'Layer description' , type: :string)
opt(:input , 'Input file to import', type: :string, required: true)
opt(:layer , 'Layer name' , type: :string)
opt(:organization, 'Layer organization' , type: :string)
opt(:password , 'CitySDK password' , type: :string)
opt(:url , 'CitySDK API base URL', type: :string)
opt(:email , 'CitySDK email' , type: :string)
opt(:id_field , 'Field for id' , type: :string)
opt(:name_field , 'Field for name' , type: :string)
opt(:id , 'Id to use' , type: :string)
opt(:name , 'Name to user' , type: :string)
end
unless opts[:config].nil?
config = open(opts.fetch(:config)) do |config_file|
JSON.load(config_file, nil, symbolize_names: true)
end # do
opts = opts.merge(config)
end # unless
required = [
:category,
:description,
:layer,
:organization,
:password,
:url,
:email,
:type
]
required.each do |opt|
Trollop::die(opt, 'must be specified.') if opts[opt].nil?
end # do
unless DATA_TYPES.include? opts[:type]
Trollop::die(:type, "must be one of #{DATA_TYPES.join(', ')}")
end # unless
opts
end
if __FILE__ == $0
exit main
end
|
482d5f05-2d48-11e5-9f2d-7831c1c36510
48336d68-2d48-11e5-b2f8-7831c1c36510
48336d68-2d48-11e5-b2f8-7831c1c36510 |
require 'rubygems'
require 'debugger'
require '/home/jschmid/reviewlette/mail'
require '/home/jschmid/reviewlette/auth'
require '/home/jschmid/reviewlette/nameparser'
require 'yaml'
require 'octokit'
# user = Auth::Basic.new
# user.basic_auth
#
# pars = Parse::Contributers.new
# pars.get_names
#
# #puts $array #debug maybe store it into a file later on
# name = $name_list.sample
#
# mail = Supporter::Mailer.new
# mail.send_email "jschmid@suse.de", :body => "#{name}"
secret = YAML.load_file('.secrets.yml')
@client = Octokit::Client.new(:access_token => secret['token'])
@client.user_authenticated? ? true : exit
@eval= @client.pull_requests('jschmid1/reviewlette')
@pull_list_old = []
@pull_list = []
@eval.each do |a|
number = a[:number]
@pull_list_old.push(number)
if @pull_list_old.push(number).length < @pull_list.push(number).length
sha = @client.pull_request('jschmid1/reviewlette', "#{@pull_list[-1]}" )
@sha_id= sha.head.sha
name = YAML.load_file('members.yml')
@client.create_pull_request_comment('jschmid1/reviewlette', "#{@pull_list[-1]}", "#{name['member'].sample} is you reviewer", "#{@sha_id}", '/', 1)
end
end
# client.user.rels[:repos].get.data.first.rels[:pulls].get.data.inspect
# @client.create_pull_request('jschmid1/reviewlette', 'master', 'review_140521_test_branch', 'title', 'body')
# @client.update_pull_request('jschmid1/reviewlette', 5, 'new title', 'updated body', 'closed')
# @client.create_pull_request_comment('jschmid1/reviewlette', 5, ":thumbsup:",
# '259b7293f03f13e71cdf7825eda2c5da8b67c59d', 'README.md', 1)
# puts @client.say
#
# count pullrequests => if pullrequests.new > pullrequests
# assign teammember to it
# create pull request comment
# send mail
# end
# will be depricated when implemented in git-review gem
# @user = @client.search_users('jschmid1').inspect
#no mehtod for asssining a teammember to a given issue
added repo var
require 'rubygems'
require 'debugger'
require '/home/jschmid/reviewlette/mail'
require '/home/jschmid/reviewlette/auth'
require '/home/jschmid/reviewlette/nameparser'
require 'yaml'
require 'octokit'
# user = Auth::Basic.new
# user.basic_auth
#
# pars = Parse::Contributers.new
# pars.get_names
#
# #puts $array #debug maybe store it into a file later on
# name = $name_list.sample
#
# mail = Supporter::Mailer.new
# mail.send_email "jschmid@suse.de", :body => "#{name}"
@repo = 'jschmid1/reviewlette'
secret = YAML.load_file('.secrets.yml')
@client = Octokit::Client.new(:access_token => secret['token'])
@client.user_authenticated? ? true : exit
@eval= @client.pull_requests('jschmid1/reviewlette')
@pull_list_old = []
@pull_list = []
@eval.each do |a|
number = a[:number]
@pull_list_old.push(number)
sleep(10)
if @pull_list_old.length < @pull_list.push(number).length
sha = @client.pull_request("#{@repo}", "#{@pull_list[-1]}" )
@sha_id= sha.head.sha
name = YAML.load_file('members.yml')
@client.create_pull_request_comment("#{@repo}", "#{@pull_list[-1]}",
"#{name['member'].sample} is you reviewer :thumbsup:", "#{@sha_id}", '', 1)
end
end
# @client.create_pull_request('jschmid1/reviewlette', 'master', 'review_140521_test_branch', 'title', 'body')
# - (Array<Sawyer::Resource>) pull_request_files(repo, number, options = {}) (also: #pull_files)
#
# List files on a pull request.
# @user = @client.search_users('jschmid1').inspect
#no mehtod for asssining a teammember to a given issue |
#!/usr/loal/bin/ruby
require 'dogapi'
require 'wiringpi2'
API_KEY=ENV['DD_API_KEY']
APP_KEY=ENV['DD_APP_KEY']
dog = Dogapi::Client.new(API_KEY, APP_KEY)
PIN_NUMBER = 2
Class SimpleLogger
MODE = { :DETAIL => 'DETAIL', :SUMMARY => 'SUMMARY' }
def new(mode)
self.mode = mode
self.switch_count = 0
self.on_count = 0
self.off_count = 0
end
def log(message)
if mode == MODE[:DETAIL]
log_detail(message)
return
end
log_summary(message)
end
def log_detail(message)
pp "[#{Time.now}] - #{message}"
end
def log_summary(message)
self.switch_count += 1
if message == 'on'
self.on_count += 1
else
self.off_count += 1
end
if self.switch_count > 1000
pp "[#{Time.now}] - on_count: #{self.on_count} off_count: #{self.off_count}"
self.switch_count = 0
self.on_count = 0
self.off_count = 0
end
end
end
def on(io, pin_number)
io.digital_write(pin_number, WiringPi::HIGH)
logger.log('on')
end
def off(io, pin_number)
io.digital_write(pin_number, WiringPi::LOW)
logger.log('off')
end
io = WiringPi::GPIO.new do |gpio|
gpio.pin_mode(2, WiringPi::OUTPUT)
end
logger = SimpleLogger.new(SimpleLogger::MODE[:DETAIL])
loop do
alart_num = dog.get_all_monitors(:group_states => ['alert'])[1].select do |item|
pp item
item['overall_state'] != 'OK'
end.size
if alart_num > 0
on(io, PIN_NUMBER)
else
off(io, PIN_NUMBER)
end
sleep 5
end
Fix logger
#!/usr/loal/bin/ruby
require 'dogapi'
require 'wiringpi2'
API_KEY=ENV['DD_API_KEY']
APP_KEY=ENV['DD_APP_KEY']
dog = Dogapi::Client.new(API_KEY, APP_KEY)
PIN_NUMBER = 2
class SimpleLogger
MODE = { :DETAIL => 'DETAIL', :SUMMARY => 'SUMMARY' }
@mode
@switch_count
@on_count
@off_count
def initialize(mode)
@mode = mode
@switch_count = 0
@on_count = 0
@off_count = 0
end
def log(message)
if @mode == MODE[:DETAIL]
log_detail(message)
else
log_summary(message)
end
end
def log_detail(message)
pp "[#{Time.now}] - #{message}"
end
def log_summary(message)
@switch_count += 1
if message == 'on'
@on_count += 1
else
@off_count += 1
end
if @switch_count > 1000
pp "[#{Time.now}] - on_count: #{@on_count} off_count: #{@off_count}"
@switch_count = 0
@on_count = 0
@off_count = 0
end
end
end
io = WiringPi::GPIO.new do |gpio|
gpio.pin_mode(2, WiringPi::OUTPUT)
end
logger = SimpleLogger.new(SimpleLogger::MODE[:DETAIL])
loop do
alart_num = dog.get_all_monitors(:group_states => ['alert'])[1].select do |item|
pp item
item['overall_state'] != 'OK'
end.size
if alart_num > 0
io.digital_write(PIN_NUMBER, WiringPi::HIGH)
logger.log('on')
else
io.digital_write(PIN_NUMBER, WiringPi::LOW)
logger.log('off')
end
sleep 5
end
|
62f92305-2d48-11e5-91be-7831c1c36510
62ff559e-2d48-11e5-ad62-7831c1c36510
62ff559e-2d48-11e5-ad62-7831c1c36510 |
68085561-2d48-11e5-8f3e-7831c1c36510
680f6bc0-2d48-11e5-8c0d-7831c1c36510
680f6bc0-2d48-11e5-8c0d-7831c1c36510 |
require 'sinatra'
require 'sinatra/base'
require_relative 'lisence_list'
require 'active_support'
require 'active_support/core_ext'
class LicenseDownload < Sinatra::Base
def error_message
message = "Please specify a type of license name.\n"
message << "\n"
message << "Supported list:\n"
message << LICENSE_LIST.map { |key, _value| key }.join(', ')
message << "\n"
end
get '*' do
license_name = params[:splat].to_a.first.delete('/').to_sym
p license_name
if LICENSE_LIST.map { |key, _value| key }.exclude? license_name
error_message
else
File.read "license_files/#{LICENSE_LIST[license_name]}"
end
end
end
Fix typo
require 'sinatra'
require 'sinatra/base'
require_relative 'license_list'
require 'active_support'
require 'active_support/core_ext'
class LicenseDownload < Sinatra::Base
def error_message
message = "Please specify a type of license name.\n"
message << "\n"
message << "Supported list:\n"
message << LICENSE_LIST.map { |key, _value| key }.join(', ')
message << "\n"
end
get '*' do
license_name = params[:splat].to_a.first.delete('/').to_sym
p license_name
if LICENSE_LIST.map { |key, _value| key }.exclude? license_name
error_message
else
File.read "license_files/#{LICENSE_LIST[license_name]}"
end
end
end
|
685d174c-2d48-11e5-bd11-7831c1c36510
686319fa-2d48-11e5-a823-7831c1c36510
686319fa-2d48-11e5-a823-7831c1c36510 |
#!/usr/bin/env ruby
require 'yaml'
$script_location = File.dirname(__FILE__)
$project_root = ""
$config = nil
require_relative "#{$script_location}/Utils"
require_relative "#{$script_location}/Store"
require_relative "#{$script_location}/Model"
require_relative "#{$script_location}/Controller"
# Elements
require_relative "#{$script_location}/elements/Grid"
require_relative "#{$script_location}/elements/Combo"
require_relative "#{$script_location}/elements/Panel"
require_relative "#{$script_location}/elements/Form"
utils = Utils.new()
# find config file
utils.set_project_root() # for now this will set global variable $project_root
options = utils.argv_parser
e = nil # element to generate
if options[:type] == "combo"
e = ComboBox.new(options[:path], options[:options])
elsif options[:type] == "grid"
e = Grid.new(options[:path], options[:options])
elsif options[:type] == "store"
e = Store.new(options[:path], options[:options])
elsif options[:type] == "model"
e = Model.new(options[:path], options[:options])
elsif options[:type] == "panel"
e = Panel.new(options[:path], options[:options])
elsif options[:type] == "form"
e = Form.new(options[:path], options[:options])
elsif options[:type] == "controller"
e = Controller.new(options[:path], options[:options])
else
puts "Error: Can not create type #{options[:type]}"
abort
end
# output generated code or put to file
if options[:options].include? "-o"
e.output
elsif
e.create
end
# display alias only if it parent class is element
if e.methods.include? 'output_path_and_alias'
e.output_path_and_alias
end
modify main to call new generator class
#!/usr/bin/env ruby
require 'yaml'
$script_location = File.dirname(__FILE__)
$project_root = ""
$config = nil
require_relative "#{$script_location}/Utils"
require_relative "#{$script_location}/Generator"
require_relative "#{$script_location}/Script"
u = Utils.new()
# find config file
u.set_project_root() # for now this will set global variable $project_root
params = u.parse_argv
Generator.new(params[:tpl], params[:path], params[:options]).generate().create()
|
5faee899-2d48-11e5-abad-7831c1c36510
5fb50c6e-2d48-11e5-ac9f-7831c1c36510
5fb50c6e-2d48-11e5-ac9f-7831c1c36510 |
542cc5c5-2d48-11e5-a9c0-7831c1c36510
5433004f-2d48-11e5-b42b-7831c1c36510
5433004f-2d48-11e5-b42b-7831c1c36510 |
#!/usr/bin/env ruby
require 'nokogiri'
require 'open-uri'
require 'fileutils'
class Bible
@base_url = "http://www.biblica.com"
@first_url = "/en-us/bible/online-bible/nvi-pt/genesis/1/"
@urls_path = "urls"
def self.create_download_files
next_url = @base_url + @first_url
Dir.mkdir(@urls_path) unless Dir.exist?(@urls_path)
urls_dir = Dir.new(@urls_path)
# while true
5.times do
body = Nokogiri::HTML(open(next_url))
download_elem = body.css("audio > source[type='audio/mpeg']").first
# header_elem = body.css("h1").first
# puts header_elem.text
# folder = header_elem.text.gsub(/The\ Bible\: /, "").gsub(/\ \d*$/, "")
folder = next_url.split("/")[-2]
filename = File.join(urls_dir, folder + ".txt")
f = File.open(filename, "a")
f.puts download_elem["src"]
f.close
next_elem = body.css(".next").first
next_url = @base_url + next_elem["href"]
end
end
def self.download_audios
Dir[File.join(@urls_path, "*.txt")].each do |file|
`wget --directory-prefix='downloads/#{file.split('/').last.gsub('.txt', '')}' -i #{file}`
end
end
end
Bible.create_download_files
Bible.download_audios
optimization
#!/usr/bin/env ruby
require 'nokogiri'
require 'open-uri'
# require 'fileutils'
class Bible
@base_url = "http://www.biblica.com"
@first_url = "/en-us/bible/online-bible/nvi-pt/genesis/1/"
@urls_path = "urls"
def self.create_download_files
next_url = @base_url + @first_url
dirs = []
while true
body = Nokogiri::HTML(open(next_url))
download_elem = body.css("audio > source[type='audio/mpeg']").first
folder = next_url.split("/")[-2]
print folder + " " if dirs.empty?
dirs << download_elem["src"]
print "#"
next_elem = body.css(".next").first
next_url = @base_url + next_elem["href"]
next_folder = next_url.split("/")[-2]
unless next_folder == folder
filename = File.join(@urls_path, folder)
File.open(filename, "w") do |file|
file.puts dirs
end
dirs = []
print "\n"
end
end
end
def self.download_audios
Dir[File.join(@urls_path, "*.txt")].each do |file|
`wget --directory-prefix='downloads/#{file.split('/').last}' -i #{file}`
end
end
end
Bible.create_download_files
# Bible.download_audios
|
660cf297-2d48-11e5-b15b-7831c1c36510
66131145-2d48-11e5-81c5-7831c1c36510
66131145-2d48-11e5-81c5-7831c1c36510 |
74b5d954-2d48-11e5-8434-7831c1c36510
74bb8e57-2d48-11e5-b735-7831c1c36510
74bb8e57-2d48-11e5-b735-7831c1c36510 |
67c0b521-2d48-11e5-bc4c-7831c1c36510
67c5b899-2d48-11e5-b39e-7831c1c36510
67c5b899-2d48-11e5-b39e-7831c1c36510 |
use Rack::Logger
use Rack::Session::Cookie, :secret => 'Web-Sync sdkjfskadfh1h3248c99sj2j4j2343'
#use Rack::FiberPool
helpers do
def logger
request.logger
end
end
configure do
set :server, 'thin'
set :sockets, []
set :template_engine, :erb
end
$dmp = DiffMatchPatch.new
class DataMapper::Adapters::RedisAdapter
attr_accessor :redis
end
DataMapper.setup(:default, "sqlite3://#{File.expand_path(File.dirname(__FILE__))}/main.db")
# Redis has issues with datamapper associations especially Many-to-many.
#$adapter = DataMapper.setup(:default, {:adapter => "redis"});
#$redis = $adapter.redis
# Monkey patched Redis for easy caching.
class Redis
def cache(key, expire=nil)
if (value = get(key)).nil?
value = yield(self)
set(key, value)
expire(key, expire) if expire
value
else
value
end
end
end
# Ease of use connection to the redis server.
$redis = Redis.new
class Document
include DataMapper::Resource
property :id, Serial
property :name, String
property :body, Text
property :created, DateTime
property :last_edit_time, DateTime
property :public, Boolean, :default=>false
has n, :assets, :through => Resource
#belongs_to :dm_user
end
# Assets could be javascript or css
class Asset
include DataMapper::Resource
property :id, Serial
property :name, String
property :description, String
property :url, String
property :type, Discriminator
has n, :documents, :through => Resource
end
class Javascript < Asset; end
class Stylesheet < Asset; end
class DmUser
#has n, :documents
end
DataMapper.finalize
DataMapper.auto_upgrade!
class Rainbows::EventMachine::Client
def backend
self
end
end
module SinatraWebsocket
module Ext
module Rainbows
module Connection
def self.included(base)
base.class_eval do
alias :receive_data_without_websocket :receive_data
alias :receive_data :receive_data_with_websocket
alias :unbind_without_websocket :unbind
alias :unbind :unbind_with_websocket
alias :receive_data_without_flash_policy_file :receive_data
alias :receive_data :receive_data_with_flash_policy_file
#alias :pre_process_without_websocket :pre_process
#alias :pre_process :pre_process_with_websocket
end
end
attr_accessor :websocket
# Set 'async.connection' Rack env
def pre_process_with_websocket
@request.env['async.connection'] = self
#pre_process_without_websocket
end
# Is this connection WebSocket?
def websocket?
!self.websocket.nil?
end
# Skip default receive_data if this is
# WebSocket connection
def receive_data_with_websocket(data)
if self.websocket?
#self.pre_process_with_websocket
self.websocket.receive_data(data)
else
receive_data_without_websocket(data)
end
end
# Skip standard unbind it this is
# WebSocket connection
def unbind_with_websocket
if self.websocket?
self.websocket.unbind
else
unbind_without_websocket
end
end
# Send flash policy file if requested
def receive_data_with_flash_policy_file(data)
# thin require data to be proper http request - in it's not
# then @request.parse raises exception and data isn't parsed
# by futher methods. Here we only check if it is flash
# policy file request ("<policy-file-request/>\000") and
# if so then flash policy file is returned. if not then
# rest of request is handled.
if (data == "<policy-file-request/>\000")
file = '<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'
# ignore errors - we will close this anyway
send_data(file) rescue nil
close_connection_after_writing
else
receive_data_without_flash_policy_file(data)
end
end
end # module::Connection
end # module::Thin
end # module::Ext
end # module::SinatraWebsocket
defined?(Rainbows) && Rainbows::EventMachine::Client.send(:include, SinatraWebsocket::Ext::Rainbows::Connection)
#defined?(Rainbows::EventMachine::Client) && Rainbows::EventMachine::Client.send(:include, SinatraWebsocket::Ext::Thin::Connection)
$table = Javascript.first_or_create(:name=>'Tables',:description=>'Table editing support',:url=>'/assets/tables.js')
get '/' do
#$redis.cache("index",300) do
@javascripts = []
erb :index
#end
end
get '/error' do
error
end
get '/new' do
login_required
doc = Document.create(
:name => 'Unnamed Document',
:body => '',
:created => Time.now,
:last_edit_time => Time.now
#,:dm_user => current_user.db_instance
)
doc.assets << Asset.get(1)
doc.save
redirect "/#{doc.id.base62_encode}/edit"
end
get '/:doc/download' do
login_required
doc_id = params[:doc].base62_decode
doc = Document.get doc_id
response.headers['content_type'] = "application/octet-stream"
attachment(doc.name+'.docx')
response.write(doc.body)
#send_data doc.body, :filename=>doc.name+".docx"
end
get '/:doc/delete' do
login_required
doc_id = params[:doc].base62_decode
doc = Document.get doc_id
doc.destroy!
redirect '/'
end
get '/:doc/edit' do
login_required
doc_id = params[:doc].base62_decode
doc = Document.get doc_id
if !request.websocket?
@javascripts = [
'/assets/bundle-edit.js'
]
@doc = doc
if !@doc.nil?
erb :edit
else
redirect '/'
end
# Websocket edit
else
redis_sock = EM::Hiredis.connect
client_id = $redis.incr("clientid")
redis_sock.subscribe("doc.#{doc_id.base62_encode}")
puts "Websocket Client ID: #{client_id}"
request.websocket do |ws|
websock = ws
ws.onopen do
warn "websocket open"
end
ws.onmessage do |msg|
data = JSON.parse(msg);
puts "JSON: #{data.to_s}"
# This replaces all the text w/ the provided content.
if data["type"]=="text_update"
doc.body = data["text"]
doc.last_edit_time = Time.now
if !doc.save
puts("Save errors: #{doc.errors.inspect}")
end
$redis.publish "doc.#{doc_id.base62_encode}", JSON.dump({type:"client_bounce",client:client_id,data:data})
# Google Diff-Match-Patch algorithm
elsif data['type']=='text_patch'
doc = Document.get doc_id
#I'm pretty sure this works just fine. The main issue seems to be diffing w/ structure content. We'll see with time.
#html_optimized_patches = diff_htmlToChars_ doc.body, URI::decode(data['patch'])
#puts html_optimized_patches.inspect
patches = $dmp.patch_from_text data['patch']
doc.body = $dmp.patch_apply(patches,doc.body)[0]
doc.last_edit_time = Time.now
if !doc.save
puts("Save errors: #{doc.errors.inspect}")
end
$redis.publish "doc.#{doc_id.base62_encode}", JSON.dump({type:"client_bounce",client:client_id,data:data})
# Sets the name
elsif data['type']=="name_update"
doc.name = data["name"]
doc.last_edit_time = Time.now
if !doc.save
puts("Save errors: #{doc.errors.inspect}")
end
$redis.publish "doc.#{doc_id.base62_encode}", JSON.dump({type:"client_bounce",client:client_id,data:data})
# Loads scripts
elsif data['type']=="load_scripts"
msg = {type:'scripts', js:[]}
doc.assets.each do |asset|
arr = :js;
if asset.type=="javascript"
arr = :js
elsif asset.type=="stylesheet"
arr = :css
end
msg[arr].push asset.url
end
ws.send_data JSON.dump msg
elsif data['type']=='connection'
end
end
ws.onclose do
warn("websocket closed")
redis_sock.close_connection
end
redis_sock.on(:message) do |channel, message|
puts "[#{client_id}]#{channel}: #{message}"
data = JSON.parse(message)
if data['client']!=client_id
if data['type']=="client_bounce"
ws.send JSON.dump(data['data'])
end
end
end
end
end
end
=begin
# This might be completely useless since it seems like you only have to structure for diff.
# Create a diff after replacing all HTML tags with unicode characters.
def diff_htmlToChars_ text1, text2
lineArray = [] # e.g. lineArray[4] == 'Hello\n'
lineHash = {} # e.g. lineHash['Hello\n'] == 4
# '\x00' is a valid character, but various debuggers don't like it.
# So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = ''
#/**
#* Split a text into an array of strings. Reduce the texts to a string of
#* hashes where each Unicode character represents one line.
#* Modifies linearray and linehash through being a closure.
#* @param {string} text String to encode.
#* @return {string} Encoded string.
#* @private
#*/
def diff_linesToCharsMunge_ text, lineArray, lineHash
chars = ""+text
#// Walk the text, pulling out a substring for each line.
#// text.split('\n') would would temporarily double our memory footprint.
#// Modifying text would create many large strings to garbage collect.
lineStart = 0
lineEnd = 0
#// Keeping our own length variable is faster than looking it up.
lineArrayLength = lineArray.length;
while lineEnd <(text.length - 1)
prevLineEnd = lineEnd
if prevLineEnd==nil
prevLineEnd=0
end
lineStart = text.index('<',lineEnd)
if lineStart.nil?
lineEnd=nil
break
else
lineEnd = text.index('>', lineStart)
end
if lineEnd.nil?
lineEnd = text.length - 1
end
line = text[lineStart..lineEnd]
lineStart = lineEnd + 1
if lineHash.has_key? line
chars.gsub!(line,[lineHash[line]].pack("U"))
else
chars.gsub!(line,[lineArrayLength].pack("U"))
lineHash[line] = lineArrayLength
lineArray[lineArrayLength] = line
lineArrayLength +=1
end
end
return chars;
end
chars1 = diff_linesToCharsMunge_(text1, lineArray,lineHash)
chars2 = diff_linesToCharsMunge_(text2,lineArray,lineHash)
return {chars1: chars1, chars2: chars2, lineArray: lineArray}
end
def diff_charsToHTML_ diffs, lineArray
(0..(diffs.length-1)).each do |x|
chars = diffs[x][1];
text = ""+chars
(0..(lineArray-1)).each do |y|
text.gsub!([y].pack("U"),lineArray[y])
end
diffs[x][1] = text;
end
end
=end
Updates
use Rack::Logger
use Rack::Session::Cookie, :secret => 'Web-Sync sdkjfskadfh1h3248c99sj2j4j2343'
#use Rack::FiberPool
helpers do
def logger
request.logger
end
end
configure do
set :server, 'thin'
set :sockets, []
set :template_engine, :erb
end
$dmp = DiffMatchPatch.new
class DataMapper::Adapters::RedisAdapter
attr_accessor :redis
end
DataMapper.setup(:default, "sqlite3://#{File.expand_path(File.dirname(__FILE__))}/main.db")
# Redis has issues with datamapper associations especially Many-to-many.
#$adapter = DataMapper.setup(:default, {:adapter => "redis"});
#$redis = $adapter.redis
# Monkey patched Redis for easy caching.
class Redis
def cache(key, expire=nil)
if (value = get(key)).nil?
value = yield(self)
set(key, value)
expire(key, expire) if expire
value
else
value
end
end
end
# Ease of use connection to the redis server.
$redis = Redis.new
class Document
include DataMapper::Resource
property :id, Serial
property :name, String
property :body, Text
property :created, DateTime
property :last_edit_time, DateTime
property :public, Boolean, :default=>false
has n, :assets, :through => Resource
#belongs_to :dm_user
end
# Assets could be javascript or css
class Asset
include DataMapper::Resource
property :id, Serial
property :name, String
property :description, String
property :url, String
property :type, Discriminator
has n, :documents, :through => Resource
end
class Javascript < Asset; end
class Stylesheet < Asset; end
class DmUser
#has n, :documents
end
DataMapper.finalize
DataMapper.auto_upgrade!
class Rainbows::EventMachine::Client
def backend
self
end
end
module SinatraWebsocket
module Ext
module Rainbows
module Connection
def self.included(base)
base.class_eval do
alias :receive_data_without_websocket :receive_data
alias :receive_data :receive_data_with_websocket
alias :unbind_without_websocket :unbind
alias :unbind :unbind_with_websocket
alias :receive_data_without_flash_policy_file :receive_data
alias :receive_data :receive_data_with_flash_policy_file
#alias :pre_process_without_websocket :pre_process
#alias :pre_process :pre_process_with_websocket
end
end
attr_accessor :websocket
# Set 'async.connection' Rack env
def pre_process_with_websocket
@env['async.connection'] = self
#pre_process_without_websocket
end
# Is this connection WebSocket?
def websocket?
!self.websocket.nil?
end
# Skip default receive_data if this is
# WebSocket connection
def receive_data_with_websocket(data)
if self.websocket?
self.pre_process_with_websocket
self.websocket.receive_data(data)
else
receive_data_without_websocket(data)
end
end
# Skip standard unbind it this is
# WebSocket connection
def unbind_with_websocket
if self.websocket?
self.websocket.unbind
else
unbind_without_websocket
end
end
# Send flash policy file if requested
def receive_data_with_flash_policy_file(data)
# thin require data to be proper http request - in it's not
# then @request.parse raises exception and data isn't parsed
# by futher methods. Here we only check if it is flash
# policy file request ("<policy-file-request/>\000") and
# if so then flash policy file is returned. if not then
# rest of request is handled.
if (data == "<policy-file-request/>\000")
file = '<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'
# ignore errors - we will close this anyway
send_data(file) rescue nil
close_connection_after_writing
else
receive_data_without_flash_policy_file(data)
end
end
end # module::Connection
end # module::Thin
end # module::Ext
end # module::SinatraWebsocket
defined?(Rainbows) && Rainbows::EventMachine::Client.send(:include, SinatraWebsocket::Ext::Rainbows::Connection)
#defined?(Rainbows::EventMachine::Client) && Rainbows::EventMachine::Client.send(:include, SinatraWebsocket::Ext::Thin::Connection)
$table = Javascript.first_or_create(:name=>'Tables',:description=>'Table editing support',:url=>'/assets/tables.js')
get '/' do
#$redis.cache("index",300) do
@javascripts = []
erb :index
#end
end
get '/error' do
error
end
get '/new' do
login_required
doc = Document.create(
:name => 'Unnamed Document',
:body => '',
:created => Time.now,
:last_edit_time => Time.now
#,:dm_user => current_user.db_instance
)
doc.assets << Asset.get(1)
doc.save
redirect "/#{doc.id.base62_encode}/edit"
end
get '/:doc/download' do
login_required
doc_id = params[:doc].base62_decode
doc = Document.get doc_id
response.headers['content_type'] = "application/octet-stream"
attachment(doc.name+'.docx')
response.write(doc.body)
#send_data doc.body, :filename=>doc.name+".docx"
end
get '/:doc/delete' do
login_required
doc_id = params[:doc].base62_decode
doc = Document.get doc_id
doc.destroy!
redirect '/'
end
get '/:doc/edit' do
login_required
doc_id = params[:doc].base62_decode
doc = Document.get doc_id
if !request.websocket?
@javascripts = [
'/assets/bundle-edit.js'
]
@doc = doc
if !@doc.nil?
erb :edit
else
redirect '/'
end
# Websocket edit
else
redis_sock = EM::Hiredis.connect
client_id = $redis.incr("clientid")
redis_sock.subscribe("doc.#{doc_id.base62_encode}")
puts "Websocket Client ID: #{client_id}"
request.websocket do |ws|
websock = ws
ws.onopen do
warn "websocket open"
end
ws.onmessage do |msg|
data = JSON.parse(msg);
puts "JSON: #{data.to_s}"
# This replaces all the text w/ the provided content.
if data["type"]=="text_update"
doc.body = data["text"]
doc.last_edit_time = Time.now
if !doc.save
puts("Save errors: #{doc.errors.inspect}")
end
$redis.publish "doc.#{doc_id.base62_encode}", JSON.dump({type:"client_bounce",client:client_id,data:data})
# Google Diff-Match-Patch algorithm
elsif data['type']=='text_patch'
doc = Document.get doc_id
#I'm pretty sure this works just fine. The main issue seems to be diffing w/ structure content. We'll see with time.
#html_optimized_patches = diff_htmlToChars_ doc.body, URI::decode(data['patch'])
#puts html_optimized_patches.inspect
patches = $dmp.patch_from_text data['patch']
doc.body = $dmp.patch_apply(patches,doc.body)[0]
doc.last_edit_time = Time.now
if !doc.save
puts("Save errors: #{doc.errors.inspect}")
end
$redis.publish "doc.#{doc_id.base62_encode}", JSON.dump({type:"client_bounce",client:client_id,data:data})
# Sets the name
elsif data['type']=="name_update"
doc.name = data["name"]
doc.last_edit_time = Time.now
if !doc.save
puts("Save errors: #{doc.errors.inspect}")
end
$redis.publish "doc.#{doc_id.base62_encode}", JSON.dump({type:"client_bounce",client:client_id,data:data})
# Loads scripts
elsif data['type']=="load_scripts"
msg = {type:'scripts', js:[]}
doc.assets.each do |asset|
arr = :js;
if asset.type=="javascript"
arr = :js
elsif asset.type=="stylesheet"
arr = :css
end
msg[arr].push asset.url
end
ws.send_data JSON.dump msg
elsif data['type']=='connection'
end
end
ws.onclose do
warn("websocket closed")
redis_sock.close_connection
end
redis_sock.on(:message) do |channel, message|
puts "[#{client_id}]#{channel}: #{message}"
data = JSON.parse(message)
if data['client']!=client_id
if data['type']=="client_bounce"
ws.send JSON.dump(data['data'])
end
end
end
end
end
end
=begin
# This might be completely useless since it seems like you only have to structure for diff.
# Create a diff after replacing all HTML tags with unicode characters.
def diff_htmlToChars_ text1, text2
lineArray = [] # e.g. lineArray[4] == 'Hello\n'
lineHash = {} # e.g. lineHash['Hello\n'] == 4
# '\x00' is a valid character, but various debuggers don't like it.
# So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = ''
#/**
#* Split a text into an array of strings. Reduce the texts to a string of
#* hashes where each Unicode character represents one line.
#* Modifies linearray and linehash through being a closure.
#* @param {string} text String to encode.
#* @return {string} Encoded string.
#* @private
#*/
def diff_linesToCharsMunge_ text, lineArray, lineHash
chars = ""+text
#// Walk the text, pulling out a substring for each line.
#// text.split('\n') would would temporarily double our memory footprint.
#// Modifying text would create many large strings to garbage collect.
lineStart = 0
lineEnd = 0
#// Keeping our own length variable is faster than looking it up.
lineArrayLength = lineArray.length;
while lineEnd <(text.length - 1)
prevLineEnd = lineEnd
if prevLineEnd==nil
prevLineEnd=0
end
lineStart = text.index('<',lineEnd)
if lineStart.nil?
lineEnd=nil
break
else
lineEnd = text.index('>', lineStart)
end
if lineEnd.nil?
lineEnd = text.length - 1
end
line = text[lineStart..lineEnd]
lineStart = lineEnd + 1
if lineHash.has_key? line
chars.gsub!(line,[lineHash[line]].pack("U"))
else
chars.gsub!(line,[lineArrayLength].pack("U"))
lineHash[line] = lineArrayLength
lineArray[lineArrayLength] = line
lineArrayLength +=1
end
end
return chars;
end
chars1 = diff_linesToCharsMunge_(text1, lineArray,lineHash)
chars2 = diff_linesToCharsMunge_(text2,lineArray,lineHash)
return {chars1: chars1, chars2: chars2, lineArray: lineArray}
end
def diff_charsToHTML_ diffs, lineArray
(0..(diffs.length-1)).each do |x|
chars = diffs[x][1];
text = ""+chars
(0..(lineArray-1)).each do |y|
text.gsub!([y].pack("U"),lineArray[y])
end
diffs[x][1] = text;
end
end
=end
|
69dcc2b8-2d48-11e5-a0d5-7831c1c36510
69e33507-2d48-11e5-883b-7831c1c36510
69e33507-2d48-11e5-883b-7831c1c36510 |
6f8dd8c7-2d48-11e5-9f58-7831c1c36510
6f9320a8-2d48-11e5-8708-7831c1c36510
6f9320a8-2d48-11e5-8708-7831c1c36510 |
7828fb85-2d48-11e5-8025-7831c1c36510
782ef430-2d48-11e5-a528-7831c1c36510
782ef430-2d48-11e5-a528-7831c1c36510 |
498f3180-2d48-11e5-b682-7831c1c36510
4994e530-2d48-11e5-a811-7831c1c36510
4994e530-2d48-11e5-a811-7831c1c36510 |
require 'json'
require 'set'
require 'nokogiri'
ANNOTATIONS_REGEXP = /(?:@[\w\.]+(?:\([^)]*\))?[[:space:]])*/
METHOD_SIGNATURE_REGEXP = /^((?:@[\w\.]+(?:\([^)]*\))?[[:space:]])*)((?:public|protected|private|abstract|static|final)[[:space:]]+)*([^(]+?)[[:space:]]+(\w+)[[:space:]]*\(([^)]*)\)[[:space:]]*(?:throws[[:space:]]+(.+))?/
SPACES_REGEXP = /[[:space:]]+/
LINE_BREAK_REGEXP = /[[:space:]]*[\r\n]+[[:space:]]*/
PARAM_SPLIT_REGEXP = /[[:space:]]*,[[:space:]]*?[\r\n]+[[:space:]]*/
PARAM_REGEXP = /[[:space:]]*(.+?)[[:space:]]+(\w+)$/
ABBREVIATED_MEMBER_KEYS = [:name, :params, :returnType, :modifiers, :description, :path].to_set
class JavadocPopulator
def initialize(dir_path, output_path, debug_mode=false)
@dir_path = dir_path
@output_path = output_path
@first_document = true
@debug_mode = debug_mode
#PARAM_REGEXP = /\s*(.+)\s+(\w+)\s*$/
end
def debug(msg)
if @debug_mode
puts msg
end
end
def populate
puts "Populating from '#{@dir_path}' to #{@output_path}' ..."
first_document = true
File.open(@output_path, 'w:UTF-8') do |out|
out.write <<-eos
{
"metadata" : {
"mapping" : {
"_all" : {
"enabled" : false
},
"properties" : {
"class" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"qualifiedClass" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"annotations" : {
"type" : "object",
"enabled" : false
},
"modifiers" : {
"type" : "string",
"index" : "no"
},
"kind" : {
"type" : "string",
"index" : "no"
},
"since" : {
"type" : "string",
"index" : "no"
},
"description" : {
"type" : "string",
"index" : "analyzed"
},
"name" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"qualifiedName" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"path" : {
"type" : "string",
"index" : "no"
},
"recognitionKeys" : {
"type" : "string",
"index" : "no"
},
"superClass" : {
"type" : "string",
"index" : "no"
},
"implements" : {
"type" : "string",
"index" : "no"
},
"methods" : {
"type" : "object",
"enabled" : false
},
"params" : {
"type" : "object",
"enabled" : false
},
"returnType" : {
"type" : "string",
"index" : "no"
},
"returns" : {
"type" : "string",
"index" : "no"
},
"throws" : {
"type" : "string",
"index" : "no"
},
"packageBoost" : {
"type" : "float",
"store" : true,
"null_value" : 1.0,
"coerce" : false
}
}
}
},
"updates" : [
eos
abs_dir_path = File.expand_path(@dir_path)
num_classes_found = 0
Dir["#{@dir_path}/**/*.html"].each do |file_path|
simple_filename = File.basename(file_path)
if !file_path.include?('class-use') && !file_path.include?('doc-files') &&
/([A-Z][a-z]*\.)*([A-Z][a-z]*)\.html/.match(simple_filename)
abs_file_path = File.expand_path(file_path)
class_name = abs_file_path.slice(abs_dir_path.length, abs_file_path.length - abs_dir_path.length)
if class_name.start_with?(File::SEPARATOR)
class_name = class_name.slice(File::SEPARATOR.length, class_name.length - File::SEPARATOR.length)
end
class_name = class_name.slice(0, class_name.length - 5).gsub('/', '.')
# unless class_name == 'java.util.LinkedList'
# next
# end
simple_class_name = simple_filename.slice(0, simple_filename.length - 5)
puts "Opening file '#{file_path}' for class '#{class_name}' ..."
File.open(file_path) do |f|
doc = Nokogiri::HTML(f)
package_name = doc.css('.header .subTitle').text()
methods = find_methods(doc, package_name, class_name, simple_class_name, out)
add_class(doc, package_name, class_name, simple_class_name, methods, out)
num_classes_found += 1
# if num_classes_found > 10
# out.write("\n ]\n}")
# return
# end
end
end
end
out.write("\n ]\n}")
puts "Found #{num_classes_found} classes."
end
end
private
def truncate(s, size=500)
unless s
return nil
end
pre_ellipsis_size = size - 3
s = s.strip.scrub
if s && (s.length > pre_ellipsis_size)
return s.slice(0, pre_ellipsis_size) + '...'
end
return s
end
def make_class_path(package_name, simple_class_name)
return package_name.gsub(/\./, '/') + '/' + simple_class_name + '.html'
end
def add_class(doc, package_name, class_name, simple_class_name, methods, out)
kind = 'class'
title = doc.css('.header h2').text().strip
if title.start_with?('Interface')
kind = 'interface'
elsif title.start_with?('Enum')
kind = 'enum'
elsif title.start_with?('Annotation')
kind = 'annotation'
end
annotations = []
pre_element = doc.css('.description ul.blockList li.blockList>pre').first
pre_text = pre_element.text().strip
modifiers_text = pre_text
m = ANNOTATIONS_REGEXP.match(pre_text)
if m
annotations = m[0].split(LINE_BREAK_REGEXP)
modifiers_text = pre_text.slice(m[0].length .. -1)
end
stop_marker = kind
if kind == 'annotation'
stop_marker = '@'
end
modifiers_text = modifiers_text.slice(0, modifiers_text.index(stop_marker)).strip
modifiers = (modifiers_text.split(SPACES_REGEXP) || []).sort
description_block = pre_element.next_element
description = nil
if description_block && (description_block.attr('class') == 'block')
description = truncate(description_block.text())
end
super_class = nil
implements = []
if kind != 'annotation'
if kind == 'class'
super_class_a = doc.css('ul.inheritance li a').last
if super_class_a
super_class = super_class_a.text().strip
end
if !super_class
super_class = 'java.lang.Object'
end
elsif kind == 'enum'
super_class = 'java.lang.Enum'
end
dt = nil
if kind == 'interface'
dt = doc.css('.description ul.blockList li.blockList dl dt').find do |dt|
dt.text.downcase.include?('superinterface')
end
else
dt = doc.css('.description ul.blockList li.blockList dl dt').find do |dt|
text = dt.text.downcase
text.include?('implemented') && text.include?('interface')
end
end
# Messes up for Comparable<Date>
if dt
dd = dt.parent.css('dd').first
links = dd.css('a')
implements = (links.collect do |a|
title = a.attr('title')
package = nil
m = /.+[[:space:]]+([\w\.]+)$/.match(title)
if m
package = m[1].strip.scrub
end
simple = a.text().strip.scrub
if package
package + '.' + simple
else
simple
end
end).sort
end
end
since = nil
since_label = doc.css('.description dt').find do |node|
node.text().include?("Since:")
end
if since_label
since = since_label.parent.css('dd').first.text().strip.scrub
end
#puts "#{class_name} description: '#{description}'"
output_doc = {
_id: class_name,
class: simple_class_name,
qualifiedClass: class_name,
name: simple_class_name,
qualifiedName: class_name,
annotations: annotations,
modifiers: modifiers,
since: since,
kind: kind,
description: description,
path: make_class_path(package_name, simple_class_name),
packageBoost: package_boost(package_name),
recognitionKeys: ['com.solveforall.recognition.programming.java.JdkClass'],
}
if (kind == 'class') || (kind == 'enum')
output_doc[:superClass] = super_class
output_doc[:methods] = methods
output_doc[:implements] = implements
elsif kind == 'interface'
output_doc[:methods] = methods
output_doc[:implements] = implements
end
if @first_document
@first_document = false
else
out.write(",\n")
end
out.write(output_doc.to_json)
#puts output_doc.to_json
end
def abbreviate_member(member)
member = member.select do |k, v|
ABBREVIATED_MEMBER_KEYS.include?(k)
end
member[:description] = truncate(member[:description], 250)
member[:params].each do |param|
param.delete(:description)
end
return member
end
def find_methods(doc, package_name, class_name, simple_class_name, out)
debug("find_methods for #{class_name}")
methods = []
method_detail_anchor = doc.css('.details h3').find do |element|
element.text().strip.downcase.include?('method detail')
end
if method_detail_anchor.nil?
return []
end
list_items = method_detail_anchor.parent.css('ul.blockList>li')
list_items.each do |item|
#puts "item = #{item}"
anchor_path = item.parent.previous_element.attr('name') || ''
path = make_class_path(package_name, simple_class_name) + '#' + anchor_path
signature = item.css('pre').first.text().strip
m = METHOD_SIGNATURE_REGEXP.match(signature)
unless m
debug("Can't match signature '#{signature}'")
next
end
annotations = (m[1] || '').strip.split(LINE_BREAK_REGEXP)
modifiers = (m[2] || '').strip.split(SPACES_REGEXP).sort
return_type = m[3]
method_name = m[4]
params = parse_parameters(m[5])
throws_text = m[6]
throws = []
if throws_text
throws = throws_text.strip.split(/[[:space:]],[[:space:]]/)
end
debug("path = '#{path}', annotations = #{annotations}, modifiers = #{modifiers}, return_type = '#{return_type}', name = '#{method_name}', params = #{params}, throws = #{throws}")
description = nil
description_block = item.css('.block').first
if description_block
description = truncate(description_block.text().strip)
end
parameters_label = item.css('dt').find do |dt|
dt.text().downcase.include?('parameters:')
end
if parameters_label
dd = parameters_label.next_element
while dd && (dd.name == 'dd') do
m = /(\w+)[[:space:]]+(?:\-[[:space:]])*(.+)/.match(dd.text().strip)
if m
param_name = m[1]
param_description = m[2]
param = params.find do |p|
p[:name] == param_name
end
if param
param[:description] = truncate(param_description, 250)
end
end
dd = dd.next_element
end
end
returns_label = item.css('dt').find do |dt|
dt.text().downcase.include?('returns:')
end
returns_description = nil
if returns_label
returns_description = returns_label.next_element.text().strip
end
output_doc = {
class: simple_class_name,
qualifiedClass: class_name,
name: method_name,
qualifiedName: class_name + '.' + method_name,
annotations: annotations,
modifiers: modifiers,
path: path,
params: params,
returnType: return_type,
returns: returns_description,
throws: throws,
kind: 'method',
description: description,
packageBoost: package_boost(package_name),
recognitionKeys: ['com.solveforall.recognition.programming.java.JdkMethod']
}
if @first_document
@first_document = false
else
out.write(",\n")
end
output_json = output_doc.to_json
out.write(output_json)
debug(output_json)
methods << abbreviate_member(output_doc)
end
debug("done find_methods for #{class_name}")
return methods
end
def parse_parameters(params_text)
params = []
if params_text && (params_text.length > 0)
#puts "got params text '#{params_text}'"
else
return params
end
params_text.split(PARAM_SPLIT_REGEXP).each do |line|
m = PARAM_REGEXP.match(line)
if m
param = {
type: m[1],
name: m[2]
}
params << param
else
puts "Unmatched param line: '#{line}'!"
end
end
params
end
def package_boost(package_name)
if package_name.start_with?('java.awt')
return 0.7
elsif package_name.start_with?('java.sql')
return 0.9 # because java.sql.Date conflicts with java.util.Date
elsif package_name.start_with?('java.lang')
return 1.0
elsif package_name.start_with?('java.')
return 0.95
elsif package_name.start_with?('javax.')
return 0.9 # because javax.print.DocFlavor.STRING conflicts with java.lang.String
else
return 0.6
end
end
end
output_filename = 'jdk7-doc.json'
if ARGV.length > 1
output_filename = ARGV[1]
end
JavadocPopulator.new(ARGV[0], output_filename).populate
system("bzip2 -kf #{output_filename}")
Add constructors of classes
require 'json'
require 'set'
require 'nokogiri'
ANNOTATIONS_REGEXP = /(?:@[\w\.]+(?:\([^)]*\))?[[:space:]])*/
CONSTRUCTOR_SIGNATURE_REGEXP = /^((?:@[\w\.]+(?:\([^)]*\))?[[:space:]])*)((?:public|protected|private)[[:space:]]+)*(\w+)[[:space:]]*\(([^)]*)\)[[:space:]]*(?:throws[[:space:]]+(.+))?/
METHOD_SIGNATURE_REGEXP = /^((?:@[\w\.]+(?:\([^)]*\))?[[:space:]])*)((?:public|protected|private|abstract|static|final)[[:space:]]+)*([^(]+?)[[:space:]]+(\w+)[[:space:]]*\(([^)]*)\)[[:space:]]*(?:throws[[:space:]]+(.+))?/
SPACES_REGEXP = /[[:space:]]+/
LINE_BREAK_REGEXP = /[[:space:]]*[\r\n]+[[:space:]]*/
PARAM_SPLIT_REGEXP = /[[:space:]]*,[[:space:]]*?[\r\n]+[[:space:]]*/
PARAM_REGEXP = /[[:space:]]*(.+?)[[:space:]]+(\w+)$/
ABBREVIATED_MEMBER_KEYS = [:name, :params, :returnType, :modifiers, :description, :path].to_set
KIND_CONSTRUCTOR = 'constructor'
KIND_METHOD = 'method'
class JavadocPopulator
def initialize(dir_path, output_path, debug_mode=false)
@dir_path = dir_path
@output_path = output_path
@first_document = true
@debug_mode = debug_mode
#PARAM_REGEXP = /\s*(.+)\s+(\w+)\s*$/
end
def debug(msg)
if @debug_mode
puts msg
end
end
def populate
puts "Populating from '#{@dir_path}' to #{@output_path}' ..."
first_document = true
File.open(@output_path, 'w:UTF-8') do |out|
out.write <<-eos
{
"metadata" : {
"mapping" : {
"_all" : {
"enabled" : false
},
"properties" : {
"class" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"qualifiedClass" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"annotations" : {
"type" : "object",
"enabled" : false
},
"modifiers" : {
"type" : "string",
"index" : "no"
},
"kind" : {
"type" : "string",
"index" : "no"
},
"since" : {
"type" : "string",
"index" : "no"
},
"description" : {
"type" : "string",
"index" : "analyzed"
},
"name" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"qualifiedName" : {
"type" : "string",
"index" : "analyzed",
"analyzer" : "simple"
},
"path" : {
"type" : "string",
"index" : "no"
},
"recognitionKeys" : {
"type" : "string",
"index" : "no"
},
"superClass" : {
"type" : "string",
"index" : "no"
},
"implements" : {
"type" : "string",
"index" : "no"
},
"constructors" : {
"type" : "object",
"enabled" : false
},
"methods" : {
"type" : "object",
"enabled" : false
},
"params" : {
"type" : "object",
"enabled" : false
},
"returnType" : {
"type" : "string",
"index" : "no"
},
"returns" : {
"type" : "string",
"index" : "no"
},
"throws" : {
"type" : "string",
"index" : "no"
},
"packageBoost" : {
"type" : "float",
"store" : true,
"null_value" : 1.0,
"coerce" : false
}
}
}
},
"updates" : [
eos
abs_dir_path = File.expand_path(@dir_path)
num_classes_found = 0
Dir["#{@dir_path}/**/*.html"].each do |file_path|
simple_filename = File.basename(file_path)
if !file_path.include?('class-use') && !file_path.include?('doc-files') &&
/([A-Z][a-z]*\.)*([A-Z][a-z]*)\.html/.match(simple_filename)
abs_file_path = File.expand_path(file_path)
class_name = abs_file_path.slice(abs_dir_path.length, abs_file_path.length - abs_dir_path.length)
if class_name.start_with?(File::SEPARATOR)
class_name = class_name.slice(File::SEPARATOR.length, class_name.length - File::SEPARATOR.length)
end
class_name = class_name.slice(0, class_name.length - 5).gsub('/', '.')
# unless class_name == 'java.util.LinkedList'
# next
# end
simple_class_name = simple_filename.slice(0, simple_filename.length - 5)
puts "Opening file '#{file_path}' for class '#{class_name}' ..."
File.open(file_path) do |f|
doc = Nokogiri::HTML(f)
package_name = doc.css('.header .subTitle').text()
constructors = find_constructors(doc, package_name, class_name, simple_class_name, out)
methods = find_methods(doc, package_name, class_name, simple_class_name, out)
add_class(doc, package_name, class_name, simple_class_name, constructors, methods, out)
num_classes_found += 1
# if num_classes_found > 10
# out.write("\n ]\n}")
# return
# end
end
end
end
out.write("\n ]\n}")
puts "Found #{num_classes_found} classes."
end
end
private
def truncate(s, size=500)
unless s
return nil
end
pre_ellipsis_size = size - 3
s = s.strip.scrub
if s && (s.length > pre_ellipsis_size)
return s.slice(0, pre_ellipsis_size) + '...'
end
return s
end
def make_class_path(package_name, simple_class_name)
return package_name.gsub(/\./, '/') + '/' + simple_class_name + '.html'
end
def add_class(doc, package_name, class_name, simple_class_name, constructors, methods, out)
kind = 'class'
title = doc.css('.header h2').text().strip
if title.start_with?('Interface')
kind = 'interface'
elsif title.start_with?('Enum')
kind = 'enum'
elsif title.start_with?('Annotation')
kind = 'annotation'
end
annotations = []
pre_element = doc.css('.description ul.blockList li.blockList>pre').first
pre_text = pre_element.text().strip
modifiers_text = pre_text
m = ANNOTATIONS_REGEXP.match(pre_text)
if m
annotations = m[0].split(LINE_BREAK_REGEXP)
modifiers_text = pre_text.slice(m[0].length .. -1)
end
stop_marker = kind
if kind == 'annotation'
stop_marker = '@'
end
modifiers_text = modifiers_text.slice(0, modifiers_text.index(stop_marker)).strip
modifiers = (modifiers_text.split(SPACES_REGEXP) || []).sort
description_block = pre_element.next_element
description = nil
if description_block && (description_block.attr('class') == 'block')
description = truncate(description_block.text())
end
super_class = nil
implements = []
if kind != 'annotation'
if kind == 'class'
super_class_a = doc.css('ul.inheritance li a').last
if super_class_a
super_class = super_class_a.text().strip
end
if !super_class
super_class = 'java.lang.Object'
end
elsif kind == 'enum'
super_class = 'java.lang.Enum'
end
dt = nil
if kind == 'interface'
dt = doc.css('.description ul.blockList li.blockList dl dt').find do |dt|
dt.text.downcase.include?('superinterface')
end
else
dt = doc.css('.description ul.blockList li.blockList dl dt').find do |dt|
text = dt.text.downcase
text.include?('implemented') && text.include?('interface')
end
end
# Messes up for Comparable<Date>
if dt
dd = dt.parent.css('dd').first
links = dd.css('a')
implements = (links.collect do |a|
title = a.attr('title')
package = nil
m = /.+[[:space:]]+([\w\.]+)$/.match(title)
if m
package = m[1].strip.scrub
end
simple = a.text().strip.scrub
if package
package + '.' + simple
else
simple
end
end).sort
end
end
since = nil
since_label = doc.css('.description dt').find do |node|
node.text().include?("Since:")
end
if since_label
since = since_label.parent.css('dd').first.text().strip.scrub
end
#puts "#{class_name} description: '#{description}'"
output_doc = {
_id: class_name,
class: simple_class_name,
qualifiedClass: class_name,
name: simple_class_name,
qualifiedName: class_name,
annotations: annotations,
modifiers: modifiers,
since: since,
kind: kind,
description: description,
path: make_class_path(package_name, simple_class_name),
packageBoost: package_boost(package_name),
recognitionKeys: ['com.solveforall.recognition.programming.java.JdkClass'],
}
if kind == 'class'
output_doc[:constructors] = constructors
end
if (kind == 'class') || (kind == 'enum')
output_doc[:superClass] = super_class
output_doc[:methods] = methods
output_doc[:implements] = implements
elsif kind == 'interface'
output_doc[:methods] = methods
output_doc[:implements] = implements
end
if @first_document
@first_document = false
else
out.write(",\n")
end
out.write(output_doc.to_json)
#puts output_doc.to_json
end
def abbreviate_member(member)
member = member.select do |k, v|
ABBREVIATED_MEMBER_KEYS.include?(k)
end
member[:description] = truncate(member[:description], 250)
member[:params].each do |param|
param.delete(:description)
end
return member
end
def find_constructors(doc, package_name, class_name, simple_class_name, out)
find_invokable(KIND_CONSTRUCTOR, doc, package_name, class_name, simple_class_name, out)
end
def find_methods(doc, package_name, class_name, simple_class_name, out)
find_invokable(KIND_METHOD, doc, package_name, class_name, simple_class_name, out)
end
def find_invokable(kind, doc, package_name, class_name, simple_class_name, out)
debug("find_invokable for #{class_name}")
methods = []
header_text_to_find = nil
signature_regexp = nil
if kind == KIND_CONSTRUCTOR
header_text_to_find = 'constructor detail'
signature_regexp = CONSTRUCTOR_SIGNATURE_REGEXP
else
header_text_to_find = 'method detail'
signature_regexp = METHOD_SIGNATURE_REGEXP
end
method_detail_anchor = doc.css('.details h3').find do |element|
element.text().strip.downcase.include?(header_text_to_find)
end
if method_detail_anchor.nil?
return []
end
list_items = method_detail_anchor.parent.css('ul.blockList>li')
list_items.each do |item|
#puts "item = #{item}"
anchor_path = item.parent.previous_element.attr('name') || ''
path = make_class_path(package_name, simple_class_name) + '#' + anchor_path
signature = item.css('pre').first.text().strip
m = signature_regexp.match(signature)
unless m
debug("Can't match signature '#{signature}'")
next
end
annotations = (m[1] || '').strip.split(LINE_BREAK_REGEXP)
modifiers = (m[2] || '').strip.split(SPACES_REGEXP).sort
group_offset = 0
return_type = nil
if kind == KIND_CONSTRUCTOR
group_offset = -1
else
return_type = m[3]
end
method_name = m[4 + group_offset]
params = parse_parameters(m[5 + group_offset])
throws_text = m[6 + group_offset]
throws = []
if throws_text
throws = throws_text.strip.split(/[[:space:]],[[:space:]]/)
end
debug("path = '#{path}', annotations = #{annotations}, modifiers = #{modifiers}, return_type = '#{return_type}', name = '#{method_name}', params = #{params}, throws = #{throws}")
description = nil
# Skip deprecated blocks
description_block = item.css('.block').last
if description_block
description = truncate(description_block.text().strip)
end
parameters_label = item.css('dt').find do |dt|
dt.text().downcase.include?('parameters:')
end
if parameters_label
dd = parameters_label.next_element
while dd && (dd.name == 'dd') do
m = /(\w+)[[:space:]]+(?:\-[[:space:]])*(.+)/.match(dd.text().strip)
if m
param_name = m[1]
param_description = m[2]
param = params.find do |p|
p[:name] == param_name
end
if param
param[:description] = truncate(param_description, 250)
end
end
dd = dd.next_element
end
end
output_doc = {
class: simple_class_name,
qualifiedClass: class_name,
name: method_name,
qualifiedName: class_name + '.' + method_name,
annotations: annotations,
modifiers: modifiers,
path: path,
params: params,
throws: throws,
kind: kind,
description: description,
packageBoost: package_boost(package_name),
recognitionKeys: ['com.solveforall.recognition.programming.java.Jdk' + kind.capitalize]
}
# Don't add constructors to the index, as it makes searching for classes hard
if kind == KIND_METHOD
returns_label = item.css('dt').find do |dt|
dt.text().downcase.include?('returns:')
end
returns_description = nil
if returns_label
returns_description = returns_label.next_element.text().strip
end
output_doc[:returnType] = return_type
output_doc[:returns] = returns_description
if @first_document
@first_document = false
else
out.write(",\n")
end
output_json = output_doc.to_json
out.write(output_json)
debug(output_json)
end
methods << abbreviate_member(output_doc)
end
debug("done find_methods for #{class_name}")
methods
end
def parse_parameters(params_text)
params = []
if params_text && (params_text.length > 0)
#puts "got params text '#{params_text}'"
else
return params
end
params_text.split(PARAM_SPLIT_REGEXP).each do |line|
m = PARAM_REGEXP.match(line)
if m
param = {
type: m[1],
name: m[2]
}
params << param
else
puts "Unmatched param line: '#{line}'!"
end
end
params
end
def package_boost(package_name)
if package_name.start_with?('java.awt')
return 0.7
elsif package_name.start_with?('java.sql')
return 0.9 # because java.sql.Date conflicts with java.util.Date
elsif package_name.start_with?('java.lang')
return 1.0
elsif package_name.start_with?('java.')
return 0.95
elsif package_name.start_with?('javax.')
return 0.9 # because javax.print.DocFlavor.STRING conflicts with java.lang.String
else
return 0.6
end
end
end
output_filename = 'jdk7-doc.json'
if ARGV.length > 1
output_filename = ARGV[1]
end
JavadocPopulator.new(ARGV[0], output_filename).populate
system("bzip2 -kf #{output_filename}") |
5119dba8-2d48-11e5-ab47-7831c1c36510
511ffc54-2d48-11e5-83d5-7831c1c36510
511ffc54-2d48-11e5-83d5-7831c1c36510 |
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
=begin
Markdown memo server
理想の Markdown メモツールを探したがなかったので自分で作った。
Ruby 1.9.3 でテスト
RDiscount が必要。
$ gem install rdiscount
DOCUMENT_ROOT と PORT を適当に書き換えて、起動してブラウザから
http://localhost:PORT/
にアクセスすればおk
DOCUMENT_ROOT 以下の Markdown で書かれたテキストを
勝手にHTMLに変換して表示します
検索も作った
Windows? 知らん
=end
DOCUMENT_ROOT = "~/Dropbox/memo"
PORT = 20000
require 'webrick'
require 'rdiscount'
require 'find'
require 'uri'
CONTENT_TYPE = "text/html; charset=utf-8"
DIR = File::expand_path(DOCUMENT_ROOT, '/')
MARKDOWN_PATTERN = /\.(md|markdown)$/
def header_html(title, path, q="")
html = <<HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="#{CONTENT_TYPE}" />
<title>#{title}</title>
<style type="text/css"><!--
body {
margin: auto;
padding-right: 1em;
padding-left: 1em;
max-width: 80%;
border-left: 1px solid black;
border-right: 1px solid black;
font-size: 100%;
line-height: 140%;
}
pre {
border: 1px dotted #090909;
background-color: #ececec;
padding: 0.5em;
}
code {
border: 1px dotted #090909;
background-color: #ececec;
padding: 2px 0.5em;
margin: 0 0.5em;
}
pre code {
border: none;
background-color: none;
padding: 0;
margin: 0;
}
a {
text-decoration: none;
}
a:link, a:visited, a:hover {
color: #4444cc;
}
a:hover {
text-decoration: underline;
}
h1 a, h2 a, h3 a, h4 a, h5 a {
text-decoration: none;
color: #2f4f4f;
}
h1, h2, h3, h4, h5 {
font-weight: bold;
color: #2f4f4f;
}
h1 {
font-size: 150%;
margin-top: 2em;
}
h2 { font-size: 130% }
h3 { font-size: 120% }
h4 {
font-size: 110%;
font-style: italic;
}
h5 {
font-size: 100%;
font-style: italic;
}
h1.title {
margin-top: 1ex;
line-height: 1.2em;
font-size: 200%;
font-weight: bold;
padding-top: 0.2em;
padding-bottom: 0.2em;
text-align: left;
border: none;
}
dt code { font-weight: bold }
dd p { margin-top: 0 }
div.footnotes {
padding-top: 1em;
color: #090909;
}
div#header {
margin-top: 1em;
padding-bottom: 1em;
border-bottom: 1px dotted black;
}
div#header > form {
display: float;
float: right;
text-align: right;
}
span.filename {
color: #666666;
}
footer {
border-top: 1px dotted black;
padding: 0.5em;
text-align: right;
}
--></style>
</head>
<body>
HTML
link_str = ""
uri = ""
path.split('/').each do |s|
next if s == ''
uri += "/" + s
link_str += File::SEPARATOR + "<a href='#{uri}'>#{s}</a>"
end
uri.gsub!('/'+File::basename(uri), "") if File.file?(path(uri))
link_str = "<a href='/'>#{DOCUMENT_ROOT}</a>" + link_str
search_form = <<HTML
<form action="/search" method="get">
<input name="path" type="hidden" value="#{uri}" />
<input name="q" type="text" value="#{q}" size="24" />
<input type="submit" value="search" />
</form>
HTML
return html + "<div id=\"header\">#{link_str}#{search_form}</div>"
end
def footer_html
html = <<HTML
<footer>
<a href="https://gist.github.com/3025885">https://gist.github.com/3025885</a>
</footer>
</body>
</html>
HTML
end
def uri(path)
s = File::expand_path(path).gsub(DIR, "").gsub(File::SEPARATOR, '/')
return s == '' ? '/' : s
end
def path(uri)
return File.join(DIR, uri.gsub('/', File::SEPARATOR))
end
def docpath(uri)
return File.join(DOCUMENT_ROOT, uri.gsub('/', File::SEPARATOR)).gsub(/#{File::SEPARATOR}$/, "")
end
def link_list(title, link)
file = path(link)
str = File.file?(file) ? sprintf("%.1fKB", File.size(file) / 1024.0) : "dir"
return "- [#{title}](#{link}) <span class='filename'>#{File.basename(link)} [#{str}]</span>\n"
end
def markdown?(file)
return file =~ MARKDOWN_PATTERN
end
def get_title(filename, str)
title = str.split(/$/)[0]
return title =~ /^\s*$/ ? File::basename(filename) : title
end
server = WEBrick::HTTPServer.new({ :Port => PORT })
server.mount_proc('/') do |req, res|
if req.path =~ /^\/search/
query = req.query
path = path(query["path"])
q = URI.decode(query["q"]).force_encoding('utf-8')
found = {}
Find.find(path) do |file|
if markdown?(file)
dir = File::dirname(file)
open(file) do |f|
c = f.read + "\n" + file
found[dir] = [] if !found[dir]
found[dir] << [get_title(file,c), uri(file)] if !q.split(' ').map{|s| /#{s}/mi =~ c }.include?(nil)
end
end
end
title = "Search #{q} in #{docpath(query['path'])}".force_encoding('utf-8')
body = title + "\n====\n"
found.sort.each do |key, value|
body += "\n#{uri(key)}\n----\n" if value != []
value.each do |v|
body += link_list(v[0], v[1])
end
end
res.body = header_html(title, uri(path), q) + RDiscount.new(body).to_html + footer_html
res.content_type = CONTENT_TYPE
else
filename = path(req.path)
if File.directory?(filename) then
title = "Index of #{docpath(req.path)}"
body = title + "\n====\n"
dirs = []
markdowns = []
files = []
Dir.entries(filename).each do |i|
next if i =~ /^\.+$/
link = uri(File.join(filename, i))
if File.directory?(path(link)) then
dirs << [File.basename(link) + File::SEPARATOR, link]
elsif markdown?(link)
File.open(path(link)) do |f|
markdowns << [get_title(link, f.read), link]
end
else
files << [File::basename(link), link]
end
end
body += "\nDirectories:\n----\n"
dirs.each {|i| body += link_list(i[0], i[1])}
body += "\nMarkdown documents:\n----\n"
markdowns.each {|i| body += link_list(i[0], i[1])}
body += "\nOther files:\n----\n"
files.each {|i| body += link_list(i[0], i[1])}
res.body = header_html(title, req.path) + RDiscount.new(body).to_html + footer_html
res.content_type = CONTENT_TYPE
elsif File.exists?(filename)
open(filename) do |file|
if markdown?(req.path)
str = file.read
title = get_title(filename, str)
res.body = header_html(title, req.path) + RDiscount.new(str).to_html + footer_html
res.content_type = CONTENT_TYPE
else
res.body = file.read
res.content_type = WEBrick::HTTPUtils.mime_type(req.path, WEBrick::HTTPUtils::DefaultMimeTypes)
res.content_length = File.stat(filename).size
end
end
else
res.status = WEBrick::HTTPStatus::RC_NOT_FOUND
end
end
end
trap(:INT){server.shutdown}
server.start
modified styles
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
=begin
Markdown memo server
理想の Markdown メモツールを探したがなかったので自分で作った。
Ruby 1.9.3 でテスト
RDiscount が必要。
$ gem install rdiscount
DOCUMENT_ROOT と PORT を適当に書き換えて、起動してブラウザから
http://localhost:PORT/
にアクセスすればおk
DOCUMENT_ROOT 以下の Markdown で書かれたテキストを
勝手にHTMLに変換して表示します
検索も作った
Windows? 知らん
=end
DOCUMENT_ROOT = "~/Dropbox/memo"
PORT = 20000
require 'webrick'
require 'rdiscount'
require 'find'
require 'uri'
CONTENT_TYPE = "text/html; charset=utf-8"
DIR = File::expand_path(DOCUMENT_ROOT, '/')
MARKDOWN_PATTERN = /\.(md|markdown)$/
def header_html(title, path, q="")
html = <<HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="#{CONTENT_TYPE}" />
<title>#{title}</title>
<style type="text/css"><!--
body {
margin: auto;
padding: 0 2em;
max-width: 80%;
border-left: 1px solid black;
border-right: 1px solid black;
font-size: 100%;
line-height: 140%;
}
pre {
border: 1px dotted #090909;
background-color: #ececec;
padding: 0.5em;
}
code {
border: 1px dotted #090909;
background-color: #ececec;
padding: 2px 0.5em;
margin: 0 0.5em;
}
pre code {
border: none;
background-color: none;
padding: 0;
margin: 0;
}
a {
text-decoration: none;
}
a:link, a:visited, a:hover {
color: #4444cc;
}
a:hover {
text-decoration: underline;
}
h1 a, h2 a, h3 a, h4 a, h5 a {
text-decoration: none;
color: #2f4f4f;
}
h1, h2, h3 {
font-weight: bold;
color: #2f4f4f;
}
h1 {
font-size: 200%;
line-height: 100%;
margin-top: 1em;
border-bottom: 1px solid #2f4f4f;
}
h2 {
font-size: 175%;
line-height: 100%;
margin-top: 1em;
padding-left: 0.5em;
border-left: 0.5em solid #2f4f4f;
}
h3 {
font-size: 150%;
line-height: 100%;
margin-top: 0.5em;
}
h4, h5 {
font-weight: bold;
color: #000000;
}
h4 { font-size: 125% }
h5 { font-size: 100% }
p {
margin: 0 1em;
}
div.footnotes {
padding-top: 1em;
color: #090909;
}
div#header {
margin-top: 1em;
padding-bottom: 1em;
border-bottom: 1px dotted black;
}
div#header > form {
display: float;
float: right;
text-align: right;
}
span.filename {
color: #666666;
}
footer {
border-top: 1px dotted black;
padding: 0.5em;
text-align: right;
margin: 5em 0 1em;
}
--></style>
</head>
<body>
HTML
link_str = ""
uri = ""
path.split('/').each do |s|
next if s == ''
uri += "/" + s
link_str += File::SEPARATOR + "<a href='#{uri}'>#{s}</a>"
end
uri.gsub!('/'+File::basename(uri), "") if File.file?(path(uri))
link_str = "<a href='/'>#{DOCUMENT_ROOT}</a>" + link_str
search_form = <<HTML
<form action="/search" method="get">
<input name="path" type="hidden" value="#{uri}" />
<input name="q" type="text" value="#{q}" size="24" />
<input type="submit" value="search" />
</form>
HTML
return html + "<div id=\"header\">#{link_str}#{search_form}</div>"
end
def footer_html
html = <<HTML
<footer>
<a href="https://gist.github.com/3025885">https://gist.github.com/3025885</a>
</footer>
</body>
</html>
HTML
end
def uri(path)
s = File::expand_path(path).gsub(DIR, "").gsub(File::SEPARATOR, '/')
return s == '' ? '/' : s
end
def path(uri)
return File.join(DIR, uri.gsub('/', File::SEPARATOR))
end
def docpath(uri)
return File.join(DOCUMENT_ROOT, uri.gsub('/', File::SEPARATOR)).gsub(/#{File::SEPARATOR}$/, "")
end
def link_list(title, link)
file = path(link)
str = File.file?(file) ? sprintf("%.1fKB", File.size(file) / 1024.0) : "dir"
return "- [#{title}](#{link}) <span class='filename'>#{File.basename(link)} [#{str}]</span>\n"
end
def markdown?(file)
return file =~ MARKDOWN_PATTERN
end
def get_title(filename, str)
title = str.split(/$/)[0]
return title =~ /^\s*$/ ? File::basename(filename) : title
end
server = WEBrick::HTTPServer.new({ :Port => PORT })
server.mount_proc('/') do |req, res|
if req.path =~ /^\/search/
query = req.query
path = path(query["path"])
q = URI.decode(query["q"]).force_encoding('utf-8')
found = {}
Find.find(path) do |file|
if markdown?(file)
dir = File::dirname(file)
open(file) do |f|
c = f.read + "\n" + file
found[dir] = [] if !found[dir]
found[dir] << [get_title(file,c), uri(file)] if !q.split(' ').map{|s| /#{s}/mi =~ c }.include?(nil)
end
end
end
title = "Search #{q} in #{docpath(query['path'])}".force_encoding('utf-8')
body = title + "\n====\n"
found.sort.each do |key, value|
body += "\n#{uri(key)}\n----\n" if value != []
value.each do |v|
body += link_list(v[0], v[1])
end
end
res.body = header_html(title, uri(path), q) + RDiscount.new(body).to_html + footer_html
res.content_type = CONTENT_TYPE
else
filename = path(req.path)
if File.directory?(filename) then
title = "Index of #{docpath(req.path)}"
body = title + "\n====\n"
dirs = []
markdowns = []
files = []
Dir.entries(filename).each do |i|
next if i =~ /^\.+$/
link = uri(File.join(filename, i))
if File.directory?(path(link)) then
dirs << [File.basename(link) + File::SEPARATOR, link]
elsif markdown?(link)
File.open(path(link)) do |f|
markdowns << [get_title(link, f.read), link]
end
else
files << [File::basename(link), link]
end
end
body += "\nDirectories:\n----\n"
dirs.each {|i| body += link_list(i[0], i[1])}
body += "\nMarkdown documents:\n----\n"
markdowns.each {|i| body += link_list(i[0], i[1])}
body += "\nOther files:\n----\n"
files.each {|i| body += link_list(i[0], i[1])}
res.body = header_html(title, req.path) + RDiscount.new(body).to_html + footer_html
res.content_type = CONTENT_TYPE
elsif File.exists?(filename)
open(filename) do |file|
if markdown?(req.path)
str = file.read
title = get_title(filename, str)
res.body = header_html(title, req.path) + RDiscount.new(str).to_html + footer_html
res.content_type = CONTENT_TYPE
else
res.body = file.read
res.content_type = WEBrick::HTTPUtils.mime_type(req.path, WEBrick::HTTPUtils::DefaultMimeTypes)
res.content_length = File.stat(filename).size
end
end
else
res.status = WEBrick::HTTPStatus::RC_NOT_FOUND
end
end
end
trap(:INT){server.shutdown}
server.start
|
require 'formula'
class Moab < Formula
homepage 'https://trac.mcs.anl.gov/projects/ITAPS/wiki/MOAB'
url 'https://bitbucket.org/fathomteam/moab/get/4.6.2.tar.gz'
sha1 '20494f8f13ea621a7b3fa30d98e0535957b237aa'
option 'without-check', "Skip build-time checks (not recommended)"
depends_on :autoconf
depends_on :automake
depends_on :libtool
depends_on 'netcdf'
depends_on 'hdf5'
depends_on :fortran if build.with? 'check'
def install
system "autoreconf", "--force", "--install"
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}", "--libdir=#{libexec}/lib"
system "make install"
# Moab installs non-lib files in libdir. Link only the libraries.
lib.install_symlink Dir["#{libexec}/lib/*.a"]
system "make check" if build.with? 'check'
end
end
moab: modernize autotools deps
require 'formula'
class Moab < Formula
homepage 'https://trac.mcs.anl.gov/projects/ITAPS/wiki/MOAB'
url 'https://bitbucket.org/fathomteam/moab/get/4.6.2.tar.gz'
sha1 '20494f8f13ea621a7b3fa30d98e0535957b237aa'
option 'without-check', "Skip build-time checks (not recommended)"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on 'netcdf'
depends_on 'hdf5'
depends_on :fortran if build.with? 'check'
def install
system "autoreconf", "--force", "--install"
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}", "--libdir=#{libexec}/lib"
system "make install"
# Moab installs non-lib files in libdir. Link only the libraries.
lib.install_symlink Dir["#{libexec}/lib/*.a"]
system "make check" if build.with? 'check'
end
end
|
# coding: utf-8
require_relative 'point2d'
require_relative 'direction'
require 'prime'
require 'date'
class Mode
# List of operators which should not be ignored while in string mode.
STRING_CMDS = "\"'\\/_|"
def initialize(state)
@state = state
end
def is_char? val
val && val >= 0 && val <= 1114111
end
def process
raise NotImplementedError
end
def process_string
raise NotImplementedError
end
# Returns true when the resulting cell is a command.
def move
raw_move if @state.cell == "'".ord
raw_move
cell = @state.cell
case cell
when '/'.ord, '\\'.ord
@state.dir = @state.dir.reflect cell.chr
@state.toggle_mode
return false
when '_'.ord, '|'.ord
@state.dir = @state.dir.reflect cell.chr
return false
end
return true if @state.string_mode
@state.print_debug_info if cell == '`'.ord
is_char?(cell) && self.class::OPERATORS.has_key?(cell.chr)
end
# Moves the IP a single cell without regard for mirrors, walls or no-ops.
# Does respect grid boundaries.
def raw_move
raise NotImplementedError
end
def push val
@state.push val
end
def pop
raise NotImplementedError
end
def push_return
@state.push_return
end
def pop_return
@state.pop_return
end
def peek
val = pop
push val
val
end
end
class Cardinal < Mode
OPERATORS = {
'@' => :terminate,
'<' => :move_west,
'>' => :move_east,
'^' => :move_north,
'v' => :move_south,
'{' => :turn_left,
'}' => :turn_right,
'#' => :trampoline,
'$' => :cond_trampoline,
'=' => :cond_sign,
'&' => :repeat_iterator,
'~' => :swap,
'.' => :dup,
';' => :discard,
',' => :rotate_stack,
'0' => :digit, '1' => :digit, '2' => :digit, '3' => :digit, '4' => :digit, '5' => :digit, '6' => :digit, '7' => :digit, '8' => :digit, '9' => :digit,
'+' => :add,
'-' => :sub,
'*' => :mul,
':' => :div,
'%' => :mod,
'!' => :store_tape,
'?' => :load_tape,
'[' => :mp_left,
']' => :mp_right,
'(' => :search_left,
')' => :search_right,
'"' => :leave_string_mode,
"'" => :escape,
'I' => :input,
'O' => :output,
'i' => :raw_input,
'o' => :raw_output,
'A' => :bitand,
'C' => :binomial,
'D' => :deduplicate,
'E' => :power,
'F' => :divides,
'G' => :gcd,
'H' => :abs,
'J' => :jump_raw,
'K' => :return_raw,
'L' => :lcm,
'M' => :divmod,
'N' => :bitnot,
'P' => :factorial,
'Q' => :convert,
'R' => :negate,
'S' => :replace_divisors,
'T' => :sleep,
'V' => :bitor,
'W' => :discard_return,
'X' => :bitxor,
'a' => :const_10,
'b' => :random,
'c' => :prime_factors,
'd' => :stack_depth,
'e' => :const_m1,
'f' => :prime_factor_pairs,
'g' => :get_cell,
'h' => :inc,
'j' => :jump,
'k' => :return,
'l' => :clear_bits,
'm' => :floor,
'n' => :not,
'p' => :put_cell,
'q' => :get_mp,
'r' => :range,
's' => :sortswap,
't' => :dec,
'u' => :set_bits,
'w' => :push_return,
'x' => :extract_bit,
'y' => :bit_if,
'z' => :transpose_ip,
}
OPERATORS.default = :nop
def raw_move
@state.ip += @state.dir.vec
@state.wrap
end
def pop
val = nil
loop do
val = @state.pop
if val.is_a?(String)
found = false
val.scan(/(?:^|(?!\G))-?\d+/) { push $&.to_i; found = true }
next if !found
val = @state.pop
end
break
end
val || 0
end
def process cmd
opcode = OPERATORS[cmd]
case opcode
when :nop
raise "No-op reached process(). This shouldn't happen."
when :terminate
@state.done = true
when :move_east
@state.dir = East.new
when :move_west
@state.dir = West.new
when :move_south
@state.dir = South.new
when :move_north
@state.dir = North.new
when :turn_left
@state.dir = @state.dir.left
when :turn_right
@state.dir = @state.dir.right
when :trampoline
move
when :cond_trampoline
move if pop == 0
when :cond_sign
val = pop
if val < 0
@state.dir = @state.dir.left
elsif val > 0
@state.dir = @state.dir.right
end
when :repeat_iterator
@state.add_iterator pop
when :transpose_ip
@state.jump(@state.ip.y, @state.ip.x)
case @state.dir
when East
@state.dir = South.new
when West
@state.dir = North.new
when South
@state.dir = East.new
when North
@state.dir = West.new
end
when :jump
push_return
y = pop
x = pop
@state.jump(x,y)
when :return
@state.jump(*pop_return)
when :jump_raw
y = pop
x = pop
@state.jump(x,y)
when :return_raw
target = pop_return
push_return target
@state.jump(*target)
when :push_return
push_return
when :discard_return
pop_return
when :get_cell
y = pop
x = pop
push @state.cell(Point2D.new(x,y))
when :put_cell
v = pop
y = pop
x = pop
@state.put_cell(Point2D.new(x,y), v)
when :store_tape
@state.tape[@state.mp] = pop
when :load_tape
push (@state.tape[@state.mp] || -1)
when :mp_left
@state.mp -= 1
when :mp_right
@state.mp += 1
when :search_left
val = pop
@state.mp -= 1 while @state.tape[@state.mp] != val
when :search_right
val = pop
@state.mp += 1 while @state.tape[@state.mp] != val
when :get_mp
push @state.mp
when :leave_string_mode
@state.stack += @state.current_string
when :escape
raw_move
push @state.cell
@state.ip -= @state.dir.vec
when :input
char = @state.in_str.getc
push(char ? char.ord : -1)
when :output
# Will throw an error when value isn't a valid code point
@state.out_str << pop.chr
when :raw_input
push(@state.in_str.getbyte || -1)
when :raw_output
# TODO: do
when :digit
push cmd.chr.to_i
when :add
push(pop + pop)
when :sub
y = pop
push(pop - y)
when :mul
push(pop * pop)
when :div
y = pop
push(pop / y)
when :mod
y = pop
push(pop % y)
when :divmod
y = pop
x = pop
push(x / y)
push(x % y)
when :inc
push(pop+1)
when :dec
push(pop-1)
when :abs
push(pop.abs)
when :power
y = pop
x = pop
if y < 0
push 0
else
push x**y
end
when :bitand
push(pop & pop)
when :bitnot
push(~pop)
when :bitor
push(pop | pop)
when :bitxor
push(pop ^ pop)
when :bitif
z = pop
y = pop
x = pop
push(x&y | ~x&z)
when :clear_bits
x = pop
if x > 0
msb = Math.log2(x).floor
elsif x < -1
msb = Math.log2(~x).floor
else
msb = 0
end
push (x & -(2**msb))
when :set_bits
x = pop
if x > 0
msb = Math.log2(x).floor
elsif x < -1
msb = Math.log2(~x).floor
else
msb = 0
end
push (x | (2**msb-1))
when :extract_bit
y = pop
x = pop
if y >= 0
push x[y]
else
if x > 0
msb = Math.log2(x).floor
elsif x < -1
msb = Math.log2(~x).floor
else
msb = 0
end
push x[msb-y+1]
end
when :factorial
val = pop
if val >= 0
push (1..val).reduce(1, :*)
else
push (val..-1).reduce(1, :*)
end
when :binomial
k = pop
n = pop
k = n-k if n > 0 && k > n/2
if k < 0
push 0
else
prod = 1
(1..k).each do |i|
prod *= n
prod /= i
n -= 1
end
push prod
end
when :negate
push -pop
when :prime_factors
# TODO: settle on behaviour for n < 2
Prime.prime_division(pop).each{ |p,n| n.times{ push p } }
when :prime_factor_pairs
# TODO: settle on behaviour for n < 2
Prime.prime_division(pop).flatten.each{ |x| push x }
when :deduplicate
Prime.int_from_prime_division(Prime.prime_division(pop.map{ |p,n| [p,1]}))
when :divides
y = pop
x = pop
if x % y == 0
push y
else
push 0
end
when :gcd
push (pop.gcd pop)
when :lcm
push (pop.lcm pop)
when :floor
y = pop
x = pop
push (x/y)*y
when :replace_divisors
z = pop
y = pop
x = pop
if x == 0
push 0
else
order = 0
while x%y == 0
order += 1
x /= y
end
x *= z**order
end
when :not
push (pop == 0 ? 1 : 0)
when :range
val = pop
if val >= 0
0.upto(val) {|i| push i}
else
(-val).downto(0) {|i| push i}
end
when :random
val = pop
if val > 0
push rand val
elsif val == 0
push 0 # TODO: or something else?
else
push -(rand val)
end
when :sortswap
top = pop
second = pop
top, second = second, top if top < second
push second
push top
when :swap
top = pop
second = pop
push top
push second
when :dup
top = pop
push top
push top
when :discard
pop
when :stack_depth
push @state.stack.size
when :rotate_stack
n = pop
if n > 0
if n >= @state.stack.size
push 0
else
push @state.stack[-n-1]
@state.stack.delete_at(-n-2)
end
elsif n < 0
top = pop
@state.stack = [0]*[-n-@state.stack.size, 0].max + @state.stack
@state.stack.insert(n-1, top)
end
when :convert
n = pop
n.times.map{pop}.reverse.each{|v| push v}
when :sleep
sleep pop/1000.0
when :const_10
push 10
when :const_m1
push -1
end
end
end
class Ordinal < Mode
OPERATORS = {
'@' => :terminate,
'0' => :digit, '1' => :digit, '2' => :digit, '3' => :digit, '4' => :digit, '5' => :digit, '6' => :digit, '7' => :digit, '8' => :digit, '9' => :digit,
'+' => :concat,
'-' => :drop,
'*' => :riffle,
':' => :occurrences,
'%' => :split,
'<' => :ensure_west,
'>' => :ensure_east,
'^' => :ensure_north,
'v' => :ensure_south,
'{' => :turn_left,
'}' => :turn_right,
'#' => :trampoline,
'$' => :cond_trampoline,
'=' => :cond_cmp,
'&' => :fold_iterator,
'~' => :swap,
'.' => :dup,
';' => :discard,
',' => :permute_stack,
'!' => :store_register,
'?' => :load_register,
'[' => :register_left,
']' => :register_right,
'(' => :search_left,
')' => :search_right,
'"' => :leave_string_mode,
"'" => :escape,
'I' => :input,
'O' => :output,
'i' => :raw_input,
'o' => :raw_output,
'A' => :intersection,
'C' => :subsequences,
'D' => :deduplicate,
'E' => :substrings,
'F' => :find,
'G' => :longest_common_substring,
'H' => :trim,
'J' => :jump_raw,
'K' => :return_raw,
'L' => :shortest_common_superstring,
'M' => :inclusive_split,
'N' => :complement,
'P' => :permutations,
'Q' => :reverse_stack,
'R' => :reverse,
'S' => :replace,
'T' => :datetime,
'V' => :union,
'W' => :discard_return,
'X' => :symdifference,
'Z' => :zip,
'a' => :const_lf,
'b' => :shuffle,
'c' => :characters,
'd' => :push_joined_stack,
'e' => :const_empty,
'f' => :runs,
'g' => :get_diagonal,
'h' => :head,
'j' => :jump,
'k' => :return,
'l' => :lower_case,
'm' => :truncate_to_shorter,
'u' => :upper_case,
'n' => :not,
'p' => :put_diagonal,
'q' => :join_tape,
'r' => :expand_ranges,
's' => :sort,
't' => :tail,
'w' => :push_return,
'x' => :permute,
'y' => :transliterate,
'z' => :transpose,
#'(' => ,
#')' => ,
#'!' => ,
#'$' => ,
#'&' => ,
#',' => ,
#'.' => ,
#';' => ,
#'=' => ,
#'?' => ,
#'`' => ,
#'A' => ,
# ...
#'Z' => ,
#'a' => ,
# ...
#'z' => ,
}
OPERATORS.default = :nop
def raw_move
if @state.width == 1 || @state.height == 1
return
end
new_pos = @state.ip + @state.dir.vec + @state.storage_offset
@state.dir = @state.dir.reflect('|') if new_pos.x < 0 || new_pos.x >= @state.width
@state.dir = @state.dir.reflect('_') if new_pos.y < 0 || new_pos.y >= @state.height
@state.ip += @state.dir.vec
end
def pop
val = @state.pop
val ? val.to_s : ''
end
def scan_source label
ip_dir = @state.dir
grid = @state.grid
while !ip_dir.is_a? NorthEast
grid = grid.transpose.reverse
ip_dir = ip_dir.left
end
height = grid.size
width = height == 0 ? 0 : grid[0].size
positions = []
(0..width+height-2).map do |d|
min_x = [0,d-height+1].max
max_x = [width-1,d].min
line = (min_x..max_x).map do |x|
y = d - x
grid[y][x].chr
end.join
line.scan(/(?=#{Regexp.escape(label)})/) do
x = min_x + $`.size + label.size - 1
y = d-x
positions << [x,y]
end
end
ip_dir = @state.dir
while !ip_dir.is_a? NorthEast
ip_dir = ip_dir.left
positions.map! {|x, y| [grid.size - y - 1, x]}
grid = grid.reverse.transpose
end
positions
end
def process cmd
opcode = OPERATORS[cmd]
case opcode
when :nop
raise "No-op reached process(). This shouldn't happen."
when :terminate
@state.done = true
when :ensure_west
@state.dir = @state.dir.reflect '|' if @state.dir.vec.x > 0
when :ensure_east
@state.dir = @state.dir.reflect '|' if @state.dir.vec.x < 0
when :ensure_north
@state.dir = @state.dir.reflect '_' if @state.dir.vec.y > 0
when :ensure_south
@state.dir = @state.dir.reflect '_' if @state.dir.vec.y < 0
when :turn_left
@state.dir = @state.dir.left
when :turn_right
@state.dir = @state.dir.right
when :trampoline
move
when :cond_trampoline
move if pop == ''
when :cond_cmp
top = pop
second = pop
if top > second
@state.dir = @state.dir.left
elsif top < second
@state.dir = @state.dir.right
end
when :fold_iterator
@state.add_iterator pop
when :jump
push_return
label = pop
positions = scan_source(label)
@state.jump(*positions[0]) if !positions.empty?
when :return
@state.jump(*pop_return)
when :jump_raw
label = pop
positions = scan_source(label)
@state.jump(*positions[0]) if !positions.empty?
when :return_raw
target = pop_return
push_return target
@state.jump(*target)
when :push_return
push_return
when :discard_return
pop_return
when :get_diagonal
label = pop
positions = scan_source(label)
if !positions.empty?
cursor = Point2D.new(*positions[0]) + @state.dir.vec
string = ''
while is_char? @state.cell(cursor)
string << @state.cell(cursor)
cursor += @state.dir.vec
end
push string
end
when :put_diagonal
value = pop
label = pop
positions = scan_source(label)
if !positions.empty?
cursor = Point2D.new(*positions[0]) + @state.dir.vec
value.each_char {|c|
@state.put_cell(cursor, c.ord)
cursor += @state.dir.vec
}
end
when :store_register
i = @state.rp
pop.each_char do |c|
@state.tape[i] = c.ord
i += 1
end
@state.tape[i] = -1
when :load_register
push @state.read_register
when :register_left
@state.rp -= 1 while is_char? @state.tape[@state.rp-1]
@state.rp -= 1
@state.rp -= 1 while is_char? @state.tape[@state.rp-1]
when :register_right
@state.rp += 1 while is_char? @state.tape[@state.rp]
@state.rp += 1
when :search_left
needle = pop
last = @state.rp
string = ""
@state.tape.keys.select{|i| i < @state.rp}.sort.reverse.map do |i|
if i+1 == last && is_char?(@state.tape[i])
string << @state.tape[i]
elsif string.reverse[needle]
@state.rp = last
break
else
string = ""
end
last = i
end
when :search_right
needle = pop
last = @state.rp-1
string = ""
@state.tape.keys.select{|i| i >= @state.rp}.sort.map do |i|
if i-1 == last && is_char?(@state.tape[i])
string << @state.tape[i]
elsif string[needle]
@state.rp = last - string.size + 1
break
else
string = ""
end
last = i
end
when :join_tape
push @state.tape.keys.sort.map{|i| @state.tape[i]}.select{|v| is_char?(v)}.map(&:chr).join
when :leave_string_mode
# Will throw an error when cell isn't a valid code point
push @state.current_string.map(&:chr).join
when :escape
raw_move
push @state.cell.chr # Will throw an error when cell isn't a valid code point
@state.ip -= @state.dir.vec
when :digit
push(pop + cmd.chr)
when :input
line = @state.in_str.gets
push(line ? line.chomp : '')
when :output
@state.out_str.puts pop
when :raw_input
push(@state.in_str.read || '')
when :raw_output
@state.out_str << pop
when :concat
top = pop
second = pop
push(second + top)
when :drop
y = pop
x = pop
result = x.chars
x.scan(/(?=#{Regexp.escape(y)})/) do
y.size.times do |i|
result[$`.size + i] = 0
end
end
push (result-[0]).join
when :riffle
sep = pop
push(pop.chars * sep)
when :occurrences
sep = pop
pop.scan(/#{Regexp.escape(sep)}/){ push sep }
when :split
sep = pop
@state.stack += pop.split(sep, -1)
when :inclusive_split
sep = pop
str = pop
splits = str.split(sep, -1)
str.scan(/#{Regexp.escape(sep)}/){ push splits.shift; push sep }
push splits.shift
when :replace
target = pop
needle = pop
haystack = pop
push haystack.gsub(needle, target)
when :trim
push pop.gsub(/^[ \n\t]+|[ \n\t]+$/, '')
when :transliterate
target = pop
source = pop
string = pop
if target.empty?
source.each_char {|c| string.gsub!(c, '')}
else
target += target[-1]*[source.size-target.size,0].max
string = string.chars.map{|c| target[source.index c]}.join
end
push string
when :transpose
lines = pop.lines
width = lines.map(&:size).max
(0...width).map do |i|
lines.map{|l| l[i] || ''}.join
end.join $/
when :find
needle = pop
haystack = pop
push(haystack[needle] || '')
when :truncate_to_shorter
top = pop
second = pop
length = [top.size, second.size].min
push second[0,length]
push top[0,length]
when :zip
top = pop.chars
second = pop.chars
result = []
while !top.empty? || !second.empty?
result << (second.shift || '')
result << (top.shift || '')
end
push result * ''
when :shortest_common_superstring
top = pop
second = pop
len = [top.size, second.size].min
len.downto(0) do |i|
if second[-i,i] == top[0,i]
push second+top[i..-1]
break
end
end
when :longest_common_substring
top = pop
second = pop
second.size.downto(0) do |l|
if l == 0
push ""
else
shared = second.chars.each_cons(l).select {|s| top[s.join]}
if !shared.empty?
shared.uniq.each{|s| push s.join}
break
end
end
end
when :intersection
second = pop
first = pop
result = first.chars.select {|c|
test = second[c]
second[c] = '' if test
test
}
push result.join
when :union
second = pop
first = pop
first.each_char {|c| second[c] = '' if second[c]}
push(first + second)
when :symdifference
second = pop
first = pop
temp_second = second.clone
first.each_char {|c| second[c] = '' if second[c]}
temp_second.each_char {|c| first[c] = '' if first[c]}
push first+second
when :complement
second = pop
first = pop
second.each_char {|c| first[c] = '' if first[c]}
push first
when :deduplicate
push pop.chars.uniq.join
when :sort
push pop.chars.sort.join
when :shuffle
push pop.chars.shuffle.join
when :characters
@stack.state += pop.chars
when :runs
pop.scan(/(.)\1*/s){push $&}
when :head
str = pop
if pop == ''
push ''
push ''
else
push str[0]
push str[1..-1]
end
when :tail
str = pop
if pop == ''
push ''
push ''
else
push str[0..-2]
push str[-1]
end
when :lower_case
push pop.downcase
when :upper_case
push pop.upcase
when :swap_case
push pop.swapcase
when :not
push(pop == '' ? 'Jabberwocky' : '')
when :reverse
push pop.reverse
when :permutations
@state.stack += pop.chars.permutation.map{|p| p.join}.to_a
when :subsequences
str = pop.chars
(0..str.size).each do |l|
str.combination(l).each {|s| push s.join}
end
when :substrings
str = pop.chars
(1..str.size).each do |l|
str.each_cons(l).each {|s| push s.join}
end
when :permute
top = pop
second = pop
push (0...second.size).stable_sort_by{|i|
c = top[i]
c ? c.ord : 1114112 # Value greater than any code point, so that trailing
# characters remain in place.
}.map{|i| second[i]}.join
when :expand_ranges
val = pop
val.chars.each_cons(2).map{ |a,b|
if a > b
(b..a).drop(1).to_a.reverse.join
else
(a...b).to_a.join
end
}.join + (val[-1] || '')
when :swap
top = pop
second = pop
push top
push second
when :dup
top = pop
push top
push top
when :discard
pop
when :push_joined_stack
push @state.stack.join
when :reverse_stack
@state.stack.reverse!.map!(:to_s)
when :permute_stack
top = pop
max_size = [@state.stack.size, top.size].max
@state.stack = (-max_size..-1).stable_sort_by{|i|
c = top[i]
c ? c.ord : -1 # Value less than any code point, so that leading
# stack elements remain in place.
}.map{|i| @state.stack[i] || ''}
when :datetime
push DateTime.now.strftime '%Y-%m-%dT%H:%M:%S.%L%:z'
when :const_lf
push "\n"
when :const_empty
push ""
end
end
end
Add unzip, fix head and tail
# coding: utf-8
require_relative 'point2d'
require_relative 'direction'
require 'prime'
require 'date'
class Mode
# List of operators which should not be ignored while in string mode.
STRING_CMDS = "\"'\\/_|"
def initialize(state)
@state = state
end
def is_char? val
val && val >= 0 && val <= 1114111
end
def process
raise NotImplementedError
end
def process_string
raise NotImplementedError
end
# Returns true when the resulting cell is a command.
def move
raw_move if @state.cell == "'".ord
raw_move
cell = @state.cell
case cell
when '/'.ord, '\\'.ord
@state.dir = @state.dir.reflect cell.chr
@state.toggle_mode
return false
when '_'.ord, '|'.ord
@state.dir = @state.dir.reflect cell.chr
return false
end
return true if @state.string_mode
@state.print_debug_info if cell == '`'.ord
is_char?(cell) && self.class::OPERATORS.has_key?(cell.chr)
end
# Moves the IP a single cell without regard for mirrors, walls or no-ops.
# Does respect grid boundaries.
def raw_move
raise NotImplementedError
end
def push val
@state.push val
end
def pop
raise NotImplementedError
end
def push_return
@state.push_return
end
def pop_return
@state.pop_return
end
def peek
val = pop
push val
val
end
end
class Cardinal < Mode
OPERATORS = {
'@' => :terminate,
'<' => :move_west,
'>' => :move_east,
'^' => :move_north,
'v' => :move_south,
'{' => :turn_left,
'}' => :turn_right,
'#' => :trampoline,
'$' => :cond_trampoline,
'=' => :cond_sign,
'&' => :repeat_iterator,
'~' => :swap,
'.' => :dup,
';' => :discard,
',' => :rotate_stack,
'0' => :digit, '1' => :digit, '2' => :digit, '3' => :digit, '4' => :digit, '5' => :digit, '6' => :digit, '7' => :digit, '8' => :digit, '9' => :digit,
'+' => :add,
'-' => :sub,
'*' => :mul,
':' => :div,
'%' => :mod,
'!' => :store_tape,
'?' => :load_tape,
'[' => :mp_left,
']' => :mp_right,
'(' => :search_left,
')' => :search_right,
'"' => :leave_string_mode,
"'" => :escape,
'I' => :input,
'O' => :output,
'i' => :raw_input,
'o' => :raw_output,
'A' => :bitand,
'C' => :binomial,
'D' => :deduplicate,
'E' => :power,
'F' => :divides,
'G' => :gcd,
'H' => :abs,
'J' => :jump_raw,
'K' => :return_raw,
'L' => :lcm,
'M' => :divmod,
'N' => :bitnot,
'P' => :factorial,
'Q' => :convert,
'R' => :negate,
'S' => :replace_divisors,
'T' => :sleep,
'V' => :bitor,
'W' => :discard_return,
'X' => :bitxor,
'a' => :const_10,
'b' => :random,
'c' => :prime_factors,
'd' => :stack_depth,
'e' => :const_m1,
'f' => :prime_factor_pairs,
'g' => :get_cell,
'h' => :inc,
'j' => :jump,
'k' => :return,
'l' => :clear_bits,
'm' => :floor,
'n' => :not,
'p' => :put_cell,
'q' => :get_mp,
'r' => :range,
's' => :sortswap,
't' => :dec,
'u' => :set_bits,
'w' => :push_return,
'x' => :extract_bit,
'y' => :bit_if,
'z' => :transpose_ip,
}
OPERATORS.default = :nop
def raw_move
@state.ip += @state.dir.vec
@state.wrap
end
def pop
val = nil
loop do
val = @state.pop
if val.is_a?(String)
found = false
val.scan(/(?:^|(?!\G))-?\d+/) { push $&.to_i; found = true }
next if !found
val = @state.pop
end
break
end
val || 0
end
def process cmd
opcode = OPERATORS[cmd]
case opcode
when :nop
raise "No-op reached process(). This shouldn't happen."
when :terminate
@state.done = true
when :move_east
@state.dir = East.new
when :move_west
@state.dir = West.new
when :move_south
@state.dir = South.new
when :move_north
@state.dir = North.new
when :turn_left
@state.dir = @state.dir.left
when :turn_right
@state.dir = @state.dir.right
when :trampoline
move
when :cond_trampoline
move if pop == 0
when :cond_sign
val = pop
if val < 0
@state.dir = @state.dir.left
elsif val > 0
@state.dir = @state.dir.right
end
when :repeat_iterator
@state.add_iterator pop
when :transpose_ip
@state.jump(@state.ip.y, @state.ip.x)
case @state.dir
when East
@state.dir = South.new
when West
@state.dir = North.new
when South
@state.dir = East.new
when North
@state.dir = West.new
end
when :jump
push_return
y = pop
x = pop
@state.jump(x,y)
when :return
@state.jump(*pop_return)
when :jump_raw
y = pop
x = pop
@state.jump(x,y)
when :return_raw
target = pop_return
push_return target
@state.jump(*target)
when :push_return
push_return
when :discard_return
pop_return
when :get_cell
y = pop
x = pop
push @state.cell(Point2D.new(x,y))
when :put_cell
v = pop
y = pop
x = pop
@state.put_cell(Point2D.new(x,y), v)
when :store_tape
@state.tape[@state.mp] = pop
when :load_tape
push (@state.tape[@state.mp] || -1)
when :mp_left
@state.mp -= 1
when :mp_right
@state.mp += 1
when :search_left
val = pop
@state.mp -= 1 while @state.tape[@state.mp] != val
when :search_right
val = pop
@state.mp += 1 while @state.tape[@state.mp] != val
when :get_mp
push @state.mp
when :leave_string_mode
@state.stack += @state.current_string
when :escape
raw_move
push @state.cell
@state.ip -= @state.dir.vec
when :input
char = @state.in_str.getc
push(char ? char.ord : -1)
when :output
# Will throw an error when value isn't a valid code point
@state.out_str << pop.chr
when :raw_input
push(@state.in_str.getbyte || -1)
when :raw_output
# TODO: do
when :digit
push cmd.chr.to_i
when :add
push(pop + pop)
when :sub
y = pop
push(pop - y)
when :mul
push(pop * pop)
when :div
y = pop
push(pop / y)
when :mod
y = pop
push(pop % y)
when :divmod
y = pop
x = pop
push(x / y)
push(x % y)
when :inc
push(pop+1)
when :dec
push(pop-1)
when :abs
push(pop.abs)
when :power
y = pop
x = pop
if y < 0
push 0
else
push x**y
end
when :bitand
push(pop & pop)
when :bitnot
push(~pop)
when :bitor
push(pop | pop)
when :bitxor
push(pop ^ pop)
when :bitif
z = pop
y = pop
x = pop
push(x&y | ~x&z)
when :clear_bits
x = pop
if x > 0
msb = Math.log2(x).floor
elsif x < -1
msb = Math.log2(~x).floor
else
msb = 0
end
push (x & -(2**msb))
when :set_bits
x = pop
if x > 0
msb = Math.log2(x).floor
elsif x < -1
msb = Math.log2(~x).floor
else
msb = 0
end
push (x | (2**msb-1))
when :extract_bit
y = pop
x = pop
if y >= 0
push x[y]
else
if x > 0
msb = Math.log2(x).floor
elsif x < -1
msb = Math.log2(~x).floor
else
msb = 0
end
push x[msb-y+1]
end
when :factorial
val = pop
if val >= 0
push (1..val).reduce(1, :*)
else
push (val..-1).reduce(1, :*)
end
when :binomial
k = pop
n = pop
k = n-k if n > 0 && k > n/2
if k < 0
push 0
else
prod = 1
(1..k).each do |i|
prod *= n
prod /= i
n -= 1
end
push prod
end
when :negate
push -pop
when :prime_factors
# TODO: settle on behaviour for n < 2
Prime.prime_division(pop).each{ |p,n| n.times{ push p } }
when :prime_factor_pairs
# TODO: settle on behaviour for n < 2
Prime.prime_division(pop).flatten.each{ |x| push x }
when :deduplicate
Prime.int_from_prime_division(Prime.prime_division(pop.map{ |p,n| [p,1]}))
when :divides
y = pop
x = pop
if x % y == 0
push y
else
push 0
end
when :gcd
push (pop.gcd pop)
when :lcm
push (pop.lcm pop)
when :floor
y = pop
x = pop
push (x/y)*y
when :replace_divisors
z = pop
y = pop
x = pop
if x == 0
push 0
else
order = 0
while x%y == 0
order += 1
x /= y
end
x *= z**order
end
when :not
push (pop == 0 ? 1 : 0)
when :range
val = pop
if val >= 0
0.upto(val) {|i| push i}
else
(-val).downto(0) {|i| push i}
end
when :random
val = pop
if val > 0
push rand val
elsif val == 0
push 0 # TODO: or something else?
else
push -(rand val)
end
when :sortswap
top = pop
second = pop
top, second = second, top if top < second
push second
push top
when :swap
top = pop
second = pop
push top
push second
when :dup
top = pop
push top
push top
when :discard
pop
when :stack_depth
push @state.stack.size
when :rotate_stack
n = pop
if n > 0
if n >= @state.stack.size
push 0
else
push @state.stack[-n-1]
@state.stack.delete_at(-n-2)
end
elsif n < 0
top = pop
@state.stack = [0]*[-n-@state.stack.size, 0].max + @state.stack
@state.stack.insert(n-1, top)
end
when :convert
n = pop
n.times.map{pop}.reverse.each{|v| push v}
when :sleep
sleep pop/1000.0
when :const_10
push 10
when :const_m1
push -1
end
end
end
class Ordinal < Mode
OPERATORS = {
'@' => :terminate,
'0' => :digit, '1' => :digit, '2' => :digit, '3' => :digit, '4' => :digit, '5' => :digit, '6' => :digit, '7' => :digit, '8' => :digit, '9' => :digit,
'+' => :concat,
'-' => :drop,
'*' => :riffle,
':' => :occurrences,
'%' => :split,
'<' => :ensure_west,
'>' => :ensure_east,
'^' => :ensure_north,
'v' => :ensure_south,
'{' => :turn_left,
'}' => :turn_right,
'#' => :trampoline,
'$' => :cond_trampoline,
'=' => :cond_cmp,
'&' => :fold_iterator,
'~' => :swap,
'.' => :dup,
';' => :discard,
',' => :permute_stack,
'!' => :store_register,
'?' => :load_register,
'[' => :register_left,
']' => :register_right,
'(' => :search_left,
')' => :search_right,
'"' => :leave_string_mode,
"'" => :escape,
'I' => :input,
'O' => :output,
'i' => :raw_input,
'o' => :raw_output,
'A' => :intersection,
'C' => :subsequences,
'D' => :deduplicate,
'E' => :substrings,
'F' => :find,
'G' => :longest_common_substring,
'H' => :trim,
'J' => :jump_raw,
'K' => :return_raw,
'L' => :shortest_common_superstring,
'M' => :inclusive_split,
'N' => :complement,
'P' => :permutations,
'Q' => :reverse_stack,
'R' => :reverse,
'S' => :replace,
'T' => :datetime,
'V' => :union,
'W' => :discard_return,
'X' => :symdifference,
'Y' => :unzip,
'Z' => :zip,
'a' => :const_lf,
'b' => :shuffle,
'c' => :characters,
'd' => :push_joined_stack,
'e' => :const_empty,
'f' => :runs,
'g' => :get_diagonal,
'h' => :head,
'j' => :jump,
'k' => :return,
'l' => :lower_case,
'm' => :truncate_to_shorter,
'u' => :upper_case,
'n' => :not,
'p' => :put_diagonal,
'q' => :join_tape,
'r' => :expand_ranges,
's' => :sort,
't' => :tail,
'w' => :push_return,
'x' => :permute,
'y' => :transliterate,
'z' => :transpose,
#'(' => ,
#')' => ,
#'!' => ,
#'$' => ,
#'&' => ,
#',' => ,
#'.' => ,
#';' => ,
#'=' => ,
#'?' => ,
#'`' => ,
#'A' => ,
# ...
#'Z' => ,
#'a' => ,
# ...
#'z' => ,
}
OPERATORS.default = :nop
def raw_move
if @state.width == 1 || @state.height == 1
return
end
new_pos = @state.ip + @state.dir.vec + @state.storage_offset
@state.dir = @state.dir.reflect('|') if new_pos.x < 0 || new_pos.x >= @state.width
@state.dir = @state.dir.reflect('_') if new_pos.y < 0 || new_pos.y >= @state.height
@state.ip += @state.dir.vec
end
def pop
val = @state.pop
val ? val.to_s : ''
end
def scan_source label
ip_dir = @state.dir
grid = @state.grid
while !ip_dir.is_a? NorthEast
grid = grid.transpose.reverse
ip_dir = ip_dir.left
end
height = grid.size
width = height == 0 ? 0 : grid[0].size
positions = []
(0..width+height-2).map do |d|
min_x = [0,d-height+1].max
max_x = [width-1,d].min
line = (min_x..max_x).map do |x|
y = d - x
grid[y][x].chr
end.join
line.scan(/(?=#{Regexp.escape(label)})/) do
x = min_x + $`.size + label.size - 1
y = d-x
positions << [x,y]
end
end
ip_dir = @state.dir
while !ip_dir.is_a? NorthEast
ip_dir = ip_dir.left
positions.map! {|x, y| [grid.size - y - 1, x]}
grid = grid.reverse.transpose
end
positions
end
def process cmd
opcode = OPERATORS[cmd]
case opcode
when :nop
raise "No-op reached process(). This shouldn't happen."
when :terminate
@state.done = true
when :ensure_west
@state.dir = @state.dir.reflect '|' if @state.dir.vec.x > 0
when :ensure_east
@state.dir = @state.dir.reflect '|' if @state.dir.vec.x < 0
when :ensure_north
@state.dir = @state.dir.reflect '_' if @state.dir.vec.y > 0
when :ensure_south
@state.dir = @state.dir.reflect '_' if @state.dir.vec.y < 0
when :turn_left
@state.dir = @state.dir.left
when :turn_right
@state.dir = @state.dir.right
when :trampoline
move
when :cond_trampoline
move if pop == ''
when :cond_cmp
top = pop
second = pop
if top > second
@state.dir = @state.dir.left
elsif top < second
@state.dir = @state.dir.right
end
when :fold_iterator
@state.add_iterator pop
when :jump
push_return
label = pop
positions = scan_source(label)
@state.jump(*positions[0]) if !positions.empty?
when :return
@state.jump(*pop_return)
when :jump_raw
label = pop
positions = scan_source(label)
@state.jump(*positions[0]) if !positions.empty?
when :return_raw
target = pop_return
push_return target
@state.jump(*target)
when :push_return
push_return
when :discard_return
pop_return
when :get_diagonal
label = pop
positions = scan_source(label)
if !positions.empty?
cursor = Point2D.new(*positions[0]) + @state.dir.vec
string = ''
while is_char? @state.cell(cursor)
string << @state.cell(cursor)
cursor += @state.dir.vec
end
push string
end
when :put_diagonal
value = pop
label = pop
positions = scan_source(label)
if !positions.empty?
cursor = Point2D.new(*positions[0]) + @state.dir.vec
value.each_char {|c|
@state.put_cell(cursor, c.ord)
cursor += @state.dir.vec
}
end
when :store_register
i = @state.rp
pop.each_char do |c|
@state.tape[i] = c.ord
i += 1
end
@state.tape[i] = -1
when :load_register
push @state.read_register
when :register_left
@state.rp -= 1 while is_char? @state.tape[@state.rp-1]
@state.rp -= 1
@state.rp -= 1 while is_char? @state.tape[@state.rp-1]
when :register_right
@state.rp += 1 while is_char? @state.tape[@state.rp]
@state.rp += 1
when :search_left
needle = pop
last = @state.rp
string = ""
@state.tape.keys.select{|i| i < @state.rp}.sort.reverse.map do |i|
if i+1 == last && is_char?(@state.tape[i])
string << @state.tape[i]
elsif string.reverse[needle]
@state.rp = last
break
else
string = ""
end
last = i
end
when :search_right
needle = pop
last = @state.rp-1
string = ""
@state.tape.keys.select{|i| i >= @state.rp}.sort.map do |i|
if i-1 == last && is_char?(@state.tape[i])
string << @state.tape[i]
elsif string[needle]
@state.rp = last - string.size + 1
break
else
string = ""
end
last = i
end
when :join_tape
push @state.tape.keys.sort.map{|i| @state.tape[i]}.select{|v| is_char?(v)}.map(&:chr).join
when :leave_string_mode
# Will throw an error when cell isn't a valid code point
push @state.current_string.map(&:chr).join
when :escape
raw_move
push @state.cell.chr # Will throw an error when cell isn't a valid code point
@state.ip -= @state.dir.vec
when :digit
push(pop + cmd.chr)
when :input
line = @state.in_str.gets
push(line ? line.chomp : '')
when :output
@state.out_str.puts pop
when :raw_input
push(@state.in_str.read || '')
when :raw_output
@state.out_str << pop
when :concat
top = pop
second = pop
push(second + top)
when :drop
y = pop
x = pop
result = x.chars
x.scan(/(?=#{Regexp.escape(y)})/) do
y.size.times do |i|
result[$`.size + i] = 0
end
end
push (result-[0]).join
when :riffle
sep = pop
push(pop.chars * sep)
when :occurrences
sep = pop
pop.scan(/#{Regexp.escape(sep)}/){ push sep }
when :split
sep = pop
@state.stack += pop.split(sep, -1)
when :inclusive_split
sep = pop
str = pop
splits = str.split(sep, -1)
str.scan(/#{Regexp.escape(sep)}/){ push splits.shift; push sep }
push splits.shift
when :replace
target = pop
needle = pop
haystack = pop
push haystack.gsub(needle, target)
when :trim
push pop.gsub(/^[ \n\t]+|[ \n\t]+$/, '')
when :transliterate
target = pop
source = pop
string = pop
if target.empty?
source.each_char {|c| string.gsub!(c, '')}
else
target += target[-1]*[source.size-target.size,0].max
string = string.chars.map{|c| target[source.index c]}.join
end
push string
when :transpose
lines = pop.lines
width = lines.map(&:size).max
(0...width).map do |i|
lines.map{|l| l[i] || ''}.join
end.join $/
when :find
needle = pop
haystack = pop
push(haystack[needle] || '')
when :truncate_to_shorter
top = pop
second = pop
length = [top.size, second.size].min
push second[0,length]
push top[0,length]
when :zip
top = pop.chars
second = pop.chars
result = []
while !top.empty? || !second.empty?
result << (second.shift || '')
result << (top.shift || '')
end
push result * ''
when :unzip
str = pop
left = ''
right = ''
str.scan(/(.)(.|$)/s) do
left << $1
right << $2
end
push left
push right
when :shortest_common_superstring
top = pop
second = pop
len = [top.size, second.size].min
len.downto(0) do |i|
if second[-i,i] == top[0,i]
push second+top[i..-1]
break
end
end
when :longest_common_substring
top = pop
second = pop
second.size.downto(0) do |l|
if l == 0
push ""
else
shared = second.chars.each_cons(l).select {|s| top[s.join]}
if !shared.empty?
shared.uniq.each{|s| push s.join}
break
end
end
end
when :intersection
second = pop
first = pop
result = first.chars.select {|c|
test = second[c]
second[c] = '' if test
test
}
push result.join
when :union
second = pop
first = pop
first.each_char {|c| second[c] = '' if second[c]}
push(first + second)
when :symdifference
second = pop
first = pop
temp_second = second.clone
first.each_char {|c| second[c] = '' if second[c]}
temp_second.each_char {|c| first[c] = '' if first[c]}
push first+second
when :complement
second = pop
first = pop
second.each_char {|c| first[c] = '' if first[c]}
push first
when :deduplicate
push pop.chars.uniq.join
when :sort
push pop.chars.sort.join
when :shuffle
push pop.chars.shuffle.join
when :characters
@stack.state += pop.chars
when :runs
pop.scan(/(.)\1*/s){push $&}
when :head
str = pop
if str == ''
push ''
push ''
else
push str[0]
push str[1..-1]
end
when :tail
str = pop
if str == ''
push ''
push ''
else
push str[0..-2]
push str[-1]
end
when :lower_case
push pop.downcase
when :upper_case
push pop.upcase
when :swap_case
push pop.swapcase
when :not
push(pop == '' ? 'Jabberwocky' : '')
when :reverse
push pop.reverse
when :permutations
@state.stack += pop.chars.permutation.map{|p| p.join}.to_a
when :subsequences
str = pop.chars
(0..str.size).each do |l|
str.combination(l).each {|s| push s.join}
end
when :substrings
str = pop.chars
(1..str.size).each do |l|
str.each_cons(l).each {|s| push s.join}
end
when :permute
top = pop
second = pop
push (0...second.size).stable_sort_by{|i|
c = top[i]
c ? c.ord : 1114112 # Value greater than any code point, so that trailing
# characters remain in place.
}.map{|i| second[i]}.join
when :expand_ranges
val = pop
val.chars.each_cons(2).map{ |a,b|
if a > b
(b..a).drop(1).to_a.reverse.join
else
(a...b).to_a.join
end
}.join + (val[-1] || '')
when :swap
top = pop
second = pop
push top
push second
when :dup
top = pop
push top
push top
when :discard
pop
when :push_joined_stack
push @state.stack.join
when :reverse_stack
@state.stack.reverse!.map!(:to_s)
when :permute_stack
top = pop
max_size = [@state.stack.size, top.size].max
@state.stack = (-max_size..-1).stable_sort_by{|i|
c = top[i]
c ? c.ord : -1 # Value less than any code point, so that leading
# stack elements remain in place.
}.map{|i| @state.stack[i] || ''}
when :datetime
push DateTime.now.strftime '%Y-%m-%dT%H:%M:%S.%L%:z'
when :const_lf
push "\n"
when :const_empty
push ""
end
end
end |
require "monitor"
class ActiveRecordTransactioner
DEFAULT_ARGS = {
call_args: [],
call_method: :save!,
transaction_method: :transaction,
transaction_size: 1000,
threadded: false,
max_running_threads: 2,
debug: false
}
EMPTY_ARGS = []
ALLOWED_ARGS = DEFAULT_ARGS.keys
def initialize(args = {})
args.each_key { |key| raise "Invalid key: '#{key}'." unless ALLOWED_ARGS.include?(key) }
@args = DEFAULT_ARGS.merge(args)
parse_and_set_args
return unless block_given?
begin
yield self
ensure
flush
join if threadded?
end
end
# Adds another model to the queue and calls 'flush' if it is over the limit.
def save!(model)
raise ActiveRecord::RecordInvalid, model unless model.valid?
queue(model, type: :save!, validate: false)
end
def update_columns(model, updates)
queue(model, type: :update_columns, validate: false, method_args: [updates])
end
def update_column(model, column_name, new_value)
update_columns(model, column_name => new_value)
end
def destroy!(model)
queue(model, type: :destroy!)
end
# Adds another model to the queue and calls 'flush' if it is over the limit.
def queue(model, args = {})
args[:type] ||= :save!
@lock.synchronize do
klass = model.class
validate = args.key?(:validate) ? args[:validate] : true
@lock_models[klass] ||= Monitor.new
@models[klass] ||= []
@models[klass] << {
model: model,
type: args.fetch(:type),
validate: validate,
method_args: args[:method_args] || EMPTY_ARGS
}
@count += 1
end
flush if should_flush?
end
# Flushes the specified method on all the queued models in a thread for each type of model.
def flush
wait_for_threads if threadded?
@lock.synchronize do
@models.each do |klass, models|
next if models.empty?
@models[klass] = []
@count -= models.length
if threadded?
work_threadded(klass, models)
else
work_models_through_transaction(klass, models)
end
end
end
end
# Waits for any remaining running threads.
def join
threads_to_join = @lock_threads.synchronize { @threads.clone }
debug "Threads to join: #{threads_to_join}" if @debug
threads_to_join.each(&:join)
end
def threadded?
@args[:threadded]
end
private
def parse_and_set_args
@models = {}
@threads = []
@count = 0
@lock = Monitor.new
@lock_threads = Monitor.new
@lock_models = {}
@max_running_threads = @args[:max_running_threads].to_i
@transaction_size = @args[:transaction_size].to_i
@debug = @args[:debug]
end
def debug(str)
print "{ActiveRecordTransactioner}: #{str}\n" if @debug
end
def wait_for_threads
loop do
debug "Running threads: #{@threads.length} / #{@max_running_threads}" if @debug
if allowed_to_start_new_thread?
break
else
debug "Waiting for threads #{@threads.length} / #{@max_running_threads}" if @debug
end
sleep 0.2
end
debug "Done waiting." if @debug
end
def work_models_through_transaction(klass, models)
debug "Synchronizing model: #{klass.name}"
@lock_models[klass].synchronize do
debug "Opening new transaction by using '#{@args[:transaction_method]}'." if @debug
klass.__send__(@args[:transaction_method]) do
debug "Going through models." if @debug
models.each do |work|
debug work if @debug
work_type = work.fetch(:type)
model = work.fetch(:model)
if work_type == :save!
validate = work.key?(:validate) ? work[:validate] : true
model.save! validate: validate
elsif work_type == :update_columns || work_type == :destroy!
model.__send__(work_type, *work.fetch(:method_args))
else
raise "Invalid type: '#{work[:type]}'."
end
end
debug "Done working with models." if @debug
end
end
end
def work_threadded(klass, models)
@lock_threads.synchronize do
@threads << Thread.new do
begin
ActiveRecord::Base.connection_pool.with_connection do
work_models_through_transaction(klass, models)
end
rescue => e
puts e.inspect
puts e.backtrace
raise e
ensure
debug "Removing thread #{Thread.current.__id__}" if @debug
@lock_threads.synchronize { @threads.delete(Thread.current) }
debug "Threads count after remove: #{@threads.length}" if @debug
end
end
end
debug "Threads-count after started to work: #{@threads.length}"
end
def should_flush?
@count >= @transaction_size
end
def allowed_to_start_new_thread?
@lock_threads.synchronize { return @threads.length < @max_running_threads }
end
end
Extracted the models loop into own method to reduce the complexity
require "monitor"
class ActiveRecordTransactioner
DEFAULT_ARGS = {
call_args: [],
call_method: :save!,
transaction_method: :transaction,
transaction_size: 1000,
threadded: false,
max_running_threads: 2,
debug: false
}
EMPTY_ARGS = []
ALLOWED_ARGS = DEFAULT_ARGS.keys
def initialize(args = {})
args.each_key { |key| raise "Invalid key: '#{key}'." unless ALLOWED_ARGS.include?(key) }
@args = DEFAULT_ARGS.merge(args)
parse_and_set_args
return unless block_given?
begin
yield self
ensure
flush
join if threadded?
end
end
# Adds another model to the queue and calls 'flush' if it is over the limit.
def save!(model)
raise ActiveRecord::RecordInvalid, model unless model.valid?
queue(model, type: :save!, validate: false)
end
def update_columns(model, updates)
queue(model, type: :update_columns, validate: false, method_args: [updates])
end
def update_column(model, column_name, new_value)
update_columns(model, column_name => new_value)
end
def destroy!(model)
queue(model, type: :destroy!)
end
# Adds another model to the queue and calls 'flush' if it is over the limit.
def queue(model, args = {})
args[:type] ||= :save!
@lock.synchronize do
klass = model.class
validate = args.key?(:validate) ? args[:validate] : true
@lock_models[klass] ||= Monitor.new
@models[klass] ||= []
@models[klass] << {
model: model,
type: args.fetch(:type),
validate: validate,
method_args: args[:method_args] || EMPTY_ARGS
}
@count += 1
end
flush if should_flush?
end
# Flushes the specified method on all the queued models in a thread for each type of model.
def flush
wait_for_threads if threadded?
@lock.synchronize do
@models.each do |klass, models|
next if models.empty?
@models[klass] = []
@count -= models.length
if threadded?
work_threadded(klass, models)
else
work_models_through_transaction(klass, models)
end
end
end
end
# Waits for any remaining running threads.
def join
threads_to_join = @lock_threads.synchronize { @threads.clone }
debug "Threads to join: #{threads_to_join}" if @debug
threads_to_join.each(&:join)
end
def threadded?
@args[:threadded]
end
private
def parse_and_set_args
@models = {}
@threads = []
@count = 0
@lock = Monitor.new
@lock_threads = Monitor.new
@lock_models = {}
@max_running_threads = @args[:max_running_threads].to_i
@transaction_size = @args[:transaction_size].to_i
@debug = @args[:debug]
end
def debug(str)
print "{ActiveRecordTransactioner}: #{str}\n" if @debug
end
def wait_for_threads
loop do
debug "Running threads: #{@threads.length} / #{@max_running_threads}" if @debug
if allowed_to_start_new_thread?
break
else
debug "Waiting for threads #{@threads.length} / #{@max_running_threads}" if @debug
end
sleep 0.2
end
debug "Done waiting." if @debug
end
def work_models_through_transaction(klass, models)
debug "Synchronizing model: #{klass.name}"
@lock_models[klass].synchronize do
debug "Opening new transaction by using '#{@args[:transaction_method]}'." if @debug
klass.__send__(@args[:transaction_method]) do
work_models(models)
end
end
end
def work_models(models)
debug "Going through models." if @debug
models.each do |work|
debug work if @debug
work_type = work.fetch(:type)
model = work.fetch(:model)
if work_type == :save!
validate = work.key?(:validate) ? work[:validate] : true
model.save! validate: validate
elsif work_type == :update_columns || work_type == :destroy!
model.__send__(work_type, *work.fetch(:method_args))
else
raise "Invalid type: '#{work[:type]}'."
end
end
debug "Done working with models." if @debug
end
def work_threadded(klass, models)
@lock_threads.synchronize do
@threads << Thread.new do
begin
ActiveRecord::Base.connection_pool.with_connection do
work_models_through_transaction(klass, models)
end
rescue => e
puts e.inspect
puts e.backtrace
raise e
ensure
debug "Removing thread #{Thread.current.__id__}" if @debug
@lock_threads.synchronize { @threads.delete(Thread.current) }
debug "Threads count after remove: #{@threads.length}" if @debug
end
end
end
debug "Threads-count after started to work: #{@threads.length}"
end
def should_flush?
@count >= @transaction_size
end
def allowed_to_start_new_thread?
@lock_threads.synchronize { return @threads.length < @max_running_threads }
end
end
|
require 'active_scaffold/config/base'
module ActiveScaffold::Config
class Core < Base
# global level configuration
# --------------------------
# provides read/write access to the global Actions DataStructure
cattr_reader :actions
def self.actions=(val)
@@actions = ActiveScaffold::DataStructures::Actions.new(*val)
end
self.actions = [:create, :list, :search, :update, :delete, :show, :nested, :subform]
# configures where the ActiveScaffold plugin itself is located. there is no instance version of this.
cattr_accessor :plugin_directory
@@plugin_directory = File.expand_path(__FILE__).match(/vendor\/plugins\/([^\/]*)/)[1]
# lets you specify a global ActiveScaffold frontend.
cattr_accessor :frontend
@@frontend = :default
# lets you specify a global ActiveScaffold theme for your frontend.
cattr_accessor :theme
@@theme = :default
# lets you disable the DHTML history
def self.dhtml_history=(val)
@@dhtml_history = val
end
def self.dhtml_history?
@@dhtml_history ? true : false
end
@@dhtml_history = true
# action links are used by actions to tie together. you can use them, too! this is a collection of ActiveScaffold::DataStructures::ActionLink objects.
cattr_reader :action_links
@@action_links = ActiveScaffold::DataStructures::ActionLinks.new
# access to the permissions configuration.
# configuration options include:
# * current_user_method - what method on the controller returns the current user. default: :current_user
# * default_permission - what the default permission is. default: true
def self.security
ActiveRecordPermissions
end
# columns that should be ignored for every model. these should be metadata columns like change dates, versions, etc.
# values in this array may be symbols or strings.
def self.ignore_columns
@@ignore_columns
end
def self.ignore_columns=(val)
@@ignore_columns = ActiveScaffold::DataStructures::Set.new(*val)
end
@@ignore_columns = ActiveScaffold::DataStructures::Set.new
# instance-level configuration
# ----------------------------
# provides read/write access to the local Actions DataStructure
attr_reader :actions
def actions=(args)
@actions = ActiveScaffold::DataStructures::Actions.new(*args)
end
# provides read/write access to the local Columns DataStructure
attr_reader :columns
def columns=(val)
@columns._inheritable = val.collect {|c| c.to_sym}
# Add virtual columns
@columns << val.collect {|c| c.to_sym unless @columns[c.to_sym]}.compact
end
# lets you override the global ActiveScaffold frontend for a specific controller
attr_accessor :frontend
# lets you override the global ActiveScaffold theme for a specific controller
attr_accessor :theme
# action links are used by actions to tie together. they appear as links for each record, or general links for the ActiveScaffold.
attr_reader :action_links
# a generally-applicable name for this ActiveScaffold ... will be used for generating page/section headers
attr_writer :label
def label(options={})
options[:count] ||= model.count
as_(@label, options) || model.human_name(options)
end
##
## internal usage only below this point
## ------------------------------------
def initialize(model_id)
# model_id is the only absolutely required configuration value. it is also not publicly accessible.
@model_id = model_id.to_s.pluralize.singularize
# inherit the actions list directly from the global level
@actions = self.class.actions.clone
# create a new default columns datastructure, since it doesn't make sense before now
attribute_names = self.model.columns.collect{ |c| c.name.to_sym }.sort_by { |c| c.to_s }
association_column_names = self.model.reflect_on_all_associations.collect{ |a| a.name.to_sym }.sort_by { |c| c.to_s }
@columns = ActiveScaffold::DataStructures::Columns.new(self.model, attribute_names + association_column_names)
# and then, let's remove some columns from the inheritable set.
@columns.exclude(*self.class.ignore_columns)
@columns.exclude(*@columns.find_all { |c| c.column and (c.column.primary or c.column.name =~ /(_id|_count)$/) }.collect {|c| c.name})
@columns.exclude(*self.model.reflect_on_all_associations.collect{|a| :"#{a.name}_type" if a.options[:polymorphic]}.compact)
# inherit the global frontend
@frontend = self.class.frontend
@theme = self.class.theme
# inherit from the global set of action links
@action_links = self.class.action_links.clone
end
# To be called after your finished configuration
def _load_action_columns
ActiveScaffold::DataStructures::ActionColumns.class_eval {include ActiveScaffold::DataStructures::ActionColumns::AfterConfiguration}
# then, register the column objects
self.actions.each do |action_name|
action = self.send(action_name)
next unless action.respond_to? :columns
action.columns.set_columns(self.columns)
end
end
# configuration routing.
# we want to route calls named like an activated action to that action's global or local Config class.
# ---------------------------
def method_missing(name, *args)
@action_configs ||= {}
titled_name = name.to_s.camelcase
underscored_name = name.to_s.underscore.to_sym
klass = "ActiveScaffold::Config::#{titled_name}".constantize rescue nil
if klass
if @actions.include? underscored_name
return @action_configs[underscored_name] ||= klass.new(self)
else
raise "#{titled_name} is not enabled. Please enable it or remove any references in your configuration (e.g. config.#{underscored_name}.columns = [...])."
end
end
super
end
def self.method_missing(name, *args)
klass = "ActiveScaffold::Config::#{name.to_s.titleize}".constantize rescue nil
if @@actions.include? name.to_s.underscore and klass
return eval("ActiveScaffold::Config::#{name.to_s.titleize}")
end
super
end
# some utility methods
# --------------------
def model_id
@model_id
end
def model
@model ||= @model_id.to_s.camelize.constantize
end
# warning - this won't work as a per-request dynamic attribute in rails 2.0. You'll need to interact with Controller#generic_view_paths
def inherited_view_paths
@inherited_view_paths||=[]
end
# must be a class method so the layout doesn't depend on a controller that uses active_scaffold
# note that this is unaffected by per-controller frontend configuration.
def self.asset_path(filename, frontend = self.frontend)
"active_scaffold/#{frontend}/#{filename}"
end
# must be a class method so the layout doesn't depend on a controller that uses active_scaffold
# note that this is unaffected by per-controller frontend configuration.
def self.javascripts(frontend = self.frontend)
javascript_dir = File.join(Rails.public_path, "javascripts", asset_path('', frontend))
Dir.entries(javascript_dir).reject { |e| !e.match(/\.js$/) or (!self.dhtml_history? and e.match('dhtml_history')) }
end
def self.available_frontends
frontends_dir = File.join(Rails.root, "vendor", "plugins", ActiveScaffold::Config::Core.plugin_directory, "frontends")
Dir.entries(frontends_dir).reject { |e| e.match(/^\./) } # Get rid of files that start with .
end
end
end
Use plural form in list header when there are no translation
require 'active_scaffold/config/base'
module ActiveScaffold::Config
class Core < Base
# global level configuration
# --------------------------
# provides read/write access to the global Actions DataStructure
cattr_reader :actions
def self.actions=(val)
@@actions = ActiveScaffold::DataStructures::Actions.new(*val)
end
self.actions = [:create, :list, :search, :update, :delete, :show, :nested, :subform]
# configures where the ActiveScaffold plugin itself is located. there is no instance version of this.
cattr_accessor :plugin_directory
@@plugin_directory = File.expand_path(__FILE__).match(/vendor\/plugins\/([^\/]*)/)[1]
# lets you specify a global ActiveScaffold frontend.
cattr_accessor :frontend
@@frontend = :default
# lets you specify a global ActiveScaffold theme for your frontend.
cattr_accessor :theme
@@theme = :default
# lets you disable the DHTML history
def self.dhtml_history=(val)
@@dhtml_history = val
end
def self.dhtml_history?
@@dhtml_history ? true : false
end
@@dhtml_history = true
# action links are used by actions to tie together. you can use them, too! this is a collection of ActiveScaffold::DataStructures::ActionLink objects.
cattr_reader :action_links
@@action_links = ActiveScaffold::DataStructures::ActionLinks.new
# access to the permissions configuration.
# configuration options include:
# * current_user_method - what method on the controller returns the current user. default: :current_user
# * default_permission - what the default permission is. default: true
def self.security
ActiveRecordPermissions
end
# columns that should be ignored for every model. these should be metadata columns like change dates, versions, etc.
# values in this array may be symbols or strings.
def self.ignore_columns
@@ignore_columns
end
def self.ignore_columns=(val)
@@ignore_columns = ActiveScaffold::DataStructures::Set.new(*val)
end
@@ignore_columns = ActiveScaffold::DataStructures::Set.new
# instance-level configuration
# ----------------------------
# provides read/write access to the local Actions DataStructure
attr_reader :actions
def actions=(args)
@actions = ActiveScaffold::DataStructures::Actions.new(*args)
end
# provides read/write access to the local Columns DataStructure
attr_reader :columns
def columns=(val)
@columns._inheritable = val.collect {|c| c.to_sym}
# Add virtual columns
@columns << val.collect {|c| c.to_sym unless @columns[c.to_sym]}.compact
end
# lets you override the global ActiveScaffold frontend for a specific controller
attr_accessor :frontend
# lets you override the global ActiveScaffold theme for a specific controller
attr_accessor :theme
# action links are used by actions to tie together. they appear as links for each record, or general links for the ActiveScaffold.
attr_reader :action_links
# a generally-applicable name for this ActiveScaffold ... will be used for generating page/section headers
attr_writer :label
def label(options={})
options[:count] ||= model.count
options[:default] ||= model.name.pluralize if options[:count].to_i > 1
as_(@label, options) || model.human_name(options)
end
##
## internal usage only below this point
## ------------------------------------
def initialize(model_id)
# model_id is the only absolutely required configuration value. it is also not publicly accessible.
@model_id = model_id.to_s.pluralize.singularize
# inherit the actions list directly from the global level
@actions = self.class.actions.clone
# create a new default columns datastructure, since it doesn't make sense before now
attribute_names = self.model.columns.collect{ |c| c.name.to_sym }.sort_by { |c| c.to_s }
association_column_names = self.model.reflect_on_all_associations.collect{ |a| a.name.to_sym }.sort_by { |c| c.to_s }
@columns = ActiveScaffold::DataStructures::Columns.new(self.model, attribute_names + association_column_names)
# and then, let's remove some columns from the inheritable set.
@columns.exclude(*self.class.ignore_columns)
@columns.exclude(*@columns.find_all { |c| c.column and (c.column.primary or c.column.name =~ /(_id|_count)$/) }.collect {|c| c.name})
@columns.exclude(*self.model.reflect_on_all_associations.collect{|a| :"#{a.name}_type" if a.options[:polymorphic]}.compact)
# inherit the global frontend
@frontend = self.class.frontend
@theme = self.class.theme
# inherit from the global set of action links
@action_links = self.class.action_links.clone
end
# To be called after your finished configuration
def _load_action_columns
ActiveScaffold::DataStructures::ActionColumns.class_eval {include ActiveScaffold::DataStructures::ActionColumns::AfterConfiguration}
# then, register the column objects
self.actions.each do |action_name|
action = self.send(action_name)
next unless action.respond_to? :columns
action.columns.set_columns(self.columns)
end
end
# configuration routing.
# we want to route calls named like an activated action to that action's global or local Config class.
# ---------------------------
def method_missing(name, *args)
@action_configs ||= {}
titled_name = name.to_s.camelcase
underscored_name = name.to_s.underscore.to_sym
klass = "ActiveScaffold::Config::#{titled_name}".constantize rescue nil
if klass
if @actions.include? underscored_name
return @action_configs[underscored_name] ||= klass.new(self)
else
raise "#{titled_name} is not enabled. Please enable it or remove any references in your configuration (e.g. config.#{underscored_name}.columns = [...])."
end
end
super
end
def self.method_missing(name, *args)
klass = "ActiveScaffold::Config::#{name.to_s.titleize}".constantize rescue nil
if @@actions.include? name.to_s.underscore and klass
return eval("ActiveScaffold::Config::#{name.to_s.titleize}")
end
super
end
# some utility methods
# --------------------
def model_id
@model_id
end
def model
@model ||= @model_id.to_s.camelize.constantize
end
# warning - this won't work as a per-request dynamic attribute in rails 2.0. You'll need to interact with Controller#generic_view_paths
def inherited_view_paths
@inherited_view_paths||=[]
end
# must be a class method so the layout doesn't depend on a controller that uses active_scaffold
# note that this is unaffected by per-controller frontend configuration.
def self.asset_path(filename, frontend = self.frontend)
"active_scaffold/#{frontend}/#{filename}"
end
# must be a class method so the layout doesn't depend on a controller that uses active_scaffold
# note that this is unaffected by per-controller frontend configuration.
def self.javascripts(frontend = self.frontend)
javascript_dir = File.join(Rails.public_path, "javascripts", asset_path('', frontend))
Dir.entries(javascript_dir).reject { |e| !e.match(/\.js$/) or (!self.dhtml_history? and e.match('dhtml_history')) }
end
def self.available_frontends
frontends_dir = File.join(Rails.root, "vendor", "plugins", ActiveScaffold::Config::Core.plugin_directory, "frontends")
Dir.entries(frontends_dir).reject { |e| e.match(/^\./) } # Get rid of files that start with .
end
end
end
|
class Fixnum
def bitcount
n = self
count = 0
while n > 0
count += n & 1
n >>= 1
end
count
end
end
Add power
class Fixnum
def bitcount
n = self
count = 0
while n > 0
count += n & 1
n >>= 1
end
count
end
def power(x)
result = 1
n = self
while x > 0
result *= n if (x & 1).nonzero?
n *= n
x >>= 1
end
result
end
end
|
# OOOR: Open Object On Rails
# Copyright (C) 2009-2011 Akretion LTDA (<http://www.akretion.com>).
# Author: Raphaël Valyi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require "java"
%w[commons-logging-1.1.jar ws-commons-util-1.0.2.jar xmlrpc-client-3.1.3.jar xmlrpc-common-3.1.3.jar].each {|i| require i}
#TODO test if symbol defined
$platform = 'jruby'
module Ooor
class OOORJavaClient
attr_accessor :client
def jruby_setup(url, p, timeout)
@config = torg.apache.xmlrpc.client.XmlRpcClientConfigImpl.new
@config.setServerURL(java.net.URL.new(url))
@config.setEnabledForExtensions(true);
@client = org.apache.xmlrpc.client.XmlRpcClient.new
@client.setTransportFactory(org.apache.xmlrpc.client.XmlRpcLiteHttpTransportFactory.new(@client));
@client.setConfig(@config)
end
def self.new2(url, p, timeout)
begin
client = OOORJavaClient.new()
client.jruby_setup(url, p, timeout)
client
rescue
puts "WARNING unable to load org.apache.xmlrpc.client from classpath; falling back on Ruby xmlrpc/client client (much slower)"
require 'app/models/ooor_client'
OOORClient.new2(url, p, timeout)
end
end
def javaize_item(e)
if e.is_a? Array
return javaize_array(e)
elsif e.is_a? Integer
return e.to_java(java.lang.Integer)
elsif e.is_a? Hash
map = {}
e.each {|k, v| map[k] = javaize_item(v)}
return map
else
return e
end
end
def javaize_array(array)
array.map{|e| javaize_item(e)} #TODO: test if we need a t=[] array
end
def rubyize(e)
if e.is_a? Java::JavaUtil::HashMap
map = {}
e.keys.each do |k|
v = e[k]
if (! v.is_a? String) && v.respond_to?('each') && (! v.is_a?(Java::JavaUtil::HashMap))
map[k] = v.map {|i| rubyize(i)} #array
else
map[k] = rubyize(v)#v
end
end
return map
elsif (! e.is_a? String) && e.respond_to?('each') && (! e.is_a?(Java::JavaUtil::HashMap))
return e.map {|i| rubyize(i)}
else
return e
end
end
def call(method, *args)
return call2(method, *args) if $platform == 'ruby'
begin
res = @client.execute(method, javaize_array(args))
return rubyize(res)
rescue
require 'app/models/ooor_client'
client = OOORClient.new2(@client.getConfig().getServerURL().to_s, nil, 900)
client.call2(method, *args)
end
end
end
end
bugfixed Java XML/RPC client
# OOOR: Open Object On Rails
# Copyright (C) 2009-2011 Akretion LTDA (<http://www.akretion.com>).
# Author: Raphaël Valyi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require "java"
#%w[commons-logging-1.1.jar ws-commons-util-1.0.2.jar xmlrpc-client-3.1.3.jar xmlrpc-common-3.1.3.jar].each {|i| require i}
#TODO test if symbol defined
module Ooor
class OOORJavaClient
attr_accessor :client
def jruby_setup(url, p, timeout)
@config = org.apache.xmlrpc.client.XmlRpcClientConfigImpl.new
@config.setServerURL(java.net.URL.new(url))
@config.setEnabledForExtensions(true);
@client = org.apache.xmlrpc.client.XmlRpcClient.new
@client.setTransportFactory(org.apache.xmlrpc.client.XmlRpcLiteHttpTransportFactory.new(@client));
@client.setConfig(@config)
end
def self.new2(url, p, timeout)
begin
wrapper = OOORJavaClient.new()
wrapper.jruby_setup(url, p, timeout)
wrapper
rescue
puts "WARNING unable to load org.apache.xmlrpc.client from classpath; falling back on Ruby xmlrpc/client client (much slower)"
require 'app/models/ooor_client'
OOORClient.new2(url, p, timeout)
end
end
def javaize_item(e)
if e.is_a? Array
return javaize_array(e)
elsif e.is_a? Integer
return e.to_java(java.lang.Integer)
elsif e.is_a? Hash
map = {}
e.each {|k, v| map[k] = javaize_item(v)}
return map
else
return e
end
end
def javaize_array(array)
array.map{|e| javaize_item(e)} #TODO: test if we need a t=[] array
end
def rubyize(e)
if e.is_a? Java::JavaUtil::HashMap
map = {}
e.keys.each do |k|
v = e[k]
if (! v.is_a? String) && v.respond_to?('each') && (! v.is_a?(Java::JavaUtil::HashMap))
map[k] = v.map {|i| rubyize(i)} #array
else
map[k] = rubyize(v)#v
end
end
return map
elsif (! e.is_a? String) && e.respond_to?('each') && (! e.is_a?(Java::JavaUtil::HashMap))
return e.map {|i| rubyize(i)}
else
return e
end
end
def call(method, *args)
return call2(method, *args) if $platform == 'ruby'
begin
res = @client.execute(method, javaize_array(args))
return rubyize(res)
rescue
require 'app/models/ooor_client'
wrapper = OOORClient.new2(@client.getConfig().getServerURL().to_s, nil, 900)
wrapper.call2(method, *args)
end
end
end
end
|
#
# File: latex-converter.rb
# Author: J. Carlson (jxxcarlson@gmail.com)
# First commit: 9/26/2014
# Date: 2/20/1015
#
# OVERVIEW
#
# Asciidoctor-latex does two things:
#
# -- provides an HTML backend which adds latex-like features to asciidoctor
# asciidoc(tor) with these additional features will be called 'asciidoctor-latex'
#
# -- provides a converter from asciidoctor-latex to asciidoctor. This converter
# is 'usable' but has limited coverage of asciidoctor-latex
#
# See http://www.noteshare.io/section/asciidoctor-latex-manual-intro
# for a description (with examples) of asciidoctor-latex.
#
# INSTALLATION
#
# Run 'rake install' to install the asciidoctor-latex gem locally.
#
# USAGE (1: html)
#
# Run
#
# 'asciidoctor-latex -b html foo.adoc'
#
# to render an asciidoctor-latex document to html
#
# Some documents (those with 'click blocks', see http://www.noteshare.io/section/homework-problems)
# For these, run
#
# 'asciidoctor-latex -b html -a click_extras=include foo.adoc'
#
# In both cases the output is 'foo.html'
#
# USAGE (2: latex)
#
# Run
#
# 'asciidoctor-latex foo.adoc'
#
# to convert foo.adoc to foo.tex. This feature
# needs a lot of work.
#
# to convert foo.tex to the latex file foo.latex
# You can put files 'macros.tex' and 'preamble.tex' to
# replace the default preamble and set of macros.
# Define your own 'newEnvironments.tex' to use yours
# as opposed to the default definitons of environments
# in tex mapping to [tex.ENVIRNOMENT] in asciidoctor-latex.
#
# TECHNICAL NOTES
#
# This is a first step towards writing a LaTeX backend
# for Asciidoctor. It is based on the
# Dan Allen's demo-converter.rb. The "convert" method
# is unchanged, the methods "document node" and "section node"
# have been redefined, and several new methods have been added.
#
# The main work will be in identifying asciidoc elements
# that need to be transformed and adding a method for
# each such element. As noted below, the "warn" clause
# in the "convert" method is a useful tool for this task.
#
# Usage:
#
# $ asciidoctor -r ./latex-converter.rb -b latex test/sample1.adoc
#
# Comments
#
# 1. The "warn" clause in the converter code is quite useful.
# For example, you will discover in running the converter on
# "test/sample-1.adoc" that you have not implemented code for
# the "olist" node. Thus you can work through ever more complex
# examples to discover what you need to do to increase the coverage
# of the converter. Hackish and ad hoc, but a process nonetheless.
#
# 2. The converter simply passes on what it does not understand, e.g.,
# LaTeX, This is good. However, we will have to map constructs
# like"+\( a^2 = b^2 \)+" to $ a^2 + b^2 $, etc.
# This can be done at the preprocessor level.
#
# 3. In view of the preceding, we may need to chain a frontend
# (preprocessor) to the backend. In any case, the main work
# is in transforming Asciidoc elements to TeX elements.
# Other than the asciidoc -> tex mapping, the tex-converter
# does not need to understand tex.
#
# 4. Included in this repo are the files "test/sample1.adoc", "test/sample2.adoc",
# and "test/elliptic.adoc" which can be used to test the code
#
# 5. Beginning with version 0.0.2 we use a new dispatch mechanism
# which should permit one to better manage growth of the code
# as the coverage of the converter increases. Briefly, the
# main convert method, whose duty is to process nodes, looks
# at node.node_name, then makes the method call node.tex_process
# if the node_name is registered in NODE_TYPES. The method
# tex_process is defined by extending the various classes to
# which the node might belong, e.g., Asciidoctor::Block,
# Asciidoctor::Inline, etc. See the file "node_processor.rb",
# where these extensions are housed for the time being.
#
# If node.node_name is not found in NODE_TYPES, then
# a warning message is issued. We can use it as a clue
# to find what to do to handle this node. All the code
# in "node_processors.rb" to date was written using this
# hackish process.
#
#
# CURRENT STATUS
#
# The following constructs are processed
#
# * sections to a depth of five, e.g., == foo, === foobar, etc.
# * ordered and unordered lists, though nestings is untested and
# likely does not work.
# * *bold* and _italic_
# * hyperlinks like http://foo.com[Nerdy Stuff]
#
require 'asciidoctor'
require 'asciidoctor/converter/html5'
require 'asciidoctor/latex/inline_macros'
require 'asciidoctor/latex/core_ext/colored_string'
require 'asciidoctor/latex/click_block'
require 'asciidoctor/latex/inject_html'
require 'asciidoctor/latex/ent_to_uni'
require 'asciidoctor/latex/environment_block'
require 'asciidoctor/latex/node_processors'
require 'asciidoctor/latex/prepend_processor'
require 'asciidoctor/latex/macro_insert'
require 'asciidoctor/latex/tex_block'
require 'asciidoctor/latex/tex_preprocessor'
require 'asciidoctor/latex/dollar'
require 'asciidoctor/latex/tex_postprocessor'
require 'asciidoctor/latex/chem'
# require 'asciidoctor/latex/preamble_processor'
$VERBOSE = true
module Asciidoctor::LaTeX
# code for Html5ConverterExtension & its insertion
# template by @mojavelinux
module Html5ConverterExtensions
# ENV_CSS_OBLIQUE = "+++<div class='env_oblique'>+++"
# ENV_CSS_NOBLIQUE = "+++<div class='env_noblique'>+++"
ENV_CSS_OBLIQUE = "+++<div style='line-height:1.5em;font-size:1.05em;font-style:oblique;margin-bottom:1.5em'>+++"
ENV_CSS_PLAIN = "+++<div style='line-height:1.5em;font-size:1.05em;;margin-bottom:1.5em'>+++"
DIV_END = '+++</div>+++'
TABLE_ROW_END = '+++</tr></table>+++'
def info node
warn "\n HTMLConverter, node: #{node.node_name}".red if $VERBOSE
end
# Dispatches a handler for the _node_ (`NODE`)
# based on its role.
def environment node
attrs = node.attributes
case attrs['role']
when 'box'
handle_null(node)
when 'equation'
handle_equation(node)
when 'equationalign'
handle_equation_align(node)
when 'chem'
handle_chem(node)
when 'jsxgraph'
handle_jsxgraph(node)
when 'texmacro'
handle_texmacro(node)
else
handle_default(node)
end
node.attributes['roles'] = (node.roles + ['environment']) * ' '
self.open node
end
def handle_texmacro node
node.title = nil
node.lines = ["+++\n\\("] + node.lines + ["\\)\n+++"]
end
def click node
if node.attributes['plain-option']
node.lines = [ENV_CSS_PLAIN] + node.lines + [DIV_END]
else
node.lines = [ENV_CSS_OBLIQUE] + node.lines + [DIV_END]
end
# node.lines = [ENV_CSS] + node.lines + [DIV_END]
node.attributes['roles'] = (node.roles + ['click']) * ' '
self.open node
end
def inline_anchor node
case node.type.to_s
when 'xref'
refid = node.attributes['refid']
if refid and refid[0] == '_'
output = "<a href=\##{refid}>#{refid.gsub('_',' ')}</a>"
else
refs = node.parent.document.references[:ids]
# FIXME: the next line is HACKISH (and it crashes the app when refs[refid]) is nil)
# FIXME: and with the fix for nil results is even more hackish
if refs[refid]
reftext = refs[refid].gsub('.', '')
reftext = reftext.gsub(/:.*/,'')
if refid =~ /\Aeq-/
output = "<span><a href=\##{refid}>equation #{reftext}</a></span>"
elsif refid =~ /\Aformula-/
output = "<span><a href=\##{refid}>formula #{reftext}</a></span>"
elsif refid =~ /\Areaction-/
output = "<span><a href=\##{refid}>reaction #{reftext}</a></span>"
else
output = "<span><a href=\##{refid} style='text-decoration:none'>#{reftext}</a></span>"
end
else
output = 'ERROR: refs[refid] was nil'
end
end
when 'link'
output = "<a href=#{node.target}>#{node.text}</a>"
else
output = 'FOOBAR'
end
output
end
def handle_equation(node)
attrs = node.attributes
options = attrs['options']
node.title = nil
warn "node.attributes (EQUATION): #{node.attributes}".cyan if $VERBOSE
number_part = '<td style="text-align:right">' + "(#{node.caption}) </td>"
number_part = ["+++ #{number_part} +++"]
equation_part = ['+++<td style="width:100%";>+++'] + ['\\['] + node.lines + ['\\]'] + ['+++</td>+++']
table_style='style="width:100%; border-collapse:collapse;border:0" class="zero" '
row_style='style="border-collapse: collapse; border:0; font-size: 12pt; "'
if options.include? 'numbered'
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + number_part + [TABLE_ROW_END]
else
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + [TABLE_ROW_END]
end
end
def handle_equation_align(node)
attrs = node.attributes
options = attrs['options']
warn "node.attributes (EQUATION ALIGN): #{node.attributes}".cyan if $VERBOSE
node.title = nil
number_part = '<td style="text-align:right">' + "(#{node.caption}) </td>"
number_part = ["+++ #{number_part} +++"]
equation_part = ['+++<td style="width:100%";>+++'] + ['\\[\\begin{split}'] + node.lines + ['\\end{split}\\]'] + ['+++</td>+++']
table_style='style="width:100%; border-collapse:collapse;border:0" class="zero" '
row_style='style="border-collapse: collapse; border:0; font-size: 12pt; "'
if options.include? 'numbered'
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + number_part + [TABLE_ROW_END]
else
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + [TABLE_ROW_END]
end
end
def handle_chem(node)
node.title = nil
number_part = '<td style="text-align:right">' + "(#{node.caption}) </td>"
number_part = ["+++ #{number_part} +++"]
equation_part = ['+++<td style="width:100%;">+++'] + [' \\[\\ce{' + node.lines[0] + '}\\] '] + ['+++</td>+++']
table_style='class="zero" style="width:100%; border-collapse:collapse; border:0"'
row_style='class="zero" style="border-collapse: collapse; border:0; font-size: 10pt; "'
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + number_part +['+++</tr></table>+++']
end
def handle_jsxgraph(node)
attrs = node.attributes
if attrs['box'] == nil
attrs['box'] = 'box'
end
if attrs['width'] == nil
attrs['width'] = 450
end
if attrs['height'] == nil
attrs['height'] = 450
end
line_array = ["\n+++\n"]
# line_array += ["<link rel='stylesheet' type='text/css' href='jsxgraph.css' />"]
line_array += ["<link rel='stylesheet' type='text/css' href='http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css' />"]
line_array += ['<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsxgraph/0.99.3/jsxgraphcore.js"></script>']
line_array += ["<script src='http://jsxgraph.uni-bayreuth.de/distrib/GeonextReader.js' type='text/javascript'></script>"]
# line_array += ['<div id="box" class="jxgbox" style="width:500px; height:500px;"></div>']
line_array += ["<div id='#{attrs['box']}' class='jxgbox' style='width:" + "#{attrs['width']}" + "px; height:" + "#{attrs['height']}" +"px;'></div>"]
line_array += ['<script type="text/javascript">']
line_array += node.lines
line_array += ['</script>']
line_array += ['<br/>']
line_array += ["\n+++\n"]
node.lines = line_array
end
def handle_null(node)
end
def handle_default(node)
if node.attributes['plain-option']
node.lines = [ENV_CSS_PLAIN] + node.lines + [DIV_END]
else
node.lines = [ENV_CSS_OBLIQUE] + node.lines + [DIV_END]
end
end
end
class Converter
include Asciidoctor::Converter
register_for 'latex'
Asciidoctor::Extensions.register do
preprocessor TeXPreprocessor
preprocessor MacroInsert if (File.exist? 'macros.tex' and document.basebackend? 'html') and !(document.attributes['noteshare'] == 'yes')
block EnvironmentBlock
block ClickBlock
inline_macro ChemInlineMacro
# preprocessor ClickStyleInsert if document.attributes['click_extras'] == 'include2'
postprocessor InjectHTML unless document.attributes['noteshare'] == 'yes'
postprocessor EntToUni if document.basebackend? 'tex' unless document.attributes['unicode'] == 'no'
postprocessor Chem if document.basebackend? 'html'
postprocessor HTMLPostprocessor if document.basebackend? 'html'
postprocessor TexPostprocessor if document.basebackend? 'tex'
end
Asciidoctor::Extensions.register :latex do
# EnvironmentBlock
end
TOP_TYPES = %w(document section)
LIST_TYPES = %w(dlist olist ulist)
INLINE_TYPES = %w(inline_anchor inline_break inline_footnote inline_quoted inline_callout)
BLOCK_TYPES = %w(admonition listing literal page_break paragraph stem pass open quote \
example floating_title image click preamble sidebar verse toc)
OTHER_TYPES = %w(environment table)
NODE_TYPES = TOP_TYPES + LIST_TYPES + INLINE_TYPES + BLOCK_TYPES + OTHER_TYPES
def initialize backend, opts
super
basebackend 'tex'
outfilesuffix '.tex'
end
# FIXME: find a solution without a global variable
$latex_environment_names = []
# FIXME: this should be retired -- still used
# in click blocks but no longer in env blocks
$label_counter = 0
def convert node, transform = nil
if NODE_TYPES.include? node.node_name
node.tex_process
else
warn %(Node to implement: #{node.node_name}, class = #{node.class}).magenta if $VERBOSE
# This warning should not be switched off by $VERBOSE
end
end
end # class Converter
end # module Asciidoctor::LaTeX
class Asciidoctor::Converter::Html5Converter
# inject our custom code into the existing Html5Converter class (Ruby 2.0 and above)
prepend Asciidoctor::LaTeX::Html5ConverterExtensions
end
[env.jsxtraph] elements are rendering as blanks.
No firm diagnosis yet
c
#
# File: latex-converter.rb
# Author: J. Carlson (jxxcarlson@gmail.com)
# First commit: 9/26/2014
# Date: 2/20/1015
#
# OVERVIEW
#
# Asciidoctor-latex does two things:
#
# -- provides an HTML backend which adds latex-like features to asciidoctor
# asciidoc(tor) with these additional features will be called 'asciidoctor-latex'
#
# -- provides a converter from asciidoctor-latex to asciidoctor. This converter
# is 'usable' but has limited coverage of asciidoctor-latex
#
# See http://www.noteshare.io/section/asciidoctor-latex-manual-intro
# for a description (with examples) of asciidoctor-latex.
#
# INSTALLATION
#
# Run 'rake install' to install the asciidoctor-latex gem locally.
#
# USAGE (1: html)
#
# Run
#
# 'asciidoctor-latex -b html foo.adoc'
#
# to render an asciidoctor-latex document to html
#
# Some documents (those with 'click blocks', see http://www.noteshare.io/section/homework-problems)
# For these, run
#
# 'asciidoctor-latex -b html -a click_extras=include foo.adoc'
#
# In both cases the output is 'foo.html'
#
# USAGE (2: latex)
#
# Run
#
# 'asciidoctor-latex foo.adoc'
#
# to convert foo.adoc to foo.tex. This feature
# needs a lot of work.
#
# to convert foo.tex to the latex file foo.latex
# You can put files 'macros.tex' and 'preamble.tex' to
# replace the default preamble and set of macros.
# Define your own 'newEnvironments.tex' to use yours
# as opposed to the default definitons of environments
# in tex mapping to [tex.ENVIRNOMENT] in asciidoctor-latex.
#
# TECHNICAL NOTES
#
# This is a first step towards writing a LaTeX backend
# for Asciidoctor. It is based on the
# Dan Allen's demo-converter.rb. The "convert" method
# is unchanged, the methods "document node" and "section node"
# have been redefined, and several new methods have been added.
#
# The main work will be in identifying asciidoc elements
# that need to be transformed and adding a method for
# each such element. As noted below, the "warn" clause
# in the "convert" method is a useful tool for this task.
#
# Usage:
#
# $ asciidoctor -r ./latex-converter.rb -b latex test/sample1.adoc
#
# Comments
#
# 1. The "warn" clause in the converter code is quite useful.
# For example, you will discover in running the converter on
# "test/sample-1.adoc" that you have not implemented code for
# the "olist" node. Thus you can work through ever more complex
# examples to discover what you need to do to increase the coverage
# of the converter. Hackish and ad hoc, but a process nonetheless.
#
# 2. The converter simply passes on what it does not understand, e.g.,
# LaTeX, This is good. However, we will have to map constructs
# like"+\( a^2 = b^2 \)+" to $ a^2 + b^2 $, etc.
# This can be done at the preprocessor level.
#
# 3. In view of the preceding, we may need to chain a frontend
# (preprocessor) to the backend. In any case, the main work
# is in transforming Asciidoc elements to TeX elements.
# Other than the asciidoc -> tex mapping, the tex-converter
# does not need to understand tex.
#
# 4. Included in this repo are the files "test/sample1.adoc", "test/sample2.adoc",
# and "test/elliptic.adoc" which can be used to test the code
#
# 5. Beginning with version 0.0.2 we use a new dispatch mechanism
# which should permit one to better manage growth of the code
# as the coverage of the converter increases. Briefly, the
# main convert method, whose duty is to process nodes, looks
# at node.node_name, then makes the method call node.tex_process
# if the node_name is registered in NODE_TYPES. The method
# tex_process is defined by extending the various classes to
# which the node might belong, e.g., Asciidoctor::Block,
# Asciidoctor::Inline, etc. See the file "node_processor.rb",
# where these extensions are housed for the time being.
#
# If node.node_name is not found in NODE_TYPES, then
# a warning message is issued. We can use it as a clue
# to find what to do to handle this node. All the code
# in "node_processors.rb" to date was written using this
# hackish process.
#
#
# CURRENT STATUS
#
# The following constructs are processed
#
# * sections to a depth of five, e.g., == foo, === foobar, etc.
# * ordered and unordered lists, though nestings is untested and
# likely does not work.
# * *bold* and _italic_
# * hyperlinks like http://foo.com[Nerdy Stuff]
#
require 'asciidoctor'
require 'asciidoctor/converter/html5'
require 'asciidoctor/latex/inline_macros'
require 'asciidoctor/latex/core_ext/colored_string'
require 'asciidoctor/latex/click_block'
require 'asciidoctor/latex/inject_html'
require 'asciidoctor/latex/ent_to_uni'
require 'asciidoctor/latex/environment_block'
require 'asciidoctor/latex/node_processors'
require 'asciidoctor/latex/prepend_processor'
require 'asciidoctor/latex/macro_insert'
require 'asciidoctor/latex/tex_block'
require 'asciidoctor/latex/tex_preprocessor'
require 'asciidoctor/latex/dollar'
require 'asciidoctor/latex/tex_postprocessor'
require 'asciidoctor/latex/chem'
# require 'asciidoctor/latex/preamble_processor'
$VERBOSE = true
module Asciidoctor::LaTeX
# code for Html5ConverterExtension & its insertion
# template by @mojavelinux
module Html5ConverterExtensions
# ENV_CSS_OBLIQUE = "+++<div class='env_oblique'>+++"
# ENV_CSS_NOBLIQUE = "+++<div class='env_noblique'>+++"
ENV_CSS_OBLIQUE = "+++<div style='line-height:1.5em;font-size:1.05em;font-style:oblique;margin-bottom:1.5em'>+++"
ENV_CSS_PLAIN = "+++<div style='line-height:1.5em;font-size:1.05em;;margin-bottom:1.5em'>+++"
DIV_END = '+++</div>+++'
TABLE_ROW_END = '+++</tr></table>+++'
def info node
warn "\n HTMLConverter, node: #{node.node_name}".red if $VERBOSE
end
# Dispatches a handler for the _node_ (`NODE`)
# based on its role.
def environment node
attrs = node.attributes
case attrs['role']
when 'box'
handle_null(node)
when 'equation'
handle_equation(node)
when 'equationalign'
handle_equation_align(node)
when 'chem'
handle_chem(node)
when 'jsxgraph'
handle_jsxgraph(node)
when 'texmacro'
handle_texmacro(node)
else
handle_default(node)
end
node.attributes['roles'] = (node.roles + ['environment']) * ' '
self.open node
end
def handle_texmacro node
node.title = nil
node.lines = ["+++\n\\("] + node.lines + ["\\)\n+++"]
end
def click node
if node.attributes['plain-option']
node.lines = [ENV_CSS_PLAIN] + node.lines + [DIV_END]
else
node.lines = [ENV_CSS_OBLIQUE] + node.lines + [DIV_END]
end
# node.lines = [ENV_CSS] + node.lines + [DIV_END]
node.attributes['roles'] = (node.roles + ['click']) * ' '
self.open node
end
def inline_anchor node
case node.type.to_s
when 'xref'
refid = node.attributes['refid']
if refid and refid[0] == '_'
output = "<a href=\##{refid}>#{refid.gsub('_',' ')}</a>"
else
refs = node.parent.document.references[:ids]
# FIXME: the next line is HACKISH (and it crashes the app when refs[refid]) is nil)
# FIXME: and with the fix for nil results is even more hackish
if refs[refid]
reftext = refs[refid].gsub('.', '')
reftext = reftext.gsub(/:.*/,'')
if refid =~ /\Aeq-/
output = "<span><a href=\##{refid}>equation #{reftext}</a></span>"
elsif refid =~ /\Aformula-/
output = "<span><a href=\##{refid}>formula #{reftext}</a></span>"
elsif refid =~ /\Areaction-/
output = "<span><a href=\##{refid}>reaction #{reftext}</a></span>"
else
output = "<span><a href=\##{refid} style='text-decoration:none'>#{reftext}</a></span>"
end
else
output = 'ERROR: refs[refid] was nil'
end
end
when 'link'
output = "<a href=#{node.target}>#{node.text}</a>"
else
output = 'FOOBAR'
end
output
end
def handle_equation(node)
attrs = node.attributes
options = attrs['options']
node.title = nil
warn "node.attributes (EQUATION): #{node.attributes}".cyan if $VERBOSE
number_part = '<td style="text-align:right">' + "(#{node.caption}) </td>"
number_part = ["+++ #{number_part} +++"]
equation_part = ['+++<td style="width:100%";>+++'] + ['\\['] + node.lines + ['\\]'] + ['+++</td>+++']
table_style='style="width:100%; border-collapse:collapse;border:0" class="zero" '
row_style='style="border-collapse: collapse; border:0; font-size: 12pt; "'
if options.include? 'numbered'
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + number_part + [TABLE_ROW_END]
else
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + [TABLE_ROW_END]
end
end
def handle_equation_align(node)
attrs = node.attributes
options = attrs['options']
warn "node.attributes (EQUATION ALIGN): #{node.attributes}".cyan if $VERBOSE
node.title = nil
number_part = '<td style="text-align:right">' + "(#{node.caption}) </td>"
number_part = ["+++ #{number_part} +++"]
equation_part = ['+++<td style="width:100%";>+++'] + ['\\[\\begin{split}'] + node.lines + ['\\end{split}\\]'] + ['+++</td>+++']
table_style='style="width:100%; border-collapse:collapse;border:0" class="zero" '
row_style='style="border-collapse: collapse; border:0; font-size: 12pt; "'
if options.include? 'numbered'
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + number_part + [TABLE_ROW_END]
else
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + [TABLE_ROW_END]
end
end
def handle_chem(node)
node.title = nil
number_part = '<td style="text-align:right">' + "(#{node.caption}) </td>"
number_part = ["+++ #{number_part} +++"]
equation_part = ['+++<td style="width:100%;">+++'] + [' \\[\\ce{' + node.lines[0] + '}\\] '] + ['+++</td>+++']
table_style='class="zero" style="width:100%; border-collapse:collapse; border:0"'
row_style='class="zero" style="border-collapse: collapse; border:0; font-size: 10pt; "'
node.lines = ["+++<table #{table_style}><tr #{row_style}>+++"] + equation_part + number_part +['+++</tr></table>+++']
end
def handle_jsxgraph(node)
attrs = node.attributes
if attrs['box'] == nil
attrs['box'] = 'box'
end
if attrs['width'] == nil
attrs['width'] = 450
end
if attrs['height'] == nil
attrs['height'] = 450
end
line_array = ["\n+++\n"]
# line_array += ["<link rel='stylesheet' type='text/css' href='jsxgraph.css' />"]
line_array += ["<link rel='stylesheet' type='text/css' href='http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css' />"]
line_array += ['<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsxgraph/0.99.3/jsxgraphcore.js"></script>']
line_array += ["<script src='http://jsxgraph.uni-bayreuth.de/distrib/GeonextReader.js' type='text/javascript'></script>"]
# line_array += ['<div id="box" class="jxgbox" style="width:500px; height:500px;"></div>']
line_array += ["<div id='#{attrs['box']}' class='jxgbox' style='width:" + "#{attrs['width']}" + "px; height:" + "#{attrs['height']}" +"px;'></div>"]
line_array += ['<script type="text/javascript">']
line_array += node.lines
line_array += ['</script>']
line_array += ['<br/>']
line_array += ["\n+++\n"]
node.lines = line_array
end
def handle_null(node)
end
def handle_default(node)
if node.attributes['plain-option']
node.lines = [ENV_CSS_PLAIN] + node.lines + [DIV_END]
else
node.lines = [ENV_CSS_OBLIQUE] + node.lines + [DIV_END]
end
end
end
class Converter
include Asciidoctor::Converter
register_for 'latex'
Asciidoctor::Extensions.register do
preprocessor TeXPreprocessor
preprocessor MacroInsert if (File.exist? 'macros.tex' and document.basebackend? 'html') and !(document.attributes['noteshare'] == 'yes')
block EnvironmentBlock
block ClickBlock
inline_macro ChemInlineMacro
# preprocessor ClickStyleInsert if document.attributes['click_extras'] == 'include2'
postprocessor InjectHTML unless document.attributes['noteshare'] == 'yes'
postprocessor EntToUni if document.basebackend? 'tex' unless document.attributes['unicode'] == 'no'
postprocessor Chem if document.basebackend? 'html'
postprocessor HTMLPostprocessor if document.basebackend? 'html'
postprocessor TexPostprocessor if document.basebackend? 'tex'
end
Asciidoctor::Extensions.register :latex do
# EnvironmentBlock
end
TOP_TYPES = %w(document section)
LIST_TYPES = %w(dlist olist ulist)
INLINE_TYPES = %w(inline_anchor inline_break inline_footnote inline_quoted inline_callout)
BLOCK_TYPES = %w(admonition listing literal page_break paragraph stem pass open quote \
example floating_title image click preamble sidebar verse toc)
OTHER_TYPES = %w(environment table)
NODE_TYPES = TOP_TYPES + LIST_TYPES + INLINE_TYPES + BLOCK_TYPES + OTHER_TYPES
def initialize backend, opts
super
basebackend 'tex'
outfilesuffix '.tex'
end
# FIXME: find a solution without a global variable
$latex_environment_names = []
# FIXME: this should be retired -- still used
# in click blocks but no longer in env blocks
$label_counter = 0
def convert node, transform = nil
if NODE_TYPES.include? node.node_name
node.tex_process
else
warn %(Node to implement: #{node.node_name}, class = #{node.class}).magenta if $VERBOSE
# This warning should not be switched off by $VERBOSE
end
end
end # class Converter
end # module Asciidoctor::LaTeX
class Asciidoctor::Converter::Html5Converter
# inject our custom code into the existing Html5Converter class (Ruby 2.0 and above)
prepend Asciidoctor::LaTeX::Html5ConverterExtensions
end
|
#!/usr/bin/env ruby
require 'thor'
require 'faraday'
require 'active_support'
require 'active_support/core_ext'
require 'uri'
class Mvmc < Thor
# desc "mvmc h", "display help"
# def h
# puts <<-LONGDESC
# This client communicates with mvmc remote services. It needs a configuration files "mvmc.conf" in current path or in /etc/mvmc.conf.
# This file must include 2 lines with mvmc credentials like this:
# email: user@mvmc-openstack.local
# password: wordpass
#
# `mvmc help` will print help about this command
# `mvmc up` launch current commit into vm
# `mvmc destroy` destroy current vm associated to this project
# `mvmc ssh` ssh into current vm
# `mvmc projects` list projects
#
# > $ mvmc up
# LONGDESC
# end
# Launch current commit into a new vms on mvmc cloud
#
desc "up", "launch current commit to remote mvmc"
def up
init
if ! @project
warn("Git repository for #{gitpath} not found, have-you already import this project ?")
exit
end
launch_req = { vm: { project_id: @project[:id], flavor_id: 1, user_id: @user[:id], systemimage_id: 1, commit_id: commitid } }
response = @conn.post do |req|
req.url "/api/v1/vms"
req.headers = rest_headers
req.body = launch_req.to_json
end
json(response.body)[:vm]
end
# Destroy current vm
#
desc "destroy", "destroy current vm"
def destroy
init
if ! @vm
warn("No vm for commit #{commitid}")
exit
end
response = @conn.delete do |req|
req.url "/api/v1/vms/#{@vm[:id]}"
req.headers = rest_headers
end
end
# List current active vms
#
desc "list", "list launched vms for current user"
def list
init
if @vms.empty?
puts "No vms for #{@user[:email]}"
return
end
@vms.each do |vm|
project = @projects.select { |project| project[:id] == vm[:project] }
puts "Project #{project[0][:name]}, Commit #{vm[:commit]}"
end
end
# List projects for current user
#
desc "projects", "list projects for current user"
def projects
init
if @projects.empty?
puts "No projects for #{@user[:email]}"
return
end
@projects.sort_by! { |project| project[:name] }
@projects.each { |project| puts "Project #{project[:name]}: git clone git@#{project[:gitpath]}" }
end
# Ssh into remote vm
#
desc "ssh", "ssh into remote vm"
def ssh
init
if ! @vm
warn("No vm for commit #{commitid}")
exit
end
exec "ssh modem@#{@vm[:floating_ip]}"
end
no_commands do
# Init datas
#
def init
init_properties
init_conn
token
init_brands
init_frameworks
get_project
get_vm
end
# Retrieve settings parameters
#
def init_properties
fp = nil
@email = nil
@password = nil
@endpoint = nil
# Open setting file
if File.exists?('mvmc.conf')
fp = File.open('mvmc.conf', 'r')
else
if ! File.exists?('/etc/mvmc.conf')
error('no mvmc.conf or /etc/mvmc.conf')
end
fp = File.open('/etc/mvmc.conf', 'r')
end
# Get properties
while (line = fp.gets)
if (line.match(/^email:.*$/))
@email = line.gsub('email:', '').squish
end
if (line.match(/^password:.*$/))
@password = line.gsub('password:', '').squish
end
if (line.match(/^endpoint:.*$/))
@endpoint = line.gsub('endpoint:', '').squish
end
end
fp.close
error("no email into mvmc.conf") if @email == nil
error("no password into mvmc.conf") if @password == nil
error("no endpoint into mvmc.conf") if @endpoint == nil
end
# Get current git url
#
# No params
# @return [String] the git path
def gitpath
%x{git config --get remote.origin.url | sed "s;^.*root/;;" | sed "s;\.git$;;"}.squish
end
# Get current commit
#
# No param
# @return [String] a commit hash
def currentcommit
%x{git rev-parse HEAD}.squish
end
# Get current branch
#
# No params
# @return [String] a branch name
def currentbranch
%x{git branch | grep "*" | sed "s;* ;;"}.squish
end
# Get unique id (for the model of mvmc) for current commit
#
# No params
# @return [String] id of the commit
def commitid
"#{@project[:id]}-#{currentbranch}-#{currentcommit}"
end
# Get current project follow the gitpath value
#
# No params
# @return [Array[String]] json output for a project
def get_project
gitp = gitpath
# if we are not into git project, return
if gitp.empty?
return
end
response = @conn.get do |req|
req.url "/api/v1/projects/git/#{gitp}"
req.headers = rest_headers
end
if response.body == "null"
@project = {}
return
end
@project = json(response.body)[:project]
end
# get he vm for current commit
#
# No params
# @return [Array[String]] json output for a vm
def get_vm
# if we are not into git project, return
gitp = gitpath
if gitp.empty?
return
end
commit = commitid
response = @conn.get do |req|
req.url "/api/v1/vms/user/#{@user[:id]}/#{commit}"
req.headers = rest_headers
end
if response.body == "null"
@vm = {}
return
end
@vm = json(response.body)[:vms][0]
end
# Init rest connection
#
def init_conn
@conn = Faraday.new(:url => "http://#{@endpoint}") do |faraday|
faraday.adapter Faraday.default_adapter
faraday.port = 80
end
end
# Authenticate user
#
# @param [String] email of the user
# @param [String] password of the user
# No return
def authuser(email, password)
auth_req = { email: email, password: password }
begin
response = @conn.post do |req|
req.url "/api/v1/users/sign_in"
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
req.body = auth_req.to_json
end
rescue Exception => e
warn("Issue during authentification, bad email or password ?")
warn(e)
exit
end
json_auth = json(response.body)
if ! json_auth[:success].nil? && json_auth[:success] == false
warn(json_auth[:message])
exit
end
@user = json_auth[:user]
init_vms(@user[:vms])
init_projects(@user[:projects])
if @user[:sshkeys][0]
init_sshkeys(@user[:sshkeys])
else
@ssh_key = { name: 'nosshkey' }
end
end
# Get all projects properties
#
# @params [Array[Integer]] id array
# No return
def init_projects(project_ids)
@projects = []
project_ids.each do |project_id|
response = @conn.get do |req|
req.url "/api/v1/projects/#{project_id}"
req.headers = rest_headers
end
@projects.push(json(response.body)[:project])
end
end
# Get all vms properties
#
# @params [Array[Integer]] id array
# No return
def init_vms(vm_ids)
@vms = []
vm_ids.each do |vm_id|
response = @conn.get do |req|
req.url "/api/v1/vms/#{vm_id}"
req.headers = rest_headers
end
@vms.push(json(response.body)[:vm])
end
end
# Get all sshkeys properties
#
# @params [Array[Integer]] id array
# No return
def init_sshkeys(ssh_ids)
@ssh_keys = []
ssh_ids.each do |ssh_id|
response = @conn.get do |req|
req.url "/api/v1/sshkeys/#{ssh_id}"
req.headers = rest_headers
end
@ssh_keys << json(response.body)[:sshkey]
@ssh_key = @ssh_keys.first
end
end
# Get all brands properties
#
# @params [Array[Integer]] id array
# No return
def init_brands
response = @conn.get do |req|
req.url "/api/v1/brands"
req.headers = rest_headers
end
@brands = json(response.body)[:brands]
end
# Get all frameworks properties
#
# @params [Array[Integer]] id array
# No return
def init_frameworks
response = @conn.get do |req|
req.url "/api/v1/frameworks"
req.headers = rest_headers
end
@frameworks = json(response.body)[:frameworks]
end
# Helper function for parse json call
#
# @param body [String] the json on input
# @return [Hash] the json hashed with symbol
def json(body)
JSON.parse(body, symbolize_names: true)
end
# Init token generate
#
def token
authuser(@email, @password)
end
# Return rest headers well formated
#
def rest_headers
{ 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => "Token token=#{@user[:authentication_token]}" }
end
# Puts errors on the output
def error(msg)
puts msg
exit 5
end
end
end
Mvmc.start(ARGV)
Fix some bugs, improve text displaying and add config / clone cmds
#!/usr/bin/env ruby
require 'thor'
require 'faraday'
require 'active_support'
require 'active_support/core_ext'
require 'uri'
class Mvmc < Thor
# desc "mvmc h", "display help"
# def h
# puts <<-LONGDESC
# This client communicates with mvmc remote services. It needs a configuration files "mvmc.conf" in current path or in /etc/mvmc.conf.
# This file must include 2 lines with mvmc credentials like this:
# email: user@mvmc-openstack.local
# password: wordpass
#
# `mvmc help` will print help about this command
# `mvmc up` launch current commit into vm
# `mvmc destroy` destroy current vm associated to this project
# `mvmc ssh` ssh into current vm
# `mvmc projects` list projects
# 'mvmc config' get current configuration and set properties
#
# > $ mvmc up
# LONGDESC
# end
# Launch current commit into a new vms on mvmc cloud
#
desc "up", "launch current commit to remote mvmc"
def up
init
if ! @project
warn("Git repository for #{gitpath} not found, have-you already import this project ?")
exit
end
# get well systemimage
system = @systems.select { |s| s[:systemimagetype] == @project[:systemimagetype] }[0]
# prepare post request
launch_req = { vm: { project_id: @project[:id], vmsize_id: @project[:vmsizes][0], user_id: @user[:id], systemimage_id: system[:id], commit_id: commitid } }
response = @conn.post do |req|
req.url "/api/v1/vms"
req.headers = rest_headers
req.body = launch_req.to_json
end
json(response.body)[:vm]
end
# Destroy current vm
#
desc "destroy", "destroy current vm"
def destroy
init
if ! @vm
warn("No vm for commit #{commitid}")
exit
end
response = @conn.delete do |req|
req.url "/api/v1/vms/#{@vm[:id]}"
req.headers = rest_headers
end
end
# List current active vms
#
desc "list", "list launched vms for current user"
def list
init
if @vms.empty?
error("No vms for #{@user[:email]}")
end
@vms.each do |vm|
project = @projects.select { |project| project[:id] == vm[:project] }
status = "RUNNING"
status = "SETUP" if vm[:status] == 0
status = "ERROR" if vm[:status] == 2
puts "#{project[0][:name]}, #{vm[:commit].gsub(/^[0-9]+-/, '')[0,16]}, #{status}"
end
end
# List projects for current user
#
desc "projects", "list projects for current user"
def projects
init
if @projects.empty?
error("No projects for #{@user[:email]}")
end
@projects.sort_by! { |project| project[:name] }
@projects.each { |project| puts "Project #{project[:name]}: git clone git@#{project[:gitpath]}" }
end
# Clone a project by his name
#
desc "clone [project-name]", "clone project in current folder"
def clone(projectname=nil)
init
if projectname == nil
error("Argument projectname is missing")
end
if @projects.empty?
error("No projects for #{@user[:email]}")
end
# select project following parameter
proj = @projects.select { |p| p[:name] == projectname }
# return if parameter is invalid
error("Project #{projectname} not found") if !proj || proj.empty?
# else clone the project
@project = proj[0]
exec "git clone git@#{@project[:gitpath]}"
end
# Ssh into remote vm
#
desc "ssh", "ssh into remote vm"
def ssh
init
if ! @vm
error("No vm for commit #{commitid}")
end
exec "ssh modem@#{@vm[:floating_ip]}"
end
# Get / set config for mvmc
#
desc "config [endpoint] [username] [password]", "get/set properties settings for mvmc"
def config(endp=nil, username=nil, pass=nil)
# get actual settings with disable error log
@nolog = true
init_properties
@nolog = nil
@endpoint = endp if endp
@email = username if username
@password = pass if pass
# write new setting file
if endp || username || pass
open(ENV['HOME']+'/.mvmc.conf', 'w') do |f|
f << "email: #{@email}\n"
f << "password: #{@password}\n"
f << "endpoint: #{@endpoint}\n"
end
end
# confirm this new settings
init_properties
puts "Username: #{@email}"
puts "Password: #{@password}"
puts "Endpoint: #{@endpoint}"
end
no_commands do
# Init datas
#
def init
init_properties
init_conn
token
init_brands
init_frameworks
init_systems
get_project
get_vm
end
# Retrieve settings parameters
#
def init_properties
fp = nil
@email = nil
@password = nil
@endpoint = nil
# Open setting file
if File.exists?('mvmc.conf')
fp = File.open('mvmc.conf', 'r')
elsif File.exists?(ENV['HOME']+'/.mvmc.conf')
fp = File.open(ENV['HOME']+'/.mvmc.conf', 'r')
else
if ! File.exists?('/etc/mvmc.conf')
error('no mvmc.conf or /etc/mvmc.conf')
end
fp = File.open('/etc/mvmc.conf', 'r')
end
# Get properties
while (line = fp.gets)
if (line.match(/^email:.*$/))
@email = line.gsub('email:', '').squish
end
if (line.match(/^password:.*$/))
@password = line.gsub('password:', '').squish
end
if (line.match(/^endpoint:.*$/))
@endpoint = line.gsub('endpoint:', '').squish
end
end
fp.close
error("no email into mvmc.conf") if @email == nil
error("no password into mvmc.conf") if @password == nil
error("no endpoint into mvmc.conf") if @endpoint == nil
end
# Get current git url
#
# No params
# @return [String] the git path
def gitpath
%x{git config --get remote.origin.url | sed "s;^.*root/;;" | sed "s;\.git$;;"}.squish
end
# Get current commit
#
# No param
# @return [String] a commit hash
def currentcommit
%x{git rev-parse HEAD}.squish
end
# Get current branch
#
# No params
# @return [String] a branch name
def currentbranch
%x{git branch | grep "*" | sed "s;* ;;"}.squish
end
# Get unique id (for the model of mvmc) for current commit
#
# No params
# @return [String] id of the commit
def commitid
"#{@project[:id]}-#{currentbranch}-#{currentcommit}"
end
# Get current project follow the gitpath value
#
# No params
# @return [Array[String]] json output for a project
def get_project
gitp = gitpath
# if we are not into git project, return
if gitp.empty?
return
end
response = @conn.get do |req|
req.url "/api/v1/projects/git/#{gitp}"
req.headers = rest_headers
end
if response.body == "null"
@project = {}
return
end
@project = json(response.body)[:project]
end
# get he vm for current commit
#
# No params
# @return [Array[String]] json output for a vm
def get_vm
# if we are not into git project, return
gitp = gitpath
if gitp.empty?
return
end
commit = commitid
response = @conn.get do |req|
req.url "/api/v1/vms/user/#{@user[:id]}/#{commit}"
req.headers = rest_headers
end
if response.body == "null" || !json(response.body)[:vms]
@vm = {}
return
end
@vm = json(response.body)[:vms][0]
end
# Init rest connection
#
def init_conn
@conn = Faraday.new(:url => "http://#{@endpoint}") do |faraday|
faraday.adapter Faraday.default_adapter
faraday.port = 80
end
end
# Authenticate user
#
# @param [String] email of the user
# @param [String] password of the user
# No return
def authuser(email, password)
auth_req = { email: email, password: password }
begin
response = @conn.post do |req|
req.url "/api/v1/users/sign_in"
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
req.body = auth_req.to_json
end
rescue Exception => e
warn("Issue during authentification, bad email or password ?")
warn(e)
exit
end
json_auth = json(response.body)
if ! json_auth[:success].nil? && json_auth[:success] == false
warn(json_auth[:message])
exit
end
@user = json_auth[:user]
init_vms(@user[:vms])
init_projects(@user[:projects])
if @user[:sshkeys][0]
init_sshkeys(@user[:sshkeys])
else
@ssh_key = { name: 'nosshkey' }
end
end
# Get all projects properties
#
# @params [Array[Integer]] id array
# No return
def init_projects(project_ids)
@projects = []
project_ids.each do |project_id|
response = @conn.get do |req|
req.url "/api/v1/projects/#{project_id}"
req.headers = rest_headers
end
@projects.push(json(response.body)[:project])
end
end
# Get all vms properties
#
# @params [Array[Integer]] id array
# No return
def init_vms(vm_ids)
@vms = []
vm_ids.each do |vm_id|
response = @conn.get do |req|
req.url "/api/v1/vms/#{vm_id}"
req.headers = rest_headers
end
@vms.push(json(response.body)[:vm])
end
end
# Get all sshkeys properties
#
# @params [Array[Integer]] id array
# No return
def init_sshkeys(ssh_ids)
@ssh_keys = []
ssh_ids.each do |ssh_id|
response = @conn.get do |req|
req.url "/api/v1/sshkeys/#{ssh_id}"
req.headers = rest_headers
end
@ssh_keys << json(response.body)[:sshkey]
@ssh_key = @ssh_keys.first
end
end
# Get all brands properties
#
# @params [Array[Integer]] id array
# No return
def init_brands
response = @conn.get do |req|
req.url "/api/v1/brands"
req.headers = rest_headers
end
@brands = json(response.body)[:brands]
end
# Get all frameworks properties
#
# @params [Array[Integer]] id array
# No return
def init_frameworks
response = @conn.get do |req|
req.url "/api/v1/frameworks"
req.headers = rest_headers
end
@frameworks = json(response.body)[:frameworks]
end
# Get all systemimages properties
#
# @params [Array[Integer]] id array
# No return
def init_systems
response = @conn.get do |req|
req.url "/api/v1/systemimages"
req.headers = rest_headers
end
@systems = json(response.body)[:systemimages]
end
# Helper function for parse json call
#
# @param body [String] the json on input
# @return [Hash] the json hashed with symbol
def json(body)
JSON.parse(body, symbolize_names: true)
end
# Init token generate
#
def token
authuser(@email, @password)
end
# Return rest headers well formated
#
def rest_headers
{ 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => "Token token=#{@user[:authentication_token]}" }
end
# Puts errors on the output
def error(msg)
return if @nolog
puts msg
exit 5
end
end
end
Mvmc.start(ARGV)
|
# callimachus-webapp.ru
#
# read by Setup.java to determine initial Callimachus webapp path
# @webapp </callimachus/1.3/>
#
PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl:<http://www.w3.org/2002/07/owl#>
PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
PREFIX sd:<http://www.w3.org/ns/sparql-service-description#>
PREFIX void:<http://rdfs.org/ns/void#>
PREFIX foaf:<http://xmlns.com/foaf/0.1/>
PREFIX msg:<http://www.openrdf.org/rdf/2011/messaging#>
PREFIX calli:<http://callimachusproject.org/rdf/2009/framework#>
################################################################
# Data to initialize an Callimachus store, but may be removed.
################################################################
################################
# Version Info
################################
INSERT {
<../> calli:hasComponent <../ontology>.
<../ontology> a <types/Serviceable>, owl:Ontology;
rdfs:label "ontology";
rdfs:comment "Vocabulary used to create local Callimachus applications";
owl:versionInfo "1.1";
calli:administrator </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { <../ontology> a owl:Ontology }
};
################################
# Stable URLs
################################
INSERT {
<../../> calli:hasComponent <../>.
} WHERE {
FILTER (<../../> != <../>)
FILTER NOT EXISTS { <../../> calli:hasComponent <../> }
};
INSERT {
<../> a <types/Folder>, calli:Folder;
rdfs:label "callimachus";
calli:reader </auth/groups/public>;
calli:administrator </auth/groups/super>;
calli:hasComponent
<../profile>,
<../changes/>,
<../getting-started-with-callimachus>,
<../callimachus-for-web-developers>,
<../callimachus-reference>,
<../scripts.js>,
<../library.xpl>,
<../error.xpl>,
<../forbidden.html>,
<../unauthorized.html>,
<../layout-functions.xq>,
<../default-layout.xq>,
<../callimachus-powered.png>,
<../document-editor.html>,
<../css-editor.html>,
<../html-editor.html>,
<../javascript-editor.html>,
<../sparql-editor.html>,
<../text-editor.html>,
<../xml-editor.html>,
<../xquery-editor.html>.
} WHERE {
FILTER NOT EXISTS { <../> a calli:Folder }
};
INSERT {
<../profile> a <types/RdfProfile>;
rdfs:label "rdf profile";
calli:administrator </auth/groups/super>;
calli:editor </auth/groups/power>,</auth/groups/admin>;
calli:subscriber </auth/groups/staff>;
calli:reader </auth/groups/system>.
} WHERE {
FILTER NOT EXISTS { <../profile> a <types/RdfProfile> }
};
INSERT {
<../changes/> a <types/Folder>, calli:Folder;
rdfs:label "changes";
calli:subscriber </auth/groups/power>,</auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { <../changes/> a calli:Folder }
};
INSERT {
<../getting-started-with-callimachus> a <types/Purl>, calli:Purl ;
rdfs:label "getting-started-with-callimachus";
calli:alternate <http://callimachusproject.org/docs/1.3/getting-started-with-callimachus.docbook?view>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../getting-started-with-callimachus> a calli:Purl }
};
INSERT {
<../callimachus-for-web-developers> a <types/Purl>, calli:Purl ;
rdfs:label "callimachus-for-web-developers";
calli:alternate <http://callimachusproject.org/docs/1.3/callimachus-for-web-developers.docbook?view>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../callimachus-for-web-developers> a calli:Purl }
};
INSERT {
<../callimachus-reference> a <types/Purl>, calli:Purl ;
rdfs:label "callimachus-reference";
calli:alternate <http://callimachusproject.org/docs/1.3/callimachus-reference.docbook?view>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../callimachus-reference> a calli:Purl }
};
INSERT {
<../scripts.js> a <types/Purl>, calli:Purl ;
rdfs:label "scripts.js";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<scripts/index?minified>) AS ?alternate)
FILTER NOT EXISTS { <../scripts.js> a calli:Purl }
};
INSERT {
<../> calli:hasComponent <../query-view.js>.
<../query-view.js> a <types/Purl>, calli:Purl ;
rdfs:label "query-view.js";
calli:alternate <scripts/query_bundle?minified>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../> calli:hasComponent <../query-view.js> }
};
INSERT {
<../> calli:hasComponent <../query-view.css>.
<../query-view.css> a <types/Purl>, calli:Purl ;
rdfs:label "query-view.css";
calli:alternate <styles/callimachus-query-view.less?less>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../> calli:hasComponent <../query-view.css> }
};
INSERT {
<../library.xpl> a <types/Purl>, calli:Purl ;
rdfs:label "library.xpl";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pipelines/library.xpl>) as ?alternate)
FILTER NOT EXISTS { <../library.xpl> a calli:Purl }
};
INSERT {
<../error.xpl> a <types/Purl>, calli:Purl ;
rdfs:label "error.xpl";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pipelines/error.xpl>) as ?alternate)
FILTER NOT EXISTS { <../error.xpl> a calli:Purl }
};
INSERT {
<../forbidden.html> a <types/Purl>, calli:Purl ;
rdfs:label "forbidden.html";
calli:alternate <pages/forbidden.xhtml?html>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../forbidden.html> a calli:Purl }
};
INSERT {
<../unauthorized.html> a <types/Purl>, calli:Purl ;
rdfs:label "unauthorized.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/unauthorized.xhtml?element=/1>) AS ?alternate)
FILTER NOT EXISTS { <../unauthorized.html> a calli:Purl }
};
INSERT {
<../layout-functions.xq> a <types/Purl>, calli:Purl ;
rdfs:label "layout-functions.xq";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<transforms/layout-functions.xq>) AS ?alternate)
FILTER NOT EXISTS { <../layout-functions.xq> a calli:Purl }
};
INSERT {
<../default-layout.xq> a <types/Purl>, calli:Purl ;
rdfs:label "default-layout.xq";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<transforms/default-layout.xq>) AS ?alternate)
FILTER NOT EXISTS { <../default-layout.xq> a calli:Purl }
};
INSERT {
<../callimachus-powered.png> a <types/Purl>, calli:Purl ;
rdfs:label "callimachus-powered.png";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<images/callimachus-powered.png>) AS ?alternate)
FILTER NOT EXISTS { <../callimachus-powered.png> a calli:Purl }
};
INSERT {
<../document-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "document-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/document-editor.html>) AS ?alternate)
FILTER NOT EXISTS { <../document-editor.html> a calli:Purl }
};
INSERT {
<../css-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "css-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#css>) AS ?alternate)
FILTER NOT EXISTS { <../css-editor.html> a calli:Purl }
};
INSERT {
<../html-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "html-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#html>) AS ?alternate)
FILTER NOT EXISTS { <../html-editor.html> a calli:Purl }
};
INSERT {
<../javascript-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "javascript-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#javascript>) AS ?alternate)
FILTER NOT EXISTS { <../javascript-editor.html> a calli:Purl }
};
INSERT {
<../sparql-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "sparql-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#sparql>) AS ?alternate)
FILTER NOT EXISTS { <../sparql-editor.html> a calli:Purl }
};
INSERT {
<../text-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "text-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html>) AS ?alternate)
FILTER NOT EXISTS { <../text-editor.html> a calli:Purl }
};
INSERT {
<../xml-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "xml-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#xml>) AS ?alternate)
FILTER NOT EXISTS { <../xml-editor.html> a calli:Purl }
};
INSERT {
<../xquery-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "xquery-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#xquery>) AS ?alternate)
FILTER NOT EXISTS { <../xquery-editor.html> a calli:Purl }
};
################################
# Authorization and Groups
################################
INSERT {
</auth/> calli:hasComponent </auth/invited-users/>.
</auth/invited-users/> a <types/Folder>, calli:Folder;
rdfs:label "invited users";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/invited-users/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/digest-users/>.
</auth/digest-users/> a <types/Folder>, calli:Folder;
rdfs:label "digest users";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/digest-users/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/secrets/>.
</auth/secrets/> a <types/Folder>, calli:Folder;
rdfs:label "secrets";
calli:editor </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/secrets/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/credentials/>.
</auth/credentials/> a <types/Folder>, calli:Folder;
rdfs:label "credentials";
calli:editor </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/credentials/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/groups/>.
</auth/groups/> a <types/Folder>, calli:Folder;
rdfs:label "groups";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>;
calli:hasComponent
</auth/groups/super>,
</auth/groups/admin>,
</auth/groups/power>,
</auth/groups/staff>,
</auth/groups/users>,
</auth/groups/everyone>,
</auth/groups/system>,
</auth/groups/public>.
</auth/groups/super> a calli:Party, calli:Group, <types/Group>;
rdfs:label "super";
rdfs:comment "The user accounts in this group have heightened privileges to change or patch the system itself".
</auth/groups/admin> a calli:Party, calli:Group, <types/Group>;
rdfs:label "admin";
rdfs:comment "Members of this grouph have the ability to edit other user accounts and access to modify the underlying data store";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/power> a calli:Party, calli:Group, <types/Group>;
rdfs:label "power";
rdfs:comment "Members of this group can access all data in the underlying data store";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/staff> a calli:Party, calli:Group, <types/Group>;
rdfs:label "staff";
rdfs:comment "Members of this group can design websites and develop applications";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/users> a calli:Party, calli:Group, <types/Group>;
rdfs:label "users";
rdfs:comment "Members of this group can view, discuss, document, link, and upload binary resources";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/everyone> a calli:Party, calli:Domain, <types/Domain>;
rdfs:label "everyone";
rdfs:comment "A virtual group of all authenticated agents";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>;
calli:everyoneFrom ".".
</auth/groups/system> a calli:Party, calli:Domain, <types/Domain>;
rdfs:label "system";
rdfs:comment "The local computer or computer systems is the member of this domain";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/public> a calli:Party, calli:Domain, <types/Domain>;
rdfs:label "public";
rdfs:comment "A virtual group of all agents";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>;
calli:anonymousFrom ".".
} WHERE {
FILTER NOT EXISTS { </auth/groups/> a calli:Folder }
};
Fixed typo.
# callimachus-webapp.ru
#
# read by Setup.java to determine initial Callimachus webapp path
# @webapp </callimachus/1.3/>
#
PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl:<http://www.w3.org/2002/07/owl#>
PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
PREFIX sd:<http://www.w3.org/ns/sparql-service-description#>
PREFIX void:<http://rdfs.org/ns/void#>
PREFIX foaf:<http://xmlns.com/foaf/0.1/>
PREFIX msg:<http://www.openrdf.org/rdf/2011/messaging#>
PREFIX calli:<http://callimachusproject.org/rdf/2009/framework#>
################################################################
# Data to initialize an Callimachus store, but may be removed.
################################################################
################################
# Version Info
################################
INSERT {
<../> calli:hasComponent <../ontology>.
<../ontology> a <types/Serviceable>, owl:Ontology;
rdfs:label "ontology";
rdfs:comment "Vocabulary used to create local Callimachus applications";
owl:versionInfo "1.1";
calli:administrator </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { <../ontology> a owl:Ontology }
};
################################
# Stable URLs
################################
INSERT {
<../../> calli:hasComponent <../>.
} WHERE {
FILTER (<../../> != <../>)
FILTER NOT EXISTS { <../../> calli:hasComponent <../> }
};
INSERT {
<../> a <types/Folder>, calli:Folder;
rdfs:label "callimachus";
calli:reader </auth/groups/public>;
calli:administrator </auth/groups/super>;
calli:hasComponent
<../profile>,
<../changes/>,
<../getting-started-with-callimachus>,
<../callimachus-for-web-developers>,
<../callimachus-reference>,
<../scripts.js>,
<../library.xpl>,
<../error.xpl>,
<../forbidden.html>,
<../unauthorized.html>,
<../layout-functions.xq>,
<../default-layout.xq>,
<../callimachus-powered.png>,
<../document-editor.html>,
<../css-editor.html>,
<../html-editor.html>,
<../javascript-editor.html>,
<../sparql-editor.html>,
<../text-editor.html>,
<../xml-editor.html>,
<../xquery-editor.html>.
} WHERE {
FILTER NOT EXISTS { <../> a calli:Folder }
};
INSERT {
<../profile> a <types/RdfProfile>;
rdfs:label "rdf profile";
calli:administrator </auth/groups/super>;
calli:editor </auth/groups/power>,</auth/groups/admin>;
calli:subscriber </auth/groups/staff>;
calli:reader </auth/groups/system>.
} WHERE {
FILTER NOT EXISTS { <../profile> a <types/RdfProfile> }
};
INSERT {
<../changes/> a <types/Folder>, calli:Folder;
rdfs:label "changes";
calli:subscriber </auth/groups/power>,</auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { <../changes/> a calli:Folder }
};
INSERT {
<../getting-started-with-callimachus> a <types/Purl>, calli:Purl ;
rdfs:label "getting-started-with-callimachus";
calli:alternate <http://callimachusproject.org/docs/1.3/getting-started-with-callimachus.docbook?view>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../getting-started-with-callimachus> a calli:Purl }
};
INSERT {
<../callimachus-for-web-developers> a <types/Purl>, calli:Purl ;
rdfs:label "callimachus-for-web-developers";
calli:alternate <http://callimachusproject.org/docs/1.3/callimachus-for-web-developers.docbook?view>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../callimachus-for-web-developers> a calli:Purl }
};
INSERT {
<../callimachus-reference> a <types/Purl>, calli:Purl ;
rdfs:label "callimachus-reference";
calli:alternate <http://callimachusproject.org/docs/1.3/callimachus-reference.docbook?view>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../callimachus-reference> a calli:Purl }
};
INSERT {
<../scripts.js> a <types/Purl>, calli:Purl ;
rdfs:label "scripts.js";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<scripts/index?minified>) AS ?alternate)
FILTER NOT EXISTS { <../scripts.js> a calli:Purl }
};
INSERT {
<../> calli:hasComponent <../query-view.js>.
<../query-view.js> a <types/Purl>, calli:Purl ;
rdfs:label "query-view.js";
calli:alternate <scripts/query_bundle?minified>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../> calli:hasComponent <../query-view.js> }
};
INSERT {
<../> calli:hasComponent <../query-view.css>.
<../query-view.css> a <types/Purl>, calli:Purl ;
rdfs:label "query-view.css";
calli:alternate <styles/callimachus-query-view.less?less>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../> calli:hasComponent <../query-view.css> }
};
INSERT {
<../library.xpl> a <types/Purl>, calli:Purl ;
rdfs:label "library.xpl";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pipelines/library.xpl>) as ?alternate)
FILTER NOT EXISTS { <../library.xpl> a calli:Purl }
};
INSERT {
<../error.xpl> a <types/Purl>, calli:Purl ;
rdfs:label "error.xpl";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pipelines/error.xpl>) as ?alternate)
FILTER NOT EXISTS { <../error.xpl> a calli:Purl }
};
INSERT {
<../forbidden.html> a <types/Purl>, calli:Purl ;
rdfs:label "forbidden.html";
calli:alternate <pages/forbidden.xhtml?html>;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
FILTER NOT EXISTS { <../forbidden.html> a calli:Purl }
};
INSERT {
<../unauthorized.html> a <types/Purl>, calli:Purl ;
rdfs:label "unauthorized.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/unauthorized.xhtml?element=/1>) AS ?alternate)
FILTER NOT EXISTS { <../unauthorized.html> a calli:Purl }
};
INSERT {
<../layout-functions.xq> a <types/Purl>, calli:Purl ;
rdfs:label "layout-functions.xq";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<transforms/layout-functions.xq>) AS ?alternate)
FILTER NOT EXISTS { <../layout-functions.xq> a calli:Purl }
};
INSERT {
<../default-layout.xq> a <types/Purl>, calli:Purl ;
rdfs:label "default-layout.xq";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<transforms/default-layout.xq>) AS ?alternate)
FILTER NOT EXISTS { <../default-layout.xq> a calli:Purl }
};
INSERT {
<../callimachus-powered.png> a <types/Purl>, calli:Purl ;
rdfs:label "callimachus-powered.png";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<images/callimachus-powered.png>) AS ?alternate)
FILTER NOT EXISTS { <../callimachus-powered.png> a calli:Purl }
};
INSERT {
<../document-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "document-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/document-editor.html>) AS ?alternate)
FILTER NOT EXISTS { <../document-editor.html> a calli:Purl }
};
INSERT {
<../css-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "css-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#css>) AS ?alternate)
FILTER NOT EXISTS { <../css-editor.html> a calli:Purl }
};
INSERT {
<../html-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "html-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#html>) AS ?alternate)
FILTER NOT EXISTS { <../html-editor.html> a calli:Purl }
};
INSERT {
<../javascript-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "javascript-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#javascript>) AS ?alternate)
FILTER NOT EXISTS { <../javascript-editor.html> a calli:Purl }
};
INSERT {
<../sparql-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "sparql-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#sparql>) AS ?alternate)
FILTER NOT EXISTS { <../sparql-editor.html> a calli:Purl }
};
INSERT {
<../text-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "text-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html>) AS ?alternate)
FILTER NOT EXISTS { <../text-editor.html> a calli:Purl }
};
INSERT {
<../xml-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "xml-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#xml>) AS ?alternate)
FILTER NOT EXISTS { <../xml-editor.html> a calli:Purl }
};
INSERT {
<../xquery-editor.html> a <types/Purl>, calli:Purl ;
rdfs:label "xquery-editor.html";
calli:alternate ?alternate;
calli:administrator </auth/groups/super>;
calli:reader </auth/groups/public> .
} WHERE {
BIND (str(<pages/text-editor.html#xquery>) AS ?alternate)
FILTER NOT EXISTS { <../xquery-editor.html> a calli:Purl }
};
################################
# Authorization and Groups
################################
INSERT {
</auth/> calli:hasComponent </auth/invited-users/>.
</auth/invited-users/> a <types/Folder>, calli:Folder;
rdfs:label "invited users";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/invited-users/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/digest-users/>.
</auth/digest-users/> a <types/Folder>, calli:Folder;
rdfs:label "digest users";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/digest-users/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/secrets/>.
</auth/secrets/> a <types/Folder>, calli:Folder;
rdfs:label "secrets";
calli:editor </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/secrets/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/credentials/>.
</auth/credentials/> a <types/Folder>, calli:Folder;
rdfs:label "credentials";
calli:editor </auth/groups/admin>.
} WHERE {
FILTER NOT EXISTS { </auth/credentials/> a calli:Folder }
};
INSERT {
</auth/> calli:hasComponent </auth/groups/>.
</auth/groups/> a <types/Folder>, calli:Folder;
rdfs:label "groups";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>;
calli:hasComponent
</auth/groups/super>,
</auth/groups/admin>,
</auth/groups/power>,
</auth/groups/staff>,
</auth/groups/users>,
</auth/groups/everyone>,
</auth/groups/system>,
</auth/groups/public>.
</auth/groups/super> a calli:Party, calli:Group, <types/Group>;
rdfs:label "super";
rdfs:comment "The user accounts in this group have heightened privileges to change or patch the system itself".
</auth/groups/admin> a calli:Party, calli:Group, <types/Group>;
rdfs:label "admin";
rdfs:comment "Members of this group have the ability to edit other user accounts and access to modify the underlying data store";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/power> a calli:Party, calli:Group, <types/Group>;
rdfs:label "power";
rdfs:comment "Members of this group can access all data in the underlying data store";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/staff> a calli:Party, calli:Group, <types/Group>;
rdfs:label "staff";
rdfs:comment "Members of this group can design websites and develop applications";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/users> a calli:Party, calli:Group, <types/Group>;
rdfs:label "users";
rdfs:comment "Members of this group can view, discuss, document, link, and upload binary resources";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/everyone> a calli:Party, calli:Domain, <types/Domain>;
rdfs:label "everyone";
rdfs:comment "A virtual group of all authenticated agents";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>;
calli:everyoneFrom ".".
</auth/groups/system> a calli:Party, calli:Domain, <types/Domain>;
rdfs:label "system";
rdfs:comment "The local computer or computer systems is the member of this domain";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>.
</auth/groups/public> a calli:Party, calli:Domain, <types/Domain>;
rdfs:label "public";
rdfs:comment "A virtual group of all agents";
calli:subscriber </auth/groups/power>;
calli:administrator </auth/groups/admin>;
calli:anonymousFrom ".".
} WHERE {
FILTER NOT EXISTS { </auth/groups/> a calli:Folder }
};
|
# frozen_string_literal: true
module Authlogic
module Session
# Between these callbacks and the configuration, this is the contract between me and
# you to safely modify Authlogic's behavior. I will do everything I can to make sure
# these do not change.
#
# Check out the sub modules of Authlogic::Session. They are very concise, clear, and
# to the point. More importantly they use the same API that you would use to extend
# Authlogic. That being said, they are great examples of how to extend Authlogic and
# add / modify behavior to Authlogic. These modules could easily be pulled out into
# their own plugin and become an "add on" without any change.
#
# Now to the point of this module. Just like in ActiveRecord you have before_save,
# before_validation, etc. You have similar callbacks with Authlogic, see the METHODS
# constant below. The order of execution is as follows:
#
# before_persisting
# persist
# after_persisting
# [save record if record.changed?]
#
# before_validation
# before_validation_on_create
# before_validation_on_update
# validate
# after_validation_on_update
# after_validation_on_create
# after_validation
# [save record if record.changed?]
#
# before_save
# before_create
# before_update
# after_update
# after_create
# after_save
# [save record if record.changed?]
#
# before_destroy
# [save record if record.changed?]
# destroy
# after_destroy
#
# Notice the "save record if changed?" lines above. This helps with performance. If
# you need to make changes to the associated record, there is no need to save the
# record, Authlogic will do it for you. This allows multiple modules to modify the
# record and execute as few queries as possible.
#
# **WARNING**: unlike ActiveRecord, these callbacks must be set up on the class level:
#
# class UserSession < Authlogic::Session::Base
# before_validation :my_method
# validate :another_method
# # ..etc
# end
#
# You can NOT define a "before_validation" method, this is bad practice and does not
# allow Authlogic to extend properly with multiple extensions. Please ONLY use the
# method above.
module Callbacks
METHODS = %w[
before_persisting
persist
after_persisting
before_validation
before_validation_on_create
before_validation_on_update
validate
after_validation_on_update
after_validation_on_create
after_validation
before_save
before_create
before_update
after_update
after_create
after_save
before_destroy
after_destroy
].freeze
class << self
def included(base) #:nodoc:
base.send :include, ActiveSupport::Callbacks
define_session_callbacks(base)
define_session_callback_installation_methods(base)
end
private
# Defines the "callback installation methods". Other modules will use
# these class methods to install their callbacks. Examples:
#
# ```
# # session/timeout.rb, in `included`
# before_persisting :reset_stale_state
#
# # session/password.rb, in `included`
# validate :validate_by_password, if: :authenticating_with_password?
# ```
def define_session_callback_installation_methods(base)
METHODS.each do |method|
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.#{method}(*filter_list, &block)
set_callback(:#{method}, *filter_list, &block)
end
EOS
end
end
# Defines session life cycle events that support callbacks.
def define_session_callbacks(base)
if Gem::Version.new(ActiveSupport::VERSION::STRING) >= Gem::Version.new("5")
base.define_callbacks(
*METHODS,
terminator: ->(_target, result_lambda) { result_lambda.call == false }
)
base.define_callbacks(
"persist",
terminator: ->(_target, result_lambda) { result_lambda.call == true }
)
else
base.define_callbacks(
*METHODS,
terminator: ->(_target, result) { result == false }
)
base.define_callbacks(
"persist",
terminator: ->(_target, result) { result == true }
)
end
end
end
METHODS.each do |method|
class_eval(
<<-EOS, __FILE__, __LINE__ + 1
def #{method}
run_callbacks(:#{method})
end
EOS
)
end
def save_record(alternate_record = nil)
r = alternate_record || record
if r&.changed? && !r.readonly?
r.save_without_session_maintenance(validate: false)
end
end
end
end
end
Docs: Fix incorrect list of callbacks
The METHODS array below does not contain 'destroy'. So, it is not
a callback.
# frozen_string_literal: true
module Authlogic
module Session
# Between these callbacks and the configuration, this is the contract between me and
# you to safely modify Authlogic's behavior. I will do everything I can to make sure
# these do not change.
#
# Check out the sub modules of Authlogic::Session. They are very concise, clear, and
# to the point. More importantly they use the same API that you would use to extend
# Authlogic. That being said, they are great examples of how to extend Authlogic and
# add / modify behavior to Authlogic. These modules could easily be pulled out into
# their own plugin and become an "add on" without any change.
#
# Now to the point of this module. Just like in ActiveRecord you have before_save,
# before_validation, etc. You have similar callbacks with Authlogic, see the METHODS
# constant below. The order of execution is as follows:
#
# before_persisting
# persist
# after_persisting
# [save record if record.changed?]
#
# before_validation
# before_validation_on_create
# before_validation_on_update
# validate
# after_validation_on_update
# after_validation_on_create
# after_validation
# [save record if record.changed?]
#
# before_save
# before_create
# before_update
# after_update
# after_create
# after_save
# [save record if record.changed?]
#
# before_destroy
# [save record if record.changed?]
# after_destroy
#
# Notice the "save record if changed?" lines above. This helps with performance. If
# you need to make changes to the associated record, there is no need to save the
# record, Authlogic will do it for you. This allows multiple modules to modify the
# record and execute as few queries as possible.
#
# **WARNING**: unlike ActiveRecord, these callbacks must be set up on the class level:
#
# class UserSession < Authlogic::Session::Base
# before_validation :my_method
# validate :another_method
# # ..etc
# end
#
# You can NOT define a "before_validation" method, this is bad practice and does not
# allow Authlogic to extend properly with multiple extensions. Please ONLY use the
# method above.
module Callbacks
METHODS = %w[
before_persisting
persist
after_persisting
before_validation
before_validation_on_create
before_validation_on_update
validate
after_validation_on_update
after_validation_on_create
after_validation
before_save
before_create
before_update
after_update
after_create
after_save
before_destroy
after_destroy
].freeze
class << self
def included(base) #:nodoc:
base.send :include, ActiveSupport::Callbacks
define_session_callbacks(base)
define_session_callback_installation_methods(base)
end
private
# Defines the "callback installation methods". Other modules will use
# these class methods to install their callbacks. Examples:
#
# ```
# # session/timeout.rb, in `included`
# before_persisting :reset_stale_state
#
# # session/password.rb, in `included`
# validate :validate_by_password, if: :authenticating_with_password?
# ```
def define_session_callback_installation_methods(base)
METHODS.each do |method|
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.#{method}(*filter_list, &block)
set_callback(:#{method}, *filter_list, &block)
end
EOS
end
end
# Defines session life cycle events that support callbacks.
def define_session_callbacks(base)
if Gem::Version.new(ActiveSupport::VERSION::STRING) >= Gem::Version.new("5")
base.define_callbacks(
*METHODS,
terminator: ->(_target, result_lambda) { result_lambda.call == false }
)
base.define_callbacks(
"persist",
terminator: ->(_target, result_lambda) { result_lambda.call == true }
)
else
base.define_callbacks(
*METHODS,
terminator: ->(_target, result) { result == false }
)
base.define_callbacks(
"persist",
terminator: ->(_target, result) { result == true }
)
end
end
end
METHODS.each do |method|
class_eval(
<<-EOS, __FILE__, __LINE__ + 1
def #{method}
run_callbacks(:#{method})
end
EOS
)
end
def save_record(alternate_record = nil)
r = alternate_record || record
if r&.changed? && !r.readonly?
r.save_without_session_maintenance(validate: false)
end
end
end
end
end
|
require 'ox'
module Bibliothecary
module Parsers
class Maven
include Bibliothecary::Analyser
# e.g. "annotationProcessor - Annotation processors and their dependencies for source set 'main'."
GRADLE_TYPE_REGEX = /^(\w+)/
# "| \\--- com.google.guava:guava:23.5-jre (*)"
GRADLE_DEP_REGEX = /(\+---|\\---){1}/
ANSI_MATCHER = '(\[)?\033(\[)?[;?\d]*[\dA-Za-z]([\];])?'
def self.mapping
{
match_filename("ivy.xml", case_insensitive: true) => {
kind: 'manifest',
parser: :parse_ivy_manifest
},
match_filename("pom.xml", case_insensitive: true) => {
kind: 'manifest',
parser: :parse_pom_manifest
},
match_filename("build.gradle", case_insensitive: true) => {
kind: 'manifest',
parser: :parse_gradle
},
match_extension(".xml", case_insensitive: true) => {
content_matcher: :ivy_report?,
kind: 'lockfile',
parser: :parse_ivy_report
},
match_filename("gradle-dependencies-q.txt", case_insensitive: true) => {
kind: 'lockfile',
parser: :parse_gradle_resolved
},
match_filename("maven-resolved-dependencies.txt", case_insensitive: true) => {
kind: 'lockfile',
parser: :parse_maven_resolved
}
}
end
def self.parse_ivy_manifest(file_contents)
manifest = Ox.parse file_contents
manifest.dependencies.locate('dependency').map do |dependency|
attrs = dependency.attributes
{
name: "#{attrs[:org]}:#{attrs[:name]}",
requirement: attrs[:rev],
type: 'runtime'
}
end
end
def self.ivy_report?(file_contents)
doc = Ox.parse file_contents
root = doc&.locate("ivy-report")&.first
return !root.nil?
rescue Exception => e # rubocop:disable Lint/RescueException
# We rescue exception here since native libs can throw a non-StandardError
# We don't want to throw errors during the matching phase, only during
# parsing after we match.
false
end
def self.parse_ivy_report(file_contents)
doc = Ox.parse file_contents
root = doc.locate("ivy-report").first
raise "ivy-report document does not have ivy-report at the root" if root.nil?
info = doc.locate("ivy-report/info").first
raise "ivy-report document lacks <info> element" if info.nil?
type = info.attributes[:conf]
type = "unknown" if type.nil?
modules = doc.locate("ivy-report/dependencies/module")
modules.map do |mod|
attrs = mod.attributes
org = attrs[:organisation]
name = attrs[:name]
version = mod.locate('revision').first&.attributes[:name]
next nil if org.nil? or name.nil? or version.nil?
{
name: "#{org}:#{name}",
requirement: version,
type: type
}
end.compact
end
def self.parse_gradle_resolved(file_contents)
type = nil
file_contents.split("\n").map do |line|
type_match = GRADLE_TYPE_REGEX.match(line)
type = type_match.captures[0] if type_match
gradle_dep_match = GRADLE_DEP_REGEX.match(line)
next unless gradle_dep_match
split = gradle_dep_match.captures[0]
# org.springframework.boot:spring-boot-starter-web:2.1.0.M3 (*)
# Lines can end with (n) or (*) to indicate that something was not resolved (n) or resolved previously (*).
dep = line.split(split)[1].sub(/\(n\)$/, "").sub(/\(\*\)$/,"").strip.split(":")
version = dep[-1]
version = version.split("->")[-1].strip if line.include?("->")
{
name: dep[0, dep.length - 1].join(":"),
requirement: version,
type: type
}
end.compact.uniq {|item| [item[:name], item[:requirement], item[:type]]}
end
def self.parse_maven_resolved(file_contents)
file_contents
.gsub(/#{ANSI_MATCHER}/, '')
.split("\n")
.map(&method(:parse_resolved_dep_line))
.compact
.uniq {|item| [item[:name], item[:requirement], item[:type]]}
end
def self.parse_resolved_dep_line(line)
dep_parts = line.strip.split(":")
return nil unless dep_parts.length == 5
# org.springframework.boot:spring-boot-starter-web:jar:2.0.3.RELEASE:compile[36m -- module spring.boot.starter.web[0;1m [auto][m
{
name: dep_parts[0, 2].join(":"),
requirement: dep_parts[3],
type: dep_parts[4].split("--").first.strip
}
end
def self.parse_pom_manifest(file_contents, parent_properties = {})
manifest = Ox.parse file_contents
xml = manifest.respond_to?('project') ? manifest.project : manifest
[].tap do |deps|
['dependencies/dependency', 'dependencyManagement/dependencies/dependency'].each do |deps_xpath|
xml.locate(deps_xpath).each do |dep|
deps.push({
name: "#{extract_pom_dep_info(xml, dep, 'groupId', parent_properties)}:#{extract_pom_dep_info(xml, dep, 'artifactId', parent_properties)}",
requirement: extract_pom_dep_info(xml, dep, 'version', parent_properties),
type: extract_pom_dep_info(xml, dep, 'scope', parent_properties) || 'runtime'
})
end
end
end
end
def self.parse_gradle(manifest)
response = Typhoeus.post("#{Bibliothecary.configuration.gradle_parser_host}/parse", body: manifest)
raise Bibliothecary::RemoteParsingError.new("Http Error #{response.response_code} when contacting: #{Bibliothecary.configuration.gradle_parser_host}/parse", response.response_code) unless response.success?
json = JSON.parse(response.body)
return [] unless json['dependencies']
json['dependencies'].map do |dependency|
name = [dependency["group"], dependency["name"]].join(':')
next unless name =~ (/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(\.[A-Za-z0-9_-])?\:[A-Za-z0-9_-]/)
{
name: name,
requirement: dependency["version"],
type: dependency["type"]
}
end.compact
end
def self.extract_pom_info(xml, location, parent_properties = {})
extract_pom_dep_info(xml, xml, location, parent_properties)
end
def self.extract_pom_dep_info(xml, dependency, name, parent_properties = {})
field = dependency.locate(name).first
return nil if field.nil?
value = field.nodes.first
match = value.match(/^\$\{(.+)\}/)
if match
# the xml root is <project> so lookup the non property name in the xml
# this converts ${project/group.id} -> ${group/id}
non_prop_name = match[1].gsub('.', '/').gsub('project/', '')
return value if !xml.respond_to?('properties') && parent_properties.empty? && !xml.locate(non_prop_name)
prop_field = xml.properties.locate(match[1]).first
parent_prop = parent_properties[match[1]]
if prop_field
return prop_field.nodes.first
elsif parent_prop
return parent_prop
elsif xml.locate(non_prop_name).first
# see if the value to look up is a field under the project
# examples are ${project.groupId} or ${project.version}
return xml.locate(non_prop_name).first.nodes.first
else
return value
end
else
return value
end
end
end
end
end
use regex directly instead of string
require 'ox'
module Bibliothecary
module Parsers
class Maven
include Bibliothecary::Analyser
# e.g. "annotationProcessor - Annotation processors and their dependencies for source set 'main'."
GRADLE_TYPE_REGEX = /^(\w+)/
# "| \\--- com.google.guava:guava:23.5-jre (*)"
GRADLE_DEP_REGEX = /(\+---|\\---){1}/
ANSI_MATCHER = /(\[)?\033(\[)?[;?\d]*[\dA-Za-z]([\];])?/
def self.mapping
{
match_filename("ivy.xml", case_insensitive: true) => {
kind: 'manifest',
parser: :parse_ivy_manifest
},
match_filename("pom.xml", case_insensitive: true) => {
kind: 'manifest',
parser: :parse_pom_manifest
},
match_filename("build.gradle", case_insensitive: true) => {
kind: 'manifest',
parser: :parse_gradle
},
match_extension(".xml", case_insensitive: true) => {
content_matcher: :ivy_report?,
kind: 'lockfile',
parser: :parse_ivy_report
},
match_filename("gradle-dependencies-q.txt", case_insensitive: true) => {
kind: 'lockfile',
parser: :parse_gradle_resolved
},
match_filename("maven-resolved-dependencies.txt", case_insensitive: true) => {
kind: 'lockfile',
parser: :parse_maven_resolved
}
}
end
def self.parse_ivy_manifest(file_contents)
manifest = Ox.parse file_contents
manifest.dependencies.locate('dependency').map do |dependency|
attrs = dependency.attributes
{
name: "#{attrs[:org]}:#{attrs[:name]}",
requirement: attrs[:rev],
type: 'runtime'
}
end
end
def self.ivy_report?(file_contents)
doc = Ox.parse file_contents
root = doc&.locate("ivy-report")&.first
return !root.nil?
rescue Exception => e # rubocop:disable Lint/RescueException
# We rescue exception here since native libs can throw a non-StandardError
# We don't want to throw errors during the matching phase, only during
# parsing after we match.
false
end
def self.parse_ivy_report(file_contents)
doc = Ox.parse file_contents
root = doc.locate("ivy-report").first
raise "ivy-report document does not have ivy-report at the root" if root.nil?
info = doc.locate("ivy-report/info").first
raise "ivy-report document lacks <info> element" if info.nil?
type = info.attributes[:conf]
type = "unknown" if type.nil?
modules = doc.locate("ivy-report/dependencies/module")
modules.map do |mod|
attrs = mod.attributes
org = attrs[:organisation]
name = attrs[:name]
version = mod.locate('revision').first&.attributes[:name]
next nil if org.nil? or name.nil? or version.nil?
{
name: "#{org}:#{name}",
requirement: version,
type: type
}
end.compact
end
def self.parse_gradle_resolved(file_contents)
type = nil
file_contents.split("\n").map do |line|
type_match = GRADLE_TYPE_REGEX.match(line)
type = type_match.captures[0] if type_match
gradle_dep_match = GRADLE_DEP_REGEX.match(line)
next unless gradle_dep_match
split = gradle_dep_match.captures[0]
# org.springframework.boot:spring-boot-starter-web:2.1.0.M3 (*)
# Lines can end with (n) or (*) to indicate that something was not resolved (n) or resolved previously (*).
dep = line.split(split)[1].sub(/\(n\)$/, "").sub(/\(\*\)$/,"").strip.split(":")
version = dep[-1]
version = version.split("->")[-1].strip if line.include?("->")
{
name: dep[0, dep.length - 1].join(":"),
requirement: version,
type: type
}
end.compact.uniq {|item| [item[:name], item[:requirement], item[:type]]}
end
def self.parse_maven_resolved(file_contents)
file_contents
.gsub(ANSI_MATCHER, '')
.split("\n")
.map(&method(:parse_resolved_dep_line))
.compact
.uniq {|item| [item[:name], item[:requirement], item[:type]]}
end
def self.parse_resolved_dep_line(line)
dep_parts = line.strip.split(":")
return nil unless dep_parts.length == 5
# org.springframework.boot:spring-boot-starter-web:jar:2.0.3.RELEASE:compile[36m -- module spring.boot.starter.web[0;1m [auto][m
{
name: dep_parts[0, 2].join(":"),
requirement: dep_parts[3],
type: dep_parts[4].split("--").first.strip
}
end
def self.parse_pom_manifest(file_contents, parent_properties = {})
manifest = Ox.parse file_contents
xml = manifest.respond_to?('project') ? manifest.project : manifest
[].tap do |deps|
['dependencies/dependency', 'dependencyManagement/dependencies/dependency'].each do |deps_xpath|
xml.locate(deps_xpath).each do |dep|
deps.push({
name: "#{extract_pom_dep_info(xml, dep, 'groupId', parent_properties)}:#{extract_pom_dep_info(xml, dep, 'artifactId', parent_properties)}",
requirement: extract_pom_dep_info(xml, dep, 'version', parent_properties),
type: extract_pom_dep_info(xml, dep, 'scope', parent_properties) || 'runtime'
})
end
end
end
end
def self.parse_gradle(manifest)
response = Typhoeus.post("#{Bibliothecary.configuration.gradle_parser_host}/parse", body: manifest)
raise Bibliothecary::RemoteParsingError.new("Http Error #{response.response_code} when contacting: #{Bibliothecary.configuration.gradle_parser_host}/parse", response.response_code) unless response.success?
json = JSON.parse(response.body)
return [] unless json['dependencies']
json['dependencies'].map do |dependency|
name = [dependency["group"], dependency["name"]].join(':')
next unless name =~ (/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(\.[A-Za-z0-9_-])?\:[A-Za-z0-9_-]/)
{
name: name,
requirement: dependency["version"],
type: dependency["type"]
}
end.compact
end
def self.extract_pom_info(xml, location, parent_properties = {})
extract_pom_dep_info(xml, xml, location, parent_properties)
end
def self.extract_pom_dep_info(xml, dependency, name, parent_properties = {})
field = dependency.locate(name).first
return nil if field.nil?
value = field.nodes.first
match = value.match(/^\$\{(.+)\}/)
if match
# the xml root is <project> so lookup the non property name in the xml
# this converts ${project/group.id} -> ${group/id}
non_prop_name = match[1].gsub('.', '/').gsub('project/', '')
return value if !xml.respond_to?('properties') && parent_properties.empty? && !xml.locate(non_prop_name)
prop_field = xml.properties.locate(match[1]).first
parent_prop = parent_properties[match[1]]
if prop_field
return prop_field.nodes.first
elsif parent_prop
return parent_prop
elsif xml.locate(non_prop_name).first
# see if the value to look up is a field under the project
# examples are ${project.groupId} or ${project.version}
return xml.locate(non_prop_name).first.nodes.first
else
return value
end
else
return value
end
end
end
end
end
|
require 'cinch'
require 'json'
require 'rest_client'
require 'bunny'
class Peppermill::PepperShaker
include Cinch::Plugin
match /^\?s ([\w\s\d\.\(\)'\-_&\+:]+),([\+\w\s\d\.\(\)'\/\-_&:]+)$/, {
:use_prefix => false,
:method => :lookup_multi
}
match /^\?s ([\w\s\d\.\(\)'\-_&\+:]+)$/, {
:use_prefix => false,
:method => :lookup_single
}
match /^!update_champions$/,{
:use_prefix => false,
:method => :update_champions
}
match /^`s$/,{
:use_prefix => false,
:method => :lookup_match
}
def initialize(*args)
super
conn = Bunny.new
conn.start
@ch = conn.create_channel
@queue = @ch.queue('com.itsdamiya.tradecaravan.update_stats', :auto_delete => true)
@exchange = @ch.default_exchange
@queue.subscribe do |delivery_info, metadata, payload|
update_stats_received(delivery_info, metadata, payload)
end
@champions = retrieve_champs_list
@admins = %w(Damiya!~damiya@a.gay.wizard.irl)
end
def update_stats_received(delivery_info, metadata, payload)
return unless payload=='WEBSOCKET_UPDATED'
data = retrieve_fight_ajax
return unless data['status']=='open'
secret_sauce = get_the_secret_sauce
match_message, rematch_message = build_multi_message(secret_sauce['player1name'], secret_sauce['player2name'])
channel = Channel('#saltybet')
channel.msg(match_message)
if rematch_message
channel.msg(rematch_message)
end
end
def check_user(prefix)
@admins.include?prefix
end
def update_champions(m)
return unless check_user(m.prefix)
@champions = retrieve_champs_list
m.reply("Updated champions list: #{@champions.length}")
end
def lookup_single(message, name)
reply = lookup_champ(name)
hightower_link = build_hightower_link(name, nil)
if hightower_link
reply += " | HT: #{Format(:bold, hightower_link)}"
end
message.reply("#{reply}")
end
#TODO: Refactor this with the new websocket. Needs more DRY
def lookup_match(message)
secret_sauce = get_the_secret_sauce
lookup_multi(message,secret_sauce['player1name'],secret_sauce['player2name'])
end
def lookup_multi(message, champ_one_name, champ_two_name)
reply, rematch_string = build_multi_message(champ_one_name, champ_two_name)
message.reply("#{reply}")
if rematch_string
message.reply(rematch_string)
end
end
def build_multi_message(champ_one_name, champ_two_name)
reply, rematch_string = lookup_fight(champ_one_name, champ_two_name)
hightower_link = build_hightower_link(champ_one_name, champ_two_name)
if hightower_link
reply += " | HT: #{Format(:bold, hightower_link)}"
end
return reply, rematch_string
end
private
def build_hightower_link(champ_one_name, champ_two_name = nil)
champ_one = get_champ_id(champ_one_name)
link = nil
if champ_one == nil
return nil
end
if champ_two_name
champ_two = get_champ_id(champ_two_name)
if champ_two
link = "http://apeppershaker.com/api/v1/f/#{champ_one}/#{champ_two}"
end
else
link = "http://apeppershaker.com/api/v1/c/#{champ_one}"
end
link
end
def lookup_fight(champ_one_name, champ_two_name)
champ_one_name = champ_one_name.downcase.strip
champ_two_name = champ_two_name.downcase.strip
fight_string = ''
rematch_string = nil
fight_obj = retrieve_fight(get_champ_id(champ_one_name), get_champ_id(champ_two_name))
if fight_obj['left']==nil
fight_string += name_not_found(champ_one_name)
else
fight_string += parse_champ(fight_obj['left'])
end
fight_string += ' | '
if fight_obj['right']==nil
fight_string += name_not_found(champ_two_name)
else
fight_string += parse_champ(fight_obj['right'])
end
if fight_obj['rematch']
rematch_string = parse_rematch(fight_obj['rematch'], champ_one_name, champ_two_name)
end
return fight_string, rematch_string
end
def parse_rematch(rematch_obj, champ_one_name, champ_two_name)
rematch_string = Format(:bold, 'Rematch! ')
if rematch_obj['left_has_won'] && rematch_obj['right_has_won']
rematch_string += Format(:bold, :red, champ_one_name) + ' and ' +
Format(:bold, :red, champ_two_name) + ' have both beaten the other.'
elsif rematch_obj['left_has_won']
rematch_string += Format(:bold, :green, champ_one_name) + ' has beaten ' +
Format(:bold, :red, champ_two_name)
elsif rematch_obj['right_has_won']
rematch_string += Format(:bold, :green, champ_two_name) + ' has beaten ' +
Format(:bold, :red, champ_one_name)
end
rematch_string
end
def lookup_champ(name)
name = name.downcase.strip
reply = name_not_found(name)
champ_id = get_champ_id(name)
if champ_id
reply = parse_champ(retrieve_champ(champ_id))
end
reply
end
def parse_champ(champ_obj)
winrate = get_winrate(champ_obj)
Format(:bold, "#{champ_obj['name']}") + ': [E: ' + color_elo(champ_obj) +
'] [' + Format(:bold, :green, "#{champ_obj['wins']}") + 'W/' + Format(:bold, :red, "#{champ_obj['losses']}") + 'L] (' +
Format(:bold, "#{winrate}%") + ' out of ' + Format(:bold, "#{get_total_matches(champ_obj)}") + ')'
end
def get_total_matches(obj)
obj['wins'] + obj['losses']
end
def color_elo(obj)
colored_elo = ''
elo = obj['elo']
if elo < 300
colored_elo = Format(:red, :bold, elo.to_s)
elsif elo >= 300 && elo < 500
colored_elo = Format(:orange, :bold, elo.to_s)
elsif elo >= 500 && elo < 700
colored_elo = Format(:green, :bold, elo.to_s)
elsif elo >= 700 && elo < 850
colored_elo = Format(:lime, :bold, elo.to_s)
elsif elo >= 850
colored_elo = Format(:lime, :bold, :underline, '-'+elo.to_s+'-')
end
colored_elo
end
def get_champ_id(name)
name = name.downcase.strip
name_apostrophe = name.gsub(/ /, '\'')
name_underscore = name.gsub(/ /, '_')
id = nil
if @champions[name]
id = @champions[name]
elsif @champions[name_apostrophe]
id = @champions[name_apostrophe]
elsif @champions[name_underscore]
id = @champions[name_underscore]
end
id
end
def retrieve_fight(id_one, id_two)
if !id_one
id_one = 99999
end
if !id_two
id_two = 99999
end
JSON.parse(RestClient.get "http://apeppershaker.com/api/v1/fight/by_id/#{id_one}/#{id_two}")
end
def retrieve_fight_ajax
JSON.parse(RestClient.get 'http://www.saltybet.com/state.json')
end
def retrieve_champ(id)
JSON.parse(RestClient.get "http://apeppershaker.com/api/v1/champion/#{id}")
end
def retrieve_champs_list
JSON.parse(RestClient.get 'http://apeppershaker.com/api/v1/champion/list')
end
def get_the_secret_sauce
JSON.parse(RestClient.get ENV['SECRET_SAUCE'])
end
def get_winrate(champ)
losses = champ['losses'].to_f
wins = champ['wins'].to_f
if losses == 0 && wins > 0
winrate = 100
elsif wins == 0
winrate = 0
else
winrate = ((wins/(losses+wins)).to_f*100).round(1)
end
winrate
end
def name_not_found(name)
Format(:bold, "#{name}") + ' was not found in the database. Check your spelling!'
end
end
Comment out `s
require 'cinch'
require 'json'
require 'rest_client'
require 'bunny'
class Peppermill::PepperShaker
include Cinch::Plugin
match /^\?s ([\w\s\d\.\(\)'\-_&\+:]+),([\+\w\s\d\.\(\)'\/\-_&:]+)$/, {
:use_prefix => false,
:method => :lookup_multi
}
match /^\?s ([\w\s\d\.\(\)'\-_&\+:]+)$/, {
:use_prefix => false,
:method => :lookup_single
}
match /^!update_champions$/,{
:use_prefix => false,
:method => :update_champions
}
#match /^`s$/,{
# :use_prefix => false,
# :method => :lookup_match
#}
def initialize(*args)
super
conn = Bunny.new
conn.start
@ch = conn.create_channel
@queue = @ch.queue('com.itsdamiya.tradecaravan.update_stats', :auto_delete => true)
@exchange = @ch.default_exchange
@queue.subscribe do |delivery_info, metadata, payload|
update_stats_received(delivery_info, metadata, payload)
end
@champions = retrieve_champs_list
@admins = %w(Damiya!~damiya@a.gay.wizard.irl)
end
def update_stats_received(delivery_info, metadata, payload)
return unless payload=='WEBSOCKET_UPDATED'
data = retrieve_fight_ajax
return unless data['status']=='open'
secret_sauce = get_the_secret_sauce
match_message, rematch_message = build_multi_message(secret_sauce['player1name'], secret_sauce['player2name'])
channel = Channel('#saltybet')
channel.msg(match_message)
if rematch_message
channel.msg(rematch_message)
end
end
def check_user(prefix)
@admins.include?prefix
end
def update_champions(m)
return unless check_user(m.prefix)
@champions = retrieve_champs_list
m.reply("Updated champions list: #{@champions.length}")
end
def lookup_single(message, name)
reply = lookup_champ(name)
hightower_link = build_hightower_link(name, nil)
if hightower_link
reply += " | HT: #{Format(:bold, hightower_link)}"
end
message.reply("#{reply}")
end
#TODO: Refactor this with the new websocket. Needs more DRY
def lookup_match(message)
secret_sauce = get_the_secret_sauce
lookup_multi(message,secret_sauce['player1name'],secret_sauce['player2name'])
end
def lookup_multi(message, champ_one_name, champ_two_name)
reply, rematch_string = build_multi_message(champ_one_name, champ_two_name)
message.reply("#{reply}")
if rematch_string
message.reply(rematch_string)
end
end
def build_multi_message(champ_one_name, champ_two_name)
reply, rematch_string = lookup_fight(champ_one_name, champ_two_name)
hightower_link = build_hightower_link(champ_one_name, champ_two_name)
if hightower_link
reply += " | HT: #{Format(:bold, hightower_link)}"
end
return reply, rematch_string
end
private
def build_hightower_link(champ_one_name, champ_two_name = nil)
champ_one = get_champ_id(champ_one_name)
link = nil
if champ_one == nil
return nil
end
if champ_two_name
champ_two = get_champ_id(champ_two_name)
if champ_two
link = "http://apeppershaker.com/api/v1/f/#{champ_one}/#{champ_two}"
end
else
link = "http://apeppershaker.com/api/v1/c/#{champ_one}"
end
link
end
def lookup_fight(champ_one_name, champ_two_name)
champ_one_name = champ_one_name.downcase.strip
champ_two_name = champ_two_name.downcase.strip
fight_string = ''
rematch_string = nil
fight_obj = retrieve_fight(get_champ_id(champ_one_name), get_champ_id(champ_two_name))
if fight_obj['left']==nil
fight_string += name_not_found(champ_one_name)
else
fight_string += parse_champ(fight_obj['left'])
end
fight_string += ' | '
if fight_obj['right']==nil
fight_string += name_not_found(champ_two_name)
else
fight_string += parse_champ(fight_obj['right'])
end
if fight_obj['rematch']
rematch_string = parse_rematch(fight_obj['rematch'], champ_one_name, champ_two_name)
end
return fight_string, rematch_string
end
def parse_rematch(rematch_obj, champ_one_name, champ_two_name)
rematch_string = Format(:bold, 'Rematch! ')
if rematch_obj['left_has_won'] && rematch_obj['right_has_won']
rematch_string += Format(:bold, :red, champ_one_name) + ' and ' +
Format(:bold, :red, champ_two_name) + ' have both beaten the other.'
elsif rematch_obj['left_has_won']
rematch_string += Format(:bold, :green, champ_one_name) + ' has beaten ' +
Format(:bold, :red, champ_two_name)
elsif rematch_obj['right_has_won']
rematch_string += Format(:bold, :green, champ_two_name) + ' has beaten ' +
Format(:bold, :red, champ_one_name)
end
rematch_string
end
def lookup_champ(name)
name = name.downcase.strip
reply = name_not_found(name)
champ_id = get_champ_id(name)
if champ_id
reply = parse_champ(retrieve_champ(champ_id))
end
reply
end
def parse_champ(champ_obj)
winrate = get_winrate(champ_obj)
Format(:bold, "#{champ_obj['name']}") + ': [E: ' + color_elo(champ_obj) +
'] [' + Format(:bold, :green, "#{champ_obj['wins']}") + 'W/' + Format(:bold, :red, "#{champ_obj['losses']}") + 'L] (' +
Format(:bold, "#{winrate}%") + ' out of ' + Format(:bold, "#{get_total_matches(champ_obj)}") + ')'
end
def get_total_matches(obj)
obj['wins'] + obj['losses']
end
def color_elo(obj)
colored_elo = ''
elo = obj['elo']
if elo < 300
colored_elo = Format(:red, :bold, elo.to_s)
elsif elo >= 300 && elo < 500
colored_elo = Format(:orange, :bold, elo.to_s)
elsif elo >= 500 && elo < 700
colored_elo = Format(:green, :bold, elo.to_s)
elsif elo >= 700 && elo < 850
colored_elo = Format(:lime, :bold, elo.to_s)
elsif elo >= 850
colored_elo = Format(:lime, :bold, :underline, '-'+elo.to_s+'-')
end
colored_elo
end
def get_champ_id(name)
name = name.downcase.strip
name_apostrophe = name.gsub(/ /, '\'')
name_underscore = name.gsub(/ /, '_')
id = nil
if @champions[name]
id = @champions[name]
elsif @champions[name_apostrophe]
id = @champions[name_apostrophe]
elsif @champions[name_underscore]
id = @champions[name_underscore]
end
id
end
def retrieve_fight(id_one, id_two)
if !id_one
id_one = 99999
end
if !id_two
id_two = 99999
end
JSON.parse(RestClient.get "http://apeppershaker.com/api/v1/fight/by_id/#{id_one}/#{id_two}")
end
def retrieve_fight_ajax
JSON.parse(RestClient.get 'http://www.saltybet.com/state.json')
end
def retrieve_champ(id)
JSON.parse(RestClient.get "http://apeppershaker.com/api/v1/champion/#{id}")
end
def retrieve_champs_list
JSON.parse(RestClient.get 'http://apeppershaker.com/api/v1/champion/list')
end
def get_the_secret_sauce
JSON.parse(RestClient.get ENV['SECRET_SAUCE'])
end
def get_winrate(champ)
losses = champ['losses'].to_f
wins = champ['wins'].to_f
if losses == 0 && wins > 0
winrate = 100
elsif wins == 0
winrate = 0
else
winrate = ((wins/(losses+wins)).to_f*100).round(1)
end
winrate
end
def name_not_found(name)
Format(:bold, "#{name}") + ' was not found in the database. Check your spelling!'
end
end
|
require "selenium/server"
require "selenium/webdriver/support/test_environment"
require "selenium/webdriver/support/jruby_test_environment"
require "selenium/webdriver/support/guards"
require "selenium/webdriver/support/helpers"
module Selenium
module WebDriver
module SpecSupport
autoload :RackServer, "selenium/webdriver/integration/support/rack_server"
end
end
end
JariBakken: Fix path to RackServer.
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@10162 07704840-8298-11de-bf8c-fd130f914ac9
require "selenium/server"
require "selenium/webdriver/support/test_environment"
require "selenium/webdriver/support/jruby_test_environment"
require "selenium/webdriver/support/guards"
require "selenium/webdriver/support/helpers"
module Selenium
module WebDriver
module SpecSupport
autoload :RackServer, "selenium/webdriver/support/rack_server"
end
end
end |
module BootstrapForm
class FormBuilder < ActionView::Helpers::FormBuilder
delegate :content_tag, to: :@template
def initialize(object_name, object, template, options, proc)
super
if options.fetch(:help, '').to_sym == :block
@help_tag = :p
@help_css = 'help-block'
else
@help_tag = :span
@help_css = 'help-inline'
end
end
%w{email_field text_field text_area password_field collection_select file_field date_select select}.each do |method_name|
define_method(method_name) do |name, *args|
options = args.extract_options!.symbolize_keys!
content_tag :div, class: "control-group#{(' error' if object.errors[name].any?)}" do
label(name, options[:label], class: 'control-label') +
content_tag(:div, class: 'controls') do
help = object.errors[name].any? ? object.errors[name].join(', ') : options[:help]
help = content_tag(@help_tag, class: @help_css) { help } if help
args << options.except(:label, :help)
if method_name == 'email_field'
content_tag(:div, content_tag(:span, content_tag(:i, nil, class:'icon-envelope'), class:'add-on') + super(name, *args), class: 'input-prepend') + help
else
super(name, *args) + help
end
end
end
end
end
def check_box(name, *args)
options = args.extract_options!.symbolize_keys!
content_tag :div, class: "control-group#{(' error' if object.errors[name].any?)}" do
content_tag(:div, class: 'controls') do
args << options.except(:label, :help)
html = super(name, *args) + ' ' + (options[:label].blank? ? object.class.human_attribute_name(name) : options[:label])
label(name, html, class: 'checkbox')
end
end
end
def actions(&block)
content_tag :div, class: "form-actions" do
block.call
end
end
def primary(name, options = {})
options.merge! class: 'btn btn-primary'
submit name, options
end
def alert_message(title, *args)
options = args.extract_options!
css = options[:class] || "alert alert-error"
if object.errors.full_messages.any?
content_tag :div, class: css do
title
end
end
end
end
end
Update form_builder.rb
module BootstrapForm
class FormBuilder < ActionView::Helpers::FormBuilder
delegate :content_tag, to: :@template
def initialize(object_name, object, template, options, proc=nil)
super
if options.fetch(:help, '').to_sym == :block
@help_tag = :p
@help_css = 'help-block'
else
@help_tag = :span
@help_css = 'help-inline'
end
end
%w{email_field text_field text_area password_field collection_select file_field date_select select}.each do |method_name|
define_method(method_name) do |name, *args|
options = args.extract_options!.symbolize_keys!
content_tag :div, class: "control-group#{(' error' if object.errors[name].any?)}" do
label(name, options[:label], class: 'control-label') +
content_tag(:div, class: 'controls') do
help = object.errors[name].any? ? object.errors[name].join(', ') : options[:help]
help = content_tag(@help_tag, class: @help_css) { help } if help
args << options.except(:label, :help)
if method_name == 'email_field'
content_tag(:div, content_tag(:span, content_tag(:i, nil, class:'icon-envelope'), class:'add-on') + super(name, *args), class: 'input-prepend') + help
else
super(name, *args) + help
end
end
end
end
end
def check_box(name, *args)
options = args.extract_options!.symbolize_keys!
content_tag :div, class: "control-group#{(' error' if object.errors[name].any?)}" do
content_tag(:div, class: 'controls') do
args << options.except(:label, :help)
html = super(name, *args) + ' ' + (options[:label].blank? ? object.class.human_attribute_name(name) : options[:label])
label(name, html, class: 'checkbox')
end
end
end
def actions(&block)
content_tag :div, class: "form-actions" do
block.call
end
end
def primary(name, options = {})
options.merge! class: 'btn btn-primary'
submit name, options
end
def alert_message(title, *args)
options = args.extract_options!
css = options[:class] || "alert alert-error"
if object.errors.full_messages.any?
content_tag :div, class: css do
title
end
end
end
end
end
|
module Capistrano
module Generals
VERSION = "0.1.4"
end
end
Version bump
module Capistrano
module Generals
VERSION = "0.1.5"
end
end
|
namespace :snapshot do
namespace :check do
desc 'Check that necessary directories exist'
task :directories do
on roles(:web) do
execute :mkdir, '-pv', fetch(:snapshot_path)
end
end
desc <<-DESC
Check if n98-magerun has been installed on the server. If not, try installing it. \
See https://github.com/netz98/n98-magerun
DESC
task :magerun do
on roles(:web) do
if test("[ -f #{fetch(:magerun_path)} ]")
# n98-magerun exists!
logger.info "n98-magerun is installed!"
else
logger.info "n98-magerun IS NOT INSTALLED! Trying to install n98-magerun via cURL within #{deploy_to}"
# try to install the n98-magerun in the :deploy_to path
within deploy_to do
execute :curl, '-sS', "#{fetch(:magerun_download_url)}", '-o', "#{fetch(:magerun_filename)}"
end
end
end
end
end
desc <<-DESC
Creates snapshot of database and saves as compressed file using the n98-magerun tool. \
See https://github.com/netz98/n98-magerun
DESC
task :create do
on roles(:web) do
within release_path do
git_sha = "#{capture("cd #{repo_path} && git rev-parse HEAD")}"
datetime = Time.now.strftime("%Y%m%d%H%M")
filename = "#{fetch(:snapshot_path)}/#{git_sha}_#{datetime}.sql.gz"
execute "#{fetch(:magerun)}", "db:dump", "--root-dir=\"#{release_path}\"", '--compression="gzip"', '--strip="@stripped"', "#{filename}"
end
end
end
end
namespace :load do
task :defaults do
# Snapshot settings
set :snapshot_path, -> { "#{fetch(:deploy_to)}/snapshots" }
# n98-magerun settings
set :magerun_filename, "n98-magerun.phar"
set :magerun_download_url, "http://files.magerun.net/n98-magerun-latest.phar"
set :magerun_path, -> { "#{fetch(:deploy_to)}/#{fetch(:magerun_filename)}" }
set :magerun, -> { "#{magerun_path}" }
end
end
Oops...forgot new SSHKit logging methods
namespace :snapshot do
namespace :check do
desc 'Check that necessary directories exist'
task :directories do
on roles(:web) do
execute :mkdir, '-pv', fetch(:snapshot_path)
end
end
desc <<-DESC
Check if n98-magerun has been installed on the server. If not, try installing it. \
See https://github.com/netz98/n98-magerun
DESC
task :magerun do
on roles(:web) do
if test("[ -f #{fetch(:magerun_path)} ]")
# n98-magerun exists!
info "n98-magerun is installed!"
else
error "n98-magerun IS NOT INSTALLED!"
info "Trying to install n98-magerun via cURL within #{deploy_to}"
# try to install the n98-magerun in the :deploy_to path
within deploy_to do
execute :curl, '-sS', "#{fetch(:magerun_download_url)}", '-o', "#{fetch(:magerun_filename)}"
end
end
end
end
end
desc <<-DESC
Creates snapshot of database and saves as compressed file using the n98-magerun tool. \
See https://github.com/netz98/n98-magerun
DESC
task :create do
on roles(:web) do
within release_path do
git_sha = "#{capture("cd #{repo_path} && git rev-parse HEAD")}"
datetime = Time.now.strftime("%Y%m%d%H%M")
filename = "#{fetch(:snapshot_path)}/#{git_sha}_#{datetime}.sql.gz"
execute "#{fetch(:magerun)}", "db:dump", "--root-dir=\"#{release_path}\"", '--compression="gzip"', '--strip="@stripped"', "#{filename}"
end
end
end
end
namespace :load do
task :defaults do
# Snapshot settings
set :snapshot_path, -> { "#{fetch(:deploy_to)}/snapshots" }
# n98-magerun settings
set :magerun_filename, "n98-magerun.phar"
set :magerun_download_url, "http://files.magerun.net/n98-magerun-latest.phar"
set :magerun_path, -> { "#{fetch(:deploy_to)}/#{fetch(:magerun_filename)}" }
set :magerun, -> { "#{magerun_path}" }
end
end
|
require 'json'
require 'nokogiri'
module Cb
class SavedSearchApi
#############################################################
## Create a Saved Search
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.create params
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_create, :body => CbSavedSearch.new(params)
json_hash = JSON.parse cb_response.response.body
saved_search = SavedSearchApi.new json_hash['SavedJobSearch']['SavedSearch']
my_api.append_api_responses user, json_hash['SavedJobSearch']
return saved_search
end
#############################################################
## Retrieve a Saved Search
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.retrieve external_id, external_user_id
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_retrieve, :body => build_retrieve_request(external_id, external_user_id)
json_hash = JSON.parse cb_response.response.body
saved_search = SavedSearchApi.new json_hash['SavedJobSearch']['SavedSearch']
my_api.append_api_responses user, json_hash['SavedJobSearch']
return saved_search
end
#############################################################
## Update a Saved Search
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.update params
result = false
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_update, :body => CbSavedSearch.new(params)
json_hash = JSON.parse cb_response.response.body
my_api.append_api_responses result, json_hash['SavedJobSearch']
if result.cb_response.status.include? 'Success'
result = true
my_api.append_api_responses result, json_hash['SavedJobSearch']
end
result
end
#############################################################
## List of Saved Search's
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.all external_user_id
result = false
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_list, :body => build_list_request(external_user_id)
json_hash = JSON.parse cb_response.response.body
my_api.append_api_responses result, json_hash['SavedJobSearch']
if result.cb_response.status.include? 'Success'
result = true
my_api.append_api_responses result, json_hash['SavedJobSearch']
end
result
end
private
def self.build_retrieve_request external_id, external_user_id
builder = Nokogiri::XML::Builder.new do
Request {
ExternalID_ external_id
ExternalUserID_ external_user_id
DeveloperKey_ Cb.configuration.dev_key
}
end
builder.to_xml
end
def self.build_list_request external_user_id
builder = Nokogiri::XML::Builder.new do
Request {
ExternalUserID_ external_user_id
DeveloperKey_ Cb.configuration.dev_key
}
end
builder.to_xml
end
end
end
Saved Search API
require 'json'
require 'nokogiri'
module Cb
class SavedSearchApi
#############################################################
## Create a Saved Search
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.create params
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_create, :body => CbSavedSearch.new(params)
json_hash = JSON.parse cb_response.response.body
saved_search = SavedSearchApi.new json_hash['SavedJobSearch']['SavedSearch']
my_api.append_api_responses saved_search, json_hash['SavedJobSearch']
return saved_search
end
#############################################################
## Retrieve a Saved Search
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.retrieve external_id, external_user_id
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_retrieve, :body => build_retrieve_request(external_id, external_user_id)
json_hash = JSON.parse cb_response.response.body
saved_search = SavedSearchApi.new json_hash['SavedJobSearch']['SavedSearch']
my_api.append_api_responses saved_search, json_hash['SavedJobSearch']
return saved_search
end
#############################################################
## Update a Saved Search
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.update params
result = false
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_update, :body => CbSavedSearch.new(params)
json_hash = JSON.parse cb_response.response.body
my_api.append_api_responses result, json_hash['SavedJobSearch']
if result.cb_response.status.include? 'Success'
result = true
my_api.append_api_responses result, json_hash['SavedJobSearch']
end
result
end
#############################################################
## List of Saved Search's
##
## For detailed information around this API please visit:
## http://api.careerbuilder.com/savedsearchinfo.aspx
#############################################################
def self.all external_id, external_user_id
my_api = Cb::Utils::Api.new
cb_response = my_api.cb_post Cb.configuration.uri_saved_search_retrieve, :body => build_retrieve_request(external_id, external_user_id)
json_hash = JSON.parse cb_response.response.body
saved_search = SavedSearchApi.new json_hash['SavedJobSearch']['SavedSearch']
my_api.append_api_responses saved_search, json_hash['SavedJobSearch']
return saved_search
end
private
def self.build_retrieve_request external_id, external_user_id
builder = Nokogiri::XML::Builder.new do
Request {
ExternalID_ external_id
ExternalUserID_ external_user_id
DeveloperKey_ Cb.configuration.dev_key
}
end
builder.to_xml
end
def self.build_list_request external_user_id
builder = Nokogiri::XML::Builder.new do
Request {
ExternalUserID_ external_user_id
DeveloperKey_ Cb.configuration.dev_key
}
end
builder.to_xml
end
end
end |
require 'chef/knife/proxmox_base'
class Chef
class Knife
class ProxmoxVmClone < Knife
include Knife::ProxmoxBase
banner "knife proxmox vm clone (options) [QEMU]"
option :vmid,
:long => "--vmid vmid",
:description => "VMID to clone"
option :name,
:long => "--name name",
:description => "Name for the new new VM"
option :pool,
:long => "--pool pool",
:description => "Pool for the new new VM"
option :storage,
:long => "--storage storage",
:description => "Target storage for full clone"
option :target,
:long => "--target node",
:description => "Node name to clone onto"
option :full,
:long => "--full",
:boolean => true,
:default => false,
:description => "Create full copy of all disks."
def run
connection
[:vmid].each do |param|
check_config_parameter(param)
end
vm_config = Hash.new
vm_config[:newid] = config[:newid] ||= new_vmid
vm_config[:target] = config[:target] if config[:target]
vm_config[:name] = config[:name] if config[:name]
vm_config[:pool] = config[:pool] if config[:pool]
vm_config[:storage] = config[:storage] if config[:storage]
vm_config[:full] = 1 if config[:full]
puts vm_config
vm_definition = vm_config.to_a.map { |v| v.join '=' }.join '&'
puts vm_definition
vm_clone(config[:vmid], vm_config[:newid], vm_definition)
end
end
end
end
add disk format to vm clone
require 'chef/knife/proxmox_base'
class Chef
class Knife
class ProxmoxVmClone < Knife
include Knife::ProxmoxBase
banner "knife proxmox vm clone (options) [QEMU]"
option :vmid,
:long => "--vmid vmid",
:description => "VMID to clone"
option :name,
:long => "--name name",
:description => "Name for the new new VM"
option :pool,
:long => "--pool pool",
:description => "Pool for the new new VM"
option :storage,
:long => "--storage storage",
:description => "Target storage for full clone"
option :target,
:long => "--target node",
:description => "Node name to clone onto"
option :format,
:long => "--format format",
:description => "Target format for file storage"
option :full,
:long => "--full",
:boolean => true,
:default => false,
:description => "Create full copy of all disks."
def run
connection
[:vmid].each do |param|
check_config_parameter(param)
end
vm_config = Hash.new
vm_config[:newid] = config[:newid] ||= new_vmid
vm_config[:target] = config[:target] if config[:target]
vm_config[:name] = config[:name] if config[:name]
vm_config[:pool] = config[:pool] if config[:pool]
vm_config[:format] = config[:format] if config[:format]
vm_config[:storage] = config[:storage] if config[:storage]
vm_config[:full] = 1 if config[:full]
puts vm_config
vm_definition = vm_config.to_a.map { |v| v.join '=' }.join '&'
puts vm_definition
vm_clone(config[:vmid], vm_config[:newid], vm_definition)
end
end
end
end
|
require 'aws-sdk'
Aws.use_bundled_cert!
require 'httparty'
require_relative 'aws_resources'
require_relative 'helper'
require_relative './synapse/synapse'
require_relative 'zenv'
module Smash
module CloudPowers
module SelfAwareness
extend Smash::CloudPowers::Helper
extend Smash::CloudPowers::Synapse::Pipe
extend Smash::CloudPowers::Synapse::Queue
extend Smash::CloudPowers::Zenv
include Smash::CloudPowers::AwsResources
# Gets the instance time or the time it was called and as seconds from
# epoch
#
# Returns Integer
#
# Notes
# * TODO: use time codes
def boot_time
begin
ec2(Smash::CloudPowers::AwsStubs.node_stub)
sqs(Smash::CloudPowers::AwsStubs.queue_stub)
sns(Smash::CloudPowers::AwsStubs.broadcast_stub)
kinesis(Smash::CloudPowers::AwsStubs.pipe_stub)
@boot_time ||=
ec2.describe_instances(dry_run: zfind(:testing), instance_ids:[instance_id]).
reservations[0].instances[0].launch_time.to_i
rescue Aws::EC2::Errors::DryRunOperation => e
logger.info "dry run for testing: #{e}"
@boot_time ||= Time.now.to_i # comment the code below for development mode
end
end
# Send a status message on the status Pipe then terminates the instance.
def die!
Thread.kill(@status_thread) unless @status_thread.nil?
# blame = errors.sort_by(&:reverse).last.first
logger.info("The cause for the shutdown is TODO: fix SmashErrors")
pipe_to(:status_stream) do
{
instanceID: @instance_id,
type: 'status-update',
content: 'dying'
# extraInfo: blame
}
end
[:count, :wip].each do |queue|
delete_queue_message(queue, max_number_of_messages: 1)
end
send_logs_to_s3
begin
ec2.terminate_instances(dry_run: zfind('testing'), ids: [@instance_id])
rescue Aws::EC2::Error::DryRunOperation => e
logger.info "dry run testing in die! #{format_error_message(e)}"
@instance_id
end
end
# Get resource metadata, public host, boot time and task name
# and set them as instance variables
#
# Returns
# +Array+ of values, each from a separate key, set in the order
# in the Array
#
# Notes
# * See +#metadata_request()+
# * See +#attr_map!()+
def get_awareness!
keys = metadata_request
attr_map!(keys) { |key| metadata_request(key) }
boot_time # gets and sets @boot_time
task_name # gets and sets @task_name
instance_url # gets and sets @instance_url
end
# Assures there is always a valid instance id because many other Aws calls require it
#
# Returns
# +String+
def instance_id
@instance_id ||= metadata_request('instance_id')
end
# Gets and sets the public hostname of the instance
#
# Returns
# +String+ - the Public Hostname for this instance
#
# Notes
# * When this is being called from somewhere other than an Aws instance,
# a hardcoded example URL is returned because of the way instance metadata is retrieved
def instance_url
@instance_url ||= unless zfind('TESTING')
hostname_uri = 'http://169.254.169.254/latest/meta-data/public-hostname'
HTTParty.get(hostname_uri).parsed_response
else
'http://ec2-000-0-000-00.compute-0.amazonaws.com'
end
end
# Makes the http request to self/meta-data to get all the metadata keys or,
# if a key is given, the method makes the http request to get that
# particular key from the metadata
#
# Parameters
# * key +String+ (optional) (default is '') - the key for the metadata information
# you want from this instance.
#
# Returns
# * +Array+ if key is blank
# * +String+ if key is given
#
# Example
# metadata_request
# # => a +Hash+ containing every key => value pair AWS provides
# metadata_request('instance-id')
# # => 'abc-1234'
def metadata_request(key = '')
key = to_hyph(key)
begin
unless zfind('TESTING')
metadata_uri = "http://169.254.169.254/latest/meta-data/#{key}"
HTTParty.get(metadata_uri).parsed_response.split("\n")
else
require_relative '../stubs/aws_stubs'
stubbed_metadata = Smash::CloudPowers::AwsStubs.instance_metadata_stub
key.empty? ? stubbed_metadata.keys : stubbed_metadata[to_hyph(key)]
end
rescue Exception => e
logger.fatal format_error_message e
end
end
# Return the time since boot_time
#
# Returns
# +Integer+
#
# Notes
# * TODO: refactor to use valid time stamps for better tracking.
# * reason -> separate regions or OSs etc.
def run_time
Time.now.to_i - boot_time
end
# Send a message on a Pipe at an interval
#
# Parameters
# * opts +Hash+ (optional)
# * * +:interval+ - how long to wait between sending updates
# * * +:stream_name+ - name of stream you want to use
def send_frequent_status_updates(opts = {})
sleep_time = opts.delete(:interval) || 10
stream = opts.delete(:stream_name)
while true
message = lambda { |o| update_message_body(o.merge(content: status)) }
logger.info "Send update to status board #{message.call(opts)}"
pipe_to(stream || :status_stream) { message.call(opts) }
sleep sleep_time
end
end
# Get the instance status.
#
# Parameters
# * id +String+ (optional) (default is @instance_id)
#
# Returns String
def status(id = @instance_id)
begin
ec2.describe_instances(dry_run: zfind('TESTING'), instance_ids: [id]).
reservations[0].instances[0].state.name
rescue Aws::EC2::Errors::DryRunOperation => e
logger.info "Dry run flag set for testing: #{e}"
'testing'
end
end
# Check self-tags for 'task' and act as an attr_accessor.
# A different node's tag's can be checked for a task by passing
# that instance's id as a parameter
#
# Parameters
# * id +String+ (optional) (default is @instance_id) - instance you want a tag from
#
# Returns
# +String+
def task_name(id = @instance_id)
# get @task_name
return @task_name unless @task_name.nil?
# set @task_name
# TODO: get all tasks instead of just the first
resp = ec2.describe_instances(instance_ids: [id].flatten).reservations.first
return @task_name = nil if resp.nil?
@task_name = resp.instances[0].tags.select do |t|
t.value if t.key == 'taskType'
end.first
end
# This method will return true if:
# * The run time is more than 5 minutes
# and
# * The run time is 5 minutes from the hour mark from when the instance started
# and will return false otherwise
#
# Returns
# +Boolean+
def time_is_up?
an_hours_time = 60 * 60
five_minutes_time = 60 * 5
return false if run_time < five_minutes_time
run_time % an_hours_time < five_minutes_time
end
end
end
end
V 0.2.7.11 remove test stubbing
require 'aws-sdk'
Aws.use_bundled_cert!
require 'httparty'
require_relative 'aws_resources'
require_relative 'helper'
require_relative './synapse/synapse'
require_relative 'zenv'
module Smash
module CloudPowers
module SelfAwareness
extend Smash::CloudPowers::Helper
extend Smash::CloudPowers::Synapse::Pipe
extend Smash::CloudPowers::Synapse::Queue
extend Smash::CloudPowers::Zenv
include Smash::CloudPowers::AwsResources
# Gets the instance time or the time it was called and as seconds from
# epoch
#
# Returns Integer
#
# Notes
# * TODO: use time codes
def boot_time
begin
@boot_time ||=
ec2.describe_instances(dry_run: zfind(:testing), instance_ids:[instance_id]).
reservations[0].instances[0].launch_time.to_i
rescue Aws::EC2::Errors::DryRunOperation => e
logger.info "dry run for testing: #{e}"
@boot_time ||= Time.now.to_i # comment the code below for development mode
end
end
# Send a status message on the status Pipe then terminates the instance.
def die!
Thread.kill(@status_thread) unless @status_thread.nil?
# blame = errors.sort_by(&:reverse).last.first
logger.info("The cause for the shutdown is TODO: fix SmashErrors")
pipe_to(:status_stream) do
{
instanceID: @instance_id,
type: 'status-update',
content: 'dying'
# extraInfo: blame
}
end
[:count, :wip].each do |queue|
delete_queue_message(queue, max_number_of_messages: 1)
end
send_logs_to_s3
begin
ec2.terminate_instances(dry_run: zfind('testing'), ids: [@instance_id])
rescue Aws::EC2::Error::DryRunOperation => e
logger.info "dry run testing in die! #{format_error_message(e)}"
@instance_id
end
end
# Get resource metadata, public host, boot time and task name
# and set them as instance variables
#
# Returns
# +Array+ of values, each from a separate key, set in the order
# in the Array
#
# Notes
# * See +#metadata_request()+
# * See +#attr_map!()+
def get_awareness!
keys = metadata_request
attr_map!(keys) { |key| metadata_request(key) }
boot_time # gets and sets @boot_time
task_name # gets and sets @task_name
instance_url # gets and sets @instance_url
end
# Assures there is always a valid instance id because many other Aws calls require it
#
# Returns
# +String+
def instance_id
@instance_id ||= metadata_request('instance_id')
end
# Gets and sets the public hostname of the instance
#
# Returns
# +String+ - the Public Hostname for this instance
#
# Notes
# * When this is being called from somewhere other than an Aws instance,
# a hardcoded example URL is returned because of the way instance metadata is retrieved
def instance_url
@instance_url ||= unless zfind('TESTING')
hostname_uri = 'http://169.254.169.254/latest/meta-data/public-hostname'
HTTParty.get(hostname_uri).parsed_response
else
'http://ec2-000-0-000-00.compute-0.amazonaws.com'
end
end
# Makes the http request to self/meta-data to get all the metadata keys or,
# if a key is given, the method makes the http request to get that
# particular key from the metadata
#
# Parameters
# * key +String+ (optional) (default is '') - the key for the metadata information
# you want from this instance.
#
# Returns
# * +Array+ if key is blank
# * +String+ if key is given
#
# Example
# metadata_request
# # => a +Hash+ containing every key => value pair AWS provides
# metadata_request('instance-id')
# # => 'abc-1234'
def metadata_request(key = '')
key = to_hyph(key)
begin
unless zfind('TESTING')
metadata_uri = "http://169.254.169.254/latest/meta-data/#{key}"
HTTParty.get(metadata_uri).parsed_response.split("\n")
else
require_relative '../stubs/aws_stubs'
stubbed_metadata = Smash::CloudPowers::AwsStubs.instance_metadata_stub
key.empty? ? stubbed_metadata.keys : stubbed_metadata[to_hyph(key)]
end
rescue Exception => e
logger.fatal format_error_message e
end
end
# Return the time since boot_time
#
# Returns
# +Integer+
#
# Notes
# * TODO: refactor to use valid time stamps for better tracking.
# * reason -> separate regions or OSs etc.
def run_time
Time.now.to_i - boot_time
end
# Send a message on a Pipe at an interval
#
# Parameters
# * opts +Hash+ (optional)
# * * +:interval+ - how long to wait between sending updates
# * * +:stream_name+ - name of stream you want to use
def send_frequent_status_updates(opts = {})
sleep_time = opts.delete(:interval) || 10
stream = opts.delete(:stream_name)
while true
message = lambda { |o| update_message_body(o.merge(content: status)) }
logger.info "Send update to status board #{message.call(opts)}"
pipe_to(stream || :status_stream) { message.call(opts) }
sleep sleep_time
end
end
# Get the instance status.
#
# Parameters
# * id +String+ (optional) (default is @instance_id)
#
# Returns String
def status(id = @instance_id)
begin
ec2.describe_instances(dry_run: zfind('TESTING'), instance_ids: [id]).
reservations[0].instances[0].state.name
rescue Aws::EC2::Errors::DryRunOperation => e
logger.info "Dry run flag set for testing: #{e}"
'testing'
end
end
# Check self-tags for 'task' and act as an attr_accessor.
# A different node's tag's can be checked for a task by passing
# that instance's id as a parameter
#
# Parameters
# * id +String+ (optional) (default is @instance_id) - instance you want a tag from
#
# Returns
# +String+
def task_name(id = @instance_id)
# get @task_name
return @task_name unless @task_name.nil?
# set @task_name
# TODO: get all tasks instead of just the first
resp = ec2.describe_instances(instance_ids: [id].flatten).reservations.first
return @task_name = nil if resp.nil?
@task_name = resp.instances[0].tags.select do |t|
t.value if t.key == 'taskType'
end.first
end
# This method will return true if:
# * The run time is more than 5 minutes
# and
# * The run time is 5 minutes from the hour mark from when the instance started
# and will return false otherwise
#
# Returns
# +Boolean+
def time_is_up?
an_hours_time = 60 * 60
five_minutes_time = 60 * 5
return false if run_time < five_minutes_time
run_time % an_hours_time < five_minutes_time
end
end
end
end
|
Added example
# (c) Copyright 2017 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
my_client = {
url: ENV['ONEVIEWSDK_URL'],
user: ENV['ONEVIEWSDK_USER'],
password: ENV['ONEVIEWSDK_PASSWORD']
}
# Does nothing (default :none)
oneview_fabric 'DefaultFabric' do
client my_client
end
# Updates the DefaultFabric fabric reserved vlan range if the values do not match
oneview_fabric 'DefaultFabric' do
client my_client
reserved_vlan_range(
'start' => 3000,
'length' => 120
)
action :set_reserved_vlan_range
end
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require File.expand_path('../../lib/discourse_api', __FILE__)
require 'dotenv'
Dotenv.load
client = DiscourseApi::Client.new
response = client.create_group(name: "engineering_team")
group_id = response["basic_group"]["id"]
client.group_add(group_id, username: "sam")
client.group_add(group_id, username: "jeff")
client.group_add(group_id, usernames: ["neil", "dan"])
client.group_add(group_id, user_id: 123)
client.group_add(group_id, user_ids: [123, 456])
client.group_remove(group_id, username: "neil")
client.group_remove(group_id, user_id: 123)
remove dotenv groups example
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require File.expand_path('../../lib/discourse_api', __FILE__)
client = DiscourseApi::Client.new
response = client.create_group(name: "engineering_team")
group_id = response["basic_group"]["id"]
client.group_add(group_id, username: "sam")
client.group_add(group_id, username: "jeff")
client.group_add(group_id, usernames: ["neil", "dan"])
client.group_add(group_id, user_id: 123)
client.group_add(group_id, user_ids: [123, 456])
client.group_remove(group_id, username: "neil")
client.group_remove(group_id, user_id: 123)
|
added a layout example
require 'examples/example_workbook'
class Layout < ExampleWorkbook
def name; "layout"; end
def build
first_sheet
end
def first_sheet
wksht = Xmlss::Worksheet.new('first')
4.times do
wksht.table.columns << Xmlss::Column.new
end
5.times do
wksht.table.rows << Xmlss::Row.new
end
# | A | B | C | D |
# 1| x | x | x | x |
# 2| x | x | x |
# 3| x | | x |
# 4| x | x | x |
# 5| x | | x |
# row 1: one cell per column
4.times do |i|
wksht.table.rows[0].cells << Xmlss::Cell.new({
:index => i+1,
:data => Xmlss::Data.new("x")
})
end
# row 2: first cell colspan=2
wksht.table.rows[1].cells << Xmlss::Cell.new({
:index => 1,
:data => Xmlss::Data.new("x"),
:merge_across => 1
})
2.times do |i|
wksht.table.rows[1].cells << Xmlss::Cell.new({
:index => i+3,
:data => Xmlss::Data.new("x")
})
end
# row 3,4,5: more complex merging
# => row 3
wksht.table.rows[2].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:index => 1
})
wksht.table.rows[2].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:merge_across => 1,
:merge_down => 2,
:index => 2
})
wksht.table.rows[2].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:index => 4
})
# => row 4
wksht.table.rows[3].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:index => 1
})
wksht.table.rows[3].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:index => 4
})
# => row 5
wksht.table.rows[4].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:index => 1
})
wksht.table.rows[4].cells << Xmlss::Cell.new({
:data => Xmlss::Data.new("x"),
:index => 4
})
self.worksheets << wksht
end
def second_sheet
end
end
Layout.new.to_file
|
require 'prawn/chart'
name = 'example.pdf'
monthly_views = {"views"=> {"Apr ’14"=>1351534, "May ’14"=>1278075, "Jun ’14"=>1686821, "Jul ’14"=>1547802, "Aug ’14"=>3558486, "Sep ’14"=>4157628, "Oct ’14"=>940739, "Nov ’14"=>970788, "Dec ’14"=>2862445, "Jan ’15"=>4748578, "Feb ’15"=>2854643, "Mar ’15"=>1298676, "Apr ’15"=>2104046}}
viewership = {"uploads"=> {"Apr 01"=>2, "Apr 02"=>0, "Apr 03"=>12, "Apr 04"=>0, "Apr 05"=>0, "Apr 06"=>1, "Apr 07"=>3, "Apr 08"=>8, "Apr 09"=>7, "Apr 10"=>12, "Apr 11"=>0, "Apr 12"=>0, "Apr 13"=>3, "Apr 14"=>0, "Apr 15"=>0, "Apr 16"=>2, "Apr 17"=>2, "Apr 18"=>0, "Apr 19"=>0, "Apr 20"=>2, "Apr 21"=>3, "Apr 22"=>2, "Apr 23"=>1, "Apr 24"=>1, "Apr 25"=>0, "Apr 26"=>0, "Apr 27"=>0, "Apr 28"=>2, "Apr 29"=>1, "Apr 30"=>2}, "views"=> {"Apr 01"=>20555, "Apr 02"=>29722, "Apr 03"=>120738, "Apr 04"=>76805, "Apr 05"=>68729, "Apr 06"=>80283, "Apr 07"=>82264, "Apr 08"=>80273, "Apr 09"=>71902, "Apr 10"=>36759, "Apr 11"=>31104, "Apr 12"=>29423, "Apr 13"=>95888, "Apr 14"=>80782, "Apr 15"=>99182, "Apr 16"=>92247, "Apr 17"=>77122, "Apr 18"=>69747, "Apr 19"=>36367, "Apr 20"=>82588, "Apr 21"=>57739, "Apr 22"=>65039, "Apr 23"=>92715, "Apr 24"=>67310, "Apr 25"=>156063, "Apr 26"=>69908, "Apr 27"=>58076, "Apr 28"=>58582, "Apr 29"=>60140, "Apr 30"=>55994}}
year_on_year = {"last_period"=> {"Apr 01"=>51048, "Apr 02"=>52024, "Apr 03"=>86399, "Apr 04"=>60243, "Apr 05"=>51371, "Apr 06"=>47709, "Apr 07"=>59965, "Apr 08"=>53363, "Apr 09"=>51726, "Apr 10"=>48251, "Apr 11"=>39498, "Apr 12"=>37114, "Apr 13"=>35470, "Apr 14"=>34531, "Apr 15"=>45624, "Apr 16"=>42130, "Apr 17"=>40163, "Apr 18"=>37859, "Apr 19"=>36400, "Apr 20"=>38218, "Apr 21"=>38319, "Apr 22"=>39631, "Apr 23"=>38917, "Apr 24"=>44720, "Apr 25"=>38561, "Apr 26"=>37407, "Apr 27"=>42400, "Apr 28"=>42998, "Apr 29"=>44114, "Apr 30"=>35361}, "this_period"=> {"Apr 01"=>20555, "Apr 02"=>29722, "Apr 03"=>120738, "Apr 04"=>76805, "Apr 05"=>68729, "Apr 06"=>80283, "Apr 07"=>82264, "Apr 08"=>80273, "Apr 09"=>71902, "Apr 10"=>36759, "Apr 11"=>31104, "Apr 12"=>29423, "Apr 13"=>95888, "Apr 14"=>80782, "Apr 15"=>99182, "Apr 16"=>92247, "Apr 17"=>77122, "Apr 18"=>69747, "Apr 19"=>36367, "Apr 20"=>82588, "Apr 21"=>57739, "Apr 22"=>65039, "Apr 23"=>92715, "Apr 24"=>67310, "Apr 25"=>156063, "Apr 26"=>69908, "Apr 27"=>58076, "Apr 28"=>58582, "Apr 29"=>60140, "Apr 30"=>55994}}
demographics = {"71.8% male"=>{"13-17"=>5.7, "18-24"=>14.0, "25-34"=>25.6, "35-44"=>13.8, "45-54"=>8.6, "55-64"=>2.6, "65-"=>1.5}, "28.3% female"=>{"13-17"=>4.5, "18-24"=>6.3, "25-34"=>7.4, "35-44"=>4.2, "45-54"=>3.3, "55-64"=>1.6, "65-"=>1.0}}
Prawn::Document.generate(name) do
# double_graph
chart viewership, type: :two_axis, legend_offset: -65, ticks: true, every: 4, colors: ['c7f464', '4ecdc4'], line_widths: [4, 4]
stroke_horizontal_rule
move_down 40
chart monthly_views, type: :column, colors: [['4ecdc4']*12 + ['c7f464']]
stroke_horizontal_rule
start_new_page
# double_bar_graph
chart demographics, format: :percentage, legend_offset: -65
stroke_horizontal_rule
move_down 40
# double_graph
chart year_on_year, type: :line, height: 124, ticks: true, every: 4, colors: ['c7f464', '4ecdc4'], line_widths: [2, 4]
stroke_horizontal_rule
end
`open #{name}`
reb color
require 'prawn/chart'
name = 'example.pdf'
monthly_views = {"views"=> {"Apr ’14"=>1351534, "May ’14"=>1278075, "Jun ’14"=>1686821, "Jul ’14"=>1547802, "Aug ’14"=>3558486, "Sep ’14"=>4157628, "Oct ’14"=>940739, "Nov ’14"=>970788, "Dec ’14"=>2862445, "Jan ’15"=>4748578, "Feb ’15"=>2854643, "Mar ’15"=>1298676, "Apr ’15"=>2104046}}
viewership = {"uploads"=> {"Apr 01"=>2, "Apr 02"=>0, "Apr 03"=>12, "Apr 04"=>0, "Apr 05"=>0, "Apr 06"=>1, "Apr 07"=>3, "Apr 08"=>8, "Apr 09"=>7, "Apr 10"=>12, "Apr 11"=>0, "Apr 12"=>0, "Apr 13"=>3, "Apr 14"=>0, "Apr 15"=>0, "Apr 16"=>2, "Apr 17"=>2, "Apr 18"=>0, "Apr 19"=>0, "Apr 20"=>2, "Apr 21"=>3, "Apr 22"=>2, "Apr 23"=>1, "Apr 24"=>1, "Apr 25"=>0, "Apr 26"=>0, "Apr 27"=>0, "Apr 28"=>2, "Apr 29"=>1, "Apr 30"=>2}, "views"=> {"Apr 01"=>20555, "Apr 02"=>29722, "Apr 03"=>120738, "Apr 04"=>76805, "Apr 05"=>68729, "Apr 06"=>80283, "Apr 07"=>82264, "Apr 08"=>80273, "Apr 09"=>71902, "Apr 10"=>36759, "Apr 11"=>31104, "Apr 12"=>29423, "Apr 13"=>95888, "Apr 14"=>80782, "Apr 15"=>99182, "Apr 16"=>92247, "Apr 17"=>77122, "Apr 18"=>69747, "Apr 19"=>36367, "Apr 20"=>82588, "Apr 21"=>57739, "Apr 22"=>65039, "Apr 23"=>92715, "Apr 24"=>67310, "Apr 25"=>156063, "Apr 26"=>69908, "Apr 27"=>58076, "Apr 28"=>58582, "Apr 29"=>60140, "Apr 30"=>55994}}
year_on_year = {"last_period"=> {"Apr 01"=>51048, "Apr 02"=>52024, "Apr 03"=>86399, "Apr 04"=>60243, "Apr 05"=>51371, "Apr 06"=>47709, "Apr 07"=>59965, "Apr 08"=>53363, "Apr 09"=>51726, "Apr 10"=>48251, "Apr 11"=>39498, "Apr 12"=>37114, "Apr 13"=>35470, "Apr 14"=>34531, "Apr 15"=>45624, "Apr 16"=>42130, "Apr 17"=>40163, "Apr 18"=>37859, "Apr 19"=>36400, "Apr 20"=>38218, "Apr 21"=>38319, "Apr 22"=>39631, "Apr 23"=>38917, "Apr 24"=>44720, "Apr 25"=>38561, "Apr 26"=>37407, "Apr 27"=>42400, "Apr 28"=>42998, "Apr 29"=>44114, "Apr 30"=>35361}, "this_period"=> {"Apr 01"=>20555, "Apr 02"=>29722, "Apr 03"=>120738, "Apr 04"=>76805, "Apr 05"=>68729, "Apr 06"=>80283, "Apr 07"=>82264, "Apr 08"=>80273, "Apr 09"=>71902, "Apr 10"=>36759, "Apr 11"=>31104, "Apr 12"=>29423, "Apr 13"=>95888, "Apr 14"=>80782, "Apr 15"=>99182, "Apr 16"=>92247, "Apr 17"=>77122, "Apr 18"=>69747, "Apr 19"=>36367, "Apr 20"=>82588, "Apr 21"=>57739, "Apr 22"=>65039, "Apr 23"=>92715, "Apr 24"=>67310, "Apr 25"=>156063, "Apr 26"=>69908, "Apr 27"=>58076, "Apr 28"=>58582, "Apr 29"=>60140, "Apr 30"=>55994}}
demographics = {"71.8% male"=>{"13-17"=>5.7, "18-24"=>14.0, "25-34"=>25.6, "35-44"=>13.8, "45-54"=>8.6, "55-64"=>2.6, "65-"=>1.5}, "28.3% female"=>{"13-17"=>4.5, "18-24"=>6.3, "25-34"=>7.4, "35-44"=>4.2, "45-54"=>3.3, "55-64"=>1.6, "65-"=>1.0}}
Prawn::Document.generate(name) do
# double_graph
chart viewership, type: :two_axis, legend_offset: -65, ticks: true, every: 4, colors: ['c7f464', '4ecdc4'], line_widths: [4, 4]
stroke_horizontal_rule
move_down 40
chart monthly_views, type: :column, colors: [['4ecdc4']*12 + ['c7f464']]
stroke_horizontal_rule
start_new_page
# double_bar_graph
chart demographics, format: :percentage, legend_offset: -65, colors: ['c7f464', '4ecdc4']
stroke_horizontal_rule
move_down 40
# double_graph
chart year_on_year, type: :line, height: 124, ticks: true, every: 4, colors: ['c7f464', '4ecdc4'], line_widths: [2, 4]
stroke_horizontal_rule
end
`open #{name}`
|
Adding the ExtronMPS409 driver
class ExtronMPS409 < ExtronVideoSwitcher
AUDIO_HASH = {1 => "1*1", 2 => "1*2", 3 => "2*1", 4 => "2*2", 5 => "3*1", 6 => "3*2", 7 => "3*3", 8 => "4*1", 9 => "4*2"}
managed_state_var :video,
:type => :option,
:display_order => 1,
:options => ("1".."6").to_a,
:response => :channel,
:action => proc{|input|
"#{input}!"
}
managed_state_var :audio,
:type => :option,
:display_order => 2,
:options => ("1".."6").to_a,
:response => :channel,
:action => proc{|input|
"#{AUDIO_HASH[input]}$"
}
responses do
match :audio, /Mod(\d+) (\d)G(\d) (\d)G(\d) (\d)G(\d) (\d)G(\d)=(\d)G(\d)/, proc{|m|
x1, x2 = [m[10].to_i, m[11].to_i]
self.audio = "#{x1}*#{x2}"
}
match :video, /Mod(\d+) (\d)G(\d) (\d)G(\d) (\d)G(\d) (\d)G(\d)=(\d)G(\d)/, proc{|m|
for i in (1..4)
if m[2*i+1] != 0
v1, v2 = [m[2*i].to_i, m[2*i+1].to_i]
break
end
end
self.video = (v1 < 3 ? ((v1-1)*2 + (v2-1) % 2 + 1) : ((v1-3)*3 + (v2-1) % 3 + 5))
}
end
end
|
# frozen_string_literal: true
module TaskVault
class ServerComponent < Component
def self.description
'No description yet...'
end
def description
self.class.description
end
end
end
Added the root method to server components to return the root server for convenience.
# frozen_string_literal: true
module TaskVault
class ServerComponent < Component
def root
parent
end
def self.description
'No description yet...'
end
def description
self.class.description
end
end
end
|
# Extracted from dm-validations 0.9.10
#
# Copyright (c) 2007 Guy van den Berg
#
# 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.
class Object
def validatable?
false
end
end
dir = File.join(Pathname(__FILE__).dirname.expand_path, '..', 'validation')
require File.join(dir, 'validation_errors')
require File.join(dir, 'contextual_validators')
require File.join(dir, 'validators', 'generic_validator')
require File.join(dir, 'validators', 'required_field_validator')
require File.join(dir, 'validators', 'absent_field_validator')
require File.join(dir, 'validators', 'format_validator')
require File.join(dir, 'validators', 'length_validator')
require File.join(dir, 'validators', 'numeric_validator')
require File.join(dir, 'validators', 'method_validator')
module CouchRest
module Validation
def self.included(base)
base.extend(ClassMethods)
base.class_eval <<-EOS, __FILE__, __LINE__
if (method_defined?(:save) && method_defined?(:_run_save_callbacks))
save_callback :before, :check_validations
end
EOS
end
# Ensures the object is valid for the context provided, and otherwise
# throws :halt and returns false.
#
def check_validations(context = :default)
throw(:halt, false) unless context.nil? || valid?(context)
end
# Return the ValidationErrors
#
def errors
@errors ||= ValidationErrors.new
end
# Mark this resource as validatable. When we validate associations of a
# resource we can check if they respond to validatable? before trying to
# recursivly validate them
#
def validatable?
true
end
# Alias for valid?(:default)
#
def valid_for_default?
valid?(:default)
end
# Check if a resource is valid in a given context
#
def valid?(context = :default)
self.class.validators.execute(context, self)
end
# Begin a recursive walk of the model checking validity
#
def all_valid?(context = :default)
recursive_valid?(self, context, true)
end
# Do recursive validity checking
#
def recursive_valid?(target, context, state)
valid = state
target.instance_variables.each do |ivar|
ivar_value = target.instance_variable_get(ivar)
if ivar_value.validatable?
valid = valid && recursive_valid?(ivar_value, context, valid)
elsif ivar_value.respond_to?(:each)
ivar_value.each do |item|
if item.validatable?
valid = valid && recursive_valid?(item, context, valid)
end
end
end
end
return valid && target.valid?
end
def validation_property_value(name)
self.respond_to?(name, true) ? self.send(name) : nil
end
# Get the corresponding Resource property, if it exists.
#
# Note: CouchRest validations can be used on non-CouchRest resources.
# In such cases, the return value will be nil.
def validation_property(field_name)
properties.find{|p| p.name == field_name}
end
module ClassMethods
include CouchRest::Validation::ValidatesPresent
include CouchRest::Validation::ValidatesAbsent
# include CouchRest::Validation::ValidatesIsConfirmed
# include CouchRest::Validation::ValidatesIsPrimitive
# include CouchRest::Validation::ValidatesIsAccepted
include CouchRest::Validation::ValidatesFormat
include CouchRest::Validation::ValidatesLength
# include CouchRest::Validation::ValidatesWithin
include CouchRest::Validation::ValidatesIsNumber
include CouchRest::Validation::ValidatesWithMethod
# include CouchRest::Validation::ValidatesWithBlock
# include CouchRest::Validation::ValidatesIsUnique
# include CouchRest::Validation::AutoValidate
# Return the set of contextual validators or create a new one
#
def validators
@validations ||= ContextualValidators.new
end
# Clean up the argument list and return a opts hash, including the
# merging of any default opts. Set the context to default if none is
# provided. Also allow :context to be aliased to :on, :when & group
#
def opts_from_validator_args(args, defaults = nil)
opts = args.last.kind_of?(Hash) ? args.pop : {}
context = :default
context = opts[:context] if opts.has_key?(:context)
context = opts.delete(:on) if opts.has_key?(:on)
context = opts.delete(:when) if opts.has_key?(:when)
context = opts.delete(:group) if opts.has_key?(:group)
opts[:context] = context
opts.mergs!(defaults) unless defaults.nil?
opts
end
# Given a new context create an instance method of
# valid_for_<context>? which simply calls valid?(context)
# if it does not already exist
#
def create_context_instance_methods(context)
name = "valid_for_#{context.to_s}?" # valid_for_signup?
if !self.instance_methods.include?(name)
class_eval <<-EOS, __FILE__, __LINE__
def #{name} # def valid_for_signup?
valid?('#{context.to_s}'.to_sym) # valid?('signup'.to_sym)
end # end
EOS
end
all = "all_valid_for_#{context.to_s}?" # all_valid_for_signup?
if !self.instance_methods.include?(all)
class_eval <<-EOS, __FILE__, __LINE__
def #{all} # def all_valid_for_signup?
all_valid?('#{context.to_s}'.to_sym) # all_valid?('signup'.to_sym)
end # end
EOS
end
end
# Create a new validator of the given klazz and push it onto the
# requested context for each of the attributes in the fields list
#
def add_validator_to_context(opts, fields, klazz)
fields.each do |field|
validator = klazz.new(field, opts)
if opts[:context].is_a?(Symbol)
unless validators.context(opts[:context]).include?(validator)
validators.context(opts[:context]) << validator
create_context_instance_methods(opts[:context])
end
elsif opts[:context].is_a?(Array)
opts[:context].each do |c|
unless validators.context(c).include?(validator)
validators.context(c) << validator
create_context_instance_methods(c)
end
end
end
end
end
end # module ClassMethods
end # module Validation
end # module CouchRest
simplified the validation callback method.
# Extracted from dm-validations 0.9.10
#
# Copyright (c) 2007 Guy van den Berg
#
# 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.
class Object
def validatable?
false
end
end
dir = File.join(Pathname(__FILE__).dirname.expand_path, '..', 'validation')
require File.join(dir, 'validation_errors')
require File.join(dir, 'contextual_validators')
require File.join(dir, 'validators', 'generic_validator')
require File.join(dir, 'validators', 'required_field_validator')
require File.join(dir, 'validators', 'absent_field_validator')
require File.join(dir, 'validators', 'format_validator')
require File.join(dir, 'validators', 'length_validator')
require File.join(dir, 'validators', 'numeric_validator')
require File.join(dir, 'validators', 'method_validator')
module CouchRest
module Validation
def self.included(base)
base.extend(ClassMethods)
base.class_eval <<-EOS, __FILE__, __LINE__
if method_defined?(:_run_save_callbacks)
save_callback :before, :check_validations
end
EOS
end
# Ensures the object is valid for the context provided, and otherwise
# throws :halt and returns false.
#
def check_validations(context = :default)
throw(:halt, false) unless context.nil? || valid?(context)
end
# Return the ValidationErrors
#
def errors
@errors ||= ValidationErrors.new
end
# Mark this resource as validatable. When we validate associations of a
# resource we can check if they respond to validatable? before trying to
# recursivly validate them
#
def validatable?
true
end
# Alias for valid?(:default)
#
def valid_for_default?
valid?(:default)
end
# Check if a resource is valid in a given context
#
def valid?(context = :default)
self.class.validators.execute(context, self)
end
# Begin a recursive walk of the model checking validity
#
def all_valid?(context = :default)
recursive_valid?(self, context, true)
end
# Do recursive validity checking
#
def recursive_valid?(target, context, state)
valid = state
target.instance_variables.each do |ivar|
ivar_value = target.instance_variable_get(ivar)
if ivar_value.validatable?
valid = valid && recursive_valid?(ivar_value, context, valid)
elsif ivar_value.respond_to?(:each)
ivar_value.each do |item|
if item.validatable?
valid = valid && recursive_valid?(item, context, valid)
end
end
end
end
return valid && target.valid?
end
def validation_property_value(name)
self.respond_to?(name, true) ? self.send(name) : nil
end
# Get the corresponding Resource property, if it exists.
#
# Note: CouchRest validations can be used on non-CouchRest resources.
# In such cases, the return value will be nil.
def validation_property(field_name)
properties.find{|p| p.name == field_name}
end
module ClassMethods
include CouchRest::Validation::ValidatesPresent
include CouchRest::Validation::ValidatesAbsent
# include CouchRest::Validation::ValidatesIsConfirmed
# include CouchRest::Validation::ValidatesIsPrimitive
# include CouchRest::Validation::ValidatesIsAccepted
include CouchRest::Validation::ValidatesFormat
include CouchRest::Validation::ValidatesLength
# include CouchRest::Validation::ValidatesWithin
include CouchRest::Validation::ValidatesIsNumber
include CouchRest::Validation::ValidatesWithMethod
# include CouchRest::Validation::ValidatesWithBlock
# include CouchRest::Validation::ValidatesIsUnique
# include CouchRest::Validation::AutoValidate
# Return the set of contextual validators or create a new one
#
def validators
@validations ||= ContextualValidators.new
end
# Clean up the argument list and return a opts hash, including the
# merging of any default opts. Set the context to default if none is
# provided. Also allow :context to be aliased to :on, :when & group
#
def opts_from_validator_args(args, defaults = nil)
opts = args.last.kind_of?(Hash) ? args.pop : {}
context = :default
context = opts[:context] if opts.has_key?(:context)
context = opts.delete(:on) if opts.has_key?(:on)
context = opts.delete(:when) if opts.has_key?(:when)
context = opts.delete(:group) if opts.has_key?(:group)
opts[:context] = context
opts.mergs!(defaults) unless defaults.nil?
opts
end
# Given a new context create an instance method of
# valid_for_<context>? which simply calls valid?(context)
# if it does not already exist
#
def create_context_instance_methods(context)
name = "valid_for_#{context.to_s}?" # valid_for_signup?
if !self.instance_methods.include?(name)
class_eval <<-EOS, __FILE__, __LINE__
def #{name} # def valid_for_signup?
valid?('#{context.to_s}'.to_sym) # valid?('signup'.to_sym)
end # end
EOS
end
all = "all_valid_for_#{context.to_s}?" # all_valid_for_signup?
if !self.instance_methods.include?(all)
class_eval <<-EOS, __FILE__, __LINE__
def #{all} # def all_valid_for_signup?
all_valid?('#{context.to_s}'.to_sym) # all_valid?('signup'.to_sym)
end # end
EOS
end
end
# Create a new validator of the given klazz and push it onto the
# requested context for each of the attributes in the fields list
#
def add_validator_to_context(opts, fields, klazz)
fields.each do |field|
validator = klazz.new(field, opts)
if opts[:context].is_a?(Symbol)
unless validators.context(opts[:context]).include?(validator)
validators.context(opts[:context]) << validator
create_context_instance_methods(opts[:context])
end
elsif opts[:context].is_a?(Array)
opts[:context].each do |c|
unless validators.context(c).include?(validator)
validators.context(c) << validator
create_context_instance_methods(c)
end
end
end
end
end
end # module ClassMethods
end # module Validation
end # module CouchRest
|
require File.join(File.dirname(__FILE__), '..', 'mixins', 'properties')
module CouchRest
module CastedModel
def self.included(base)
base.send(:include, CouchRest::Mixins::Properties)
base.send(:attr_accessor, :casted_by)
base.send(:attr_accessor, :document_saved)
end
def initialize(keys={})
raise StandardError unless self.is_a? Hash
apply_defaults # defined in CouchRest::Mixins::Properties
super()
keys.each do |k,v|
self[k.to_s] = v
end if keys
cast_keys # defined in CouchRest::Mixins::Properties
end
def []= key, value
super(key.to_s, value)
end
def [] key
super(key.to_s)
end
# True if the casted model has already
# been saved in the containing document
def new_model?
!@document_saved
end
alias :new_record? :new_model?
# Sets the attributes from a hash
def update_attributes_without_saving(hash)
hash.each do |k, v|
raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
end
hash.each do |k, v|
self.send("#{k}=",v)
end
end
alias :attributes= :update_attributes_without_saving
end
end
Fixed a comment
require File.join(File.dirname(__FILE__), '..', 'mixins', 'properties')
module CouchRest
module CastedModel
def self.included(base)
base.send(:include, CouchRest::Mixins::Properties)
base.send(:attr_accessor, :casted_by)
base.send(:attr_accessor, :document_saved)
end
def initialize(keys={})
raise StandardError unless self.is_a? Hash
apply_defaults # defined in CouchRest::Mixins::Properties
super()
keys.each do |k,v|
self[k.to_s] = v
end if keys
cast_keys # defined in CouchRest::Mixins::Properties
end
def []= key, value
super(key.to_s, value)
end
def [] key
super(key.to_s)
end
# False if the casted model has already
# been saved in the containing document
def new_model?
!@document_saved
end
alias :new_record? :new_model?
# Sets the attributes from a hash
def update_attributes_without_saving(hash)
hash.each do |k, v|
raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
end
hash.each do |k, v|
self.send("#{k}=",v)
end
end
alias :attributes= :update_attributes_without_saving
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.