CombinedText
stringlengths
4
3.42M
# encoding: utf-8 module Rubocop module Cop class ClassMethods < Cop MSG = 'Prefer self over class/module for class/module methods.' def inspect(file, source, tokens, ast) # defs nodes correspond to class & module methods on_node(:defs, ast) do |s| if s.children.first.type == :const add_offence(:convention, s.src.line, MSG) end end end end end end Port ClassMethods cop to AST::Processor # encoding: utf-8 module Rubocop module Cop class ClassMethods < Cop MSG = 'Prefer self over class/module for class/module methods.' def on_defs(node) definee, _name, _args, _body = *node add_offence(:convention, node.src.line, MSG) if definee.type == :const end end end end
module Ruboty module Handlers class Shinchoku < Base env :TUMBLR_API_KEY, 'Tumblr API Key' on( /.*(進捗).*/, name: 'shinchoku', description: 'Get random image from shinchokudodesuka.tumblr.com' ) def shinchoku(message) Ruboty::Shinchoku::Actions::GetRandomImage.new(message).call end end end end Add `all` option module Ruboty module Handlers class Shinchoku < Base env :TUMBLR_API_KEY, 'Tumblr API Key' on( /.*(進捗).*/, name: 'shinchoku', description: 'Get random image from shinchokudodesuka.tumblr.com', all: true ) def shinchoku(message) Ruboty::Shinchoku::Actions::GetRandomImage.new(message).call end end end end
module Kirpich::Providers class Image class << self def ass_image response = Faraday.get 'http://rails.gusar.1cb9d70e.svc.dockerapp.io/api/images/random?q[nsfw_lt]=0.6' json = JSON.parse(response.body) json['picture_url'] end def boobs_image response = Faraday.get 'http://rails.gusar.1cb9d70e.svc.dockerapp.io/api/images/random?q[nsfw_lt]=0.6' json = JSON.parse(response.body) json['picture_url'] end def developerslife_image connection = Faraday.new(url: 'http://developerslife.ru/random'.freeze) do |faraday| faraday.use FaradayMiddleware::FollowRedirects, limit: 5 faraday.adapter Faraday.default_adapter end response = connection.get page = Nokogiri::HTML(response.body) image = page.css('.entry .image .gif video source') text = page.css('.entry .code .value') [image.first['src'], text.first.text.delete("'")] if image.any? && text.any? end def devopsreactions_image response = Faraday.get('http://devopsreactions.tumblr.com/random'.freeze) response.headers['location'.freeze] end end end end More nsfw module Kirpich::Providers class Image class << self def ass_image response = Faraday.get 'http://rails.gusar.1cb9d70e.svc.dockerapp.io/api/images/random?q[nsfw_lt]=0.6&q[nsfw_gt]=0.01' json = JSON.parse(response.body) json['picture_url'] end def boobs_image response = Faraday.get 'http://rails.gusar.1cb9d70e.svc.dockerapp.io/api/images/random?q[nsfw_lt]=0.6&q[nsfw_gt]=0.01' json = JSON.parse(response.body) json['picture_url'] end def developerslife_image connection = Faraday.new(url: 'http://developerslife.ru/random'.freeze) do |faraday| faraday.use FaradayMiddleware::FollowRedirects, limit: 5 faraday.adapter Faraday.default_adapter end response = connection.get page = Nokogiri::HTML(response.body) image = page.css('.entry .image .gif video source') text = page.css('.entry .code .value') [image.first['src'], text.first.text.delete("'")] if image.any? && text.any? end def devopsreactions_image response = Faraday.get('http://devopsreactions.tumblr.com/random'.freeze) response.headers['location'.freeze] end end end end
module KnifeProfitbricks module Base LVS_ATTRIBUTES = [ :cpuHotPlug, :ramHotPlug, :nicHotPlug, :nicHotUnplug, :discVirtioHotPlug, :discVirtioHotUnplug ] def self.included(base) base.class_eval do deps do require 'profitbricks' require 'chef/knife' require 'knife_profitbricks/extension/profitbricks/profitbricks' require 'knife_profitbricks/extension/profitbricks/model' require 'knife_profitbricks/extension/profitbricks/has_location' require 'knife_profitbricks/extension/profitbricks/server' require 'knife_profitbricks/extension/profitbricks/datacenter' require 'knife_profitbricks/extension/profitbricks/volume' require 'knife_profitbricks/extension/profitbricks/nic' require 'knife_profitbricks/extension/profitbricks/location' require 'knife_profitbricks/extension/profitbricks/image' require 'knife_profitbricks/extension/profitbricks/lan' require 'knife_profitbricks/extension/profitbricks/request' require 'knife_profitbricks/extension/profitbricks/ipblock' require 'knife_profitbricks/extension/profitbricks/firewall' require 'knife_profitbricks/extension/profitbricks/location' require 'knife_profitbricks/extension/profitbricks/wait_for' require 'knife_profitbricks/extension/profitbricks/billing' require 'knife_profitbricks/extension/profitbricks/billing/traffic' Chef::Knife.load_deps Chef::Config[:solo] = true end option :profitbricks_data_bag, :short => "-a NAME", :long => "--profitbricks-data-bag NAME", :description => "Data bag for profitbricks account", :proc => lambda { |o| Chef::Config[:knife][:profitbricks_data_bag] = o } def self.method_added(name) if name.to_s == 'run' && !@run_added @run_added = true alias run_without_establish_connection run alias run run_with_establish_connection end end end end def run_with_establish_connection establish_connection run_without_establish_connection end private def establish_connection user, password = detect_user_and_password log "Establish connection to ProfitBricks for #{user.inspect}" ProfitBricks.configure do |config| config.username = user config.password = password config.global_classes = false config.timeout = 300 end log "Established ..." log "\n" end def load_data_bag(*args) secret_path = Chef::Config[:encrypted_data_bag_secret] secret_key = Chef::EncryptedDataBagItem.load_secret secret_path content = Chef::DataBagItem.load(*args).raw_data Chef::EncryptedDataBagItem.new(content, secret_key).to_hash end def detect_user_and_password if data_bag_name = Chef::Config[:knife][:profitbricks_data_bag] data_bag = load_data_bag 'profitbricks', data_bag_name [data_bag['user'], data_bag['password']] else [ENV['PROFITBRICKS_USER'], ENV['PROFITBRICKS_PASSWORD']] end end def log(m) ui.info m end def log_error(m) error m, :abort => false end def error(m, options={}) ui.error m exit 1 if !options.has_key?(:abort) || options[:abort] end end end * config for chef solo fixed module KnifeProfitbricks module Base LVS_ATTRIBUTES = [ :cpuHotPlug, :ramHotPlug, :nicHotPlug, :nicHotUnplug, :discVirtioHotPlug, :discVirtioHotUnplug ] def self.included(base) base.class_eval do deps do require 'profitbricks' require 'chef/knife' require 'knife_profitbricks/extension/profitbricks/profitbricks' require 'knife_profitbricks/extension/profitbricks/model' require 'knife_profitbricks/extension/profitbricks/has_location' require 'knife_profitbricks/extension/profitbricks/server' require 'knife_profitbricks/extension/profitbricks/datacenter' require 'knife_profitbricks/extension/profitbricks/volume' require 'knife_profitbricks/extension/profitbricks/nic' require 'knife_profitbricks/extension/profitbricks/location' require 'knife_profitbricks/extension/profitbricks/image' require 'knife_profitbricks/extension/profitbricks/lan' require 'knife_profitbricks/extension/profitbricks/request' require 'knife_profitbricks/extension/profitbricks/ipblock' require 'knife_profitbricks/extension/profitbricks/firewall' require 'knife_profitbricks/extension/profitbricks/location' require 'knife_profitbricks/extension/profitbricks/wait_for' require 'knife_profitbricks/extension/profitbricks/billing' require 'knife_profitbricks/extension/profitbricks/billing/traffic' Chef::Knife.load_deps Chef::Config[:solo] = true Chef::Config[:solo_legacy_mode] = true end option :profitbricks_data_bag, :short => "-a NAME", :long => "--profitbricks-data-bag NAME", :description => "Data bag for profitbricks account", :proc => lambda { |o| Chef::Config[:knife][:profitbricks_data_bag] = o } def self.method_added(name) if name.to_s == 'run' && !@run_added @run_added = true alias run_without_establish_connection run alias run run_with_establish_connection end end end end def run_with_establish_connection establish_connection run_without_establish_connection end private def establish_connection user, password = detect_user_and_password log "Establish connection to ProfitBricks for #{user.inspect}" ProfitBricks.configure do |config| config.username = user config.password = password config.global_classes = false config.timeout = 300 if config.path_prefix == '/rest/v2' config.path_prefix = '/cloudapi/v3/' end end log "Established ..." log "\n" end def load_data_bag(*args) secret_path = Chef::Config[:encrypted_data_bag_secret] secret_key = Chef::EncryptedDataBagItem.load_secret secret_path content = Chef::DataBagItem.load(*args).raw_data Chef::EncryptedDataBagItem.new(content, secret_key).to_hash end def detect_user_and_password if data_bag_name = Chef::Config[:knife][:profitbricks_data_bag] data_bag = load_data_bag 'profitbricks', data_bag_name [data_bag['user'], data_bag['password']] else [ENV['PROFITBRICKS_USER'], ENV['PROFITBRICKS_PASSWORD']] end end def log(m) ui.info m end def log_error(m) error m, :abort => false end def error(m, options={}) ui.error m exit 1 if !options.has_key?(:abort) || options[:abort] end end end
module RubyNessus module Version2 class Host include Enumerable # # Creates A New Host Object # # @param [Object] Host Object # # @example # Host.new(object) # def initialize(host) @host = host end def to_s "#{ip}" end # # Return the Host Object hostname. # # @return [String] # The Host Object Hostname # # @example # host.hostname #=> "example.com" # def hostname if (host = @host.at('tag[name=host-fqdn]')) host.inner_text end end alias name hostname alias fqdn hostname alias dns_name hostname # # Return the Host Object IP. # # @return [String] # The Host Object IP # # @example # host.ip #=> "127.0.0.1" # def ip if (ip = @host.at('tag[name=host-ip]')) ip.inner_text end end # # Return the host scan start time. # # @return [DateTime] # The Host Scan Start Time # # @example # scan.scan_start_time #=> 'Fri Nov 11 23:36:54 1985' # def start_time if (start_time = @host.at('tag[name=HOST_START]')) DateTime.strptime(start_time.inner_text, fmt='%a %b %d %H:%M:%S %Y') else false end end # # Return the host scan stop time. # # @return [DateTime] # The Host Scan Stop Time # # @example # scan.scan_start_time #=> 'Fri Nov 11 23:36:54 1985' # def stop_time if (stop_time = @host.at('tag[name=HOST_END]')) DateTime.strptime(stop_time.inner_text, fmt='%a %b %d %H:%M:%S %Y') else false end end # # Return the host run time. # # @return [String] # The Host Scan Run Time # # @example # scan.scan_run_time #=> '2 hours 5 minutes and 16 seconds' # def runtime get_runtime end alias scan_runtime runtime # # Return the Host Netbios Name. # # @return [String] # The Host Netbios Name # # @example # host.netbios_name #=> "SOMENAME4243" # def netbios_name if (netbios = @host.at('tag[name=netbios-name]')) netbios.inner_text end end # # Return the Host Mac Address. # # @return [String] # Return the Host Mac Address # # @example # host.mac_addr #=> "00:11:22:33:44:55" # def mac_addr if (mac_addr = @host.at('tag[name=mac-addr]')) mac_addr.inner_text end end alias mac_address mac_addr # # Return the Host OS Name. # # @return [String] # Return the Host OS Name # # @example # host.dns_name #=> "Microsoft Windows 2000, Microsoft Windows Server 2003" # def os_name if (os_name = @host.at('tag[name=operating-system]')) os_name.inner_text end end alias os os_name alias operating_system os_name # # Return the open ports for a given host object. # # @return [Integer] # Return the open ports for a given host object. # # @example # host.open_ports #=> 213 # def open_ports @scanned_ports ||= host_stats[:open_ports].to_i end # # Returns All Informational Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Informational Event Count For A Given Host. # # @example # host.informational_severity_events do |info| # puts info.port # puts info.data if info.data # end # def informational_severity_events(&block) unless @informational_events @informational_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 0 @informational_events << Event.new(event) end end @informational_events.each(&block) end # # Returns All Low Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Low Event Count For A Given Host. # # @example # host.low_severity_events do |low| # puts low.name if low.name # end # def low_severity_events(&block) unless @low_severity_events @low_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 1 @low_severity_events << Event.new(event) end end @low_severity_events.each(&block) end # # Returns All Medium Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Medium Event Count For A Given Host. # # @example # host.medium_severity_events do |medium| # puts medium.name if medium.name # end # def medium_severity_events(&block) unless @medium_severity_events @medium_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 2 @medium_severity_events << Event.new(event) end end @medium_severity_events.each(&block) end def medium_severity self.to_enum(:medium_severity_events).to_a end # # Returns All High Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The High Event Count For A Given Host. # # @example # host.high_severity_events do |high| # puts high.name if high.name # end # def high_severity_events(&block) unless @high_severity_events @high_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 3 @high_severity_events << Event.new(event) end end @high_severity_events.each(&block) end # # Returns All Critical Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Critical Event Count For A Given Host. # # @example # host.critical_severity_events do |critical| # puts critical.name if critical.name # end # def critical_severity_events(&block) unless @critical_severity_events @critical_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 4 @critical_severity_events << Event.new(event) end end @critical_severity_events.each(&block) end # # Return the total event count for a given host. # # @return [Integer] # Return the total event count for a given host. # # @example # host.event_count #=> 3456 # def event_count ((low_severity_events.count) + (medium_severity_events.count) + (high_severity_events.count) + (critical_severity_events.count)).to_i end # # Creates a new Event object to be parser # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # @yieldparam [EVENT] prog The newly created Event object. # # @example # host.each_event do |event| # puts event.name if event.name # puts event.port # end # def each_event(&block) @host.xpath("ReportItem").each do |event| block.call(Event.new(event)) if block end end # # Parses the events of the host. # # @return [Array<String>] # The events of the host. # def events self.to_enum(:each_event).to_a end # # Return an Array of open ports. # # @return [Array] # The open ports # # @example # scan.ports #=> ['22', '80', '443'] # def ports unless @ports @ports = [] @host.xpath("ReportItem").each do |port| @ports << port['port'] end @ports.uniq! @ports.sort! end @ports end # # Return the TCP Event Count. # # @return [Integer] # The TCP Event Count # # @example # scan.tcp_count #=> 3 # def tcp_count host_stats[:tcp].to_i end # # Return the UDP Event Count. # # @return [Integer] # The UDP Event Count # # @example # scan.udp_count #=> 3 # def udp_count host_stats[:udp].to_i end # # Return the ICMP Event Count. # # @return [Integer] # The ICMP Event Count # # @example # scan.icmp_count #=> 3 # def icmp_count host_stats[:icmp].to_i end # # Return the informational severity count. # # @return [Integer] # The Informational Severity Count # # @example # scan.informational_severity_count #=> 1203 # def informational_severity_count host_stats[:informational].to_i end # # Return the Critical severity count. # # @return [Integer] # The Critical Severity Count # # @example # scan.critical_severity_count #=> 10 # def critical_severity_count host_stats[:critical].to_i end # # Return the High severity count. # # @return [Integer] # The High Severity Count # # @example # scan.high_severity_count #=> 10 # def high_severity_count host_stats[:high].to_i end # # Return the Medium severity count. # # @return [Integer] # The Medium Severity Count # # @example # scan.medium_severity_count #=> 234 # def medium_severity_count host_stats[:medium].to_i end # # Return the Low severity count. # # @return [Integer] # The Low Severity Count # # @example # scan.low_severity_count #=> 114 # def low_severity_count host_stats[:low].to_i end # # Return the Total severity count. [high, medium, low, informational] # # @return [Integer] # The Total Severity Count # # @example # scan.total_event_count #=> 1561 # def total_event_count(count_informational = false) if count_informational host_stats[:all].to_i + informational_severity_count else host_stats[:all].to_i end end # # Return the Total severity count. # # @param [String] severity the severity in which to calculate percentage for. # # @param [true, false] round round the result to the nearest whole number. # # @raise [ExceptionClass] One of the following severity options must be passed. [high, medium, low, informational, all] # # @return [Integer] # The Percentage Of Events For A Passed Severity # # @example # scan.event_percentage_for("low", true) #=> 11% # def event_percentage_for(type, round_percentage=false) @sc ||= host_stats if %W(high medium low tcp udp icmp all).include?(type) calc = ((@sc[:"#{type}"].to_f / (@sc[:all].to_f)) * 100) if round_percentage return "#{calc.round}" else return "#{calc}" end else raise "Error: #{type} is not an acceptable severity. Possible options include: all, tdp, udp, icmp, high, medium and low." end end private def get_runtime if stop_time && start_time h = ("#{Time.parse(stop_time.to_s).strftime('%H').to_i - Time.parse(start_time.to_s).strftime('%H').to_i}").gsub('-', '') m = ("#{Time.parse(stop_time.to_s).strftime('%M').to_i - Time.parse(start_time.to_s).strftime('%M').to_i}").gsub('-', '') s = ("#{Time.parse(stop_time.to_s).strftime('%S').to_i - Time.parse(start_time.to_s).strftime('%S').to_i}").gsub('-', '') return "#{h} hours #{m} minutes and #{s} seconds" else false end end def host_stats unless @host_stats @host_stats = {} @open_ports, @tcp, @udp, @icmp, @informational, @low, @medium, @high, @critical = 0,0,0,0,0,0,0,0,0 @host.xpath("ReportItem").each do |s| case s['severity'].to_i when 0 @informational += 1 when 1 @low += 1 when 2 @medium += 1 when 3 @high += 1 when 4 @critical += 1 end unless s['severity'].to_i == 0 @tcp += 1 if s['protocol'] == 'tcp' @udp += 1 if s['protocol'] == 'udp' @icmp += 1 if s['protocol'] == 'icmp' end @open_ports += 1 if s['port'].to_i != 0 end @host_stats = {:open_ports => @open_ports, :tcp => @tcp, :udp => @udp, :icmp => @icmp, :informational => @informational, :low => @low, :medium => @medium, :high => @high, :critical => @critical, :all => (@low + @medium + @high + @critical)} end @host_stats end end end end corrected wrong tag for mac-address module RubyNessus module Version2 class Host include Enumerable # # Creates A New Host Object # # @param [Object] Host Object # # @example # Host.new(object) # def initialize(host) @host = host end def to_s "#{ip}" end # # Return the Host Object hostname. # # @return [String] # The Host Object Hostname # # @example # host.hostname #=> "example.com" # def hostname if (host = @host.at('tag[name=host-fqdn]')) host.inner_text end end alias name hostname alias fqdn hostname alias dns_name hostname # # Return the Host Object IP. # # @return [String] # The Host Object IP # # @example # host.ip #=> "127.0.0.1" # def ip if (ip = @host.at('tag[name=host-ip]')) ip.inner_text end end # # Return the host scan start time. # # @return [DateTime] # The Host Scan Start Time # # @example # scan.scan_start_time #=> 'Fri Nov 11 23:36:54 1985' # def start_time if (start_time = @host.at('tag[name=HOST_START]')) DateTime.strptime(start_time.inner_text, fmt='%a %b %d %H:%M:%S %Y') else false end end # # Return the host scan stop time. # # @return [DateTime] # The Host Scan Stop Time # # @example # scan.scan_start_time #=> 'Fri Nov 11 23:36:54 1985' # def stop_time if (stop_time = @host.at('tag[name=HOST_END]')) DateTime.strptime(stop_time.inner_text, fmt='%a %b %d %H:%M:%S %Y') else false end end # # Return the host run time. # # @return [String] # The Host Scan Run Time # # @example # scan.scan_run_time #=> '2 hours 5 minutes and 16 seconds' # def runtime get_runtime end alias scan_runtime runtime # # Return the Host Netbios Name. # # @return [String] # The Host Netbios Name # # @example # host.netbios_name #=> "SOMENAME4243" # def netbios_name if (netbios = @host.at('tag[name=netbios-name]')) netbios.inner_text end end # # Return the Host Mac Address. # # @return [String] # Return the Host Mac Address # # @example # host.mac_addr #=> "00:11:22:33:44:55" # def mac_addr if (mac_addr = @host.at('tag[name=mac-address]')) mac_addr.inner_text end end alias mac_address mac_addr # # Return the Host OS Name. # # @return [String] # Return the Host OS Name # # @example # host.dns_name #=> "Microsoft Windows 2000, Microsoft Windows Server 2003" # def os_name if (os_name = @host.at('tag[name=operating-system]')) os_name.inner_text end end alias os os_name alias operating_system os_name # # Return the open ports for a given host object. # # @return [Integer] # Return the open ports for a given host object. # # @example # host.open_ports #=> 213 # def open_ports @scanned_ports ||= host_stats[:open_ports].to_i end # # Returns All Informational Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Informational Event Count For A Given Host. # # @example # host.informational_severity_events do |info| # puts info.port # puts info.data if info.data # end # def informational_severity_events(&block) unless @informational_events @informational_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 0 @informational_events << Event.new(event) end end @informational_events.each(&block) end # # Returns All Low Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Low Event Count For A Given Host. # # @example # host.low_severity_events do |low| # puts low.name if low.name # end # def low_severity_events(&block) unless @low_severity_events @low_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 1 @low_severity_events << Event.new(event) end end @low_severity_events.each(&block) end # # Returns All Medium Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Medium Event Count For A Given Host. # # @example # host.medium_severity_events do |medium| # puts medium.name if medium.name # end # def medium_severity_events(&block) unless @medium_severity_events @medium_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 2 @medium_severity_events << Event.new(event) end end @medium_severity_events.each(&block) end def medium_severity self.to_enum(:medium_severity_events).to_a end # # Returns All High Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The High Event Count For A Given Host. # # @example # host.high_severity_events do |high| # puts high.name if high.name # end # def high_severity_events(&block) unless @high_severity_events @high_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 3 @high_severity_events << Event.new(event) end end @high_severity_events.each(&block) end # # Returns All Critical Event Objects For A Given Host. # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # # @yieldparam [EVENT] prog The newly created Event object. # # @return [Integer] # Return The Critical Event Count For A Given Host. # # @example # host.critical_severity_events do |critical| # puts critical.name if critical.name # end # def critical_severity_events(&block) unless @critical_severity_events @critical_severity_events = [] @host.xpath("ReportItem").each do |event| next if event['severity'].to_i != 4 @critical_severity_events << Event.new(event) end end @critical_severity_events.each(&block) end # # Return the total event count for a given host. # # @return [Integer] # Return the total event count for a given host. # # @example # host.event_count #=> 3456 # def event_count ((low_severity_events.count) + (medium_severity_events.count) + (high_severity_events.count) + (critical_severity_events.count)).to_i end # # Creates a new Event object to be parser # # @yield [prog] If a block is given, it will be passed the newly # created Event object. # @yieldparam [EVENT] prog The newly created Event object. # # @example # host.each_event do |event| # puts event.name if event.name # puts event.port # end # def each_event(&block) @host.xpath("ReportItem").each do |event| block.call(Event.new(event)) if block end end # # Parses the events of the host. # # @return [Array<String>] # The events of the host. # def events self.to_enum(:each_event).to_a end # # Return an Array of open ports. # # @return [Array] # The open ports # # @example # scan.ports #=> ['22', '80', '443'] # def ports unless @ports @ports = [] @host.xpath("ReportItem").each do |port| @ports << port['port'] end @ports.uniq! @ports.sort! end @ports end # # Return the TCP Event Count. # # @return [Integer] # The TCP Event Count # # @example # scan.tcp_count #=> 3 # def tcp_count host_stats[:tcp].to_i end # # Return the UDP Event Count. # # @return [Integer] # The UDP Event Count # # @example # scan.udp_count #=> 3 # def udp_count host_stats[:udp].to_i end # # Return the ICMP Event Count. # # @return [Integer] # The ICMP Event Count # # @example # scan.icmp_count #=> 3 # def icmp_count host_stats[:icmp].to_i end # # Return the informational severity count. # # @return [Integer] # The Informational Severity Count # # @example # scan.informational_severity_count #=> 1203 # def informational_severity_count host_stats[:informational].to_i end # # Return the Critical severity count. # # @return [Integer] # The Critical Severity Count # # @example # scan.critical_severity_count #=> 10 # def critical_severity_count host_stats[:critical].to_i end # # Return the High severity count. # # @return [Integer] # The High Severity Count # # @example # scan.high_severity_count #=> 10 # def high_severity_count host_stats[:high].to_i end # # Return the Medium severity count. # # @return [Integer] # The Medium Severity Count # # @example # scan.medium_severity_count #=> 234 # def medium_severity_count host_stats[:medium].to_i end # # Return the Low severity count. # # @return [Integer] # The Low Severity Count # # @example # scan.low_severity_count #=> 114 # def low_severity_count host_stats[:low].to_i end # # Return the Total severity count. [high, medium, low, informational] # # @return [Integer] # The Total Severity Count # # @example # scan.total_event_count #=> 1561 # def total_event_count(count_informational = false) if count_informational host_stats[:all].to_i + informational_severity_count else host_stats[:all].to_i end end # # Return the Total severity count. # # @param [String] severity the severity in which to calculate percentage for. # # @param [true, false] round round the result to the nearest whole number. # # @raise [ExceptionClass] One of the following severity options must be passed. [high, medium, low, informational, all] # # @return [Integer] # The Percentage Of Events For A Passed Severity # # @example # scan.event_percentage_for("low", true) #=> 11% # def event_percentage_for(type, round_percentage=false) @sc ||= host_stats if %W(high medium low tcp udp icmp all).include?(type) calc = ((@sc[:"#{type}"].to_f / (@sc[:all].to_f)) * 100) if round_percentage return "#{calc.round}" else return "#{calc}" end else raise "Error: #{type} is not an acceptable severity. Possible options include: all, tdp, udp, icmp, high, medium and low." end end private def get_runtime if stop_time && start_time h = ("#{Time.parse(stop_time.to_s).strftime('%H').to_i - Time.parse(start_time.to_s).strftime('%H').to_i}").gsub('-', '') m = ("#{Time.parse(stop_time.to_s).strftime('%M').to_i - Time.parse(start_time.to_s).strftime('%M').to_i}").gsub('-', '') s = ("#{Time.parse(stop_time.to_s).strftime('%S').to_i - Time.parse(start_time.to_s).strftime('%S').to_i}").gsub('-', '') return "#{h} hours #{m} minutes and #{s} seconds" else false end end def host_stats unless @host_stats @host_stats = {} @open_ports, @tcp, @udp, @icmp, @informational, @low, @medium, @high, @critical = 0,0,0,0,0,0,0,0,0 @host.xpath("ReportItem").each do |s| case s['severity'].to_i when 0 @informational += 1 when 1 @low += 1 when 2 @medium += 1 when 3 @high += 1 when 4 @critical += 1 end unless s['severity'].to_i == 0 @tcp += 1 if s['protocol'] == 'tcp' @udp += 1 if s['protocol'] == 'udp' @icmp += 1 if s['protocol'] == 'icmp' end @open_ports += 1 if s['port'].to_i != 0 end @host_stats = {:open_ports => @open_ports, :tcp => @tcp, :udp => @udp, :icmp => @icmp, :informational => @informational, :low => @low, :medium => @medium, :high => @high, :critical => @critical, :all => (@low + @medium + @high + @critical)} end @host_stats end end end end
require 'ruby-swagger/data/operation' module Swagger::Grape class Method attr_reader :operation def initialize(route_name, route) @route_name = route_name @route = route new_operation operation_params operation_responses operation_security self end private #generate the base of the operation def new_operation @operation = Swagger::Data::Operation.new @operation.tags = grape_tags @operation.operationId = @route.route_api_name if @route.route_api_name && @route.route_api_name.length > 0 @operation.summary = @route.route_description @operation.description = (@route.route_detail && @route.route_detail.length > 0) ? @route.route_detail : @route.route_description @operation.deprecated = @route.route_deprecated if @route.route_deprecated #grape extension @operation end def operation_params extract_params_and_types @params.each do |param_name, parameter| operation.add_parameter(parameter) end end def operation_responses @operation.responses = Swagger::Data::Responses.new #Long TODO - document here all the possible responses @operation.responses.add_response('200', Swagger::Data::Response.parse({'description' => 'Successful operation'})) @operation.responses.add_response('default', Swagger::Data::Response.parse({'description' => 'Unexpected error'})) end def operation_security # if route.route_scopes #grape extensions # security = Swagger::Data::SecurityRequirement.new # route.route_scopes.each do |name, requirements| # security.add_requirement(name, requirements) # end # # operations.security = route.route_scopes # end end #extract the tags def grape_tags (@route.route_tags && !@route.route_tags.empty?) ? @route.route_tags : [@route_name.split('/')[1]] end def extract_params_and_types @params, @types = {}, [] header_params path_params case @route.route_method.downcase when 'get' query_params when 'delete' query_params when 'post' body_params when 'put' body_params when 'patch' body_params when 'head' raise ArgumentError.new("Don't know how to handle the http verb HEAD for #{@route_name}") else raise ArgumentError.new("Don't know how to handle the http verb #{@route.route_method} for #{@route_name}") end @params end def header_params @params ||= {} #include all the parameters that are in the headers if @route.route_headers @route.route_headers.each do |header_key, header_value| @params[header_key] = {'name' => header_key, 'in' => 'header', 'required' => (header_value[:required] == true), 'type' => 'string', 'description' => header_value[:description]} end end @params end def path_params #include all the parameters that are in the path @route_name.scan(/\{[a-zA-Z0-9\-\_]+\}/).each do |parameter| #scan all parameters in the url param_name = parameter[1..parameter.length-2] @params[param_name] = {'name' => param_name, 'in' => 'path', 'required' => true, 'type' => 'string'} end end def query_params @route.route_params.each do |parameter| swag_param = Swagger::Data::Parameter.from_grape(parameter) next unless swag_param @params[parameter.first.to_s] = swag_param end end def body_params #include all the parameters that are in the content-body return unless @route.route_params && @route.route_params.length > 0 root_param = Swagger::Data::Parameter.parse({'name' => 'body', 'in' => 'body', 'description' => 'the content of the request', 'schema' => {'type' => 'object', 'properties' => {}}}) #create the params schema @route.route_params.each do |parameter| param_name = parameter.first param_value = parameter.last schema = root_param.schema next if @params.keys.include?(param_name) if param_name.scan(/[0-9a-zA-Z_]+/).count == 1 #it's a simple parameter, adding it to the properties of the main object schema.properties[param_name] = grape_param_to_swagger(param_value) required_parameter(schema, param_name, param_value) else schema_with_subobjects(schema, param_name, parameter.last) end end schema= root_param.schema @params['body'] = root_param if !schema.properties.nil? && schema.properties.keys.length > 0 end def required_parameter(schema, name, parameter) return if parameter.nil? || parameter[:required].nil? || parameter[:required] == false schema['required'] ||= [] schema['required'] << name end def schema_with_subobjects(schema, param_name, parameter) path = param_name.scan(/[0-9a-zA-Z_]+/) append_to = find_elem_in_schema(schema, path.dup) append_to['properties'][path.last] = grape_param_to_swagger(parameter) required_parameter(append_to, path.last, parameter) end def find_elem_in_schema(root, schema_path) return root if schema_path.nil? || schema_path.empty? next_elem = schema_path.shift return root if root['properties'][next_elem].nil? case root['properties'][next_elem]['type'] when 'array' #to descend an array this must be an array of objects root['properties'][next_elem]['items']['type'] = 'object' root['properties'][next_elem]['items']['properties'] ||= {} find_elem_in_schema(root['properties'][next_elem]['items'], schema_path) when 'object' find_elem_in_schema(root['properties'][next_elem], schema_path) else raise ArgumentError.new("Don't know how to handle the schema path #{schema_path.join('/')}") end end def grape_param_to_swagger(param) type = (param[:type] && param[:type].downcase) || 'string' response = {} response['description'] = param[:desc] if param[:desc].present? response['default'] = param[:default] if param[:default].present? case type when 'string' response['type'] = 'string' when 'integer' response['type'] = 'integer' when 'array' response['type'] = 'array' response['items'] = {'type' => 'string'} when 'hash' response['type'] = 'object' response['properties'] = {} when 'virtus::attribute::boolean' response['type'] = 'boolean' when 'symbol' response['type'] = 'string' when 'float' response['type'] = 'number' response['format'] = 'float' when 'rack::multipart::uploadedfile' response['type'] = 'file' when 'date' response['type'] = 'date' when 'datetime' response['format'] = 'date-time' response['format'] = 'string' else raise "Don't know how to convert they grape type #{type}" end response end end end skip parameters already processed require 'ruby-swagger/data/operation' module Swagger::Grape class Method attr_reader :operation def initialize(route_name, route) @route_name = route_name @route = route new_operation operation_params operation_responses operation_security self end private #generate the base of the operation def new_operation @operation = Swagger::Data::Operation.new @operation.tags = grape_tags @operation.operationId = @route.route_api_name if @route.route_api_name && @route.route_api_name.length > 0 @operation.summary = @route.route_description @operation.description = (@route.route_detail && @route.route_detail.length > 0) ? @route.route_detail : @route.route_description @operation.deprecated = @route.route_deprecated if @route.route_deprecated #grape extension @operation end def operation_params extract_params_and_types @params.each do |param_name, parameter| operation.add_parameter(parameter) end end def operation_responses @operation.responses = Swagger::Data::Responses.new #Long TODO - document here all the possible responses @operation.responses.add_response('200', Swagger::Data::Response.parse({'description' => 'Successful operation'})) @operation.responses.add_response('default', Swagger::Data::Response.parse({'description' => 'Unexpected error'})) end def operation_security # if route.route_scopes #grape extensions # security = Swagger::Data::SecurityRequirement.new # route.route_scopes.each do |name, requirements| # security.add_requirement(name, requirements) # end # # operations.security = route.route_scopes # end end #extract the tags def grape_tags (@route.route_tags && !@route.route_tags.empty?) ? @route.route_tags : [@route_name.split('/')[1]] end def extract_params_and_types @params, @types = {}, [] header_params path_params case @route.route_method.downcase when 'get' query_params when 'delete' query_params when 'post' body_params when 'put' body_params when 'patch' body_params when 'head' raise ArgumentError.new("Don't know how to handle the http verb HEAD for #{@route_name}") else raise ArgumentError.new("Don't know how to handle the http verb #{@route.route_method} for #{@route_name}") end @params end def header_params @params ||= {} #include all the parameters that are in the headers if @route.route_headers @route.route_headers.each do |header_key, header_value| @params[header_key] = {'name' => header_key, 'in' => 'header', 'required' => (header_value[:required] == true), 'type' => 'string', 'description' => header_value[:description]} end end @params end def path_params #include all the parameters that are in the path @route_name.scan(/\{[a-zA-Z0-9\-\_]+\}/).each do |parameter| #scan all parameters in the url param_name = parameter[1..parameter.length-2] @params[param_name] = {'name' => param_name, 'in' => 'path', 'required' => true, 'type' => 'string'} end end def query_params @route.route_params.each do |parameter| next if @params[parameter.first.to_s] swag_param = Swagger::Data::Parameter.from_grape(parameter) next unless swag_param swag_param.in = 'query' @params[parameter.first.to_s] = swag_param end end def body_params #include all the parameters that are in the content-body return unless @route.route_params && @route.route_params.length > 0 root_param = Swagger::Data::Parameter.parse({'name' => 'body', 'in' => 'body', 'description' => 'the content of the request', 'schema' => {'type' => 'object', 'properties' => {}}}) #create the params schema @route.route_params.each do |parameter| param_name = parameter.first param_value = parameter.last schema = root_param.schema next if @params.keys.include?(param_name) if param_name.scan(/[0-9a-zA-Z_]+/).count == 1 #it's a simple parameter, adding it to the properties of the main object schema.properties[param_name] = grape_param_to_swagger(param_value) required_parameter(schema, param_name, param_value) else schema_with_subobjects(schema, param_name, parameter.last) end end schema= root_param.schema @params['body'] = root_param if !schema.properties.nil? && schema.properties.keys.length > 0 end def required_parameter(schema, name, parameter) return if parameter.nil? || parameter[:required].nil? || parameter[:required] == false schema['required'] ||= [] schema['required'] << name end def schema_with_subobjects(schema, param_name, parameter) path = param_name.scan(/[0-9a-zA-Z_]+/) append_to = find_elem_in_schema(schema, path.dup) append_to['properties'][path.last] = grape_param_to_swagger(parameter) required_parameter(append_to, path.last, parameter) end def find_elem_in_schema(root, schema_path) return root if schema_path.nil? || schema_path.empty? next_elem = schema_path.shift return root if root['properties'][next_elem].nil? case root['properties'][next_elem]['type'] when 'array' #to descend an array this must be an array of objects root['properties'][next_elem]['items']['type'] = 'object' root['properties'][next_elem]['items']['properties'] ||= {} find_elem_in_schema(root['properties'][next_elem]['items'], schema_path) when 'object' find_elem_in_schema(root['properties'][next_elem], schema_path) else raise ArgumentError.new("Don't know how to handle the schema path #{schema_path.join('/')}") end end def grape_param_to_swagger(param) type = (param[:type] && param[:type].downcase) || 'string' response = {} response['description'] = param[:desc] if param[:desc].present? response['default'] = param[:default] if param[:default].present? case type when 'string' response['type'] = 'string' when 'integer' response['type'] = 'integer' when 'array' response['type'] = 'array' response['items'] = {'type' => 'string'} when 'hash' response['type'] = 'object' response['properties'] = {} when 'virtus::attribute::boolean' response['type'] = 'boolean' when 'symbol' response['type'] = 'string' when 'float' response['type'] = 'number' response['format'] = 'float' when 'rack::multipart::uploadedfile' response['type'] = 'file' when 'date' response['type'] = 'date' when 'datetime' response['format'] = 'date-time' response['format'] = 'string' else raise "Don't know how to convert they grape type #{type}" end response end end end
module ForecastIo module Constants def scale 'f' end def ansi_chars %w[_ ▁ ▃ ▅ ▇ █] # Thx, agj #pdxtech end def ozone_chars %w[・ o O @ ◎ ◉] end def ascii_chars %w[_ . - ~ * '] end # Based on the chance of precipitation. def get_rain_range_colors { 0..0.10 => :blue, 0.11..0.20 => :purple, 0.21..0.30 => :teal, 0.31..0.40 => :green, 0.41..0.50 => :lime, 0.51..0.60 => :aqua, 0.61..0.70 => :yellow, 0.71..0.80 => :orange, 0.81..0.90 => :red, 0.91..1 => :pink } end # Based on the precipIntensity field, tested mostly on Portland data. YIMV. def get_rain_intensity_range_colors { 0..0.0050 => :blue, 0.0051..0.0100 => :purple, 0.0101..0.0130 => :teal, 0.0131..0.0170 => :green, 0.0171..0.0220 => :lime, 0.0221..0.0280 => :aqua, 0.0281..0.0330 => :yellow, 0.0331..0.0380 => :orange, 0.0381..0.0430 => :red, 0.0431..5 => :pink } end # Based on the temp in F. def get_temp_range_colors # Absolute zero? You never know. { -459.7..24.99 => :blue, 25..31.99 => :purple, 32..38 => :teal, 38..45 => :green, 45..55 => :lime, 55..65 => :aqua, 65..75 => :yellow, 75..85 => :orange, 85..95 => :red, 95..99.999 => :brown, 100..159.3 => :pink } end # Based on the wind ground speed in mph. def get_wind_range_colors { 0..3 => :blue, 3..6 => :purple, 6..9 => :teal, 9..12 => :aqua, 12..15 => :yellow, 15..18 => :orange, 18..21 => :red, 21..999 => :pink, } end # Based on the chance of sun. def get_sun_range_colors { 0..0.20 => :green, 0.21..0.50 => :lime, 0.51..0.70 => :orange, 0.71..1 => :yellow } end # Based on the percentage of relative humidity. def get_humidity_range_colors { 0..0.12 => :blue, 0.13..0.25 => :purple, 0.26..0.38 => :teal, 0.39..0.5 => :aqua, 0.51..0.63 => :yellow, 0.64..0.75 => :orange, 0.76..0.88 => :red, 0.89..1 => :pink, } end # IRC colors. def colors { :white => '00', :black => '01', :blue => '02', :green => '03', :red => '04', :brown => '05', :purple => '06', :orange => '07', :yellow => '08', :lime => '09', :teal => '10', :aqua => '11', :royal => '12', :pink => '13', :grey => '14', :silver => '15' } end # Just a shorthand function to return the configured snowflake. def get_snowman(config) # '⛄' # Fancy emoji snowman # '❄️' # Fancy snowflake # '❄' # Regular snowflake config.snowflake end # I have no use for these yet, and yet they're handy to know. # def attributes # { :bold => 2.chr, # :underlined => 31.chr, # :underline => 31.chr, # :reversed => 22.chr, # :reverse => 22.chr, # :italic => 22.chr, # :reset => 15.chr, # } # end def get_uvindex_colors { 0..0 => :black, 1..1 => :royal, 2..2 => :brown, 3..3 => :purple, 4..4 => :green, 5..5 => :lime, 6..6 => :red, 7..7 => :orange, 8..8 => :yellow, 9..9 => :aqua, 10..10 => :pink, 11..11 => :white } end end end Fixed the temp colors for si units. module ForecastIo module Constants def scale 'f' end def ansi_chars %w[_ ▁ ▃ ▅ ▇ █] # Thx, agj #pdxtech end def ozone_chars %w[・ o O @ ◎ ◉] end def ascii_chars %w[_ . - ~ * '] end # Based on the chance of precipitation. def get_rain_range_colors { 0..0.10 => :blue, 0.11..0.20 => :purple, 0.21..0.30 => :teal, 0.31..0.40 => :green, 0.41..0.50 => :lime, 0.51..0.60 => :aqua, 0.61..0.70 => :yellow, 0.71..0.80 => :orange, 0.81..0.90 => :red, 0.91..1 => :pink } end # Based on the precipIntensity field, tested mostly on Portland data. YIMV. def get_rain_intensity_range_colors { 0..0.0050 => :blue, 0.0051..0.0100 => :purple, 0.0101..0.0130 => :teal, 0.0131..0.0170 => :green, 0.0171..0.0220 => :lime, 0.0221..0.0280 => :aqua, 0.0281..0.0330 => :yellow, 0.0331..0.0380 => :orange, 0.0381..0.0430 => :red, 0.0431..5 => :pink } end # Based on the temp in F. def get_temp_range_colors # Absolute zero? You never know. { -273.17..-3.899 => :blue, -3.9..-0.009 => :purple, 0..3.333 => :teal, 3.334..7.222 => :green, 7.223..12.78 => :lime, 12.79..18.333 => :aqua, 18.334..23.89 => :yellow, 23.90..29.44 => :orange, 29.45..35 => :red, 35.001..37.777 => :brown, 37.778..71 => :pink } end # Based on the wind ground speed in mph. def get_wind_range_colors { 0..3 => :blue, 3..6 => :purple, 6..9 => :teal, 9..12 => :aqua, 12..15 => :yellow, 15..18 => :orange, 18..21 => :red, 21..999 => :pink, } end # Based on the chance of sun. def get_sun_range_colors { 0..0.20 => :green, 0.21..0.50 => :lime, 0.51..0.70 => :orange, 0.71..1 => :yellow } end # Based on the percentage of relative humidity. def get_humidity_range_colors { 0..0.12 => :blue, 0.13..0.25 => :purple, 0.26..0.38 => :teal, 0.39..0.5 => :aqua, 0.51..0.63 => :yellow, 0.64..0.75 => :orange, 0.76..0.88 => :red, 0.89..1 => :pink, } end # IRC colors. def colors { :white => '00', :black => '01', :blue => '02', :green => '03', :red => '04', :brown => '05', :purple => '06', :orange => '07', :yellow => '08', :lime => '09', :teal => '10', :aqua => '11', :royal => '12', :pink => '13', :grey => '14', :silver => '15' } end # Just a shorthand function to return the configured snowflake. def get_snowman(config) # '⛄' # Fancy emoji snowman # '❄️' # Fancy snowflake # '❄' # Regular snowflake config.snowflake end # I have no use for these yet, and yet they're handy to know. # def attributes # { :bold => 2.chr, # :underlined => 31.chr, # :underline => 31.chr, # :reversed => 22.chr, # :reverse => 22.chr, # :italic => 22.chr, # :reset => 15.chr, # } # end def get_uvindex_colors { 0..0 => :black, 1..1 => :royal, 2..2 => :brown, 3..3 => :purple, 4..4 => :green, 5..5 => :lime, 6..6 => :red, 7..7 => :orange, 8..8 => :yellow, 9..9 => :aqua, 10..10 => :pink, 11..11 => :white } end end end
Enable commands require 'rubygems-compile/commands/compile_command' Gem::CommandManager.instance.register_command :compile require 'rubygems-compile/commands/uncompile_command' Gem::CommandManager.instance.register_command :uncompile require 'rubygems-compile/commands/autocompile_command' Gem::CommandManager.instance.register_command :auto_compile
require "securerandom" require "jarvis/commands/ping" require "concurrent" require "stud/interval" require "time" module Lita module Handlers # This handler exists because sometimes Hipchat's connection will simply # die or go stale and the bot will never notice. # # The goal is to have the bot periodically ping itself through chat and # restart if chat appears dead. class Heartbeat < Handler # This key unique to each run of Lita/Jarvis. HEARTBEAT_KEY = SecureRandom.uuid HEARTBEAT_INTERVAL = 60 # seconds HEARTBEAT_TIMEOUT = 180 # seconds # Initial assumed "last heartbeat time" is start time of the program LastHeartBeat = ::Concurrent::AtomicReference.new(Time.now.utc) route(/^heartbeat (\S+) (\d+(?:\.\d+)?)/, :heartbeat, command: true) route(/^ping\s*$/, :ping, :command => true) on(:loaded) do |*args| #if robot.config.adapter.any? if robot.config.adapters.respond_to?(:hipchat) puts "Starting chat health checker" Thread.new { self.class.heartbeat_loop(robot) } Thread.new { self.class.health_check_loop(robot) } else puts "No Lita adapter is configured. Chat health checker is disabled! This is OK only if the adapter is Shell. The rest of the time (production?) you will want this" end end def self.heartbeat_loop(robot) # Periodically send a heartbeat via chat to ourselves to verify that the actual chat system is alive. Stud.interval(HEARTBEAT_INTERVAL) { send_heartbeat(robot) } rescue => e puts "Heartbeat loop died: #{e.class}: #{e}" end def self.send_heartbeat(robot) robot.send_message(robot.name, "heartbeat #{HEARTBEAT_KEY} #{Time.now.to_f}") end def self.health_check_loop(robot) Stud.interval(HEARTBEAT_TIMEOUT) { health_check(robot) } rescue Exception => e puts "Health check loop died: #{e}" end def self.health_check(robot) last = LastHeartBeat.get age = Time.now - last if age > HEARTBEAT_TIMEOUT puts "Last heartbeat was #{age} seconds ago; expiration time is #{HEARTBEAT_TIMEOUT}. Aborting..." # Restart exec($0) end rescue Exception => e puts "Health check loop died: #{e.class}: #{e}" end def heartbeat(response) key = response.match_data[1] time = Time.at(response.match_data[2]) now = Time.now if key != HEARTBEAT_KEY response.reply("Invalid heartbeat key") return end # Make sure the heartbeat isn't too old age = now - time if age > HEARTBEAT_TIMEOUT puts "Received old heartbeat (#{age} seconds). Ignoring" return end LastHeartBeat.set(now.utc) end def ping(response) response.reply(I18n.t("lita.handlers.jarvis.ping response", :last_heartbeat => LastHeartBeat.get.iso8601)) end Lita.register_handler(self) end end end Disable heartbeats; they don't work right. Will revisit later. require "securerandom" require "jarvis/commands/ping" require "concurrent" require "stud/interval" require "time" module Lita module Handlers # This handler exists because sometimes Hipchat's connection will simply # die or go stale and the bot will never notice. # # The goal is to have the bot periodically ping itself through chat and # restart if chat appears dead. class Heartbeat < Handler # This key unique to each run of Lita/Jarvis. HEARTBEAT_KEY = SecureRandom.uuid HEARTBEAT_INTERVAL = 60 # seconds HEARTBEAT_TIMEOUT = 180 # seconds # Initial assumed "last heartbeat time" is start time of the program LastHeartBeat = ::Concurrent::AtomicReference.new(Time.now.utc) route(/^heartbeat (\S+) (\d+(?:\.\d+)?)/, :heartbeat, command: true) route(/^ping\s*$/, :ping, :command => true) #on(:loaded) do |*args| ##if robot.config.adapter.any? #if robot.config.adapters.respond_to?(:hipchat) #puts "Starting chat health checker" #Thread.new { self.class.heartbeat_loop(robot) } #Thread.new { self.class.health_check_loop(robot) } #else #puts "No Lita adapter is configured. Chat health checker is disabled! This is OK only if the adapter is Shell. The rest of the time (production?) you will want this" #end #end def self.heartbeat_loop(robot) # Periodically send a heartbeat via chat to ourselves to verify that the actual chat system is alive. Stud.interval(HEARTBEAT_INTERVAL) { send_heartbeat(robot) } rescue => e puts "Heartbeat loop died: #{e.class}: #{e}" end def self.send_heartbeat(robot) robot.send_message(robot.name, "heartbeat #{HEARTBEAT_KEY} #{Time.now.to_f}") end def self.health_check_loop(robot) Stud.interval(HEARTBEAT_TIMEOUT) { health_check(robot) } rescue Exception => e puts "Health check loop died: #{e}" end def self.health_check(robot) last = LastHeartBeat.get age = Time.now - last if age > HEARTBEAT_TIMEOUT puts "Last heartbeat was #{age} seconds ago; expiration time is #{HEARTBEAT_TIMEOUT}. Aborting..." # Restart exec($0) end rescue Exception => e puts "Health check loop died: #{e.class}: #{e}" end def heartbeat(response) key = response.match_data[1] time = Time.at(response.match_data[2]) now = Time.now if key != HEARTBEAT_KEY response.reply("Invalid heartbeat key") return end # Make sure the heartbeat isn't too old age = now - time if age > HEARTBEAT_TIMEOUT puts "Received old heartbeat (#{age} seconds). Ignoring" return end LastHeartBeat.set(now.utc) end def ping(response) response.reply(I18n.t("lita.handlers.jarvis.ping response", :last_heartbeat => LastHeartBeat.get.iso8601)) end Lita.register_handler(self) end end end
module Rufus module Drivers class DriverBase attr_reader :config def capabilities; raise Exception; end def start selenium.get url end def quit selenium.quit @selenium_driver = nil end def server_url @url end def find(locator) how = locator.keys[0].to_sym what = locator[how] begin selenium.find_element(how, what) rescue Selenium::WebDriver::Error::NoSuchElementError return nil end end def contains_name_key?(locator) locator.keys[0].to_s.eql?('name') end def cells(locator) element = find(locator) raise 'Expected view to be of type UIATableView' unless element.tag_name.eql? 'UIATableView' element.find_elements(:tag_name, 'UIATableCell') end def exists?(locator) not find(locator).nil? end def click(locator) find(locator).click end def press_button name click(:name => name) end def enabled?(locator) find(locator).enabled? end def displayed?(locator) find(locator).displayed? end def text(locator) find(locator).text end def class(locator) find(locator).tag_name end def orientation selenium.orientation.to_s end def rotate(orientation) selenium.rotate orientation end def type(keys, name) element = find(:name => name) element.click sleep 1 element.send_keys keys end def sequence(*names, times) timed_sequence(names, times, 1) end def buttons buttons = [] elements = elements_by_tag 'UIAButton' elements.each do |element| buttons << element.text end buttons end def text_fields fields = [] elements = elements_by_tag 'UIATextField' elements.each do |element| fields << element.text end fields end def labels labels = [] elements = elements_by_tag 'UIAStaticText' elements.each do |element| labels << element.text end labels end def timed_sequence(names, times, seconds) current = 0 until current == times names.each do |name| click(:name => name) sleep seconds end current += 1 puts "sequence #{current} completed" end end def find_alert(locator) alert = nil all_elements.each do |element| if is_alert?(element) alert = element if match?(element, locator[:name]) end end alert end def click_alert(button) if alert_shown? click_alert_button(button) end end def alert_shown? all_elements.each do |element| if is_alert?(element) return true end end false end def class_for(element) element.tag_name end def match?(element, name) element.attribute(:name).eql? name end def page_source selenium.page_source end def all_elements elements_by_tag('UIAElement') end def elements_by_tag(name) selenium.find_elements(:tag_name, name) end def scroll_to(locator) id = find(locator).ref selenium.execute_script 'mobile: scrollTo', {'element' => id} end def touch_and_hold(element, duration) #selenium.execute_script script, args end def tap(x, y) selenium.execute_script 'mobile: tap', :x => x, :y => y end def screenshot(name) selenium.save_screenshot name end private def url if @config["appium_url"].nil? || @config["appium_url"].eql?("") 'http://127.0.0.1:4723/wd/hub' else @config["appium_url"] end end def click_alert_button(button) all_elements.each do |element| element.click if is_table_view_cell?(element) && match?(element, button) end end def is_alert?(element) class_for(element).eql?('UIAAlert') end def is_table_view_cell?(element) class_for(element).eql?('UIATableCell') end def selenium @selenium_driver ||= Selenium::WebDriver.for(:remote, :desired_capabilities => capabilities, :url => url) end end end end uncommented method module Rufus module Drivers class DriverBase attr_reader :config def capabilities; raise Exception; end def start selenium.get url end def quit selenium.quit @selenium_driver = nil end def server_url @url end def find(locator) how = locator.keys[0].to_sym what = locator[how] begin selenium.find_element(how, what) rescue Selenium::WebDriver::Error::NoSuchElementError return nil end end def contains_name_key?(locator) locator.keys[0].to_s.eql?('name') end def cells(locator) element = find(locator) raise 'Expected view to be of type UIATableView' unless element.tag_name.eql? 'UIATableView' element.find_elements(:tag_name, 'UIATableCell') end def exists?(locator) not find(locator).nil? end def click(locator) find(locator).click end def press_button name click(:name => name) end def enabled?(locator) find(locator).enabled? end def displayed?(locator) find(locator).displayed? end def text(locator) find(locator).text end def class(locator) find(locator).tag_name end def orientation selenium.orientation.to_s end def rotate(orientation) selenium.rotate orientation end def type(keys, name) element = find(:name => name) element.click sleep 1 element.send_keys keys end def sequence(*names, times) timed_sequence(names, times, 1) end def buttons buttons = [] elements = elements_by_tag 'UIAButton' elements.each do |element| buttons << element.text end buttons end def text_fields fields = [] elements = elements_by_tag 'UIATextField' elements.each do |element| fields << element.text end fields end def labels labels = [] elements = elements_by_tag 'UIAStaticText' elements.each do |element| labels << element.text end labels end def timed_sequence(names, times, seconds) current = 0 until current == times names.each do |name| click(:name => name) sleep seconds end current += 1 puts "sequence #{current} completed" end end def find_alert(locator) alert = nil all_elements.each do |element| if is_alert?(element) alert = element if match?(element, locator[:name]) end end alert end def click_alert(button) if alert_shown? click_alert_button(button) end end def alert_shown? all_elements.each do |element| if is_alert?(element) return true end end false end def class_for(element) element.tag_name end def match?(element, name) element.attribute(:name).eql? name end def page_source selenium.page_source end def all_elements elements_by_tag('UIAElement') end def elements_by_tag(name) selenium.find_elements(:tag_name, name) end def scroll_to(locator) id = find(locator).ref selenium.execute_script 'mobile: scrollTo', {'element' => id} end def touch_and_hold(element, duration) selenium.execute_script 'mobile: tap', element, duration end def tap(x, y) selenium.execute_script 'mobile: tap', :x => x, :y => y end def screenshot(name) selenium.save_screenshot name end private def url if @config["appium_url"].nil? || @config["appium_url"].eql?("") 'http://127.0.0.1:4723/wd/hub' else @config["appium_url"] end end def click_alert_button(button) all_elements.each do |element| element.click if is_table_view_cell?(element) && match?(element, button) end end def is_alert?(element) class_for(element).eql?('UIAAlert') end def is_table_view_cell?(element) class_for(element).eql?('UIATableCell') end def selenium @selenium_driver ||= Selenium::WebDriver.for(:remote, :desired_capabilities => capabilities, :url => url) end end end end
module Localizer::Parser::Writer # Handles translation in JS source. Returns translated parameter. def translate prefix, key, value qualified_key = join_keys prefix, key if trnaslation_entry = translations[qualified_key] value.replace_with trnaslation_entry.send locale else value end end # Produces parser output. In case of Writer, concatenates all the unchanged # chunks of parsed source and inserted translations. def output lines lines.flatten.lazy.map{ |x| (x.respond_to? :raw) ? x.raw : x }.reduce(:<<) end end Fixed typo module Localizer::Parser::Writer # Handles translation in JS source. Returns translated parameter. def translate prefix, key, value qualified_key = join_keys prefix, key if translation_entry = translations[qualified_key] value.replace_with translation_entry.send locale else value end end # Produces parser output. In case of Writer, concatenates all the unchanged # chunks of parsed source and inserted translations. def output lines lines.flatten.lazy.map{ |x| (x.respond_to? :raw) ? x.raw : x }.reduce(:<<) end end
require "logstash/filters/base" require "logstash/namespace" require "logstash/time" # The mutate filter allows you to do general mutations to fields. You # can rename, remove, replace, and modify fields in your events. # # TODO(sissel): Support regexp replacements like String#gsub ? class LogStash::Filters::Mutate < LogStash::Filters::Base config_name "mutate" plugin_status "stable" # Rename one or more fields. # # Example: # # filter { # mutate { # # Renames the 'HOSTORIP' field to 'client_ip' # rename => [ "HOSTORIP", "client_ip" ] # } # } config :rename, :validate => :hash # Remove one or more fields. # # Example: # # filter { # mutate { # remove => [ "client" ] # Removes the 'client' field # } # } config :remove, :validate => :array # Replace a field with a new value. The new value can include %{foo} strings # to help you build a new value from other parts of the event. # # Example: # # filter { # mutate { # replace => [ "@message", "%{source_host}: My new message" ] # } # } config :replace, :validate => :hash # Convert a field's value to a different type, like turning a string to an # integer. If the field value is an array, all members will be converted. # If the field is a hash, no action will be taken. # # Valid conversion targets are: integer, float, string # # Example: # # filter { # mutate { # convert => [ "fieldname", "integer" ] # } # } config :convert, :validate => :hash # Convert a string field by applying a regular expression and a replacement # if the field is not a string, no action will be taken # # this configuration takes an array consisting of 3 elements per field/substitution # # be aware of escaping any backslash in the config file # # for example: # # mutate { # … # gsub => [ # "fieldname", "\\/", "_", #replace all forward slashes with underscore # "fieldname", "[\\?#-]", "_" #replace backslashes, question marks, hashes and minuses with underscore # ] # … # } # config :gsub, :validate => :array public def register valid_conversions = %w(string integer float) # TODO(sissel): Validate conversion requests if provided. @convert.nil? or @convert.each do |field, type| if !valid_conversions.include?(type) @logger.error("Invalid conversion type", "type" => type, "expected one of" => valid_types) # TODO(sissel): It's 2011, man, let's actually make like.. a proper # 'configuration broken' exception raise "Bad configuration, aborting." end end # @convert.each @gsub_parsed = [] @gsub.nil? or @gsub.each_slice(3) do |field, needle, replacement| if [field, needle, replacement].any? {|n| n.nil?} @logger.error("Invalid gsub configuration. gsub has to define 3 elements per config entry", :file => file, :needle => needle, :replacement => replacement) raise "Bad configuration, aborting." end @gsub_parsed << { :field => field, :needle => Regexp.new(needle), :replacement => replacement } end end # def register public def filter(event) return unless filter?(event) rename(event) if @rename remove(event) if @remove replace(event) if @replace convert(event) if @convert gsub(event) if @gsub filter_matched(event) end # def filter private def remove(event) # TODO(sissel): use event.sprintf on the field names? @remove.each do |field| event.remove(field) end end # def remove private def rename(event) # TODO(sissel): use event.sprintf on the field names? @rename.each do |old, new| event[new] = event[old] event.remove(old) end end # def rename private def replace(event) # TODO(sissel): use event.sprintf on the field names? @replace.each do |field, newvalue| next unless event[field] event[field] = event.sprintf(newvalue) end end # def replace def convert(event) @convert.each do |field, type| original = event[field] # calls convert_{string,integer,float} depending on type requested. converter = method("convert_" + type) if original.is_a?(Hash) @logger.debug("I don't know how to type convert a hash, skipping", :field => field, :value => original) next elsif original.is_a?(Array) value = original.map { |v| converter.call(v) } else value = converter.call(original) end event[field] = value end end # def convert def convert_string(value) return value.to_s end # def convert_string def convert_integer(value) return value.to_i end # def convert_integer def convert_float(value) return value.to_f end # def convert_float private def gsub(event) @gsub_parsed.each do |config| field = config[:field] needle = config[:needle] replacement = config[:replacement] if event[field].is_a?(Array) event[field] = event[field].map do |v| if not v.is_a?(String) @logger.warn("gsub mutation is only applicable for Strings, " + "skipping", :field => field, :value => v) v else v.gsub(needle, replacement) end end else if not event[field].is_a?(String) @logger.debug("gsub mutation is only applicable for Strings, " + "skipping", :field => field, :value => event[field]) next end event[field] = event[field].gsub(needle, replacement) end end # @gsub_parsed.each end # def gsub end # class LogStash::Filters::Mutate Added the lowercase and uppercase mutations to the mutate filter. A fairly simple feature addition, each mutation will check to see if the input is a string before calling either .upcase! or .downcase! require "logstash/filters/base" require "logstash/namespace" require "logstash/time" # The mutate filter allows you to do general mutations to fields. You # can rename, remove, replace, and modify fields in your events. # # TODO(sissel): Support regexp replacements like String#gsub ? class LogStash::Filters::Mutate < LogStash::Filters::Base config_name "mutate" plugin_status "stable" # Rename one or more fields. # # Example: # # filter { # mutate { # # Renames the 'HOSTORIP' field to 'client_ip' # rename => [ "HOSTORIP", "client_ip" ] # } # } config :rename, :validate => :hash # Remove one or more fields. # # Example: # # filter { # mutate { # remove => [ "client" ] # Removes the 'client' field # } # } config :remove, :validate => :array # Replace a field with a new value. The new value can include %{foo} strings # to help you build a new value from other parts of the event. # # Example: # # filter { # mutate { # replace => [ "@message", "%{source_host}: My new message" ] # } # } config :replace, :validate => :hash # Convert a field's value to a different type, like turning a string to an # integer. If the field value is an array, all members will be converted. # If the field is a hash, no action will be taken. # # Valid conversion targets are: integer, float, string # # Example: # # filter { # mutate { # convert => [ "fieldname", "integer" ] # } # } config :convert, :validate => :hash # Convert a string field by applying a regular expression and a replacement # if the field is not a string, no action will be taken # # this configuration takes an array consisting of 3 elements per field/substitution # # be aware of escaping any backslash in the config file # # for example: # # mutate { # … # gsub => [ # "fieldname", "\\/", "_", #replace all forward slashes with underscore # "fieldname", "[\\?#-]", "_" #replace backslashes, question marks, hashes and minuses with underscore # ] # … # } # config :gsub, :validate => :array # Convert a string to its uppercase equivalent # # Example: # # mutate { # uppercase => [ "fieldname" ] # } # config :uppercase, :validate => :array # Convert a string to its lowercase equivalent # # Example: # # mutate { # lowercase => [ "fieldname" ] # } # config :lowercase, :validate => :array public def register valid_conversions = %w(string integer float) # TODO(sissel): Validate conversion requests if provided. @convert.nil? or @convert.each do |field, type| if !valid_conversions.include?(type) @logger.error("Invalid conversion type", "type" => type, "expected one of" => valid_types) # TODO(sissel): It's 2011, man, let's actually make like.. a proper # 'configuration broken' exception raise "Bad configuration, aborting." end end # @convert.each @gsub_parsed = [] @gsub.nil? or @gsub.each_slice(3) do |field, needle, replacement| if [field, needle, replacement].any? {|n| n.nil?} @logger.error("Invalid gsub configuration. gsub has to define 3 elements per config entry", :file => file, :needle => needle, :replacement => replacement) raise "Bad configuration, aborting." end @gsub_parsed << { :field => field, :needle => Regexp.new(needle), :replacement => replacement } end end # def register public def filter(event) return unless filter?(event) rename(event) if @rename remove(event) if @remove replace(event) if @replace convert(event) if @convert gsub(event) if @gsub uppercase(event) if @uppercase lowercase(event) if @lowercase filter_matched(event) end # def filter private def remove(event) # TODO(sissel): use event.sprintf on the field names? @remove.each do |field| event.remove(field) end end # def remove private def rename(event) # TODO(sissel): use event.sprintf on the field names? @rename.each do |old, new| event[new] = event[old] event.remove(old) end end # def rename private def replace(event) # TODO(sissel): use event.sprintf on the field names? @replace.each do |field, newvalue| next unless event[field] event[field] = event.sprintf(newvalue) end end # def replace def convert(event) @convert.each do |field, type| original = event[field] # calls convert_{string,integer,float} depending on type requested. converter = method("convert_" + type) if original.is_a?(Hash) @logger.debug("I don't know how to type convert a hash, skipping", :field => field, :value => original) next elsif original.is_a?(Array) value = original.map { |v| converter.call(v) } else value = converter.call(original) end event[field] = value end end # def convert def convert_string(value) return value.to_s end # def convert_string def convert_integer(value) return value.to_i end # def convert_integer def convert_float(value) return value.to_f end # def convert_float private def gsub(event) @gsub_parsed.each do |config| field = config[:field] needle = config[:needle] replacement = config[:replacement] if event[field].is_a?(Array) event[field] = event[field].map do |v| if not v.is_a?(String) @logger.warn("gsub mutation is only applicable for Strings, " + "skipping", :field => field, :value => v) v else v.gsub(needle, replacement) end end else if not event[field].is_a?(String) @logger.debug("gsub mutation is only applicable for Strings, " + "skipping", :field => field, :value => event[field]) next end event[field] = event[field].gsub(needle, replacement) end end # @gsub_parsed.each end # def gsub private def uppercase(event) @uppercase.each do |field| if event[field].is_a?(String) event[field].upcase! else @logger.debug("Can't uppercase something that isn't a string", :field => field, :value => event[field]) end end end # def uppercase private def lowercase(event) @lowercase.each do |field| if event[field].is_a?(String) event[field].downcase! else @logger.debug("Can't lowercase something that isn't a string", :field => field, :value => event[field]) end end end # def lowercase end # class LogStash::Filters::Mutate
Pod::Spec.new do |s| s.name = "Organic" s.version = "0.2" s.summary = "The intuitive UITableViewController." s.homepage = "https://github.com/mamaral/Organic" s.license = "MIT" s.author = { "Mike Amaral" => "mike.amaral36@gmail.com" } s.social_media_url = "http://twitter.com/MikeAmaral" s.platform = :ios s.source = { :git => "https://github.com/mamaral/Organic.git", :tag => "v0.2" } s.source_files = "Organic/Source/OrganicViewController.{h,m}", "Organic/Source/OrganicSection.{h,m}", "Organic/Source/OrganicCell.{h,m}" s.requires_arc = true end Updated podspec with new minor version update. Pod::Spec.new do |s| s.name = "Organic" s.version = "0.3" s.summary = "The intuitive UITableViewController." s.homepage = "https://github.com/mamaral/Organic" s.license = "MIT" s.author = { "Mike Amaral" => "mike.amaral36@gmail.com" } s.social_media_url = "http://twitter.com/MikeAmaral" s.platform = :ios s.source = { :git => "https://github.com/mamaral/Organic.git", :tag => "v0.3" } s.source_files = "Organic/Source/OrganicViewController.{h,m}", "Organic/Source/OrganicSection.{h,m}", "Organic/Source/OrganicCell.{h,m}" s.requires_arc = true end
module SemanticFormFor VERSION = '0.5.0' end Bump version for release module SemanticFormFor VERSION = '0.5.1' end
namespace :firms do desc 'Index all existing firms' task :index => :environment do puts 'Do you want to index all existing firms? [type `yes` to confirm]' confirmation = STDIN.gets.chomp if confirmation.downcase == 'yes' puts 'Building firms index...' Firm.registered.each {|f| IndexFirmJob.perform_later(f) } puts '...indexing done.' else puts 'Indexing aborted.' end end end Conform firms index rake task to style namespace :firms do desc 'Index all existing firms' task index: :environment do puts 'Do you want to index all existing firms? [type `yes` to confirm]' confirmation = STDIN.gets.chomp if confirmation.downcase == 'yes' puts 'Building firms index...' Firm.registered.each { |f| IndexFirmJob.perform_later(f) } puts '...indexing done.' else puts 'Indexing aborted.' end end end
module Sepa # Handles OP specific response logic. Mainly certificate specific stuff. class OpResponse < Response include Utilities BYPASS_COMMANDS = %i( get_certificate get_service_certificates ) # Extracts own signing certificate from the response. # # @return [String] own signing certificate as string it it is found # @return [nil] if the certificate cannot be found def own_signing_certificate application_response = extract_application_response(OP_PKI) at = 'xmlns|Certificate > xmlns|Certificate' node = Nokogiri::XML(application_response).at(at, xmlns: OP_XML_DATA) return unless node cert_value = process_cert_value node.content cert = x509_certificate cert_value cert.to_s end # Returns the response code in the response. Overrides {Response#response_code} if {#command} is # `:get_certificate`, because the namespace is different with that command. # # @return [String] response code if it is found # @return [nil] if response code cannot be found # @see Response#response_code def response_code return super unless %i( get_certificate get_service_certificates ).include? command node = doc.at('xmlns|ResponseCode', xmlns: OP_PKI) node.content if node end # Returns the response text in the response. Overrides {Response#response_text} if {#command} is # `:get_certificate`, because the namespace is different with that command. # # @return [String] response text if it is found # @return [nil] if response text cannot be found # @see Response#response_text def response_text return super unless %i( get_certificate get_service_certificates ).include? command node = doc.at('xmlns|ResponseText', xmlns: OP_PKI) node.content if node end # Checks whether the certificate embedded in the response soap has been signed with OP's # root certificate. The check is skipped in test environment, because a different root # certificate is used. The check is also skipped for certificate requests because they are not # signed # # @return [true] if certificate is trusted # @return [false] if certificate fails to verify # @see DanskeResponse#certificate_is_trusted? def certificate_is_trusted? if environment == :test || BYPASS_COMMANDS.include?(command) return true end verify_certificate_against_root_certificate(certificate, OP_ROOT_CERTIFICATE) end # Some OP's certificate responses aren't signed def validate_hashes super unless BYPASS_COMMANDS.include?(command) end # Some OP's certificate responses aren't signed def verify_signature super unless BYPASS_COMMANDS.include?(command) end end end Reformat module Sepa # Handles OP specific response logic. Mainly certificate specific stuff. class OpResponse < Response include Utilities BYPASS_COMMANDS = %i( get_certificate get_service_certificates ) # Extracts own signing certificate from the response. # # @return [String] own signing certificate as string it it is found # @return [nil] if the certificate cannot be found def own_signing_certificate application_response = extract_application_response(OP_PKI) at = 'xmlns|Certificate > xmlns|Certificate' node = Nokogiri::XML(application_response).at(at, xmlns: OP_XML_DATA) return unless node cert_value = process_cert_value node.content cert = x509_certificate cert_value cert.to_s end # Returns the response code in the response. Overrides {Response#response_code} if {#command} is # `:get_certificate`, because the namespace is different with that command. # # @return [String] response code if it is found # @return [nil] if response code cannot be found # @see Response#response_code def response_code return super unless %i( get_certificate get_service_certificates ).include? command node = doc.at('xmlns|ResponseCode', xmlns: OP_PKI) node.content if node end # Returns the response text in the response. Overrides {Response#response_text} if {#command} is # `:get_certificate`, because the namespace is different with that command. # # @return [String] response text if it is found # @return [nil] if response text cannot be found # @see Response#response_text def response_text return super unless %i( get_certificate get_service_certificates ).include? command node = doc.at('xmlns|ResponseText', xmlns: OP_PKI) node.content if node end # Checks whether the certificate embedded in the response soap has been signed with OP's # root certificate. The check is skipped in test environment, because a different root # certificate is used. The check is also skipped for certificate requests because they are not # signed # # @return [true] if certificate is trusted # @return [false] if certificate fails to verify # @see DanskeResponse#certificate_is_trusted? def certificate_is_trusted? return true if environment == :test || BYPASS_COMMANDS.include?(command) verify_certificate_against_root_certificate(certificate, OP_ROOT_CERTIFICATE) end # Some OP's certificate responses aren't signed def validate_hashes super unless BYPASS_COMMANDS.include?(command) end # Some OP's certificate responses aren't signed def verify_signature super unless BYPASS_COMMANDS.include?(command) end end end
# First the sepa gem is loaded by requiring it require 'sepa' # A test payload with no actual data payload = "test_payload" # Keys private_key = OpenSSL::PKey::RSA.new(File.read("sepa/nordea_testing/keys/nordea.key")) cert = OpenSSL::X509::Certificate.new(File.read("sepa/nordea_testing/keys/nordea.crt")) # The params hash is populated with the data that is needed for gem to function params = { # Path for your own private key private_key: private_key, # Path to your certificate cert: cert, # Command :download_file_list, :upload_file, :download_file or :get_user_info command: :download_file, # Unique customer ID customer_id: '11111111', # Set the environment to be either PRODUCTION or TEST environment: 'PRODUCTION', # For filtering stuff. Must be either NEW, DOWNLOADED or ALL status: 'NEW', # Some specification of the folder which to access in the bank. I have no idea how this works however. target_id: '11111111A1', # Language must be either FI, EN or SV language: 'FI', # File types to upload or download: # - LMP300 = Laskujen maksupalvelu (lähtevä) # - LUM2 = Valuuttamaksut (lähtevä) # - KTL = Saapuvat viitemaksut (saapuva) # - TITO = Konekielinen tiliote (saapuva) # - NDCORPAYS = Yrityksen maksut XML (lähtevä) # - NDCAMT53L = Konekielinen XML-tiliote (saapuva) # - NDCAMT54L = Saapuvat XML viitemaksu (saapuva) file_type: 'TITO', # The WSDL file used by nordea. Is identical between banks except for the address. wsdl: 'sepa/wsdl/wsdl_nordea.xml', # The actual payload to send. content: payload, # File reference for :download_file command file_reference: "11111111A12006030329501800000014" } # You just create the client with the parameters described above. sepa_client = Sepa::Client.new(params) puts Sepa::Response.new(sepa_client.send) Testing with nordea seems to work. # First the sepa gem is loaded by requiring it require 'sepa' # A test payload with no actual data payload = "test_payload" # Keys private_key = OpenSSL::PKey::RSA.new(File.read("sepa/nordea_testing/keys/nordea.key")) cert = OpenSSL::X509::Certificate.new(File.read("sepa/nordea_testing/keys/nordea.crt")) # The params hash is populated with the data that is needed for gem to function params = { # Path for your own private key private_key: private_key, # Path to your certificate cert: cert, # Command :download_file_list, :upload_file, :download_file or :get_user_info command: :get_user_info, # Unique customer ID customer_id: '11111111', # Set the environment to be either PRODUCTION or TEST environment: 'PRODUCTION', # For filtering stuff. Must be either NEW, DOWNLOADED or ALL status: 'NEW', # Some specification of the folder which to access in the bank. I have no idea how this works however. target_id: '11111111A1', # Language must be either FI, EN or SV language: 'FI', # File types to upload or download: # - LMP300 = Laskujen maksupalvelu (lähtevä) # - LUM2 = Valuuttamaksut (lähtevä) # - KTL = Saapuvat viitemaksut (saapuva) # - TITO = Konekielinen tiliote (saapuva) # - NDCORPAYS = Yrityksen maksut XML (lähtevä) # - NDCAMT53L = Konekielinen XML-tiliote (saapuva) # - NDCAMT54L = Saapuvat XML viitemaksu (saapuva) file_type: 'TITO', # The WSDL file used by nordea. Is identical between banks except for the address. wsdl: 'sepa/wsdl/wsdl_nordea.xml', # The actual payload to send. content: payload, # File reference for :download_file command file_reference: "11111111A12006030329501800000014" } # You just create the client with the parameters described above. sepa_client = Sepa::Client.new(params) response = sepa_client.send response = Nokogiri::XML(response.to_xml) response = Sepa::Response.new(response) puts response.soap_hashes_match? puts response.soap_signature_is_valid?
# encoding: utf-8 module MemcachedStore VERSION = "1.1.0" end Prepare v1.1.1 # encoding: utf-8 module MemcachedStore VERSION = "1.1.1" end
module ServerspecRunner VERSION = "1.0.0" end Bump version to 1.0.0 module ServerspecRunner VERSION = "1.0.1" end
# frozen_string_literal: true module MemoryProfiler class Results UNIT_PREFIXES = { 0 => 'B', 3 => 'kB', 6 => 'MB', 9 => 'GB', 12 => 'TB', 15 => 'PB', 18 => 'EB', 21 => 'ZB', 24 => 'YB' }.freeze def self.register_type(name, stat_attribute) @@lookups ||= [] @@lookups << [name, stat_attribute] ["allocated", "retained"].product(["objects", "memory"]).each do |type, metric| attr_accessor "#{type}_#{metric}_by_#{name}" end end register_type 'gem', :gem register_type 'file', :file register_type 'location', :location register_type 'class', :class_name attr_accessor :strings_retained, :strings_allocated attr_accessor :total_retained, :total_allocated attr_accessor :total_retained_memsize, :total_allocated_memsize def register_results(allocated, retained, top) @@lookups.each do |name, stat_attribute| memsize_results, count_results = allocated.top_n(top, stat_attribute) self.send("allocated_memory_by_#{name}=", memsize_results) self.send("allocated_objects_by_#{name}=", count_results) memsize_results, count_results = retained.top_n(top, stat_attribute) self.send("retained_memory_by_#{name}=", memsize_results) self.send("retained_objects_by_#{name}=", count_results) end self.strings_allocated = string_report(allocated, top) self.strings_retained = string_report(retained, top) self.total_allocated = allocated.size self.total_allocated_memsize = allocated.values.map!(&:memsize).inject(0, :+) self.total_retained = retained.size self.total_retained_memsize = retained.values.map!(&:memsize).inject(0, :+) self end def scale_bytes(bytes) return "0 B" if bytes.zero? scale = Math.log10(bytes).div(3) * 3 scale = 24 if scale > 24 "%.2f #{UNIT_PREFIXES[scale]}" % (bytes / 10.0**scale) end def string_report(data, top) grouped_strings = data.values. keep_if { |stat| stat.string_value }. group_by { |stat| stat.string_value.object_id }. values if grouped_strings.size > top cutoff = grouped_strings.sort_by!(&:size)[-top].size grouped_strings.keep_if { |list| list.size >= cutoff } end grouped_strings. sort! { |a, b| a.size == b.size ? a[0].string_value <=> b[0].string_value : b.size <=> a.size }. first(top). # Return array of [string, [[location, count], [location, count], ...] map! { |list| [list[0].string_value, list.group_by { |stat| stat.location }. map { |location, stat_list| [location, stat_list.size] }. sort_by!(&:last).reverse! ] } end # Output the results of the report # @param [Hash] options the options for output # @option opts [String] :to_file a path to your log file # @option opts [Boolean] :color_output a flag for whether to colorize output # @option opts [Integer] :retained_strings how many retained strings to print # @option opts [Integer] :allocated_strings how many allocated strings to print # @option opts [Boolean] :detailed_report should report include detailed information # @option opts [Boolean] :scale_bytes calculates unit prefixes for the numbers of bytes def pretty_print(io = $stdout, **options) # Handle the special case that Ruby PrettyPrint expects `pretty_print` # to be a customized pretty printing function for a class return io.pp_object(self) if defined?(PP) && io.is_a?(PP) io = File.open(options[:to_file], "w") if options[:to_file] color_output = options.fetch(:color_output) { io.respond_to?(:isatty) && io.isatty } @colorize = color_output ? Polychrome.new : Monochrome.new if options[:scale_bytes] total_allocated_output = scale_bytes(total_allocated_memsize) total_retained_output = scale_bytes(total_retained_memsize) else total_allocated_output = "#{total_allocated_memsize} bytes" total_retained_output = "#{total_retained_memsize} bytes" end io.puts "Total allocated: #{total_allocated_output} (#{total_allocated} objects)" io.puts "Total retained: #{total_retained_output} (#{total_retained} objects)" if options[:detailed_report] != false io.puts ["allocated", "retained"] .product(["memory", "objects"]) .product(["gem", "file", "location", "class"]) .each do |(type, metric), name| scale_data = metric == "memory" && options[:scale_bytes] dump "#{type} #{metric} by #{name}", self.send("#{type}_#{metric}_by_#{name}"), io, scale_data end end io.puts dump_strings(io, "Allocated", strings_allocated, limit: options[:allocated_strings]) io.puts dump_strings(io, "Retained", strings_retained, limit: options[:retained_strings]) io.close if io.is_a? File end private def dump_strings(io, title, strings, limit: nil) return unless strings if limit return if limit == 0 strings = strings[0...limit] end io.puts "#{title} String Report" io.puts @colorize.line("-----------------------------------") strings.each do |string, stats| io.puts "#{stats.reduce(0) { |a, b| a + b[1] }.to_s.rjust(10)} #{@colorize.string((string.inspect))}" stats.sort_by { |x, y| [-y, x] }.each do |location, count| io.puts "#{@colorize.path(count.to_s.rjust(10))} #{location}" end io.puts end nil end def dump(description, data, io, scale_data) io.puts description io.puts @colorize.line("-----------------------------------") if data && !data.empty? data.each do |item| data_string = scale_data ? scale_bytes(item[:count]) : item[:count].to_s io.puts "#{data_string.rjust(10)} #{item[:data]}" end else io.puts "NO DATA" end io.puts end end end Reduce array allocations by nesting blocks # frozen_string_literal: true module MemoryProfiler class Results UNIT_PREFIXES = { 0 => 'B', 3 => 'kB', 6 => 'MB', 9 => 'GB', 12 => 'TB', 15 => 'PB', 18 => 'EB', 21 => 'ZB', 24 => 'YB' }.freeze def self.register_type(name, stat_attribute) @@lookups ||= [] @@lookups << [name, stat_attribute] ["allocated", "retained"].each do |type| ["objects", "memory"].each do |metric| attr_accessor "#{type}_#{metric}_by_#{name}" end end end register_type 'gem', :gem register_type 'file', :file register_type 'location', :location register_type 'class', :class_name attr_accessor :strings_retained, :strings_allocated attr_accessor :total_retained, :total_allocated attr_accessor :total_retained_memsize, :total_allocated_memsize def register_results(allocated, retained, top) @@lookups.each do |name, stat_attribute| memsize_results, count_results = allocated.top_n(top, stat_attribute) self.send("allocated_memory_by_#{name}=", memsize_results) self.send("allocated_objects_by_#{name}=", count_results) memsize_results, count_results = retained.top_n(top, stat_attribute) self.send("retained_memory_by_#{name}=", memsize_results) self.send("retained_objects_by_#{name}=", count_results) end self.strings_allocated = string_report(allocated, top) self.strings_retained = string_report(retained, top) self.total_allocated = allocated.size self.total_allocated_memsize = allocated.values.map!(&:memsize).inject(0, :+) self.total_retained = retained.size self.total_retained_memsize = retained.values.map!(&:memsize).inject(0, :+) self end def scale_bytes(bytes) return "0 B" if bytes.zero? scale = Math.log10(bytes).div(3) * 3 scale = 24 if scale > 24 "%.2f #{UNIT_PREFIXES[scale]}" % (bytes / 10.0**scale) end def string_report(data, top) grouped_strings = data.values. keep_if { |stat| stat.string_value }. group_by { |stat| stat.string_value.object_id }. values if grouped_strings.size > top cutoff = grouped_strings.sort_by!(&:size)[-top].size grouped_strings.keep_if { |list| list.size >= cutoff } end grouped_strings. sort! { |a, b| a.size == b.size ? a[0].string_value <=> b[0].string_value : b.size <=> a.size }. first(top). # Return array of [string, [[location, count], [location, count], ...] map! { |list| [list[0].string_value, list.group_by { |stat| stat.location }. map { |location, stat_list| [location, stat_list.size] }. sort_by!(&:last).reverse! ] } end # Output the results of the report # @param [Hash] options the options for output # @option opts [String] :to_file a path to your log file # @option opts [Boolean] :color_output a flag for whether to colorize output # @option opts [Integer] :retained_strings how many retained strings to print # @option opts [Integer] :allocated_strings how many allocated strings to print # @option opts [Boolean] :detailed_report should report include detailed information # @option opts [Boolean] :scale_bytes calculates unit prefixes for the numbers of bytes def pretty_print(io = $stdout, **options) # Handle the special case that Ruby PrettyPrint expects `pretty_print` # to be a customized pretty printing function for a class return io.pp_object(self) if defined?(PP) && io.is_a?(PP) io = File.open(options[:to_file], "w") if options[:to_file] color_output = options.fetch(:color_output) { io.respond_to?(:isatty) && io.isatty } @colorize = color_output ? Polychrome.new : Monochrome.new if options[:scale_bytes] total_allocated_output = scale_bytes(total_allocated_memsize) total_retained_output = scale_bytes(total_retained_memsize) else total_allocated_output = "#{total_allocated_memsize} bytes" total_retained_output = "#{total_retained_memsize} bytes" end io.puts "Total allocated: #{total_allocated_output} (#{total_allocated} objects)" io.puts "Total retained: #{total_retained_output} (#{total_retained} objects)" if options[:detailed_report] != false io.puts ["allocated", "retained"] .product(["memory", "objects"]) .product(["gem", "file", "location", "class"]) .each do |(type, metric), name| scale_data = metric == "memory" && options[:scale_bytes] dump "#{type} #{metric} by #{name}", self.send("#{type}_#{metric}_by_#{name}"), io, scale_data end end io.puts dump_strings(io, "Allocated", strings_allocated, limit: options[:allocated_strings]) io.puts dump_strings(io, "Retained", strings_retained, limit: options[:retained_strings]) io.close if io.is_a? File end private def dump_strings(io, title, strings, limit: nil) return unless strings if limit return if limit == 0 strings = strings[0...limit] end io.puts "#{title} String Report" io.puts @colorize.line("-----------------------------------") strings.each do |string, stats| io.puts "#{stats.reduce(0) { |a, b| a + b[1] }.to_s.rjust(10)} #{@colorize.string((string.inspect))}" stats.sort_by { |x, y| [-y, x] }.each do |location, count| io.puts "#{@colorize.path(count.to_s.rjust(10))} #{location}" end io.puts end nil end def dump(description, data, io, scale_data) io.puts description io.puts @colorize.line("-----------------------------------") if data && !data.empty? data.each do |item| data_string = scale_data ? scale_bytes(item[:count]) : item[:count].to_s io.puts "#{data_string.rjust(10)} #{item[:data]}" end else io.puts "NO DATA" end io.puts end end end
Pod::Spec.new do |s| s.name = "P2PCore" s.version = "0.0.1" s.summary = "P2PCore - Framework for network requests Wallet One P2P" s.homepage = "https://github.com/WalletOne/P2P.git" s.license = 'MIT' s.author = { "Vitaliy" => "vitaly.kuzmenko@walletone.com" } s.ios.deployment_target = '8.0' s.source = { :git => s.homepage, :tag => s.version.to_s } s.source_files = "P2PCore/**/*.swift" s.requires_arc = 'true' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0', } s.preserve_paths = 'CocoaPods/**/*' s.pod_target_xcconfig = { 'SWIFT_INCLUDE_PATHS[sdk=macosx*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/macosx', 'SWIFT_INCLUDE_PATHS[sdk=iphoneos*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/iphoneos', 'SWIFT_INCLUDE_PATHS[sdk=iphonesimulator*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/iphonesimulator', 'SWIFT_INCLUDE_PATHS[sdk=appletvos*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/appletvos', 'SWIFT_INCLUDE_PATHS[sdk=appletvsimulator*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/appletvsimulator', 'SWIFT_INCLUDE_PATHS[sdk=watchos*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/watchos', 'SWIFT_INCLUDE_PATHS[sdk=watchsimulator*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/watchsimulator' } end path fix Pod::Spec.new do |s| s.name = "P2PCore" s.version = "0.0.1" s.summary = "P2PCore - Framework for network requests Wallet One P2P" s.homepage = "https://github.com/WalletOne/P2P.git" s.license = 'MIT' s.author = { "Vitaliy" => "vitaly.kuzmenko@walletone.com" } s.ios.deployment_target = '8.0' s.source = { :git => s.homepage, :tag => s.version.to_s } s.source_files = "P2PCore/**/*.swift" s.requires_arc = 'true' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0', } s.preserve_paths = 'P2PCore/CocoaPods/**/*' s.pod_target_xcconfig = { 'SWIFT_INCLUDE_PATHS[sdk=macosx*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/macosx', 'SWIFT_INCLUDE_PATHS[sdk=iphoneos*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/iphoneos', 'SWIFT_INCLUDE_PATHS[sdk=iphonesimulator*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/iphonesimulator', 'SWIFT_INCLUDE_PATHS[sdk=appletvos*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/appletvos', 'SWIFT_INCLUDE_PATHS[sdk=appletvsimulator*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/appletvsimulator', 'SWIFT_INCLUDE_PATHS[sdk=watchos*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/watchos', 'SWIFT_INCLUDE_PATHS[sdk=watchsimulator*]' => '$(PODS_ROOT)/P2PCore/CocoaPods/watchsimulator' } end
module Methadone module Rails VERSION = "0.0.1" end end version bump module Methadone module Rails VERSION = "0.1.0" end end
module SmallCage::Commands # # 'smc update' command # class Update include SmallCage def self.execute(opts) new(opts).execute end def initialize(opts) @opts = opts end def execute start = Time.now target = Pathname.new(@opts[:path]) fail 'target directory or file does not exist.: ' + target.to_s unless target.exist? @loader = Loader.new(target) @renderer = Renderer.new(@loader) @list = UpdateList.create(@loader.root, target) STDERR.puts 'WARN: Can\'t load tmp/list.yml file.' if @list.load_error render_smc_files expire_old_files @list.expire @list.save count = @list.update_count elapsed = Time.now - start puts "-- #{count} files. #{sprintf('%.3f', elapsed)} sec." + " #{sprintf('%.3f', count == 0 ? 0 : elapsed / count)} sec/file." unless @opts[:quiet] end def expire_old_files(uris) root = @loader.root uris.each do |uri| file = root + uri[1..-1] if file.exist? puts "D #{uri}" unless @opts[:quiet] file.delete end end end private :expire_old_files def render_smc_files @loader.each_smc_obj do |obj| render_smc_obj(obj) end end private :render_smc_files def render_smc_obj(obj) uris = @renderer.render(obj['template'] + '.uri', obj) if uris render_multi(obj, uris.split(/\r\n|\r|\n/)) else render_single(obj) end end private :render_smc_obj def render_single(obj, mtime = nil) mark = obj['path'].exist? ? 'U ' : 'A ' mtime ||= obj['path'].smc.stat.mtime.to_i result = @renderer.render(obj['template'], obj) result = after_rendering_filters(obj, result) output_result(obj, result) puts mark + obj['uri'] unless @opts[:quiet] # create new uri String to remove smc instance-specific method. @list.update(obj['uri'].smc, mtime, String.new(obj['uri'])) end private :render_single def render_multi(obj, uris) obj['uris'] ||= uris uris = uris.map { |uri| uri.strip } smcuri = obj['uri'].smc smcpath = obj['path'].smc base = obj['path'].parent mtime = smcpath.stat.mtime.to_i uris.each_with_index do |uri, index| next if uri.empty? docpath = DocumentPath.create_with_uri(@loader.root, uri, base) next if docpath.path.directory? FileUtils.mkpath(docpath.path.parent) obj['uri'] = DocumentPath.add_smc_method(docpath.uri, smcuri) obj['path'] = DocumentPath.add_smc_method(docpath.path, smcpath) obj['cursor'] = index render_single(obj, mtime) end end private :render_multi def after_rendering_filters(obj, result) filters = @loader.filters('after_rendering_filters') filters.each do |f| result = f.after_rendering_filter(obj, result) end result end private :after_rendering_filters def output_result(obj, str) open(obj['path'], 'w') do |io| io << str end end private :output_result end end add --fast option to update command module SmallCage::Commands # # 'smc update' command # class Update include SmallCage def self.execute(opts) new(opts).execute end def initialize(opts) @opts = opts end def execute start = Time.now target = Pathname.new(@opts[:path]) fail 'target directory or file does not exist.: ' + target.to_s unless target.exist? @loader = Loader.new(target) @renderer = Renderer.new(@loader) @list = UpdateList.create(@loader.root, target) STDERR.puts 'WARN: Can\'t load tmp/list.yml file.' if @list.load_error render_smc_files expire_old_files @list.expire @list.save count = @list.update_count elapsed = Time.now - start puts "-- #{count} files. #{sprintf('%.3f', elapsed)} sec." + " #{sprintf('%.3f', count == 0 ? 0 : elapsed / count)} sec/file." unless @opts[:quiet] end def expire_old_files(uris) root = @loader.root uris.each do |uri| file = root + uri[1..-1] if file.exist? puts "D #{uri}" unless @opts[:quiet] file.delete end end end private :expire_old_files def render_smc_files @loader.each_smc_obj do |obj| render_smc_obj(obj) end end private :render_smc_files def render_smc_obj(obj) uris = @renderer.render(obj['template'] + '.uri', obj) if uris render_multi(obj, uris.split(/\r\n|\r|\n/)) else render_single(obj) end end private :render_smc_obj def render_single(obj, mtime = nil) mark = obj['path'].exist? ? 'U ' : 'A ' mtime ||= obj['path'].smc.stat.mtime.to_i if @opts[:fast] last_mtime = @list.mtime(obj['uri'].smc) if mtime == last_mtime @list.update(obj['uri'].smc, mtime, String.new(obj['uri'])) return end end result = @renderer.render(obj['template'], obj) result = after_rendering_filters(obj, result) output_result(obj, result) puts mark + obj['uri'] unless @opts[:quiet] # create new uri String to remove smc instance-specific method. @list.update(obj['uri'].smc, mtime, String.new(obj['uri'])) end private :render_single def render_multi(obj, uris) obj['uris'] ||= uris uris = uris.map { |uri| uri.strip } smcuri = obj['uri'].smc smcpath = obj['path'].smc base = obj['path'].parent mtime = smcpath.stat.mtime.to_i uris.each_with_index do |uri, index| next if uri.empty? docpath = DocumentPath.create_with_uri(@loader.root, uri, base) next if docpath.path.directory? FileUtils.mkpath(docpath.path.parent) obj['uri'] = DocumentPath.add_smc_method(docpath.uri, smcuri) obj['path'] = DocumentPath.add_smc_method(docpath.path, smcpath) obj['cursor'] = index render_single(obj, mtime) end end private :render_multi def after_rendering_filters(obj, result) filters = @loader.filters('after_rendering_filters') filters.each do |f| result = f.after_rendering_filter(obj, result) end result end private :after_rendering_filters def output_result(obj, str) open(obj['path'], 'w') do |io| io << str end end private :output_result end end
require 'mock_redis/assertions' require 'mock_redis/utility_methods' class MockRedis module HashMethods include Assertions include UtilityMethods def hdel(key, field) with_hash_at(key) do |hash| if field.is_a?(Array) orig_size = hash.size fields = field.map(&:to_s) hash.delete_if { |k, _v| fields.include?(k) } orig_size - hash.size else hash.delete(field.to_s) ? 1 : 0 end end end def hexists(key, field) with_hash_at(key) { |h| h.key?(field.to_s) } end def hget(key, field) with_hash_at(key) { |h| h[field.to_s] } end def hgetall(key) with_hash_at(key) { |h| h } end def hincrby(key, field, increment) with_hash_at(key) do |hash| field = field.to_s unless can_incr?(data[key][field]) raise Redis::CommandError, 'ERR hash value is not an integer' end unless looks_like_integer?(increment.to_s) raise Redis::CommandError, 'ERR value is not an integer or out of range' end new_value = (hash[field] || '0').to_i + increment.to_i hash[field] = new_value.to_s new_value end end def hincrbyfloat(key, field, increment) with_hash_at(key) do |hash| field = field.to_s unless can_incr_float?(data[key][field]) raise Redis::CommandError, 'ERR hash value is not a valid float' end unless looks_like_float?(increment.to_s) raise Redis::CommandError, 'ERR value is not a valid float' end new_value = (hash[field] || '0').to_f + increment.to_f new_value = new_value.to_i if new_value % 1 == 0 hash[field] = new_value.to_s new_value end end def hkeys(key) with_hash_at(key, &:keys) end def hlen(key) hkeys(key).length end def hmget(key, *fields) assert_has_args(fields, 'hmget') fields.flatten.map { |f| hget(key, f) } end def mapped_hmget(key, *fields) reply = hmget(key, *fields) if reply.is_a?(Array) Hash[fields.zip(reply)] else reply end end def hmset(key, *kvpairs) assert_has_args(kvpairs, 'hmset') if kvpairs.length.odd? raise Redis::CommandError, 'ERR wrong number of arguments for HMSET' end kvpairs.each_slice(2) do |(k, v)| hset(key, k, v) end 'OK' end def mapped_hmset(key, hash) kvpairs = hash.to_a.flatten assert_has_args(kvpairs, 'hmset') if kvpairs.length.odd? raise Redis::CommandError, "ERR wrong number of arguments for 'hmset' command" end hmset(key, *kvpairs) end def hscan(key, cursor, opts = {}) opts = opts.merge(key: lambda { |x| x[0] }) common_scan(hgetall(key).to_a, cursor, opts) end def hscan_each(key, opts = {}, &block) return to_enum(:hscan_each, key, opts) unless block_given? cursor = 0 loop do cursor, values = hscan(key, cursor, opts) values.each(&block) break if cursor == '0' end end def hset(key, field, value) with_hash_at(key) { |h| h[field.to_s] = value.to_s } true end def hsetnx(key, field, value) if hget(key, field) false else hset(key, field, value) true end end def hvals(key) with_hash_at(key, &:values) end private def with_hash_at(key, &blk) with_thing_at(key, :assert_hashy, proc { {} }, &blk) end def hashy?(key) data[key].nil? || data[key].is_a?(Hash) end def assert_hashy(key) unless hashy?(key) raise Redis::CommandError, 'WRONGTYPE Operation against a key holding the wrong kind of value' end end end end Flatten the args for hmset require 'mock_redis/assertions' require 'mock_redis/utility_methods' class MockRedis module HashMethods include Assertions include UtilityMethods def hdel(key, field) with_hash_at(key) do |hash| if field.is_a?(Array) orig_size = hash.size fields = field.map(&:to_s) hash.delete_if { |k, _v| fields.include?(k) } orig_size - hash.size else hash.delete(field.to_s) ? 1 : 0 end end end def hexists(key, field) with_hash_at(key) { |h| h.key?(field.to_s) } end def hget(key, field) with_hash_at(key) { |h| h[field.to_s] } end def hgetall(key) with_hash_at(key) { |h| h } end def hincrby(key, field, increment) with_hash_at(key) do |hash| field = field.to_s unless can_incr?(data[key][field]) raise Redis::CommandError, 'ERR hash value is not an integer' end unless looks_like_integer?(increment.to_s) raise Redis::CommandError, 'ERR value is not an integer or out of range' end new_value = (hash[field] || '0').to_i + increment.to_i hash[field] = new_value.to_s new_value end end def hincrbyfloat(key, field, increment) with_hash_at(key) do |hash| field = field.to_s unless can_incr_float?(data[key][field]) raise Redis::CommandError, 'ERR hash value is not a valid float' end unless looks_like_float?(increment.to_s) raise Redis::CommandError, 'ERR value is not a valid float' end new_value = (hash[field] || '0').to_f + increment.to_f new_value = new_value.to_i if new_value % 1 == 0 hash[field] = new_value.to_s new_value end end def hkeys(key) with_hash_at(key, &:keys) end def hlen(key) hkeys(key).length end def hmget(key, *fields) assert_has_args(fields, 'hmget') fields.flatten.map { |f| hget(key, f) } end def mapped_hmget(key, *fields) reply = hmget(key, *fields) if reply.is_a?(Array) Hash[fields.zip(reply)] else reply end end def hmset(key, *kvpairs) kvpairs.flatten! assert_has_args(kvpairs, 'hmset') if kvpairs.length.odd? raise Redis::CommandError, 'ERR wrong number of arguments for HMSET' end kvpairs.each_slice(2) do |(k, v)| hset(key, k, v) end 'OK' end def mapped_hmset(key, hash) kvpairs = hash.to_a.flatten assert_has_args(kvpairs, 'hmset') if kvpairs.length.odd? raise Redis::CommandError, "ERR wrong number of arguments for 'hmset' command" end hmset(key, *kvpairs) end def hscan(key, cursor, opts = {}) opts = opts.merge(key: lambda { |x| x[0] }) common_scan(hgetall(key).to_a, cursor, opts) end def hscan_each(key, opts = {}, &block) return to_enum(:hscan_each, key, opts) unless block_given? cursor = 0 loop do cursor, values = hscan(key, cursor, opts) values.each(&block) break if cursor == '0' end end def hset(key, field, value) with_hash_at(key) { |h| h[field.to_s] = value.to_s } true end def hsetnx(key, field, value) if hget(key, field) false else hset(key, field, value) true end end def hvals(key) with_hash_at(key, &:values) end private def with_hash_at(key, &blk) with_thing_at(key, :assert_hashy, proc { {} }, &blk) end def hashy?(key) data[key].nil? || data[key].is_a?(Hash) end def assert_hashy(key) unless hashy?(key) raise Redis::CommandError, 'WRONGTYPE Operation against a key holding the wrong kind of value' end end end end
module SocialShares class Sharedcount < Base def shares! response = RestClient.get(url) JSON.parse(response)["total_count"] || 0 end private def url "https://free.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.secrets.socialshared_api_key}" end end end Update sharedcount.rb module SocialShares class Sharedcount < Base def shares! response = RestClient.get(url) JSON.parse(response)["Facebook.share_count"] || 0 end private def url "https://free.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.secrets.socialshared_api_key}" end end end
# encoding: BINARY module Monotable class Router < TopServerComponent attr_accessor :server_clients #options[:local_store] => LocalStore def initialize(server) super @server_clients=[] end # find the servers containing the chunk that covers key def chunk_servers(internal_key) global_index.chunk_servers(internal_key) end def server_client(ikey) server_list = chunk_servers(ikey) server_address = server_list[rand(server_list.length)] server.cluster_manager.server_client(server_address) end end # see ReadAPI module RoutedReadAPI include ReadAPI # see ReadAPI def get(key,field_names=nil) route(key) {|store,key| store.get(key,field_names)} end # see ReadAPI def get_first(options={}) route_get_range(options,:gte) {|store,options| process_get_range_result store.get_first(options)} end # see ReadAPI def get_last(options={}) route_get_range(options,:lte) {|store,options| process_get_range_result store.get_last(options)} end end # see WriteAPI module RoutedWriteAPI include WriteAPI # see WriteAPI def set(key,fields) route(key) {|store,key| store.set(key,fields)} end # see WriteAPI def update(key,fields) route(key) {|store,key| store.update(key,fields)} end # see WriteAPI def delete(key) route(key) {|store,key| store.delete(key)} end end class RequestRouter USER_SPACE_PREFIX="u/" include RoutedReadAPI include RoutedWriteAPI attr_accessor :router # options # :user_keys => true, all keys going in and out are in userspace (prefixed by USER_SPACE_PREFIX) # :forward => true, forward requests which cannot be fullfilled locally to the appropriate remote machine # otehrwise, returns {:error=>'...'} if the request cannot be carried out locally def initialize(router,options={}) @router = router @forward = options[:forward] @user_keys = options[:user_keys] raise ArgumentError,"router.kind_of?(Router) required (router.class==#{router.class})" unless router.kind_of?(Router) raise InternalError,"router.local_store not set" unless router.local_store end #routing_option should be :gte or :lte # yields the store to route to and the options, internalized def route_get_range(options,routing_option) normal_options = Tools.normalize_range_options(options) route(normal_options[routing_option]) do |store,key| yield store, @user_keys ? internalize_range_options(options) : options end end def process_get_range_result(result) if @user_keys result[:records]=result[:records].collect do |rec| Monotable::MemoryRecord.new.init(externalize_key(rec.key),rec.fields) end end result end # external keys, or user-space keys, are prefixed to distinguish them from other internal-use keys def internalize_key(external_key) USER_SPACE_PREFIX+external_key end def externalize_key(internal_key) internal_key[USER_SPACE_PREFIX.length..-1] end def internalize_range_options(range_options) [:gte,:gt,:lte,:lt,:with_prefix].each do |key| range_options[key]=internalize_key(range_options[key]) if range_options[key] end range_options end # yields store, key # store => store to route to # key => use this key instead of the key passed to route # TODO - should allow a block to be passed in which is the "what to do with the result" block def route(key) ikey = @user_keys ? internalize_key(key) : key work_log=[] #puts "routing: ikey=#{ikey[0..10].inspect}" ret = if router.local_store.local?(ikey) #puts "routing: #{ikey[0..10].inspect} -> local" work_log<<"(#{router.cluster_manager.local_server}) processed locally" yield router.local_store,ikey else #puts "routing: #{ikey[0..10].inspect} -> remote" unless @forward {:error=>"key not covered by local chunks"} else sc=router.server_client(ikey) work_log<<"(#{router.cluster_manager.local_server}) forwarded request to: #{sc}" yield sc,ikey end end ret[:work_log]=work_log + (ret[:work_log]||[]) ret end end end the work_log now trackes every additional request processed to service the original request # encoding: BINARY module Monotable class Router < TopServerComponent attr_accessor :server_clients #options[:local_store] => LocalStore def initialize(server) super @server_clients=[] end # find the servers containing the chunk that covers key def chunk_servers(internal_key,work_log=nil) global_index.chunk_servers(internal_key,work_log) end def server_client(ikey,work_log=nil) server_list = chunk_servers(ikey,work_log) server_address = server_list[rand(server_list.length)] server.cluster_manager.server_client(server_address) end end # see ReadAPI module RoutedReadAPI include ReadAPI # see ReadAPI def get(key,field_names=nil) route(:get,key) {|store,key| store.get(key,field_names)} end # see ReadAPI def get_first(options={}) route_get_range(options,:gte) {|store,options| process_get_range_result store.get_first(options)} end # see ReadAPI def get_last(options={}) route_get_range(options,:lte) {|store,options| process_get_range_result store.get_last(options)} end end # see WriteAPI module RoutedWriteAPI include WriteAPI # see WriteAPI def set(key,fields) route(:set,key) {|store,key| store.set(key,fields)} end # see WriteAPI def update(key,fields) route(:update,key) {|store,key| store.update(key,fields)} end # see WriteAPI def delete(key) route(:delete,key) {|store,key| store.delete(key)} end end class RequestRouter USER_SPACE_PREFIX="u/" include RoutedReadAPI include RoutedWriteAPI attr_accessor :router # options # :user_keys => true, all keys going in and out are in userspace (prefixed by USER_SPACE_PREFIX) # :forward => true, forward requests which cannot be fullfilled locally to the appropriate remote machine # otehrwise, returns {:error=>'...'} if the request cannot be carried out locally def initialize(router,options={}) @router = router @forward = options[:forward] @user_keys = options[:user_keys] raise ArgumentError,"router.kind_of?(Router) required (router.class==#{router.class})" unless router.kind_of?(Router) raise InternalError,"router.local_store not set" unless router.local_store end #routing_option should be :gte or :lte # yields the store to route to and the options, internalized def route_get_range(options,routing_option) normal_options = Tools.normalize_range_options(options) route(:get_range,normal_options[routing_option]) do |store,key| yield store, @user_keys ? internalize_range_options(options) : options end end def process_get_range_result(result) if @user_keys result[:records]=result[:records].collect do |rec| Monotable::MemoryRecord.new.init(externalize_key(rec.key),rec.fields) end end result end # external keys, or user-space keys, are prefixed to distinguish them from other internal-use keys def internalize_key(external_key) USER_SPACE_PREFIX+external_key end def externalize_key(internal_key) internal_key[USER_SPACE_PREFIX.length..-1] end def internalize_range_options(range_options) [:gte,:gt,:lte,:lt,:with_prefix].each do |key| range_options[key]=internalize_key(range_options[key]) if range_options[key] end range_options end # yields store, key # store => store to route to # key => use this key instead of the key passed to route # TODO - should allow a block to be passed in which is the "what to do with the result" block def route(request_type, key) ikey = @user_keys ? internalize_key(key) : key work_log=[] ret = if router.local_store.local?(ikey) yield router.local_store,ikey else unless @forward {:error=>"key not covered by local chunks"} else sc = router.server_client(ikey,work_log) work_log<<{:server => router.cluster_manager.local_server.to_s, :action => [sc.to_s, request_type, ikey]} yield sc,ikey end end ret[:work_log]=work_log + (ret[:work_log]||[]) raise NetworkError.new("too may requests. work_log: #{ret[:work_log].inspect}") if ret[:work_log].length >= 100 ret end end end
require 'mrg/grid/config/QmfUtils' require 'set' require 'yaml' FakeList = Mrg::Grid::Config::FakeList FakeSet = Mrg::Grid::Config::FakeSet module Mrg module Grid module SerializedConfigs module DefaultStruct module Cm def saved_fields @saved_fields ||= {} end def field(name, kind=String) saved_fields[name] = kind attr_accessor name end end module Im def initialize(kwargs=nil) kwargs ||= {} sf = self.class.saved_fields sf.keys.each do |key| if kwargs[key] self.send("#{key}=".to_sym, kwargs[key]) else what = sf[key] default = what.is_a?(Class) ? what.new : what self.send("#{key}=".to_sym, default) end end end end def self.included(receiver) receiver.extend Cm receiver.send :include, Im end end class Configuration def initialize raise "Configuration proxy not implemented" end end class Store include DefaultStruct field :nodes, Set field :groups, Set field :params, Set field :features, Set field :subsystems, Set end class Feature include DefaultStruct field :name, String field :params, Hash field :included, Array field :conflicts, Set field :depends, Array field :subsystems, Set end class Group include DefaultStruct field :name, String field :is_identity_group, false field :features, Array field :params, Hash end class Parameter include DefaultStruct field :name, String field :kind, String field :default_val, String field :description, String field :must_change, false field :level, 0 field :needs_restart, false field :conflicts, Set field :depends, Set end class Node include DefaultStruct field :name, String field :pool, String field :idgroup, String field :membership, Array end class Subsystem include DefaultStruct field :name, String field :params, Set end class ConfigSerializer module QmfConfigSerializer # this is a no-op if we're using ConfigClients def get_object(o) o end def get_instances(klass) @console.objects(:class=>klass.to_s, :timeout=>45).map do |obj| # obj = @console.object(:object_id=>obj) ::Mrg::Grid::ConfigClient.const_get(klass).new(obj, @console) end end end module InStoreConfigSerializer # this is a no-op if we aren't over qmf def get_object(o) o end def get_instances(klass) ::Mrg::Grid::Config.const_get(klass).find_all end end def initialize(store, over_qmf=false, console=nil) @store = store @console = console if over_qmf @struct = Store.new if over_qmf class << self include QmfConfigSerializer end else class << self include InStoreConfigSerializer end end end def serialize @struct.nodes = serialize_nodes @struct.groups = serialize_groups @struct.params = serialize_params @struct.features = serialize_features @struct.subsystems = serialize_subsystems @struct end private def serialize_nodes get_instances(:Node).map do |n| node = get_object(n) out = Node.new out.name = node.name out.pool = node.GetPool # XXX: idgroup should be set up automatically out.membership = FakeList.normalize(node.GetMemberships).to_a out end end def serialize_groups get_instances(:Group).map do |g| group = get_object(g) out = Group.new out.name = group.GetName out.is_identity_group = group.is_identity_group out.features = FakeList.normalize(group.GetFeatures).to_a out.params = group.GetParams out end end def serialize_params get_instances(:Parameter).map do |p| param = get_object(p) out = Parameter.new out.name = param.name out.kind = param.GetType out.default_val = param.GetDefault.to_s out.description = param.GetDescription out.must_change = param.GetDefaultMustChange out.level = param.GetVisibilityLevel out.needs_restart = param.GetRequiresRestart out.conflicts = fs_normalize(param.GetConflicts) out.depends = fs_normalize(param.GetDepends) out end end def serialize_features get_instances(:Feature).map do |f| feature = get_object(f) out = Feature.new out.name = feature.GetName out.params = feature.GetParams out.included = FakeList.normalize(feature.GetFeatures).to_a out.conflicts = fs_normalize(feature.GetConflicts) out.depends = FakeList.normalize(feature.GetDepends).to_a out.subsystems = fs_normalize(feature.GetSubsys) out end end def serialize_subsystems get_instances(:Subsystem).map do |s| subsys = get_object(s) out = Subsystem.new out.name = subsys.GetName out.params = fs_normalize(subsys.GetParams) puts out.inspect out end end def fs_normalize(fs) return fs if fs.is_a? Array fs.keys end end end end end Serialization fix: Subsystem has a property named name, but no GetName method. require 'mrg/grid/config/QmfUtils' require 'set' require 'yaml' FakeList = Mrg::Grid::Config::FakeList FakeSet = Mrg::Grid::Config::FakeSet module Mrg module Grid module SerializedConfigs module DefaultStruct module Cm def saved_fields @saved_fields ||= {} end def field(name, kind=String) saved_fields[name] = kind attr_accessor name end end module Im def initialize(kwargs=nil) kwargs ||= {} sf = self.class.saved_fields sf.keys.each do |key| if kwargs[key] self.send("#{key}=".to_sym, kwargs[key]) else what = sf[key] default = what.is_a?(Class) ? what.new : what self.send("#{key}=".to_sym, default) end end end end def self.included(receiver) receiver.extend Cm receiver.send :include, Im end end class Configuration def initialize raise "Configuration proxy not implemented" end end class Store include DefaultStruct field :nodes, Set field :groups, Set field :params, Set field :features, Set field :subsystems, Set end class Feature include DefaultStruct field :name, String field :params, Hash field :included, Array field :conflicts, Set field :depends, Array field :subsystems, Set end class Group include DefaultStruct field :name, String field :is_identity_group, false field :features, Array field :params, Hash end class Parameter include DefaultStruct field :name, String field :kind, String field :default_val, String field :description, String field :must_change, false field :level, 0 field :needs_restart, false field :conflicts, Set field :depends, Set end class Node include DefaultStruct field :name, String field :pool, String field :idgroup, String field :membership, Array end class Subsystem include DefaultStruct field :name, String field :params, Set end class ConfigSerializer module QmfConfigSerializer # this is a no-op if we're using ConfigClients def get_object(o) o end def get_instances(klass) @console.objects(:class=>klass.to_s, :timeout=>45).map do |obj| # obj = @console.object(:object_id=>obj) ::Mrg::Grid::ConfigClient.const_get(klass).new(obj, @console) end end end module InStoreConfigSerializer # this is a no-op if we aren't over qmf def get_object(o) o end def get_instances(klass) ::Mrg::Grid::Config.const_get(klass).find_all end end def initialize(store, over_qmf=false, console=nil) @store = store @console = console if over_qmf @struct = Store.new if over_qmf class << self include QmfConfigSerializer end else class << self include InStoreConfigSerializer end end end def serialize @struct.nodes = serialize_nodes @struct.groups = serialize_groups @struct.params = serialize_params @struct.features = serialize_features @struct.subsystems = serialize_subsystems @struct end private def serialize_nodes get_instances(:Node).map do |n| node = get_object(n) out = Node.new out.name = node.name out.pool = node.GetPool # XXX: idgroup should be set up automatically out.membership = FakeList.normalize(node.GetMemberships).to_a out end end def serialize_groups get_instances(:Group).map do |g| group = get_object(g) out = Group.new out.name = group.GetName out.is_identity_group = group.is_identity_group out.features = FakeList.normalize(group.GetFeatures).to_a out.params = group.GetParams out end end def serialize_params get_instances(:Parameter).map do |p| param = get_object(p) out = Parameter.new out.name = param.name out.kind = param.GetType out.default_val = param.GetDefault.to_s out.description = param.GetDescription out.must_change = param.GetDefaultMustChange out.level = param.GetVisibilityLevel out.needs_restart = param.GetRequiresRestart out.conflicts = fs_normalize(param.GetConflicts) out.depends = fs_normalize(param.GetDepends) out end end def serialize_features get_instances(:Feature).map do |f| feature = get_object(f) out = Feature.new out.name = feature.GetName out.params = feature.GetParams out.included = FakeList.normalize(feature.GetFeatures).to_a out.conflicts = fs_normalize(feature.GetConflicts) out.depends = FakeList.normalize(feature.GetDepends).to_a out.subsystems = fs_normalize(feature.GetSubsys) out end end def serialize_subsystems get_instances(:Subsystem).map do |s| subsys = get_object(s) out = Subsystem.new out.name = subsys.name out.params = fs_normalize(subsys.GetParams) puts out.inspect out end end def fs_normalize(fs) return fs if fs.is_a? Array fs.keys end end end end end
require "pry" module MyMongoid module MyCallbacks extend ActiveSupport::Concern class Callback attr_accessor :kind, :filter def initialize(filter, kind) @kind = kind @filter = filter end def invoke(target, &block) target.send filter, &block end def compile lambda { |target, &block| target.send filter, &block } end end class CallbackChain def initialize(name = nil) @name = name @chain ||= [] end def empty? @chain.empty? end def chain @chain end def append(callback) @chain << callback end def invoke(target, &block) _invoke(0, target, block) end def _invoke(i, target, block) if i == chain.length block.call else callback = chain[i] case callback.kind when :before callback.invoke(target) _invoke(i+1, target, block) when :after _invoke(i+1, target, block) callback.invoke(target) when :around callback.invoke(target) do _invoke(i+1, target, block) end end end end def compile k = nil i = chain.length while i >= 0 k = _compile(k, i) i -= 1 end k end def _compile(k, i) if i == chain.length lambda { |_, &block| block.call } else callback = chain[i] case callback.kind when :before lambda { |target, &block| callback.invoke(target) k.call(target, &block) } end end end end def run_callbacks(name, &block) cbs = send("_#{name}_callbacks") if cbs.empty? yield if block_given? else cbs.invoke(self, &block) end end module ClassMethods def set_callback(name, kind, filter) get_callbacks(name).append(Callback.new(filter, kind)) end def define_callbacks(*names) names.each do |name| class_attribute "_#{name}_callbacks" set_callbacks name, CallbackChain.new(name) end end def set_callbacks(name, callbacks) send "_#{name}_callbacks=", callbacks end def get_callbacks(name) send "_#{name}_callbacks" end end end end Implement Memoize Compilation require "pry" module MyMongoid module MyCallbacks extend ActiveSupport::Concern class Callback attr_accessor :kind, :filter def initialize(filter, kind) @kind = kind @filter = filter end def invoke(target, &block) target.send filter, &block end def compile lambda { |target, &block| target.send filter, &block } end end class CallbackChain def initialize(name = nil) @name = name @chain ||= [] @callbacks = nil end def empty? @chain.empty? end def chain @chain end def append(callback) @callbacks = nil @chain << callback end def invoke(target, &block) _invoke(0, target, block) end def _invoke(i, target, block) if i == chain.length block.call else callback = chain[i] case callback.kind when :before callback.invoke(target) _invoke(i+1, target, block) when :after _invoke(i+1, target, block) callback.invoke(target) when :around callback.invoke(target) do _invoke(i+1, target, block) end end end end def compile unless @callbacks i = chain.length while i >= 0 @callbacks = _compile(@callbacks, i) i -= 1 end end @callbacks end def _compile(k, i) if i == chain.length lambda { |_, &block| block.call } else callback = chain[i] case callback.kind when :before lambda { |target, &block| callback.invoke(target) k.call(target, &block) } end end end end def run_callbacks(name, &block) cbs = send("_#{name}_callbacks") if cbs.empty? yield if block_given? else cbs.invoke(self, &block) end end module ClassMethods def set_callback(name, kind, filter) get_callbacks(name).append(Callback.new(filter, kind)) end def define_callbacks(*names) names.each do |name| class_attribute "_#{name}_callbacks" set_callbacks name, CallbackChain.new(name) end end def set_callbacks(name, callbacks) send "_#{name}_callbacks=", callbacks end def get_callbacks(name) send "_#{name}_callbacks" end end end end
# Version of nbasalarycrape module SalaryScraper VERSION = '0.1.1' end Changed version number # Version of nbasalarycrape module SalaryScraper VERSION = '0.1.2' end
# https://system.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteCloudCustomizationScriptingWebServices/SuiteTalkWebServices/search.html module NetSuite module Actions class Search include Support::Requests def initialize(klass, options = { }) @klass = klass @options = options end def class_name @class_name ||= if @klass.respond_to? :search_class_name @klass.search_class_name else @klass.to_s.split("::").last end end private def request(credentials={}) # https://system.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteCloudCustomizationScriptingWebServices/SuiteTalkWebServices/SettingSearchPreferences.html # https://webservices.netsuite.com/xsd/platform/v2012_2_0/messages.xsd preferences = NetSuite::Configuration.auth_header(credentials) .update(NetSuite::Configuration.soap_header) .merge( (@options.delete(:preferences) || {}).inject({'platformMsgs:SearchPreferences' => {}}) do |h, (k, v)| h['platformMsgs:SearchPreferences'][k.to_s.lower_camelcase] = v h end ) NetSuite::Configuration .connection({ soap_header: preferences }, credentials) .call (@options.has_key?(:search_id)? :search_more_with_id : :search), :message => request_body end # basic search XML # <soap:Body> # <platformMsgs:search> # <searchRecord xsi:type="ContactSearch"> # <customerJoin xsi:type="CustomerSearchBasic"> # <email operator="contains" xsi:type="platformCore:SearchStringField"> # <platformCore:searchValue>shutterfly.com</platformCore:searchValue> # <email> # <customerJoin> # </searchRecord> # </search> # </soap:Body> def request_body if @options.has_key?(:search_id) return { 'pageIndex' => @options[:page_index], 'searchId' => @options[:search_id], } end # columns is only needed for advanced search results columns = @options[:columns] || {} criteria = @options[:criteria] || @options # TODO find cleaner solution for pulling the namespace of the record, which is a instance method namespace = if @klass.respond_to?(:search_class_namespace) @klass.search_class_namespace else @klass.new.record_namespace end # extract the class name criteria_structure = {} columns_structure = columns saved_search_id = criteria.delete(:saved) # TODO this whole thing needs to be refactored so we can apply some of the same logic to the # column creation xml criteria.each_pair do |condition_category, conditions| criteria_structure["#{namespace}:#{condition_category}"] = conditions.inject({}) do |h, condition| element_name = "platformCommon:#{condition[:field]}" case condition[:field] when 'recType' # TODO this seems a bit brittle, look into a way to handle this better h[element_name] = { :@internalId => condition[:value].internal_id } when 'customFieldList' # === START CUSTOM FIELD # there isn't a clean way to do lists of the same element # Gyoku doesn't seem support the nice :@attribute and :content! syntax for lists of elements of the same name # https://github.com/savonrb/gyoku/issues/18#issuecomment-17825848 # TODO with the latest version of savon we can easily improve the code here, should be rewritten with new attribute syntax custom_field_list = condition[:value].map do |h| if h[:value].is_a?(Array) && h[:value].first.respond_to?(:to_record) { "platformCore:searchValue" => h[:value].map(&:to_record), :attributes! => { 'platformCore:searchValue' => { 'internalId' => h[:value].map(&:internal_id) } } } elsif h[:value].respond_to?(:to_record) { "platformCore:searchValue" => { :content! => h[:value].to_record, :@internalId => h[:value].internal_id } } else { "platformCore:searchValue" => h[:value] } end end h[element_name] = { 'platformCore:customField' => custom_field_list, :attributes! => { 'platformCore:customField' => { 'scriptId' => condition[:value].map { |h| h[:field] }, 'operator' => condition[:value].map { |h| h[:operator] }, 'xsi:type' => condition[:value].map { |h| "platformCore:#{h[:type]}" } } } } # https://github.com/NetSweet/netsuite/commit/54d7b011d9485dad33504135dfe8153c86cae9a0#commitcomment-8443976 if NetSuite::Configuration.api_version < "2013_2" h[element_name][:attributes!]['platformCore:customField']['internalId'] = h[element_name][:attributes!]['platformCore:customField'].delete('scriptId') end # === END CUSTOM FIELD else if condition[:value].is_a?(Array) && condition[:value].first.respond_to?(:to_record) # TODO need to update to the latest savon so we don't need to duplicate the same workaround above again # TODO it's possible that this might break, not sure if platformCore:SearchMultiSelectField is the right type in every situation h[element_name] = { '@operator' => condition[:operator], '@xsi:type' => 'platformCore:SearchMultiSelectField', "platformCore:searchValue" => { :content! => condition[:value].map(&:to_record), '@internalId' => condition[:value].map(&:internal_id), '@xsi:type' => 'platformCore:RecordRef', '@type' => 'account' } } elsif condition[:value].is_a?(Array) && condition[:type] == 'SearchDateField' # date ranges are handled via searchValue (start range) and searchValue2 (end range) h[element_name] = { '@operator' => condition[:operator], "platformCore:searchValue" => condition[:value].first.to_s, "platformCore:searchValue2" => condition[:value].last.to_s } elsif condition[:value].is_a?(Array) && condition[:operator] == 'between' h[element_name] = { '@operator' => condition[:operator], "platformCore:searchValue" => condition[:value].first.to_s, "platformCore:searchValue2" => condition[:value].last.to_s } else h[element_name] = { :content! => { "platformCore:searchValue" => condition[:value] }, } h[element_name][:@operator] = condition[:operator] if condition[:operator] end end h end end # TODO this needs to be DRYed up a bit if saved_search_id { 'searchRecord' => { '@savedSearchId' => saved_search_id, '@xsi:type' => "#{namespace}:#{class_name}SearchAdvanced", :content! => { "#{namespace}:criteria" => criteria_structure # TODO need to optionally support columns here } } } elsif !columns_structure.empty? { 'searchRecord' => { '@xsi:type' => "#{namespace}:#{class_name}SearchAdvanced", :content! => { "#{namespace}:criteria" => criteria_structure, "#{namespace}:columns" => columns_structure } } } else { 'searchRecord' => { :content! => criteria_structure, '@xsi:type' => "#{namespace}:#{class_name}Search" } } end end def response_header @response_header ||= response_header_hash end def response_header_hash @response_header_hash = @response.header[:document_info] end def response_body @response_body ||= search_result end def search_result @search_result = if @response.body.has_key?(:search_more_with_id_response) @response.body[:search_more_with_id_response] else @response.body[:search_response] end[:search_result] end def success? @success ||= search_result[:status][:@is_success] == 'true' end protected def method_name end module Support def self.included(base) base.extend(ClassMethods) end module ClassMethods def search(options = { }, credentials={}) response = NetSuite::Actions::Search.call([self, options], credentials) if response.success? NetSuite::Support::SearchResult.new(response, self) else false end end end end end end end Support saved search with return columns # https://system.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteCloudCustomizationScriptingWebServices/SuiteTalkWebServices/search.html module NetSuite module Actions class Search include Support::Requests def initialize(klass, options = { }) @klass = klass @options = options end def class_name @class_name ||= if @klass.respond_to? :search_class_name @klass.search_class_name else @klass.to_s.split("::").last end end private def request(credentials={}) # https://system.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteCloudCustomizationScriptingWebServices/SuiteTalkWebServices/SettingSearchPreferences.html # https://webservices.netsuite.com/xsd/platform/v2012_2_0/messages.xsd preferences = NetSuite::Configuration.auth_header(credentials) .update(NetSuite::Configuration.soap_header) .merge( (@options.delete(:preferences) || {}).inject({'platformMsgs:SearchPreferences' => {}}) do |h, (k, v)| h['platformMsgs:SearchPreferences'][k.to_s.lower_camelcase] = v h end ) NetSuite::Configuration .connection({ soap_header: preferences }, credentials) .call (@options.has_key?(:search_id)? :search_more_with_id : :search), :message => request_body end # basic search XML # <soap:Body> # <platformMsgs:search> # <searchRecord xsi:type="ContactSearch"> # <customerJoin xsi:type="CustomerSearchBasic"> # <email operator="contains" xsi:type="platformCore:SearchStringField"> # <platformCore:searchValue>shutterfly.com</platformCore:searchValue> # <email> # <customerJoin> # </searchRecord> # </search> # </soap:Body> def request_body if @options.has_key?(:search_id) return { 'pageIndex' => @options[:page_index], 'searchId' => @options[:search_id], } end # columns is only needed for advanced search results columns = @options[:columns] || {} criteria = @options[:criteria] || @options # TODO find cleaner solution for pulling the namespace of the record, which is a instance method namespace = if @klass.respond_to?(:search_class_namespace) @klass.search_class_namespace else @klass.new.record_namespace end # extract the class name criteria_structure = {} columns_structure = columns saved_search_id = criteria.delete(:saved) # TODO this whole thing needs to be refactored so we can apply some of the same logic to the # column creation xml criteria.each_pair do |condition_category, conditions| criteria_structure["#{namespace}:#{condition_category}"] = conditions.inject({}) do |h, condition| element_name = "platformCommon:#{condition[:field]}" case condition[:field] when 'recType' # TODO this seems a bit brittle, look into a way to handle this better h[element_name] = { :@internalId => condition[:value].internal_id } when 'customFieldList' # === START CUSTOM FIELD # there isn't a clean way to do lists of the same element # Gyoku doesn't seem support the nice :@attribute and :content! syntax for lists of elements of the same name # https://github.com/savonrb/gyoku/issues/18#issuecomment-17825848 # TODO with the latest version of savon we can easily improve the code here, should be rewritten with new attribute syntax custom_field_list = condition[:value].map do |h| if h[:value].is_a?(Array) && h[:value].first.respond_to?(:to_record) { "platformCore:searchValue" => h[:value].map(&:to_record), :attributes! => { 'platformCore:searchValue' => { 'internalId' => h[:value].map(&:internal_id) } } } elsif h[:value].respond_to?(:to_record) { "platformCore:searchValue" => { :content! => h[:value].to_record, :@internalId => h[:value].internal_id } } else { "platformCore:searchValue" => h[:value] } end end h[element_name] = { 'platformCore:customField' => custom_field_list, :attributes! => { 'platformCore:customField' => { 'scriptId' => condition[:value].map { |h| h[:field] }, 'operator' => condition[:value].map { |h| h[:operator] }, 'xsi:type' => condition[:value].map { |h| "platformCore:#{h[:type]}" } } } } # https://github.com/NetSweet/netsuite/commit/54d7b011d9485dad33504135dfe8153c86cae9a0#commitcomment-8443976 if NetSuite::Configuration.api_version < "2013_2" h[element_name][:attributes!]['platformCore:customField']['internalId'] = h[element_name][:attributes!]['platformCore:customField'].delete('scriptId') end # === END CUSTOM FIELD else if condition[:value].is_a?(Array) && condition[:value].first.respond_to?(:to_record) # TODO need to update to the latest savon so we don't need to duplicate the same workaround above again # TODO it's possible that this might break, not sure if platformCore:SearchMultiSelectField is the right type in every situation h[element_name] = { '@operator' => condition[:operator], '@xsi:type' => 'platformCore:SearchMultiSelectField', "platformCore:searchValue" => { :content! => condition[:value].map(&:to_record), '@internalId' => condition[:value].map(&:internal_id), '@xsi:type' => 'platformCore:RecordRef', '@type' => 'account' } } elsif condition[:value].is_a?(Array) && condition[:type] == 'SearchDateField' # date ranges are handled via searchValue (start range) and searchValue2 (end range) h[element_name] = { '@operator' => condition[:operator], "platformCore:searchValue" => condition[:value].first.to_s, "platformCore:searchValue2" => condition[:value].last.to_s } elsif condition[:value].is_a?(Array) && condition[:operator] == 'between' h[element_name] = { '@operator' => condition[:operator], "platformCore:searchValue" => condition[:value].first.to_s, "platformCore:searchValue2" => condition[:value].last.to_s } else h[element_name] = { :content! => { "platformCore:searchValue" => condition[:value] }, } h[element_name][:@operator] = condition[:operator] if condition[:operator] end end h end end if saved_search_id || !columns_structure.empty? search_structure = { 'searchRecord' => { '@xsi:type' => "#{namespace}:#{class_name}SearchAdvanced", :content! => { "#{namespace}:criteria" => criteria_structure } } } if saved_search_id search_structure['searchRecord']['@savedSearchId'] = saved_search_id end if !columns_structure.empty? search_structure['searchRecord'][:content!]["#{namespace}:columns"] = columns_structure end search_structure else { 'searchRecord' => { :content! => criteria_structure, '@xsi:type' => "#{namespace}:#{class_name}Search" } } end end def response_header @response_header ||= response_header_hash end def response_header_hash @response_header_hash = @response.header[:document_info] end def response_body @response_body ||= search_result end def search_result @search_result = if @response.body.has_key?(:search_more_with_id_response) @response.body[:search_more_with_id_response] else @response.body[:search_response] end[:search_result] end def success? @success ||= search_result[:status][:@is_success] == 'true' end protected def method_name end module Support def self.included(base) base.extend(ClassMethods) end module ClassMethods def search(options = { }, credentials={}) response = NetSuite::Actions::Search.call([self, options], credentials) if response.success? NetSuite::Support::SearchResult.new(response, self) else false end end end end end end end
module Spex class CreatedCheck < FileCheck as :created, 'file creation' option :type, "Type ('file' or 'directory'), optional" example "File was created", "check '/tmp/foo', :created => true" example "File was not created", "check '/tmp/foo', :created => false" example "Regular file was created", "check '/tmp/foo', :created => {:type => 'file'}" example "Directory was created", "check '/tmp/foo', :created => {:type => 'directory'}" def before assert !File.exist?(target), "File already exists at #{target}" end def after assert File.exist?(target), "File was not created at #{target}" check_type end private def check_type case kind when :file assert File.file?(target), "File created at #{target} is not a regular file" when :directory assert File.directory?(target), "File created at #{target} is not a directory" end end end end Support :created => false (regression) module Spex class CreatedCheck < FileCheck as :created, 'file creation' option :type, "Type ('file' or 'directory'), optional" example "File was created", "check '/tmp/foo', :created => true" example "File was not created", "check '/tmp/foo', :created => false" example "Regular file was created", "check '/tmp/foo', :created => {:type => 'file'}" example "Directory was created", "check '/tmp/foo', :created => {:type => 'directory'}" def before if active? assert !File.exist?(target), "File already exists at #{target}" end end def after if active? assert File.exist?(target), "File was not created at #{target}" else assert !File.exist?(target), "File was created at #{target}" end check_type end private def check_type case kind when :file assert File.file?(target), "File created at #{target} is not a regular file" when :directory assert File.directory?(target), "File created at #{target} is not a directory" end end end end
require "aws-sdk" module NewRelicAWS module Collectors class Base < Struct.new(:options); end class EC2 < Base; end class RDS < Base; end end end [cloudwatch] base collector sets up cloudwatch require "aws-sdk" module NewRelicAWS module Collectors class Base def initialize(options={}) @cloudwatch = AWS::CloudWatch.new( :access_key_id => options[:access_key], :secret_access_key => options[:secret_key], :region => options[:region] ) end def collect!; end end class EC2 < Base; end class RDS < Base; end end end
require 'spiderfw/model/mixins/state_machine' require 'spiderfw/model/element' require 'spiderfw/model/integrated_element' require 'iconv' module Spider; module Model # The main class for interacting with data. # When not dealing with legacy storages, subclasses should use Managed instead, which provides an id and # other conveniences. # # Each BaseModel subclass defines a model; instances can be used as "data objects": # they will interact with the Mapper loading and saving the values associated with the BaseModel's defined elements. # # Each element defines an instance variable, a getter and a setter. If the instance is set to #autoload, # when a getter is first called the mapper will fetch the value from the Storage . # # Elements can be of one of the base types (Spider::Model.base_types), of a DataType, or other models. In the last # case, they define a relationship between models. # # Basic usage: # model Food < BaseModel # element :name, String # end # model Animal < BaseModel # element :name, String # many :friends, Animal # choice :favorite_food, Food # end # # salmon = Food.new(:name => 'Salmon') # salmon.save # cat = Animal.new(:name => 'Cat', :favorite_food = salmon) # weasel = Animal.new(:name => 'Weasel', :friends => [cat]) # weasel.save # cat.friends << weasel # cat.save # # wizzy = Animal.load(:name => 'Weasel') # p wizzy.friends # => 'Cat' # p wizzy.friends[0].favorite_food # => 'Salmon' # # bear = Animal.new(:name => 'Bear', :favorite_food = salmon) # bear.save # salmon_lovers = Animal.where{ favorite_food == salmon } # p salmon_lovers.length # => 2 # p salmon_lovers[0].name # => 'Cat' class BaseModel include Spider::Logger include DataTypes include Spider::QueryFuncs include EventSource # include StateMachine # The BaseModel class itself. Used when dealing with proxy objects. attr_reader :model # An Hash of loaded elements attr_reader :loaded_elements # Model instance or QuerySet containing the object attr_accessor :_parent # If _parent is a model instance, which element points to this one attr_accessor :_parent_element # If this object is used as a superclass in class_table_inheritance, points to the current subclass attr_accessor :_subclass_object class <<self # An Hash of model attributes. They can be used freely. attr_reader :attributes # An array of element names, in definition order. attr_reader :elements_order # An Hash of integrated models => corresponding integrated element name. attr_reader :integrated_models # An Hash of polymorphic models => polymorphic params attr_reader :polymorphic_models # An Array of named sequences. attr_reader :sequences end # Copies this class' elements to the subclass. def self.inherited(subclass) #:nodoc: # FIXME: might need to clone every element @subclasses ||= [] @subclasses << subclass each_element do |el| subclass.add_element(el.clone) unless el.attributes[:local_pk] end subclass.instance_variable_set("@mapper_procs_subclass", @mapper_procs_subclass.clone) if @mapper_procs_subclass subclass.instance_variable_set("@mapper_modules", @mapper_modules.clone) if @mapper_modules subclass.instance_variable_set("@extended_models", @extended_models.clone) if @extended_models em = subclass.const_set(:ElementMethods, Module.new) subclass.send(:include, em) super end def self.subclasses @subclasses || [] end # Returns the parent Spider::App of the module def self.app return @app if @app app = self while (!app.include?(Spider::App)) app = app.parent_module end @app = app end ####################################### # Model definition methods # ####################################### # Defines an element. # Arguments are element name (a Symbol), element type, and a Hash of attributes. # # Type may be a Class: a base type (see Spider::Model.base_types), a DataType subclass, # or a BaseModel subclass; or an Array or a Hash, in which case an InlineModel will be created. # # An Element instance will be available in Model::BaseModel.elements; getter and setter methods will be defined on # the class. # # If a block is passed to this method, type will be 'extended': a custom junction association will be created, # effectively adding elements to the type only in this model's context. # Example: # class Animal < BaseModel # element :name, String # element :friends, Animal, :multiple => true do # element :how_much, String # end # end # cat = Animal.new(:name => 'Cat') # dog = Animal.new(:name => 'Dog') # cat.friends << dog # cat.friend[0].how_much = 'Not very much' # # Returns the created Element. # # Some used attributes: # :primary_key:: (bool) The element is a primary key # :length:: (number) Maximum length of the element (if meaningful) # :required:: (bool) The element must always have a value # :multiple:: (bool) defines a 1|n -> n relationship # :label:: (string) a short description, used by the UI # :association:: (symbol) A named association (such as :choice, :multiple_choice, etc.) # :lazy:: (bool, array or symbol) If true, the element will be placed in the :default lazy group; # if a symbol or an array of symbols is passed, the element will be placed in those groups. # (see Element#lazy_groups) # :reverse:: (symbol) The reverse element in the relationship to the other model # :add_reverse:: (symbol) Adds an element on the other model, and sets it as the association reverse. # :add_multiple_reverse:: (symbol) Adds a multiple element on the other model, and sets it as the association reverse. # :element_position:: (number) inserts the element at the specified position in the elements order # :auto:: (bool) Informative: the value is set automatically through some mechanism # :autoincrement:: (bool) The value (which must be a Fixnum) will be autoincremented by the mapper # :integrate:: (bool or symbol) type's elements will be available to this class # as if they were defined here (see #integrate) # :integrated_from:: (symbol) the name of the element from which this element is integrated # :integrated_from_element:: (symbol) the name of the element of the child object from which this element is integrated # :hidden:: (bool) a hint that the element shouldn't be shown by the UI # :computed_from:: (array of symbols) the element is not mapped; its value is computed # by the class from the given elements. # :unmapped:: (bool) the element is not mapped. # :sortable:: (bool or Array of symbols) specifies that an unmapped element can be used for sorting. # The model must provide a meaningful order using the prepare_query method. # :check:: (a Proc, or a Regexp, or a Hash of messages => Regexp|Proc). See #check # :through:: (a BaseModel subclass) model representing the many to many relationship. # :read_only:: (bool) hint to the UI that the element should not be user modifiable. # :owned:: (bool) only this model holds references to type # :condition:: (hash or Condition) Restricts an association always adding the condition. # :order:: (true or Fixnum) When doing queries, sort by this element. More than one element can have the # :order attribute; if it is a Fixnum, it will mean the position in the ordering. # :default:: (Proc or value) default value for the element. If it is a Proc, it will be passed # the object. # :desc:: (true or Fixnum) Use this element for the to_s string. Multiple elements # with the :desc attribute will be joined by spaces; order may be specified if # a Fixnum is used for the parameter # # Other attributes may be used by DataTypes (see #DataType::ClassMethods.take_attributes), and other code. # See also Element. def self.element(name, type, attributes={}, &proc) name = name.to_sym @elements ||= {} @elements_order ||= [] raise "Element called #{name} already exists in #{self}" if @elements[name] if type.class == Class default_attributes = case type.name when 'String' {:length => 255} else {} end else default_attributes = {} end attributes = default_attributes.merge(attributes) # if (type.class == Class && Model.base_type(type)) # type = Model.base_type(type) # els if (type.class <= Hash) type = create_inline_model(name, type) attributes[:inline] = true end if (attributes[:integrated_from]) if (attributes[:integrated_from].class == String) parts = attributes[:integrated_from].split('.') attributes[:integrated_from] = @elements[parts[0].to_sym] attributes[:integrated_from_element] = parts[1].to_sym if parts[1] elsif (attributes[:integrated_from].is_a?(Symbol)) attributes[:integrated_from] = @elements[attributes[:integrated_from]] end if (!attributes[:integrated_from_element]) attributes[:integrated_from_element] = name end end if (attributes[:condition] && !attributes[:condition].is_a?(Condition)) attributes[:condition] = Condition.new(attributes[:condition]) end if attributes[:computed_from] && !attributes[:computed_from].is_a?(Enumerable) attributes[:computed_from] = [attributes[:computed_from]] end type.set_element_attributes(attributes) if type < Spider::DataType orig_type = type assoc_type = nil if (proc || attributes[:junction] || (attributes[:multiple] && (!attributes[:add_reverse]) && (!attributes[:has_single_reverse]) && \ # FIXME! the first check is needed when the referenced class has not been parsed yet # but now it assumes that the reverse is not multiple if it is not defined (attributes[:has_single_reverse] == false || !attributes[:reverse] || (!type.elements[attributes[:reverse]] || type.elements[attributes[:reverse]].multiple?)))) attributes[:anonymous_model] = true attributes[:owned] = true unless attributes[:owned] != nil first_model = self.first_definer(name, type) assoc_type_name = Spider::Inflector.camelize(name) create_junction = true if (attributes[:through]) assoc_type = attributes[:through] create_junction = false elsif (first_model.const_defined?(assoc_type_name) ) assoc_type = first_model.const_get(assoc_type_name) if (!assoc_type.attributes[:sub_model]) # other kind of inline model assoc_type_name += 'Junction' create_junction = false if (first_model.const_defined?(assoc_type_name)) else create_junction = false end end attributes[:junction] = true attributes[:junction_id] = :id unless attributes.has_key?(:junction_id) if (attributes[:junction_our_element]) self_name = attributes[:junction_our_element] else self_name = first_model.short_name.gsub('/', '_').downcase.to_sym end attributes[:reverse] = self_name unless attributes[:junction_their_element] other_name = Spider::Inflector.underscore(orig_type.short_name == self.short_name ? orig_type.name : orig_type.short_name).gsub('/', '_').downcase.to_sym other_name = :"#{other_name}_ref" if (orig_type.elements[other_name]) attributes[:junction_their_element] = other_name end other_name = attributes[:junction_their_element] if (create_junction) assoc_type = first_model.const_set(assoc_type_name, Class.new(BaseModel)) assoc_type.attributes[:sub_model] = self assoc_type.attributes[:sub_model_element] = name assoc_type.element(attributes[:junction_id], Fixnum, :primary_key => true, :autoincrement => true, :hidden => true) if attributes[:junction_id] assoc_type.element(self_name, self, :hidden => true, :reverse => name, :association => :choice, :junction_reference => true) # FIXME: must check if reverse exists? # FIXME! fix in case of clashes with existent elements assoc_type.element(other_name, orig_type, :association => :choice, :junction_reference => true) assoc_type.integrate(other_name, :hidden => true, :no_pks => true) # FIXME: in some cases we want the integrated elements if (proc) # to be hidden, but the integrated el instead attributes[:extended] = true attributes[:keep_junction] = true assoc_type.class_eval(&proc) end end orig_type.referenced_by_junctions << [assoc_type, other_name] attributes[:keep_junction] = true if (attributes[:through] && attributes[:keep_junction] != false) attributes[:association_type] = assoc_type if attributes[:polymorph] assoc_type.elements[attributes[:junction_their_element]].attributes[:polymorph] = attributes[:polymorph] attributes.delete(:polymorph) end end add_element(Element.new(name, type, attributes)) if (attributes[:add_reverse] && attributes[:add_reverse].is_a?(Symbol)) attributes[:add_reverse] = {:name => attributes[:add_reverse]} end if (attributes[:add_multiple_reverse] && attributes[:add_multiple_reverse].is_a?(Symbol)) attributes[:add_multiple_reverse] = {:name => attributes[:add_multiple_reverse]} end if (attributes[:add_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_reverse][:name] rev = attributes[:add_reverse].merge(:reverse => name, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:keep_junction] = false rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end elsif (attributes[:add_multiple_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_multiple_reverse][:name] rev = attributes[:add_multiple_reverse].merge(:reverse => name, :multiple => true, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end end if (attributes[:lazy] == nil) # if attributes[:primary_key] # attributes[:lazy] = true # els if (type < BaseModel && (attributes[:multiple] || attributes[:polymorph])) # FIXME: we can load eagerly single relations if we can do a join attributes[:lazy] = true else attributes[:lazy_check_owner] = true if type < BaseModel attributes[:lazy] = :default end end # class element getter unless respond_to?(name) (class << self; self; end).instance_eval do define_method("#{name}") do @elements[name] end end end define_element_methods(name) attr_reader "#{name}_junction" if attributes[:junction] && !attributes[:keep_junction] if (attributes[:integrate]) integrate_params = attributes[:integrate].is_a?(Hash) ? attributes[:integrate] : {} integrate(name, integrate_params) end if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |imod, iel| imod.integrate_element(iel, self.elements[name]) unless imod.elements[name] end end if (@subclasses) @subclasses.each do |sub| next if sub.elements[name] # if subclass already defined an element with this name, don't overwrite it sub.elements[name] = @elements[name].clone sub.elements_order << name end end element_defined(@elements[name]) @elements[name].model? return @elements[name] end def self.define_element_methods(name) ivar = :"@#{ name }" unless self.const_defined?(:ElementMethods) em = self.const_set(:ElementMethods, Module.new) include em end element_methods = self.const_get(:ElementMethods) #instance variable getter element_methods.send(:define_method, name) do element = self.class.elements[name] raise "Internal error! Element method #{name} exists, but element not found" unless element return element.attributes[:fixed] if element.attributes[:fixed] if (element.integrated?) integrated = get(element.integrated_from.name) return integrated.send(element.integrated_from_element) if integrated return nil end if element_has_value?(name) || element_loaded?(name) val = instance_variable_get(ivar) val.set_parent(self, name) if val && element.model? && !val._parent # FIXME!!! return val end # Spider.logger.debug("Element not loaded #{name} (i'm #{self.class} #{self.object_id})") if autoload? && primary_keys_set? if (autoload? == :save_mode) mapper.load_element!(self, element) else mapper.load_element(self, element) end val = instance_variable_get(ivar) end if !val && element.model? && (element.multiple? || element.attributes[:extended_model]) val = instance_variable_set(ivar, instantiate_element(name)) end if !val && element.attributes[:default] if element.attributes[:default].is_a?(Proc) val = element.attributes[:default].call(self) else val = element.attributes[:default] end val = element.model.new(val) if element.model? && !val.is_a?(BaseModel) end val.set_parent(self, name) if element.model? && val && val.respond_to?(:parent) && !val._parent # FIXME!!! return val end alias_method :"#{name}?", name if self.elements[name].type <= Spider::DataTypes::Bool #instance_variable_setter element_methods.send(:define_method, "#{name}=") do |val| element = self.class.elements[name] raise "Internal error! Element method #{name}= exists, but element not found" unless element return if element.attributes[:fixed] was_loaded = element_loaded?(element) #@_autoload = false unless element.primary_key? if (element.integrated?) integrated_obj = get(element.integrated_from) unless integrated_obj integrated_obj = instantiate_element(element.integrated_from.name) set(element.integrated_from, integrated_obj) end #integrated_obj.autoload = false begin res = integrated_obj.send("#{element.integrated_from_element}=", val) rescue IdentityMapperException set(element.integrated_from, Spider::Model.get(integrated_obj)) get(element.integrated_from).merge!(integrated_obj) end @modified_elements[name] = true unless element.primary_key? return res end if (val && element.model?) if (element.multiple?) unless (val.is_a?(QuerySet)) qs = instantiate_element(name) if (val.is_a?(Enumerable)) val.each do |row| row = element.type.new(row) unless row.is_a?(BaseModel) qs << row end else qs << val end val = qs end else val = element.model.get(val) unless val.is_a?(BaseModel) end end val = prepare_child(element.name, val) _check(name, val) notify_observers(name, val) @_has_values = true unless @_primary_keys_set if self.class.elements[element.name].primary_key? && primary_keys_set? @_primary_keys_set = true if Spider::Model.identity_mapper Spider::Model.identity_mapper.put(self, true, true) else Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work end end end old_val = instance_variable_get(ivar) @modified_elements[name] = true if !element.primary_key? && (!was_loaded || val != old_val) instance_variable_set(ivar, val) set_reverse(element, val) if element.model? if val && element.model? && !self.class.attributes[:no_type_check] klass = val.is_a?(QuerySet) ? val.model : val.class if val && !(klass <= element.type || klass <= element.model) raise TypeError, "Object #{val} (#{klass}) is of the wrong type for element #{element.name} in #{self.class} (expected #{element.model})" end end val #extend_element(name) end end def self.add_element(el) @elements ||= {} @elements[el.name] = el @elements_order ||= [] if (el.attributes[:element_position]) @elements_order.insert(el.attributes[:element_position], el.name) else @elements_order << el.name end @primary_keys ||= [] if el.attributes[:primary_key] && !@primary_keys.include?(el) @primary_keys << el end end # Removes a defined element def self.remove_element(el) return unless @elements el = el.name if el.is_a?(Element) element = @elements[el] if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |mod, iel| i = mod.elements[el] mod.remove_element(el) if i && i.integrated? && i.integrated_from.name == iel end end self.elements_array.select{ |e| e.integrated? && e.integrated_from.name == el}.each{ |e| remove_element(e) } self.const_get(:ElementMethods).send(:remove_method, :"#{el}") rescue NameError self.const_get(:ElementMethods).send(:remove_method, :"#{el}=") rescue NameError @elements.delete(el) @elements_order.delete(el) @primary_keys.delete_if{ |pk| pk.name == el} # if (@subclasses) # @subclasses.each do |sub| # sub.remove_element(el) # end # end end def self.element_defined(el) if (@on_element_defined && @on_element_defined[el.name]) @on_element_defined[el.name].each do |proc| proc.call(el) end end end def self.on_element_defined(el_name, &proc) @on_element_defined ||= {} @on_element_defined[el_name] ||= [] @on_element_defined[el_name] << proc end # Integrates an element: any call to the child object's elements will be passed to the child. # The element must not be multiple. # Example: # class Address < BaseModel # element :street, String # element :area_code, String # end # class Person < BaseModel # element :name, String # element :address, Address # integrate :address # end # p = Person.new(...) # p.street == p.address.street def self.integrate(element_name, params={}) params ||= {} elements[element_name].attributes[:integrated_model] = true model = elements[element_name].type self.attributes[:integrated_models] ||= {} self.attributes[:integrated_models][model] = element_name params[:except] ||= [] model.each_element do |el| next if params[:except].include?(el.name) next if elements[el.name] unless params[:overwrite] # don't overwrite existing elements integrate_element(element_name, el, params) end model.attributes[:integrated_from_elements] ||= [] model.attributes[:integrated_from_elements] << [self, element_name] end def self.integrate_element(element_name, element_element, params={}) el = element_element integrated_attributes = {} integrated_attributes[:primary_key] = false if params[:no_pks] integrated_attributes[:hidden] = params[:hidden] unless (params[:hidden].nil?) integrated_attributes[:primary_key] = false unless (params[:keep_pks]) # attributes.delete(:required) # attributes.delete(:integrate) # attributes.delete(:local_pk) integrated_attributes[:local_pk] = false integrated_attributes[:lazy] = element_name name = params[:mapping] && params[:mapping][el.name] ? params[:mapping][el.name] : el.name add_element(IntegratedElement.new(name, self, element_name, el.name, integrated_attributes)) define_element_methods(name) end def self.remove_integrate(element_name) element = element_name.is_a?(Element) ? element_name : self.elements[element_name] model = element.model self.elements_array.select{ |el| el.attributes[:integrated_from] && el.attributes[:integrated_from].name == element.name }.each do |el| self.remove_element(el) end model.attributes[:integrated_from_elements].reject!{ |item| item[0] == self } end # Sets additional attributes on the element # # _Warning:_ for attributes which are parsed by the BaseModel during element definition, # this will not have the desired effect; remove and redefine the element instead. def self.element_attributes(element_name, attributes) elements[element_name].attributes = elements[element_name].attributes.merge(attributes) if attributes[:primary_key] && !@primary_keys.include?(elements[element_name]) @primary_keys << elements[element_name] elsif !attributes[:primary_key] @primary_keys.delete(elements[element_name]) end end # Defines a multiple element. Equivalent to calling # element(name, type, :multiple => true, :association => :many, ...) def self.many(name, type, attributes={}, &proc) attributes[:multiple] = true attributes[:association] ||= :many element(name, type, attributes, &proc) end # Defines an element with choice association. Shorthand for # element(name, type, :association => :choice, ...) def self.choice(name, type, attributes={}, &proc) attributes[:association] = :choice element(name, type, attributes, &proc) end # Defines a multiple element with :multiple_choice association. Shorthand for # many(name, type, :association => :multiple_choice, ...) def self.multiple_choice(name, type, attributes={}, &proc) attributes[:association] = :multiple_choice many(name, type, attributes, &proc) end def self.element_query(name, element_name, attributes={}) orig_element = self.elements[element_name] set_el_query = lambda do orig_element = self.elements[element_name] attributes = attributes.merge(orig_element.attributes) attributes[:unmapped] = true attributes[:element_query] = element_name attributes[:association] = :element_query attributes[:lazy] = true attributes.delete(:add_reverse) attributes.delete(:add_multiple_reverse) if (orig_element.attributes[:condition]) cond = orig_element.attributes[:condition].clone cond = cond.and(attributes[:condition]) if attributes[:condition] attributes[:condition] = cond end element(name, orig_element.type, attributes) end if (orig_element) set_el_query.call else on_element_defined(element_name, &set_el_query) end end # Saves the element definition and evals it when first needed, avoiding problems with classes not # available yet when the model is defined. # FIXME: remove? def self.define_elements(&proc) #:nodoc: @elements_definition = proc end # Creates an inline model def self.create_inline_model(name, hash) #:nodoc: model = self.const_set(Spider::Inflector.camelize(name), Class.new(InlineModel)) model.instance_eval do hash.each do |key, val| key = key.to_s if key.is_a?(Symbol) element(:id, key.class, :primary_key => true) if (val.class == Hash) # TODO: allow passing of multiple values like {:element1 => 'el1', :element2 => 'el2'} else element(:desc, val.class, :desc => true) end break end end model.data = hash return model end # An array of other models this class points to. def self.submodels elements.select{ |name, el| el.model? }.map{ |name, el| el.model } end def self.extend_model(model, params={}) #:nodoc: if (model == superclass) # first undo table per class inheritance @elements = {} @elements_order = [] @extended_models.delete(model.superclass) if @extended_models end primary_keys.each{ |k| remove_element(k) } if (params[:replace_pks]) model.primary_keys.each{ |k| remove_element(k) } integrated_name = params[:name] if (!integrated_name) integrated_name = (self.parent_module == model.parent_module) ? model.short_name : model.name integrated_name = Spider::Inflector.underscore(integrated_name).gsub('/', '_') end integrated_name = integrated_name.to_sym @extended_models ||= {} @extended_models[model] = integrated_name attributes = {} attributes[:hidden] = true unless (params[:hide_integrated] == false) attributes[:delete_cascade] = params[:delete_cascade] attributes[:extended_model] = true integrated = element(integrated_name, model, attributes) integrate_options = {:keep_pks => true}.merge((params[:integrate_options] || {})) integrate(integrated_name, integrate_options) model.elements_array.select{ |el| el.attributes[:local_pk] }.each{ |el| remove_element(el.name) } unless (params[:no_local_pk] || !elements_array.select{ |el| el.attributes[:local_pk] }.empty?) # FIXME: check if :id is already defined pk_name = @elements[:id] ? :"id_#{self.short_name.downcase}" : :id element(pk_name, Fixnum, :autoincrement => true, :local_pk => true, :hidden => true) end model.polymorphic(self, :through => integrated_name) end # Externalizes the superclass elements making the superclass an external integrated element. # Parameters may be: # * :name (symbol) name of the created element # * :delete_cascade (bool) delete cascade the superclass instance # * :no_local_pk (bool) do not define an id for this class def self.class_table_inheritance(params={}) self.extend_model(superclass, params) end # Makes the class use the superclass storage def self.inherit_storage self.attributes[:inherit_storage] = true (class << self; self; end).instance_eval do define_method(:storage) do superclass.storage end end end # Sets a fixed condition. def self.condition(condition) self.attributes[:condition] = condition end # #-- # TODO: document me def self.group(name, &proc) #:nodoc: proxy = Class.new(ProxyModel).proxy(name.to_s+'_', self) proxy.instance_eval(&proc) proxy.each_element do |el| element(name.to_s+'_'+el.name.to_s, el.type, el.attributes.clone) end define_method(name) do @proxies ||= {} return @proxies[name] ||= proxy.new end end # Add a subclass, allowing polymorphic queries on it. def self.polymorphic(model, options) through = options[:through] || Spider::Inflector.underscore(self.name).gsub('/', '_') through = through.to_sym @polymorphic_models ||= {} @polymorphic_models[model] = {:through => through} end # Sets or gets class attributes (a Hash). # If given a hash of attributes, will merge them with class attributes. # Model attributes are generally empty, and can be used by apps. def self.attributes(val=nil) @attributes ||= {} if (val) @attributes.merge!(val) end @attributes end # Sets a model attribute. See #self.attributes def self.attribute(name, value) @attributes ||= {} @attributes[name] = value end # Adds a sequence to the model. def self.sequence(name) @sequences ||= [] @sequences << name end # Model sequences. def self.sequences @sequences ||= [] end # Does nothing. This method is to keep note of elements created in other models. def self._added_elements(&proc) end def self.referenced_by_junctions @referenced_by_junctions ||= [] end ##################################################### # Methods returning information about the model # ##################################################### # Underscored local name (without namespaces) def self.short_name return Inflector.underscore(self.name.match(/([^:]+)$/)[1]) end # False for BaseModel (true for Spider::Model::Managed). def self.managed? return false end # Name def self.to_s self.name end # Sets the singolar and/or the plural label for the model # Returns the singlular label def self.label(sing=nil, plur=nil) @label = sing if sing @label_plural = plur if plur _(@label || self.name || '') end # Sets/retrieves the plural form for the label def self.label_plural(val=nil) @label_plural = val if (val) _(@label_plural || self.name || '') end def self.auto_primary_keys? self.primary_keys.select{ |k| !k.autogenerated? }.empty? end def self.containing_module par = self.parent_module while par <= BaseModel par = par.parent_module end par end def self.get_element(el) el = el.name if el.is_a?(Element) el = el.to_sym raise "No element called #{el} in #{self}" unless @elements[el] @elements[el] end def self.junction? !!self.attributes[:sub_model] end ######################################################## # Methods returning information about the elements # ######################################################## # An Hash of Elements, indexed by name. def self.elements @elements end # An array of the model's Elements. def self.elements_array @elements_order.map{ |key| @elements[key] } end # Yields each element in order. def self.each_element return unless @elements_order @elements_order.each do |name| yield elements[name] end end # Returns true if the model has given element name. def self.has_element?(name) return elements[name] ? true : false end # An array of elements with primary_key attribute set. def self.primary_keys @primary_keys end # Returns the model actually defining element_name; that could be the model # itself, a superclass, or an integrated model. def self.first_definer(element_name, type) if (@extended_models && @extended_models[self.superclass] && self.superclass.elements[element_name] && self.superclass.elements[element_name].type == type) return self.superclass.first_definer(element_name, type) end if (self.attributes[:integrated_models]) self.attributes[:integrated_models].keys.each do |mod| return mod.first_definer(element_name, type) if (mod.elements[element_name] && mod.elements[element_name].type == type) end end return self end # Returns true if the element with given name is associated with the passed # association. # This method should be used instead of querying the element's association directly, # since subclasses and mixins may extend this method to provide association equivalence. def self.element_association?(element_name, association) return true if elements[element_name].association = association end # An Hash of extended models => element name of the extended model element def self.extended_models @extended_models ||= {} end ############################################################## # Storage, mapper and loading (Class methods) # ############################################################## # The given module will be mixed in any mapper used by the class. def self.mapper_include(mod) @mapper_modules ||= [] @mapper_modules << mod end def self.mapper_include_for(params, mod) @mapper_modules_for ||= [] @mapper_modules_for << [params, mod] end # The given proc will be mixed in the mapper used by this class # Note that the proc will be converted to a Module, so any overridden methods will still have # access to the super method. def self.with_mapper(*params, &proc) # @mapper_procs ||= [] # @mapper_procs << proc mod = Module.new(&proc) mapper_include(mod) end # FIXME: remove def self.with_mapper_subclasses(*params, &proc) #:nodoc: @mapper_procs_subclass ||= [] @mapper_procs_subclass << proc end # Like #with_mapper, but will mixin the block only if the mapper matches params. # Possible params are: # - a String, matching the class' use_storage def self.with_mapper_for(*params, &proc) @mapper_procs_for ||= [] @mapper_procs_for << [params, proc] end # Sets the url or the name of the storage to use def self.use_storage(name=nil) @use_storage = name if name @use_storage end # Returns the current default storage for the class # The storage to use can be set with #use_storage def self.storage return @storage if @storage if (!@use_storage && self.attributes[:sub_model]) @use_storage = self.attributes[:sub_model].use_storage end return @use_storage ? get_storage(@use_storage) : get_storage end # Returns an instancethe storage corresponding to the storage_string if it is given, # or of the default storage otherwise. # The storage string can be a storage url (see #Storage.get_storage), or a named storage # defined in configuration #-- # Mixin! def self.get_storage(storage_string='default') storage_regexp = /([\w\d]+?):(.+)/ orig_string = nil if (storage_string !~ storage_regexp) orig_string = storage_string storage_conf = Spider.conf.get('storages')[storage_string] storage_string = storage_conf['url'] if storage_conf if (!storage_string || storage_string !~ storage_regexp) raise ModelException, "No storage '#{orig_string}' found" end end type, url = $1, $2 storage = Storage.get_storage(type, url) storage.instance_name = orig_string storage.configure(storage_conf) if storage_conf return storage end # Returns an instance of the default mapper for the class. def self.mapper @mapper ||= get_mapper(storage) end # Returns an instance of the mapper for the given storage def self.get_mapper(storage) # map_class = self.attributes[:inherit_storage] ? superclass : self mapper = storage.get_mapper(self) if (@mapper_modules) @mapper_modules.each{ |mod| mapper.extend(mod) } end if (@mapper_modules_for) @mapper_modules_for.each do |params, mod| if params.is_a?(String) mapper.extend(mod) if self.use_storage == params end end end if (@mapper_procs) @mapper_procs.each{ |proc| mapper.instance_eval(&proc) } end if (@mapper_procs_for) @mapper_procs_for.each do |params, proc| if (params.length == 1 && params[0].class == String) mapper.instance_eval(&proc) if (self.use_storage == params[0]) end end end if (@mapper_procs_subclass) @mapper_procs_subclass.each{ |proc| mapper.instance_eval(&proc) } end return mapper end # Syncs the schema with the storage. def self.sync_schema(options={}) options = ({ :force => false, :drop_fields => false, :update_sequences => false, :no_foreign_key_constraints => true }).merge(options) Spider::Model.sync_schema(self, options[:force], options) end # Executes #self.where, and calls QuerySet#load on the result. # Returns nil if the result is empty, the QuerySet otherwise # See #self.where for parameter syntax def self.find(*params, &proc) qs = self.where(*params, &proc) return qs.empty? ? nil : qs end # Executes #self.where, returning the first result. # See #self.where for parameter syntax. def self.load(*params, &proc) qs = self.where(*params, &proc) qs.limit = 1 return qs[0] end # Returns a queryset without conditions def self.all return self.where end # Constructs a Query based on params, and returns a QuerySet # Allowed parameters are: # * a Query object # * a Condition and an (optional) Request, or anything that can be parsed by Condition.new and Request.new # If a block is provided, it is passed to Condition.parse_block. # Examples: # felines = Animals.where({:family => 'felines'}) # felines = Animals.where({:family => 'felines'}, [:name, :description]) # cool_animals = Animals.where{ (has_fangs == true) | (has_claws == true)} # See also Condition#parse_block def self.where(*params, &proc) if (params[0] && params[0].is_a?(Query)) query = params[0] qs = QuerySet.new(self, query) elsif(proc) qs = QuerySet.new(self) qs.autoload = true qs.where(&proc) else condition = Condition.and(params[0]) request = Request.new(params[1]) query = Query.new(condition, request) qs = QuerySet.new(self, query) end return qs end # Returns the condition for a "free" text query # Examples: # condition = News.free_query_condition('animals') # animal_news = News.where(condition) def self.free_query_condition(q) c = Condition.or self.elements_array.each do |el| if (el.type == String || el.type == Text) c.set(el.name, 'ilike', '%'+q+'%') end end return c end # Returns the number of objects in storage def self.count(condition=nil) mapper.count(condition) end # Can be defined to provide functionality to this model's querysets. def self.extend_queryset(qs) end ################################################# # Instance methods # ################################################# # The constructor may take: # * an Hash of values, that will be set on the new instance; or # * a BaseModel instance; its values will be set on the new instance; or # * a single value; it will be set on the first primary key. def initialize(values=nil) @_autoload = true @_has_values = false @loaded_elements = {} @modified_elements = {} @value_observers = nil @all_values_observers = nil @_extra = {} @model = self.class @_primary_keys_set = false set_values(values) if values # if primary_keys_set? # @_primary_keys_set = true # if Spider::Model.identity_mapper # Spider::Model.identity_mapper.put(self, true) # else # Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work # end # else # #nil # end end # Returns an instance of the Model with #autoload set to false def self.static(values=nil) obj = self.new obj.autoload = false obj.set_values(values) if values return obj end def self.create(values) obj = self.static(values) obj.save return obj end def self.get(values) return self.new(values) unless Spider::Model.identity_mapper values = [values] unless values.is_a?(Hash) || values.is_a?(Array) if values.is_a?(Array) vals = {} self.primary_keys.each_with_index do |k, i| vals[k.name] = values[i] end values = vals end curr = Spider::Model.identity_mapper.get(self, values) return curr if curr obj = self.new(values) Spider::Model.identity_mapper.put(obj) obj end def set_values(values) if (values.is_a? Hash) values.keys.select{ |k| k = k.name if k.is_a?(Element) self.class.elements[k.to_sym] && self.class.elements[k.to_sym].primary_key? }.each do |k| set!(k, values[k]) end values.each do |key, val| set!(key, val) end elsif (values.is_a? BaseModel) values.each_val do |name, val| set(name, val) if self.class.has_element?(name) end elsif (values.is_a? Array) self.class.primary_keys.each_index do |i| set(self.class.primary_keys[i], values[i]) end # Single unset key, single value elsif ((empty_keys = self.class.primary_keys.select{ |key| !element_has_value?(key) }).length == 1) set(empty_keys[0], values) else raise ArgumentError, "Don't know how to construct a #{self.class} from #{values.inspect}" end end # Returns the instance's IdentityMapper def identity_mapper return Spider::Model.identity_mapper if Spider::Model.identity_mapper @identity_mapper ||= IdentityMapper.new end # Sets the instance's IdentityMapper. def identity_mapper=(im) @identity_mapper = im end # Returns a new instance for given element name. def instantiate_element(name) element = self.class.elements[name] if (element.model?) if (element.multiple?) val = QuerySet.static(element.model) else val = element.type.new val.autoload = autoload? end end val = prepare_child(name, val) instance_variable_set("@#{name}", val) set_reverse(element, val) if element.model? val end # Prepares an object that is being set as a child. def prepare_child(name, obj) return obj if obj.nil? element = self.class.elements[name] if (element.model?) # convert between junction and real type if needed if element.attributes[:junction] if obj.is_a?(QuerySet) obj.no_autoload do if (element.attributes[:keep_junction] && obj.model == element.type) qs = QuerySet.new(element.model) obj.each{ |el_obj| qs << {element.reverse => self, element.attributes[:junction_their_element] => el_obj} } obj = qs elsif (!element.attributes[:keep_junction] && obj.model == element.model) instance_variable_set("@#{element.name}_junction", obj) qs = QuerySet.new(element.type, obj.map{ |el_obj| el_obj.get(element.attributes[:junction_their_element])}) obj = qs end end else if (!element.attributes[:keep_junction] && obj.class == element.model) obj = obj.get(element.attributes[:junction_their_element]) end end end self.class.elements_array.select{ |el| el.attributes[:fixed] }.each do |el| if el.integrated_from == element obj.set(el.integrated_from_element, el.attributes[:fixed]) end end obj.identity_mapper = self.identity_mapper if obj.respond_to?(:identity_mapper) if (element.multiple? && element.attributes[:junction] && element.attributes[:keep_junction]) obj.append_element = element.attributes[:junction_their_element] end if (element.attributes[:set] && element.attributes[:set].is_a?(Hash)) element.attributes[:set].each{ |k, v| obj.set(k, v) } obj.reset_modified_elements(*element.attributes[:set].keys) # FIXME: is it always ok to not set the element as modified? But otherwise sub objects # are always saved (and that's definitely no good) end if element.type == self.class.superclass && self.class.extended_models[element.type] && self.class.extended_models[element.type] == element.name obj._subclass_object = self end else obj = prepare_value(element, obj) end return obj end # Returns all children that can be reached from the current path. # Path is expressed as a dotted String. def all_children(path) children = [] no_autoload do el = path.shift if self.class.elements[el] && element_has_value?(el) && children = get(el) if path.length >= 1 children = children.all_children(path) end end end return children end # Sets the object currently containing this one (BaseModel or QuerySet) def set_parent(obj, element) @_parent = obj @_parent_element = element end def set_reverse(element, obj) return unless element.model? && obj if element.has_single_reverse? && (!element.attributes[:junction] || element.attributes[:keep_junction]) unless element.multiple? val = obj.get_no_load(element.reverse) return if val && val.object_id == self.object_id end obj.set(element.reverse, self) end end ################################################# # Get and set # ################################################# # Returns an element. # The element may be a symbol, or a dotted path String. # Will call the associated getter. # cat.get('favorite_food.name') def get(element) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) sub_val = send(first) return nil unless sub_val return sub_val.get(rest) end return send(element) end # Returns an element without autoloading it. def get_no_load(element) res = nil no_autoload do res = get(element) end return res end # Sets an element. # The element can be a symbol, or a dotted path String. # Will call the associated setter. # cat.set('favorite_food.name', 'Salmon') def set(element, value, options={}) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) first_val = send(first) unless first_val if (options[:instantiate]) first_val = instantiate_element(first.to_sym) set(first, first_val) else raise "Element #{first} is nil, can't set #{element}" end end return first_val.set(rest, value, options) end return send("#{element}=", value) end # Sets an element, instantiating intermediate objects if needed def set!(element, value, options={}) options[:instantiate] = true set(element, value, options) end # Calls #get on element; whenever no getter responds, returns the extra data. # See #[]= def [](element) element = element.name if element.is_a?(Element) begin get(element) rescue NoMethodError return @_extra[element] end end # If element is a model's element, calls #set. # Otherwise, stores the value in an "extra" hash, where it will be accessible by #[] def []=(element, value) element = element.name if element.is_a?(Element) if (self.class.elements[element]) set(element, value) else @_extra[element] = value end end # Sets each value of a Hash. def set_hash(hash) hash.each { |key, val| set(key, val) } end # Prepares a value going to be set on the object. Will convert the value to the # appropriate type. def self.prepare_value(element, value) element = self.class.elements[element] unless element.is_a?(Element) if (element.type < Spider::DataType) value = element.type.from_value(value) unless value.is_a?(element.type) if value element.type.take_attributes.each do |a| if element.attributes[a].is_a?(Proc) value.attributes[a] = value.instance_eval(&element.attributes[a]) else value.attributes[a] = element.attributes[a] end end value = value.prepare end elsif element.model? value.autoload(autoload?, true) if value && value.respond_to?(:autolad) else case element.type.name when 'Date', 'DateTime' return nil if value.is_a?(String) && value.empty? parsed = nil if (value.is_a?(String)) begin parsed = element.type.strptime(value, "%Y-%m-%dT%H:%M:%S") rescue parsed = nil parsed ||= element.type.lparse(value, :short) rescue parsed = nil parsed ||= element.type.parse(value) rescue ArgumentError => exc raise FormatError.new(element, value, _("'%s' is not a valid date")) end value = parsed end when 'String' when 'Spider::DataTypes::Text' value = value.to_s when 'Fixnum' value = value.to_i end end value end def prepare_value(element, value) self.class.prepare_value(element, value) end # Sets a value without calling the associated setter; used by the mapper. def set_loaded_value(element, value, mark_loaded=true) element_name = element.is_a?(Element) ? element.name : element element = self.class.elements[element_name] if (element.integrated?) get(element.integrated_from).set_loaded_value(element.integrated_from_element, value) else value = prepare_child(element.name, value) current = instance_variable_get("@#{element_name}") current.set_parent(nil, nil) if current && current.is_a?(BaseModel) value.set_parent(self, element.name) if value.is_a?(BaseModel) instance_variable_set("@#{element_name}", value) end value.loaded = true if (value.is_a?(QuerySet)) element_loaded(element_name) if mark_loaded set_reverse(element, value) if element.model? @modified_elements[element_name] = false end # Records that the element has been loaded. def element_loaded(element_name) element_name = self.class.get_element(element_name).name @loaded_elements[element_name] = true end # Returns true if the element has been loaded by the mapper. def element_loaded?(element) element = self.class.get_element(element).name return @loaded_elements[element] end # Apply element checks for given element name and value. (See also #element, :check attribute). # Checks may be defined by the DataType, or be given as an element attribute. # The check can be a Regexp, that will be checked against the value, or a Proc, which is expected to # return true if the check is succesful, and false otherwise. # Will raise a Model::FormatError when a check is not succesful. # If the :check attribute is an Hash, the Hash keys will be used as messages, which will be passed # to the FormatError. def _check(name, val) element = self.class.elements[name] element.type.check(val) if (element.type.respond_to?(:check)) if (checks = element.attributes[:check]) checks = {(_("'%s' is not in the correct format") % element.label) => checks} unless checks.is_a?(Hash) checks.each do |msg, check| test = case check when Regexp val == nil || val.empty? ? true : check.match(val) when Proc check.call(val) end raise FormatError.new(element, val, msg) unless test end end end # Converts the object to the instance of a subclass for which this model is polymorphic. def polymorphic_become(model) return self if self.is_a?(model) unless self.class.polymorphic_models && self.class.polymorphic_models[model] sup = model.superclass while sup < Spider::Model::BaseModel && !self.class.polymorphic_models[sup] sup = sup.superclass end raise ModelException, "#{self.class} is not polymorphic for #{model}" unless self.class.polymorphic_models[sup] sup_poly = polymorphic_become(sup) return sup_poly.polymorphic_become(model) end el = self.class.polymorphic_models[model][:through] obj = model.new(el => self) obj = Spider::Model.identity_mapper.get(obj) if Spider::Model.identity_mapper obj.element_loaded(el) return obj end def become(model) return self if self.class == model obj = polymorphic_become(model) rescue ModelException return obj end # Converts the object to the instance of a subclass. This will instantiate the model # passed as an argument, and set each value of the current object on the new one. # No checks are made that this makes sense, so the method will fail if the "subclass" does # not contain all of the current model's elements. def subclass(model) obj = model.new self.class.elements_array.each do |el| obj.set(el, self.get(el)) if element_has_value?(el) && model.elements[el.name] end return obj end # Returns the current autoload status def autoload? @_autoload end # Enables or disables autoloading. # An autoloading object will try to load all missing elements on first access. # (see also Element#lazy_groups) def autoload=(val) autoload(val, false) end # Sets autoload mode # The first parameter the value of autoload to be set; it can be true, false or :save_mode (see #save_mode)) # the second bool parameter specifies if the value should be propagated on all child objects. def autoload(a, traverse=true) #:nodoc: return if @_tmp_autoload_walk @_tmp_autoload_walk = true @_autoload = a if (traverse) self.class.elements_array.select{ |el| el.model? && \ (element_has_value?(el.name) || el.attributes[:extended_model])}.each do |el| val = get(el) val.autoload = a if val.respond_to?(:autoload=) end end @_tmp_autoload_walk = nil end # Disables autoload. # If a block is given, the current autoload setting will be restored after yielding. def no_autoload prev_autoload = autoload? self.autoload = false if block_given? yield self.autoload = prev_autoload end return prev_autoload end # Sets autoload to :save_mode; elements will be autoloaded only one by one, so that # any already set data will not be overwritten # If a block is given, the current autoload setting will be restored after yielding. def save_mode prev_autoload = autoload? self.autoload = :save_mode if (block_given?) yield self.autoload = prev_autoload end return prev_autoload end ############################################################## # Methods for getting information about element values # ############################################################## # Returns true if other is_a?(self.class), and has the same values for this class' primary keys. def ==(other) return false unless other return false unless other.is_a?(self.class) self.class.primary_keys.each do |k| return false unless get(k) == other.get(k) end return true end ############################################################## # Iterators # ############################################################## # Iterates over elements and yields name-value pairs def each # :yields: element_name, element_value self.class.elements.each do |name, el| yield name, get(name) end end # Iterates over non-nil elements, yielding name-value pairs def each_val # :yields: element_name, element_value self.class.elements.select{ |name, el| element_has_value?(name) }.each do |name, el| yield name, get(name) end end # Returns an array of current primary key values def primary_keys self.class.primary_keys.map{ |k| val = get(k) k.model? && val ? val.primary_keys : val } end # Returns an hash of primary keys names and values def primary_keys_hash h = {} self.class.primary_keys.each{ |k| h[k.name] = get(k) } h end # Returns a string with the primary keys joined by ',' def keys_string self.class.primary_keys.map{ |pk| self.get(pk) }.join(',') end # Returns true if the element instance variable is set #-- # FIXME: should probably try to get away without this method # it is the only method that relies on the mapper def element_has_value?(element) element = self.class.get_element(element) if (element.integrated?) return false unless obj = instance_variable_get(:"@#{element.integrated_from.name}") return obj.element_has_value?(element.integrated_from_element) end if (element.attributes[:computed_from]) element.attributes[:computed_from].each{ |el| return false unless element_has_value?(el) } return true end ivar = nil ivar = instance_variable_get(:"@#{element.name}") if instance_variable_defined?(:"@#{element.name}") return nil == ivar ? false : true # FIXME: is this needed? # if (!mapper.mapped?(element) # return send("#{element_name}?") if (respond_to?("#{element_name}?")) # return get(element) == nil ? false : true if (!mapper.mapped?(element)) # end end # Returns true if the element value has been modified since instantiating or loading def element_modified?(element) element = self.class.get_element(element) set_mod = @modified_elements[element.name] return set_mod if set_mod if (element.integrated?) return false unless integrated = get_no_load(element.integrated_from) return integrated.element_modified?(element.integrated_from_element) end if element_has_value?(element) && (val = get(element)).respond_to?(:modified?) return val.modified? end return false end # Returns true if any of elements has been modified def elements_modified?(*elements) elements = elements[0] if elements[0].is_a?(Array) elements.each{ |el| return true if element_modified?(el) } return false end # Returns true if any element, or any child object, has been modified def modified? return true unless @modified_elements.reject{ |key, val| !val }.empty? self.class.elements_array.select{ |el| !el.model? && element_has_value?(el) && el.type.is_a?(Spider::DataType) }.each do |el| return true if get(el).modified? end return false end def in_storage? return false unless primary_keys_set? return self.class.load(primary_keys_hash) end # Given elements are set as modified def set_modified(request) #:nodoc: request.each do |key, val| # FIXME: go deep @modified_elements[key] = true end end # Resets modified elements def reset_modified_elements(*elements) #:nodoc: if (elements.length > 0) elements.each{ |el_name| @modified_elements.delete(el_name) } else @modified_elements = {} end end # Returns true if all primary keys have a value; false if some primary key # is not set or the model has no primary key def primary_keys_set? primary_keys = self.class.primary_keys return false unless primary_keys.length > 0 primary_keys.each do |el| if (el.integrated?) return false unless (int_obj = instance_variable_get(:"@#{el.integrated_from.name}")) #return false unless int_obj.instance_variable_get(:"@#{el.integrated_from_element}") return false unless int_obj.element_has_value?(el.integrated_from_element) else return false unless self.instance_variable_get(:"@#{el.name}") end end return true end # Returns true if no element has a value def empty? return @_has_values end # Sets all values of obj on the current object def merge!(obj, only=nil) obj.class.elements_array.select{ |el| (only || obj.element_has_value?(el)) && !el.integrated? && !el.attributes[:computed_from] }.each do |el| next if only && !only.key?(el.name) val = obj.get_no_load(el) set_loaded_value(el, val, false) end end # Returns a deep copy of the object def clone obj = self.class.new obj.merge!(self) return obj end # Returns a new instance with the same primary keys def get_new obj = nil Spider::Model.no_identity_mapper do obj = self.class.new self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } end return obj end # Returns a new static instance with the same primary keys def get_new_static obj = self.class.static self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } return obj end # Returns a condition based on the current primary keys def keys_to_condition c = Condition.and self.class.primary_keys.each do |key| val = get(key) if (key.model?) c[key.name] = val.keys_to_condition else c[key.name] = val end end return c end ################################################# # Object observers methods # ################################################# # The given block will be called whenever a value is modified. # The block will be passed three arguments: the object, the element name, and the previous value # Example: # obj.observe_all_values do |instance, element_name, old_val| # puts "#{element_name} for object #{instance} has changed from #{old_val} to #{instance.get(element_name) }" def observe_all_values(&proc) @all_values_observers ||= [] @all_values_observers << proc end def observe_element(element_name, &proc) @value_observers ||= {} @value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.observer_all_values(&proc) self.all_values_observers << proc end def self.observe_element(element_name, &proc) self.value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.value_observers @value_observers ||= {} end def self.all_values_observers @all_values_observers ||= [] end # Calls the observers for element_name def notify_observers(element_name, new_val) #:nodoc: if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(self, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(self, element_name, new_val) } end end # Calls the observers for element_name def self.notify_observers(element_name, new_val) if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(self, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(self, element_name, new_val) } end end ############################################################## # Storage, mapper and schema loading (instance methods) # ############################################################## # Returns the current @storage, or instantiates the default calling Spider::BaseModel.storage def storage return @storage || self.class.storage end # Instantiates the storage for the instance. # Accepts a string (url or named storage) which will be passed to Spider::BaseModel.get_storage # Example: # obj.use_storage('my_named_db') # obj.use_storage('db:oracle://username:password@XE') def use_storage(storage) @storage = self.class.get_storage(storage) @mapper = self.class.get_mapper(@storage) end # Returns the current mapper, or instantiates a new one (base on the current storage, if set) def mapper @storage ||= nil if (@storage) @mapper ||= self.class.get_mapper(@storage) else @mapper ||= self.class.mapper end return @mapper end # Sets the current mapper def mapper=(mapper) @mapper = mapper end ############################################################## # Saving and loading from storage methods # ############################################################## # Saves the object to the storage # (see Mapper#save) def save if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else save! end end self end def save! mapper.save(self) self end # Saves the object and all child objects to the storage # (see Mapper#save_all) def save_all mapper.save_all(self) self end def insert if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self, :save, :force => :insert) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else insert! end end self end # Inserts the object in the storage # Note: if the object is already present in the storage and unique indexes are enforced, # this will raise an error. # (See Mapper#insert). def insert! mapper.insert(self) reset_modified_elements end # Updates the object in the storage # Note: the update will silently fail if the object is not present in the storage # (see Mapper#update). def update mapper.update(self) reset_modified_elements end # Deletes the object from the storage # (see Mapper#delete). def delete if @unit_of_work @unit_of_work.add(self, :delete) return end before_delete unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self, :delete) if @unit_of_work @unit_of_work.commit @unit_of_work.stop if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else delete! end end def delete! mapper.delete(self) end def before_delete end def before_save end def use_unit_of_work had_uow = true unless Spider.current[:unit_of_work] had_wow = false @unit_of_work = Spider::Model.start_unit_of_work end unless Spider::Model.identity_mapper @uow_identity_mapper = Spider::Model::IdentityMapper.new Spider.current[:identity_mapper] = @uow_identity_mapper @uow_identity_mapper.put(self) if self.primary_keys_set? end # Spider.current[:unit_of_work].add(self) Spider.current[:unit_of_work] return had_uow end # Loads the object from the storage # Acceptable arguments are: # * a Query object, or # * a Request object, or a Hash, which will be converted to a Request, or # * a list of elements to request # It will then construct a Condition with current primary keys, and call Mapper#load # Note that an error will be raised by the Mapper if not all primary keys are set. def load(*params) if (params[0].is_a? Query) query = params[0] else return false unless primary_keys_set? query = Query.new if (params[0].is_a?(Request)) query.request = params.shift elsif (params[0].is_a?(Hash)) query.request = Request.new(params.shift) end elements = params.length > 0 ? params : self.class.elements.keys return true unless elements.select{ |el| !element_loaded?(el) }.length > 0 elements.each do |name| query.request[name] = true end query.condition.conjunction = :and self.class.primary_keys.each do |key| query.condition[key.name] = get(key.name) end end #clear_values() return mapper.load(self, query) end # Sets all values to nil def clear_values() self.class.elements.each_key do |element_name| instance_variable_set(:"@#{element_name}", nil) end end def remove_association(element, object) mapper.delete_element_associations(self, element, object) end # Method that will be called by the mapper before a query. May be overridden to preprocess the query. # Must return the modified query. Note: to prepare conditions, use prepare_condition, since it will # be called on subconditions as well. def self.prepare_query(query) query end ############################################################## # Method missing # ############################################################## # Tries the method on integrated models def method_missing(method, *args) #:nodoc: # UNUSED # case method.to_s # when /load_by_(.+)/ # element = $1 # if !self.class.elements[element.to_sym].attributes[:primary_key] # raise ModelException, "load_by_ called for element #{element} which is not a primary key" # elsif self.class.primary_keys.length > 1 # raise ModelException, "can't call #{method} because #{element} is not the only primary key" # end # query = Query.new # query.condition[element.to_sym] = args[0] # load(query) # else if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| obj = send(name) if (obj.respond_to?(method)) return obj.send(method, *args) end end end raise NoMethodError, "undefined method `#{method}' for #{self.class}" #super # end end def respond_to?(symbol, include_private=false) return true if super if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| if (model.method_defined?(symbol)) return true end end end return false end # Returns a descriptive string for the object. # By default this method returns the value of the first String element, if any; otherwise, # the string representation of the first element of any type. # Descendant classes may well provide a better representation. def to_s desc_elements = self.class.elements_array.select{ |el| el.attributes[:desc] } unless desc_elements.empty? return desc_elements.sort{ |a, b| ad = a.attributes[:desc]; bd = b.attributes[:desc] if ad == true && bd == true 0 elsif bd == true -1 elsif ad == true 1 else ad <=> bd end }.map{ |el| self.get(el).to_s }.join(' ') end self.class.each_element do |el| if ((el.type == String || el.type == Text) && !el.primary_key?) v = get(el) return v ? v.to_s : '' end end el = self.class.elements_array[0] if element_has_value?(el) v = get(el) return v ? v.to_s : '' end return '' end # A compact representation of the object. # Note: inspect will not autoload the object. def inspect self.class.name+': {' + self.class.elements_array.select{ |el| (element_loaded?(el) || element_has_value?(el)) && !el.hidden? } \ .map{ |el| ":#{el.name} => #{get(el.name).to_s}"}.join(',') + '}' end # Returns a JSON representation of the object. # # The tree will be traversed outputting all encountered objects; when an already seen object # is met, the primary keys will be output (as a single value if one, as an array if many) and traversing # will stop. # # For more fine-grained control of the output, it is better to use the #cut method and call to_json on it. def to_json(state=nil, &proc) require 'json' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') if (@tmp_json_seen && !block_given?) pks = self.class.primary_keys.map{ |k| get(k).to_json } pks = pks[0] if pks.length == 1 return pks.to_json end @tmp_json_seen = true json = "" #Spider::Model.with_identity_mapper do |im| self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", true) end if (block_given?) select_elements = Proc.new{ true } else select_elements = Proc.new{ |name, el| !el.hidden? # && # #!el.attributes[:integrated_model] && # (element_has_value?(el) || (el.integrated? && element_has_value?(el.integrated_from))) } end json = "{" + self.class.elements.select(&select_elements).map{ |name, el| if (block_given?) val = yield(self, el) val ? "#{name.to_json}: #{val.to_json}" : nil else val = get(name) if (el.type == 'text' || el.type == 'longText') val = ic.iconv(val + ' ')[0..-2] end val = val.to_json "#{name.to_json}: #{val}" end }.select{ |pair| pair}.join(',') + "}" @tmp_json_seen = false self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", false) end #end return json end # Returns a part of the object tree, converted to Hashes, Arrays and Strings. # Arguments can be: # * a String, followed by a list of elements; the String will be sprintf'd with element values # or # * a depth Fixnum; depth 0 means obj.to_s will be returned, depth 1 will return an hash containing the # object's element values converted to string, and so on # or # * a Hash, whith element names as keys, and depths, or Hashes, or Procs as values; each element # will be traversed up to the depth given, or recursively according to the has; or, if a Proc is given, # it will be called with the current object and element name as arguments # or # * a list of elements; this is equivalent to passing a hash of the elements with depth 0. # # Examples: # obj.inspect # => Zoo::Animal: {:name => Llama, :family => Camelidae, :friends => Sheep, Camel} # obj.cut(0) # => 'Llama' # obj.cut(:name, :friends) # => {:name => 'Llama', :friends => 'Sheep, Camel'} # obj.cut(:name => 0, :friends => 1) # => {:name => 'Llama', :friends => [ # {:name => 'Sheep', :family => 'Bovidae', :friends => 'Llama'}, # {:name => 'Camel', :family => 'Camelidae', :friens => 'Dromedary, LLama'} # ]} # obj.cut(:name => 0, :friends => {:name => 0}) # => {:name => 'Llama', :friends => [{:name => 'Sheep'}, {:name => 'Camel'}]} # objs.cut(:name => 0, :friends => lambda{ |instance, element| # instance.get(element).name.upcase # }) # => {:name => 'Llama', :friends => ['SHEEP', 'CAMEL']} # obj.cut("Hi, i'm a %s and my friends are %s", :name, :friends) # => "Hi, i'm a Llama and my friends are Sheep, Camel" def cut(*params, &proc) h = {} if (params[0].is_a?(String)) return sprintf(params[0], *params[1..-1].map{ |el| get(el) }) elsif (params[0].is_a?(Fixnum)) p = params.shift if (p < 1) if (block_given?) return proc.call(self) else return self.to_s end end lev = p where = {} self.class.elements_array.each { |el| where[el.name] = lev-1} end if (params[0].is_a?(Hash)) where ||= {} params[0].each{ |k, v| where[k.to_sym] = v} else where ||= {} params.each{ |p| where[p] = 0 if p.is_a?(Symbol)} end Spider::Model.with_identity_mapper do |im| where.keys.each do |name| next unless where[name] if (where[name].is_a?(Proc)) val = where[name].call(self, name) else el = self.class.elements[name] if el val = get(el) val = val.cut(where[name], &proc) if el.model? && val else raise ModelException, "Element #{name} does not exist" unless self.respond_to?(name) val = self.send(name) val = val.cut(where[name], &proc) if val.is_a?(BaseModel) end end h[name] = val end end return h end # Returns a element_name => value Hash def to_hash() h = {} self.class.elements.select{ |name, el| element_loaded? el }.each do |name, el| h[name] = get(name) end return h end # Returns a yaml representation of the object. Will try to autoload all elements, unless autoload is false; # foreign keys will be expressed as an array if multiple, as a single primary key value otherwise def to_yaml(params={}) require 'yaml' return YAML::dump(to_yaml_h(params)) end def to_yaml_h(params={}) h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next if params[:except] && params[:except].include?(el.name) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else h[el.name] = get(el) end end h end def self.from_yaml(yaml) h = YAML::load(yaml) obj = self.static h.each do |key, value| el = elements[key.to_sym] if (el.multiple?) el_obj = el.model.static el.model.primary_keys.each do |pk| el_obj.set(pk, value.unshift) end obj.set(el, el_obj) else obj.set(el, value) end end return obj end def dump_to_hash h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next unless mapper.have_references?(el) || (el.junction? && el.model.attributes[:sub_model] == self.class) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else val = get(el) if val case val.class.name.to_sym when :Date, :DateTime, :Time val = val.strftime end end h[el.name] = val end end h end def dump_to_all_data_hash(options={}, h={}, seen={}) Spider::Model.with_identity_mapper do |im| clname = self.class.name.to_sym seen[clname] ||= {} return if seen[clname][self.primary_keys] seen[clname][self.primary_keys] = true h[clname] ||= [] h[clname] << self.dump_to_hash self.class.elements_array.each do |el| next unless el.model? next if el.model < Spider::Model::InlineModel next if options[:models] && !options[:models].include?(el.type) next if options[:except_models] && options[:except_models].include?(el.type) el_clname == el.type.name.to_sym next if options[:elements] && (options[:elements][el_clname] && !options[:elements][el_clname].include?(el.name)) next if options[:except_elements] && (options[:except_elements][el_clname] && options[:except_elements][el_clname].include?(el.name)) val = self.get(el) next unless val val = [val] unless val.is_a?(Enumerable) val.each do |v| v.dump_to_all_data_hash(options, h, seen) end end end h end def self.in_transaction self.storage.in_transaction yield self.storage.commit_or_continue end def self.dump_element(el) remove_elements = [] method = case el.attributes[:association] when :many :many when :choice :choice when :multiple_choice :multiple_choice when :tree :tree else :element end type = el.type attributes = el.attributes.clone if (method == :many || method == :multiple_choice) attributes.delete(:multiple) end attributes.delete(:association) if method != :element if (attributes[:association_type]) attributes[:through] = attributes[:association_type] unless attributes[:anonymous_model] attributes.delete(:association_type) end attributes.delete(:lazy) if attributes[:lazy] == :default if (method == :tree) delete_attrs = [:queryset_module, :multiple] delete_attrs.each{ |a| attributes.delete(a) } remove_elements += [attributes[:reverse], attributes[:tree_left], attributes[:tree_right], attributes[:tree_depth]] type = nil end return { :name => el.name, :type => type, :attributes => attributes, :method => method, :remove_elements => remove_elements } end def self.prepare_to_code modules = self.name.split('::')[0..-2] included = (self.included_modules - Spider::Model::BaseModel.included_modules).select do |m| m.name !~ /^#{Regexp.quote(self.name)}/ end local_name = self.name.split('::')[-1] superklass = self.superclass.name elements = [] remove_elements = [] self.elements_array.each do |el| next if el.integrated? next if (el.reverse && el.model.elements[el.reverse] && \ (el.model.elements[el.reverse].attributes[:add_reverse] || \ el.model.elements[el.reverse].attributes[:add_multiple_reverse])) el_hash = dump_element(el) return nil unless el_hash elements << el_hash remove_elements += el_hash[:remove_elements] end elements.reject!{ |el| remove_elements.include?(el[:name]) } return { :modules => modules, :included => included, :attributes => self.attributes, :elements => elements, :local_name => local_name, :superclass => superklass, :use_storage => @use_storage, :additional_code => [] } end def self.to_code(options={}) c = prepare_to_code str = "" indent = 0 append = lambda do |val| str += " "*indent str += val str end str += c[:modules].map{ |m| "module #{m}" }.join('; ') + "\n" str += "\n" indent = 4 append.call "class #{c[:local_name]} < #{c[:superclass]}\n" indent += 4 c[:included].each do |i| append.call "include #{i.name}\n" end c[:attributes].each do |k, v| append.call "attribute :#{k}, #{v.inspect}" end str += "\n" c[:elements].each do |el| append.call("#{el[:method].to_s} #{el[:name].inspect}") str += ", #{el[:type]}" if el[:type] str += ", #{el[:attributes].inspect[1..-2]}\n" if el[:attributes] && !el[:attributes].empty? end str += "\n" append.call "use_storage '#{c[:use_storage]}'\n" if c[:use_storage] c[:additional_code].each do |block| block.each_line do |line| append.call line end str += "\n" end indent -= 4 append.call("end\n") str += c[:modules].map{ "end" }.join(';') return str end end end; end Only set element modified if integrated object tells so require 'spiderfw/model/mixins/state_machine' require 'spiderfw/model/element' require 'spiderfw/model/integrated_element' require 'iconv' module Spider; module Model # The main class for interacting with data. # When not dealing with legacy storages, subclasses should use Managed instead, which provides an id and # other conveniences. # # Each BaseModel subclass defines a model; instances can be used as "data objects": # they will interact with the Mapper loading and saving the values associated with the BaseModel's defined elements. # # Each element defines an instance variable, a getter and a setter. If the instance is set to #autoload, # when a getter is first called the mapper will fetch the value from the Storage . # # Elements can be of one of the base types (Spider::Model.base_types), of a DataType, or other models. In the last # case, they define a relationship between models. # # Basic usage: # model Food < BaseModel # element :name, String # end # model Animal < BaseModel # element :name, String # many :friends, Animal # choice :favorite_food, Food # end # # salmon = Food.new(:name => 'Salmon') # salmon.save # cat = Animal.new(:name => 'Cat', :favorite_food = salmon) # weasel = Animal.new(:name => 'Weasel', :friends => [cat]) # weasel.save # cat.friends << weasel # cat.save # # wizzy = Animal.load(:name => 'Weasel') # p wizzy.friends # => 'Cat' # p wizzy.friends[0].favorite_food # => 'Salmon' # # bear = Animal.new(:name => 'Bear', :favorite_food = salmon) # bear.save # salmon_lovers = Animal.where{ favorite_food == salmon } # p salmon_lovers.length # => 2 # p salmon_lovers[0].name # => 'Cat' class BaseModel include Spider::Logger include DataTypes include Spider::QueryFuncs include EventSource # include StateMachine # The BaseModel class itself. Used when dealing with proxy objects. attr_reader :model # An Hash of loaded elements attr_reader :loaded_elements # Model instance or QuerySet containing the object attr_accessor :_parent # If _parent is a model instance, which element points to this one attr_accessor :_parent_element # If this object is used as a superclass in class_table_inheritance, points to the current subclass attr_accessor :_subclass_object class <<self # An Hash of model attributes. They can be used freely. attr_reader :attributes # An array of element names, in definition order. attr_reader :elements_order # An Hash of integrated models => corresponding integrated element name. attr_reader :integrated_models # An Hash of polymorphic models => polymorphic params attr_reader :polymorphic_models # An Array of named sequences. attr_reader :sequences end # Copies this class' elements to the subclass. def self.inherited(subclass) #:nodoc: # FIXME: might need to clone every element @subclasses ||= [] @subclasses << subclass each_element do |el| subclass.add_element(el.clone) unless el.attributes[:local_pk] end subclass.instance_variable_set("@mapper_procs_subclass", @mapper_procs_subclass.clone) if @mapper_procs_subclass subclass.instance_variable_set("@mapper_modules", @mapper_modules.clone) if @mapper_modules subclass.instance_variable_set("@extended_models", @extended_models.clone) if @extended_models em = subclass.const_set(:ElementMethods, Module.new) subclass.send(:include, em) super end def self.subclasses @subclasses || [] end # Returns the parent Spider::App of the module def self.app return @app if @app app = self while (!app.include?(Spider::App)) app = app.parent_module end @app = app end ####################################### # Model definition methods # ####################################### # Defines an element. # Arguments are element name (a Symbol), element type, and a Hash of attributes. # # Type may be a Class: a base type (see Spider::Model.base_types), a DataType subclass, # or a BaseModel subclass; or an Array or a Hash, in which case an InlineModel will be created. # # An Element instance will be available in Model::BaseModel.elements; getter and setter methods will be defined on # the class. # # If a block is passed to this method, type will be 'extended': a custom junction association will be created, # effectively adding elements to the type only in this model's context. # Example: # class Animal < BaseModel # element :name, String # element :friends, Animal, :multiple => true do # element :how_much, String # end # end # cat = Animal.new(:name => 'Cat') # dog = Animal.new(:name => 'Dog') # cat.friends << dog # cat.friend[0].how_much = 'Not very much' # # Returns the created Element. # # Some used attributes: # :primary_key:: (bool) The element is a primary key # :length:: (number) Maximum length of the element (if meaningful) # :required:: (bool) The element must always have a value # :multiple:: (bool) defines a 1|n -> n relationship # :label:: (string) a short description, used by the UI # :association:: (symbol) A named association (such as :choice, :multiple_choice, etc.) # :lazy:: (bool, array or symbol) If true, the element will be placed in the :default lazy group; # if a symbol or an array of symbols is passed, the element will be placed in those groups. # (see Element#lazy_groups) # :reverse:: (symbol) The reverse element in the relationship to the other model # :add_reverse:: (symbol) Adds an element on the other model, and sets it as the association reverse. # :add_multiple_reverse:: (symbol) Adds a multiple element on the other model, and sets it as the association reverse. # :element_position:: (number) inserts the element at the specified position in the elements order # :auto:: (bool) Informative: the value is set automatically through some mechanism # :autoincrement:: (bool) The value (which must be a Fixnum) will be autoincremented by the mapper # :integrate:: (bool or symbol) type's elements will be available to this class # as if they were defined here (see #integrate) # :integrated_from:: (symbol) the name of the element from which this element is integrated # :integrated_from_element:: (symbol) the name of the element of the child object from which this element is integrated # :hidden:: (bool) a hint that the element shouldn't be shown by the UI # :computed_from:: (array of symbols) the element is not mapped; its value is computed # by the class from the given elements. # :unmapped:: (bool) the element is not mapped. # :sortable:: (bool or Array of symbols) specifies that an unmapped element can be used for sorting. # The model must provide a meaningful order using the prepare_query method. # :check:: (a Proc, or a Regexp, or a Hash of messages => Regexp|Proc). See #check # :through:: (a BaseModel subclass) model representing the many to many relationship. # :read_only:: (bool) hint to the UI that the element should not be user modifiable. # :owned:: (bool) only this model holds references to type # :condition:: (hash or Condition) Restricts an association always adding the condition. # :order:: (true or Fixnum) When doing queries, sort by this element. More than one element can have the # :order attribute; if it is a Fixnum, it will mean the position in the ordering. # :default:: (Proc or value) default value for the element. If it is a Proc, it will be passed # the object. # :desc:: (true or Fixnum) Use this element for the to_s string. Multiple elements # with the :desc attribute will be joined by spaces; order may be specified if # a Fixnum is used for the parameter # # Other attributes may be used by DataTypes (see #DataType::ClassMethods.take_attributes), and other code. # See also Element. def self.element(name, type, attributes={}, &proc) name = name.to_sym @elements ||= {} @elements_order ||= [] raise "Element called #{name} already exists in #{self}" if @elements[name] if type.class == Class default_attributes = case type.name when 'String' {:length => 255} else {} end else default_attributes = {} end attributes = default_attributes.merge(attributes) # if (type.class == Class && Model.base_type(type)) # type = Model.base_type(type) # els if (type.class <= Hash) type = create_inline_model(name, type) attributes[:inline] = true end if (attributes[:integrated_from]) if (attributes[:integrated_from].class == String) parts = attributes[:integrated_from].split('.') attributes[:integrated_from] = @elements[parts[0].to_sym] attributes[:integrated_from_element] = parts[1].to_sym if parts[1] elsif (attributes[:integrated_from].is_a?(Symbol)) attributes[:integrated_from] = @elements[attributes[:integrated_from]] end if (!attributes[:integrated_from_element]) attributes[:integrated_from_element] = name end end if (attributes[:condition] && !attributes[:condition].is_a?(Condition)) attributes[:condition] = Condition.new(attributes[:condition]) end if attributes[:computed_from] && !attributes[:computed_from].is_a?(Enumerable) attributes[:computed_from] = [attributes[:computed_from]] end type.set_element_attributes(attributes) if type < Spider::DataType orig_type = type assoc_type = nil if (proc || attributes[:junction] || (attributes[:multiple] && (!attributes[:add_reverse]) && (!attributes[:has_single_reverse]) && \ # FIXME! the first check is needed when the referenced class has not been parsed yet # but now it assumes that the reverse is not multiple if it is not defined (attributes[:has_single_reverse] == false || !attributes[:reverse] || (!type.elements[attributes[:reverse]] || type.elements[attributes[:reverse]].multiple?)))) attributes[:anonymous_model] = true attributes[:owned] = true unless attributes[:owned] != nil first_model = self.first_definer(name, type) assoc_type_name = Spider::Inflector.camelize(name) create_junction = true if (attributes[:through]) assoc_type = attributes[:through] create_junction = false elsif (first_model.const_defined?(assoc_type_name) ) assoc_type = first_model.const_get(assoc_type_name) if (!assoc_type.attributes[:sub_model]) # other kind of inline model assoc_type_name += 'Junction' create_junction = false if (first_model.const_defined?(assoc_type_name)) else create_junction = false end end attributes[:junction] = true attributes[:junction_id] = :id unless attributes.has_key?(:junction_id) if (attributes[:junction_our_element]) self_name = attributes[:junction_our_element] else self_name = first_model.short_name.gsub('/', '_').downcase.to_sym end attributes[:reverse] = self_name unless attributes[:junction_their_element] other_name = Spider::Inflector.underscore(orig_type.short_name == self.short_name ? orig_type.name : orig_type.short_name).gsub('/', '_').downcase.to_sym other_name = :"#{other_name}_ref" if (orig_type.elements[other_name]) attributes[:junction_their_element] = other_name end other_name = attributes[:junction_their_element] if (create_junction) assoc_type = first_model.const_set(assoc_type_name, Class.new(BaseModel)) assoc_type.attributes[:sub_model] = self assoc_type.attributes[:sub_model_element] = name assoc_type.element(attributes[:junction_id], Fixnum, :primary_key => true, :autoincrement => true, :hidden => true) if attributes[:junction_id] assoc_type.element(self_name, self, :hidden => true, :reverse => name, :association => :choice, :junction_reference => true) # FIXME: must check if reverse exists? # FIXME! fix in case of clashes with existent elements assoc_type.element(other_name, orig_type, :association => :choice, :junction_reference => true) assoc_type.integrate(other_name, :hidden => true, :no_pks => true) # FIXME: in some cases we want the integrated elements if (proc) # to be hidden, but the integrated el instead attributes[:extended] = true attributes[:keep_junction] = true assoc_type.class_eval(&proc) end end orig_type.referenced_by_junctions << [assoc_type, other_name] attributes[:keep_junction] = true if (attributes[:through] && attributes[:keep_junction] != false) attributes[:association_type] = assoc_type if attributes[:polymorph] assoc_type.elements[attributes[:junction_their_element]].attributes[:polymorph] = attributes[:polymorph] attributes.delete(:polymorph) end end add_element(Element.new(name, type, attributes)) if (attributes[:add_reverse] && attributes[:add_reverse].is_a?(Symbol)) attributes[:add_reverse] = {:name => attributes[:add_reverse]} end if (attributes[:add_multiple_reverse] && attributes[:add_multiple_reverse].is_a?(Symbol)) attributes[:add_multiple_reverse] = {:name => attributes[:add_multiple_reverse]} end if (attributes[:add_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_reverse][:name] rev = attributes[:add_reverse].merge(:reverse => name, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:keep_junction] = false rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end elsif (attributes[:add_multiple_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_multiple_reverse][:name] rev = attributes[:add_multiple_reverse].merge(:reverse => name, :multiple => true, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end end if (attributes[:lazy] == nil) # if attributes[:primary_key] # attributes[:lazy] = true # els if (type < BaseModel && (attributes[:multiple] || attributes[:polymorph])) # FIXME: we can load eagerly single relations if we can do a join attributes[:lazy] = true else attributes[:lazy_check_owner] = true if type < BaseModel attributes[:lazy] = :default end end # class element getter unless respond_to?(name) (class << self; self; end).instance_eval do define_method("#{name}") do @elements[name] end end end define_element_methods(name) attr_reader "#{name}_junction" if attributes[:junction] && !attributes[:keep_junction] if (attributes[:integrate]) integrate_params = attributes[:integrate].is_a?(Hash) ? attributes[:integrate] : {} integrate(name, integrate_params) end if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |imod, iel| imod.integrate_element(iel, self.elements[name]) unless imod.elements[name] end end if (@subclasses) @subclasses.each do |sub| next if sub.elements[name] # if subclass already defined an element with this name, don't overwrite it sub.elements[name] = @elements[name].clone sub.elements_order << name end end element_defined(@elements[name]) @elements[name].model? return @elements[name] end def self.define_element_methods(name) ivar = :"@#{ name }" unless self.const_defined?(:ElementMethods) em = self.const_set(:ElementMethods, Module.new) include em end element_methods = self.const_get(:ElementMethods) #instance variable getter element_methods.send(:define_method, name) do element = self.class.elements[name] raise "Internal error! Element method #{name} exists, but element not found" unless element return element.attributes[:fixed] if element.attributes[:fixed] if (element.integrated?) integrated = get(element.integrated_from.name) return integrated.send(element.integrated_from_element) if integrated return nil end if element_has_value?(name) || element_loaded?(name) val = instance_variable_get(ivar) val.set_parent(self, name) if val && element.model? && !val._parent # FIXME!!! return val end # Spider.logger.debug("Element not loaded #{name} (i'm #{self.class} #{self.object_id})") if autoload? && primary_keys_set? if (autoload? == :save_mode) mapper.load_element!(self, element) else mapper.load_element(self, element) end val = instance_variable_get(ivar) end if !val && element.model? && (element.multiple? || element.attributes[:extended_model]) val = instance_variable_set(ivar, instantiate_element(name)) end if !val && element.attributes[:default] if element.attributes[:default].is_a?(Proc) val = element.attributes[:default].call(self) else val = element.attributes[:default] end val = element.model.new(val) if element.model? && !val.is_a?(BaseModel) end val.set_parent(self, name) if element.model? && val && val.respond_to?(:parent) && !val._parent # FIXME!!! return val end alias_method :"#{name}?", name if self.elements[name].type <= Spider::DataTypes::Bool #instance_variable_setter element_methods.send(:define_method, "#{name}=") do |val| element = self.class.elements[name] raise "Internal error! Element method #{name}= exists, but element not found" unless element return if element.attributes[:fixed] was_loaded = element_loaded?(element) #@_autoload = false unless element.primary_key? if (element.integrated?) integrated_obj = get(element.integrated_from) unless integrated_obj integrated_obj = instantiate_element(element.integrated_from.name) set(element.integrated_from, integrated_obj) end #integrated_obj.autoload = false begin res = integrated_obj.send("#{element.integrated_from_element}=", val) rescue IdentityMapperException set(element.integrated_from, Spider::Model.get(integrated_obj)) get(element.integrated_from).merge!(integrated_obj) end if !element.primary_key? && integrated_obj.element_modified?(name) @modified_elements[name] = true end return res end if (val && element.model?) if (element.multiple?) unless (val.is_a?(QuerySet)) qs = instantiate_element(name) if (val.is_a?(Enumerable)) val.each do |row| row = element.type.new(row) unless row.is_a?(BaseModel) qs << row end else qs << val end val = qs end else val = element.model.get(val) unless val.is_a?(BaseModel) end end val = prepare_child(element.name, val) _check(name, val) notify_observers(name, val) @_has_values = true unless @_primary_keys_set if self.class.elements[element.name].primary_key? && primary_keys_set? @_primary_keys_set = true if Spider::Model.identity_mapper Spider::Model.identity_mapper.put(self, true, true) else Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work end end end old_val = instance_variable_get(ivar) @modified_elements[name] = true if !element.primary_key? && (!was_loaded || val != old_val) instance_variable_set(ivar, val) set_reverse(element, val) if element.model? if val && element.model? && !self.class.attributes[:no_type_check] klass = val.is_a?(QuerySet) ? val.model : val.class if val && !(klass <= element.type || klass <= element.model) raise TypeError, "Object #{val} (#{klass}) is of the wrong type for element #{element.name} in #{self.class} (expected #{element.model})" end end val #extend_element(name) end end def self.add_element(el) @elements ||= {} @elements[el.name] = el @elements_order ||= [] if (el.attributes[:element_position]) @elements_order.insert(el.attributes[:element_position], el.name) else @elements_order << el.name end @primary_keys ||= [] if el.attributes[:primary_key] && !@primary_keys.include?(el) @primary_keys << el end end # Removes a defined element def self.remove_element(el) return unless @elements el = el.name if el.is_a?(Element) element = @elements[el] if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |mod, iel| i = mod.elements[el] mod.remove_element(el) if i && i.integrated? && i.integrated_from.name == iel end end self.elements_array.select{ |e| e.integrated? && e.integrated_from.name == el}.each{ |e| remove_element(e) } self.const_get(:ElementMethods).send(:remove_method, :"#{el}") rescue NameError self.const_get(:ElementMethods).send(:remove_method, :"#{el}=") rescue NameError @elements.delete(el) @elements_order.delete(el) @primary_keys.delete_if{ |pk| pk.name == el} # if (@subclasses) # @subclasses.each do |sub| # sub.remove_element(el) # end # end end def self.element_defined(el) if (@on_element_defined && @on_element_defined[el.name]) @on_element_defined[el.name].each do |proc| proc.call(el) end end end def self.on_element_defined(el_name, &proc) @on_element_defined ||= {} @on_element_defined[el_name] ||= [] @on_element_defined[el_name] << proc end # Integrates an element: any call to the child object's elements will be passed to the child. # The element must not be multiple. # Example: # class Address < BaseModel # element :street, String # element :area_code, String # end # class Person < BaseModel # element :name, String # element :address, Address # integrate :address # end # p = Person.new(...) # p.street == p.address.street def self.integrate(element_name, params={}) params ||= {} elements[element_name].attributes[:integrated_model] = true model = elements[element_name].type self.attributes[:integrated_models] ||= {} self.attributes[:integrated_models][model] = element_name params[:except] ||= [] model.each_element do |el| next if params[:except].include?(el.name) next if elements[el.name] unless params[:overwrite] # don't overwrite existing elements integrate_element(element_name, el, params) end model.attributes[:integrated_from_elements] ||= [] model.attributes[:integrated_from_elements] << [self, element_name] end def self.integrate_element(element_name, element_element, params={}) el = element_element integrated_attributes = {} integrated_attributes[:primary_key] = false if params[:no_pks] integrated_attributes[:hidden] = params[:hidden] unless (params[:hidden].nil?) integrated_attributes[:primary_key] = false unless (params[:keep_pks]) # attributes.delete(:required) # attributes.delete(:integrate) # attributes.delete(:local_pk) integrated_attributes[:local_pk] = false integrated_attributes[:lazy] = element_name name = params[:mapping] && params[:mapping][el.name] ? params[:mapping][el.name] : el.name add_element(IntegratedElement.new(name, self, element_name, el.name, integrated_attributes)) define_element_methods(name) end def self.remove_integrate(element_name) element = element_name.is_a?(Element) ? element_name : self.elements[element_name] model = element.model self.elements_array.select{ |el| el.attributes[:integrated_from] && el.attributes[:integrated_from].name == element.name }.each do |el| self.remove_element(el) end model.attributes[:integrated_from_elements].reject!{ |item| item[0] == self } end # Sets additional attributes on the element # # _Warning:_ for attributes which are parsed by the BaseModel during element definition, # this will not have the desired effect; remove and redefine the element instead. def self.element_attributes(element_name, attributes) elements[element_name].attributes = elements[element_name].attributes.merge(attributes) if attributes[:primary_key] && !@primary_keys.include?(elements[element_name]) @primary_keys << elements[element_name] elsif !attributes[:primary_key] @primary_keys.delete(elements[element_name]) end end # Defines a multiple element. Equivalent to calling # element(name, type, :multiple => true, :association => :many, ...) def self.many(name, type, attributes={}, &proc) attributes[:multiple] = true attributes[:association] ||= :many element(name, type, attributes, &proc) end # Defines an element with choice association. Shorthand for # element(name, type, :association => :choice, ...) def self.choice(name, type, attributes={}, &proc) attributes[:association] = :choice element(name, type, attributes, &proc) end # Defines a multiple element with :multiple_choice association. Shorthand for # many(name, type, :association => :multiple_choice, ...) def self.multiple_choice(name, type, attributes={}, &proc) attributes[:association] = :multiple_choice many(name, type, attributes, &proc) end def self.element_query(name, element_name, attributes={}) orig_element = self.elements[element_name] set_el_query = lambda do orig_element = self.elements[element_name] attributes = attributes.merge(orig_element.attributes) attributes[:unmapped] = true attributes[:element_query] = element_name attributes[:association] = :element_query attributes[:lazy] = true attributes.delete(:add_reverse) attributes.delete(:add_multiple_reverse) if (orig_element.attributes[:condition]) cond = orig_element.attributes[:condition].clone cond = cond.and(attributes[:condition]) if attributes[:condition] attributes[:condition] = cond end element(name, orig_element.type, attributes) end if (orig_element) set_el_query.call else on_element_defined(element_name, &set_el_query) end end # Saves the element definition and evals it when first needed, avoiding problems with classes not # available yet when the model is defined. # FIXME: remove? def self.define_elements(&proc) #:nodoc: @elements_definition = proc end # Creates an inline model def self.create_inline_model(name, hash) #:nodoc: model = self.const_set(Spider::Inflector.camelize(name), Class.new(InlineModel)) model.instance_eval do hash.each do |key, val| key = key.to_s if key.is_a?(Symbol) element(:id, key.class, :primary_key => true) if (val.class == Hash) # TODO: allow passing of multiple values like {:element1 => 'el1', :element2 => 'el2'} else element(:desc, val.class, :desc => true) end break end end model.data = hash return model end # An array of other models this class points to. def self.submodels elements.select{ |name, el| el.model? }.map{ |name, el| el.model } end def self.extend_model(model, params={}) #:nodoc: if (model == superclass) # first undo table per class inheritance @elements = {} @elements_order = [] @extended_models.delete(model.superclass) if @extended_models end primary_keys.each{ |k| remove_element(k) } if (params[:replace_pks]) model.primary_keys.each{ |k| remove_element(k) } integrated_name = params[:name] if (!integrated_name) integrated_name = (self.parent_module == model.parent_module) ? model.short_name : model.name integrated_name = Spider::Inflector.underscore(integrated_name).gsub('/', '_') end integrated_name = integrated_name.to_sym @extended_models ||= {} @extended_models[model] = integrated_name attributes = {} attributes[:hidden] = true unless (params[:hide_integrated] == false) attributes[:delete_cascade] = params[:delete_cascade] attributes[:extended_model] = true integrated = element(integrated_name, model, attributes) integrate_options = {:keep_pks => true}.merge((params[:integrate_options] || {})) integrate(integrated_name, integrate_options) model.elements_array.select{ |el| el.attributes[:local_pk] }.each{ |el| remove_element(el.name) } unless (params[:no_local_pk] || !elements_array.select{ |el| el.attributes[:local_pk] }.empty?) # FIXME: check if :id is already defined pk_name = @elements[:id] ? :"id_#{self.short_name.downcase}" : :id element(pk_name, Fixnum, :autoincrement => true, :local_pk => true, :hidden => true) end model.polymorphic(self, :through => integrated_name) end # Externalizes the superclass elements making the superclass an external integrated element. # Parameters may be: # * :name (symbol) name of the created element # * :delete_cascade (bool) delete cascade the superclass instance # * :no_local_pk (bool) do not define an id for this class def self.class_table_inheritance(params={}) self.extend_model(superclass, params) end # Makes the class use the superclass storage def self.inherit_storage self.attributes[:inherit_storage] = true (class << self; self; end).instance_eval do define_method(:storage) do superclass.storage end end end # Sets a fixed condition. def self.condition(condition) self.attributes[:condition] = condition end # #-- # TODO: document me def self.group(name, &proc) #:nodoc: proxy = Class.new(ProxyModel).proxy(name.to_s+'_', self) proxy.instance_eval(&proc) proxy.each_element do |el| element(name.to_s+'_'+el.name.to_s, el.type, el.attributes.clone) end define_method(name) do @proxies ||= {} return @proxies[name] ||= proxy.new end end # Add a subclass, allowing polymorphic queries on it. def self.polymorphic(model, options) through = options[:through] || Spider::Inflector.underscore(self.name).gsub('/', '_') through = through.to_sym @polymorphic_models ||= {} @polymorphic_models[model] = {:through => through} end # Sets or gets class attributes (a Hash). # If given a hash of attributes, will merge them with class attributes. # Model attributes are generally empty, and can be used by apps. def self.attributes(val=nil) @attributes ||= {} if (val) @attributes.merge!(val) end @attributes end # Sets a model attribute. See #self.attributes def self.attribute(name, value) @attributes ||= {} @attributes[name] = value end # Adds a sequence to the model. def self.sequence(name) @sequences ||= [] @sequences << name end # Model sequences. def self.sequences @sequences ||= [] end # Does nothing. This method is to keep note of elements created in other models. def self._added_elements(&proc) end def self.referenced_by_junctions @referenced_by_junctions ||= [] end ##################################################### # Methods returning information about the model # ##################################################### # Underscored local name (without namespaces) def self.short_name return Inflector.underscore(self.name.match(/([^:]+)$/)[1]) end # False for BaseModel (true for Spider::Model::Managed). def self.managed? return false end # Name def self.to_s self.name end # Sets the singolar and/or the plural label for the model # Returns the singlular label def self.label(sing=nil, plur=nil) @label = sing if sing @label_plural = plur if plur _(@label || self.name || '') end # Sets/retrieves the plural form for the label def self.label_plural(val=nil) @label_plural = val if (val) _(@label_plural || self.name || '') end def self.auto_primary_keys? self.primary_keys.select{ |k| !k.autogenerated? }.empty? end def self.containing_module par = self.parent_module while par <= BaseModel par = par.parent_module end par end def self.get_element(el) el = el.name if el.is_a?(Element) el = el.to_sym raise "No element called #{el} in #{self}" unless @elements[el] @elements[el] end def self.junction? !!self.attributes[:sub_model] end ######################################################## # Methods returning information about the elements # ######################################################## # An Hash of Elements, indexed by name. def self.elements @elements end # An array of the model's Elements. def self.elements_array @elements_order.map{ |key| @elements[key] } end # Yields each element in order. def self.each_element return unless @elements_order @elements_order.each do |name| yield elements[name] end end # Returns true if the model has given element name. def self.has_element?(name) return elements[name] ? true : false end # An array of elements with primary_key attribute set. def self.primary_keys @primary_keys end # Returns the model actually defining element_name; that could be the model # itself, a superclass, or an integrated model. def self.first_definer(element_name, type) if (@extended_models && @extended_models[self.superclass] && self.superclass.elements[element_name] && self.superclass.elements[element_name].type == type) return self.superclass.first_definer(element_name, type) end if (self.attributes[:integrated_models]) self.attributes[:integrated_models].keys.each do |mod| return mod.first_definer(element_name, type) if (mod.elements[element_name] && mod.elements[element_name].type == type) end end return self end # Returns true if the element with given name is associated with the passed # association. # This method should be used instead of querying the element's association directly, # since subclasses and mixins may extend this method to provide association equivalence. def self.element_association?(element_name, association) return true if elements[element_name].association = association end # An Hash of extended models => element name of the extended model element def self.extended_models @extended_models ||= {} end ############################################################## # Storage, mapper and loading (Class methods) # ############################################################## # The given module will be mixed in any mapper used by the class. def self.mapper_include(mod) @mapper_modules ||= [] @mapper_modules << mod end def self.mapper_include_for(params, mod) @mapper_modules_for ||= [] @mapper_modules_for << [params, mod] end # The given proc will be mixed in the mapper used by this class # Note that the proc will be converted to a Module, so any overridden methods will still have # access to the super method. def self.with_mapper(*params, &proc) # @mapper_procs ||= [] # @mapper_procs << proc mod = Module.new(&proc) mapper_include(mod) end # FIXME: remove def self.with_mapper_subclasses(*params, &proc) #:nodoc: @mapper_procs_subclass ||= [] @mapper_procs_subclass << proc end # Like #with_mapper, but will mixin the block only if the mapper matches params. # Possible params are: # - a String, matching the class' use_storage def self.with_mapper_for(*params, &proc) @mapper_procs_for ||= [] @mapper_procs_for << [params, proc] end # Sets the url or the name of the storage to use def self.use_storage(name=nil) @use_storage = name if name @use_storage end # Returns the current default storage for the class # The storage to use can be set with #use_storage def self.storage return @storage if @storage if (!@use_storage && self.attributes[:sub_model]) @use_storage = self.attributes[:sub_model].use_storage end return @use_storage ? get_storage(@use_storage) : get_storage end # Returns an instancethe storage corresponding to the storage_string if it is given, # or of the default storage otherwise. # The storage string can be a storage url (see #Storage.get_storage), or a named storage # defined in configuration #-- # Mixin! def self.get_storage(storage_string='default') storage_regexp = /([\w\d]+?):(.+)/ orig_string = nil if (storage_string !~ storage_regexp) orig_string = storage_string storage_conf = Spider.conf.get('storages')[storage_string] storage_string = storage_conf['url'] if storage_conf if (!storage_string || storage_string !~ storage_regexp) raise ModelException, "No storage '#{orig_string}' found" end end type, url = $1, $2 storage = Storage.get_storage(type, url) storage.instance_name = orig_string storage.configure(storage_conf) if storage_conf return storage end # Returns an instance of the default mapper for the class. def self.mapper @mapper ||= get_mapper(storage) end # Returns an instance of the mapper for the given storage def self.get_mapper(storage) # map_class = self.attributes[:inherit_storage] ? superclass : self mapper = storage.get_mapper(self) if (@mapper_modules) @mapper_modules.each{ |mod| mapper.extend(mod) } end if (@mapper_modules_for) @mapper_modules_for.each do |params, mod| if params.is_a?(String) mapper.extend(mod) if self.use_storage == params end end end if (@mapper_procs) @mapper_procs.each{ |proc| mapper.instance_eval(&proc) } end if (@mapper_procs_for) @mapper_procs_for.each do |params, proc| if (params.length == 1 && params[0].class == String) mapper.instance_eval(&proc) if (self.use_storage == params[0]) end end end if (@mapper_procs_subclass) @mapper_procs_subclass.each{ |proc| mapper.instance_eval(&proc) } end return mapper end # Syncs the schema with the storage. def self.sync_schema(options={}) options = ({ :force => false, :drop_fields => false, :update_sequences => false, :no_foreign_key_constraints => true }).merge(options) Spider::Model.sync_schema(self, options[:force], options) end # Executes #self.where, and calls QuerySet#load on the result. # Returns nil if the result is empty, the QuerySet otherwise # See #self.where for parameter syntax def self.find(*params, &proc) qs = self.where(*params, &proc) return qs.empty? ? nil : qs end # Executes #self.where, returning the first result. # See #self.where for parameter syntax. def self.load(*params, &proc) qs = self.where(*params, &proc) qs.limit = 1 return qs[0] end # Returns a queryset without conditions def self.all return self.where end # Constructs a Query based on params, and returns a QuerySet # Allowed parameters are: # * a Query object # * a Condition and an (optional) Request, or anything that can be parsed by Condition.new and Request.new # If a block is provided, it is passed to Condition.parse_block. # Examples: # felines = Animals.where({:family => 'felines'}) # felines = Animals.where({:family => 'felines'}, [:name, :description]) # cool_animals = Animals.where{ (has_fangs == true) | (has_claws == true)} # See also Condition#parse_block def self.where(*params, &proc) if (params[0] && params[0].is_a?(Query)) query = params[0] qs = QuerySet.new(self, query) elsif(proc) qs = QuerySet.new(self) qs.autoload = true qs.where(&proc) else condition = Condition.and(params[0]) request = Request.new(params[1]) query = Query.new(condition, request) qs = QuerySet.new(self, query) end return qs end # Returns the condition for a "free" text query # Examples: # condition = News.free_query_condition('animals') # animal_news = News.where(condition) def self.free_query_condition(q) c = Condition.or self.elements_array.each do |el| if (el.type == String || el.type == Text) c.set(el.name, 'ilike', '%'+q+'%') end end return c end # Returns the number of objects in storage def self.count(condition=nil) mapper.count(condition) end # Can be defined to provide functionality to this model's querysets. def self.extend_queryset(qs) end ################################################# # Instance methods # ################################################# # The constructor may take: # * an Hash of values, that will be set on the new instance; or # * a BaseModel instance; its values will be set on the new instance; or # * a single value; it will be set on the first primary key. def initialize(values=nil) @_autoload = true @_has_values = false @loaded_elements = {} @modified_elements = {} @value_observers = nil @all_values_observers = nil @_extra = {} @model = self.class @_primary_keys_set = false set_values(values) if values # if primary_keys_set? # @_primary_keys_set = true # if Spider::Model.identity_mapper # Spider::Model.identity_mapper.put(self, true) # else # Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work # end # else # #nil # end end # Returns an instance of the Model with #autoload set to false def self.static(values=nil) obj = self.new obj.autoload = false obj.set_values(values) if values return obj end def self.create(values) obj = self.static(values) obj.save return obj end def self.get(values) return self.new(values) unless Spider::Model.identity_mapper values = [values] unless values.is_a?(Hash) || values.is_a?(Array) if values.is_a?(Array) vals = {} self.primary_keys.each_with_index do |k, i| vals[k.name] = values[i] end values = vals end curr = Spider::Model.identity_mapper.get(self, values) return curr if curr obj = self.new(values) Spider::Model.identity_mapper.put(obj) obj end def set_values(values) if (values.is_a? Hash) values.keys.select{ |k| k = k.name if k.is_a?(Element) self.class.elements[k.to_sym] && self.class.elements[k.to_sym].primary_key? }.each do |k| set!(k, values[k]) end values.each do |key, val| set!(key, val) end elsif (values.is_a? BaseModel) values.each_val do |name, val| set(name, val) if self.class.has_element?(name) end elsif (values.is_a? Array) self.class.primary_keys.each_index do |i| set(self.class.primary_keys[i], values[i]) end # Single unset key, single value elsif ((empty_keys = self.class.primary_keys.select{ |key| !element_has_value?(key) }).length == 1) set(empty_keys[0], values) else raise ArgumentError, "Don't know how to construct a #{self.class} from #{values.inspect}" end end # Returns the instance's IdentityMapper def identity_mapper return Spider::Model.identity_mapper if Spider::Model.identity_mapper @identity_mapper ||= IdentityMapper.new end # Sets the instance's IdentityMapper. def identity_mapper=(im) @identity_mapper = im end # Returns a new instance for given element name. def instantiate_element(name) element = self.class.elements[name] if (element.model?) if (element.multiple?) val = QuerySet.static(element.model) else val = element.type.new val.autoload = autoload? end end val = prepare_child(name, val) instance_variable_set("@#{name}", val) set_reverse(element, val) if element.model? val end # Prepares an object that is being set as a child. def prepare_child(name, obj) return obj if obj.nil? element = self.class.elements[name] if (element.model?) # convert between junction and real type if needed if element.attributes[:junction] if obj.is_a?(QuerySet) obj.no_autoload do if (element.attributes[:keep_junction] && obj.model == element.type) qs = QuerySet.new(element.model) obj.each{ |el_obj| qs << {element.reverse => self, element.attributes[:junction_their_element] => el_obj} } obj = qs elsif (!element.attributes[:keep_junction] && obj.model == element.model) instance_variable_set("@#{element.name}_junction", obj) qs = QuerySet.new(element.type, obj.map{ |el_obj| el_obj.get(element.attributes[:junction_their_element])}) obj = qs end end else if (!element.attributes[:keep_junction] && obj.class == element.model) obj = obj.get(element.attributes[:junction_their_element]) end end end self.class.elements_array.select{ |el| el.attributes[:fixed] }.each do |el| if el.integrated_from == element obj.set(el.integrated_from_element, el.attributes[:fixed]) end end obj.identity_mapper = self.identity_mapper if obj.respond_to?(:identity_mapper) if (element.multiple? && element.attributes[:junction] && element.attributes[:keep_junction]) obj.append_element = element.attributes[:junction_their_element] end if (element.attributes[:set] && element.attributes[:set].is_a?(Hash)) element.attributes[:set].each{ |k, v| obj.set(k, v) } obj.reset_modified_elements(*element.attributes[:set].keys) # FIXME: is it always ok to not set the element as modified? But otherwise sub objects # are always saved (and that's definitely no good) end if element.type == self.class.superclass && self.class.extended_models[element.type] && self.class.extended_models[element.type] == element.name obj._subclass_object = self end else obj = prepare_value(element, obj) end return obj end # Returns all children that can be reached from the current path. # Path is expressed as a dotted String. def all_children(path) children = [] no_autoload do el = path.shift if self.class.elements[el] && element_has_value?(el) && children = get(el) if path.length >= 1 children = children.all_children(path) end end end return children end # Sets the object currently containing this one (BaseModel or QuerySet) def set_parent(obj, element) @_parent = obj @_parent_element = element end def set_reverse(element, obj) return unless element.model? && obj if element.has_single_reverse? && (!element.attributes[:junction] || element.attributes[:keep_junction]) unless element.multiple? val = obj.get_no_load(element.reverse) return if val && val.object_id == self.object_id end obj.set(element.reverse, self) end end ################################################# # Get and set # ################################################# # Returns an element. # The element may be a symbol, or a dotted path String. # Will call the associated getter. # cat.get('favorite_food.name') def get(element) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) sub_val = send(first) return nil unless sub_val return sub_val.get(rest) end return send(element) end # Returns an element without autoloading it. def get_no_load(element) res = nil no_autoload do res = get(element) end return res end # Sets an element. # The element can be a symbol, or a dotted path String. # Will call the associated setter. # cat.set('favorite_food.name', 'Salmon') def set(element, value, options={}) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) first_val = send(first) unless first_val if (options[:instantiate]) first_val = instantiate_element(first.to_sym) set(first, first_val) else raise "Element #{first} is nil, can't set #{element}" end end return first_val.set(rest, value, options) end return send("#{element}=", value) end # Sets an element, instantiating intermediate objects if needed def set!(element, value, options={}) options[:instantiate] = true set(element, value, options) end # Calls #get on element; whenever no getter responds, returns the extra data. # See #[]= def [](element) element = element.name if element.is_a?(Element) begin get(element) rescue NoMethodError return @_extra[element] end end # If element is a model's element, calls #set. # Otherwise, stores the value in an "extra" hash, where it will be accessible by #[] def []=(element, value) element = element.name if element.is_a?(Element) if (self.class.elements[element]) set(element, value) else @_extra[element] = value end end # Sets each value of a Hash. def set_hash(hash) hash.each { |key, val| set(key, val) } end # Prepares a value going to be set on the object. Will convert the value to the # appropriate type. def self.prepare_value(element, value) element = self.class.elements[element] unless element.is_a?(Element) if (element.type < Spider::DataType) value = element.type.from_value(value) unless value.is_a?(element.type) if value element.type.take_attributes.each do |a| if element.attributes[a].is_a?(Proc) value.attributes[a] = value.instance_eval(&element.attributes[a]) else value.attributes[a] = element.attributes[a] end end value = value.prepare end elsif element.model? value.autoload(autoload?, true) if value && value.respond_to?(:autolad) else case element.type.name when 'Date', 'DateTime' return nil if value.is_a?(String) && value.empty? parsed = nil if (value.is_a?(String)) begin parsed = element.type.strptime(value, "%Y-%m-%dT%H:%M:%S") rescue parsed = nil parsed ||= element.type.lparse(value, :short) rescue parsed = nil parsed ||= element.type.parse(value) rescue ArgumentError => exc raise FormatError.new(element, value, _("'%s' is not a valid date")) end value = parsed end when 'String' when 'Spider::DataTypes::Text' value = value.to_s when 'Fixnum' value = value.to_i end end value end def prepare_value(element, value) self.class.prepare_value(element, value) end # Sets a value without calling the associated setter; used by the mapper. def set_loaded_value(element, value, mark_loaded=true) element_name = element.is_a?(Element) ? element.name : element element = self.class.elements[element_name] if (element.integrated?) get(element.integrated_from).set_loaded_value(element.integrated_from_element, value) else value = prepare_child(element.name, value) current = instance_variable_get("@#{element_name}") current.set_parent(nil, nil) if current && current.is_a?(BaseModel) value.set_parent(self, element.name) if value.is_a?(BaseModel) instance_variable_set("@#{element_name}", value) end value.loaded = true if (value.is_a?(QuerySet)) element_loaded(element_name) if mark_loaded set_reverse(element, value) if element.model? @modified_elements[element_name] = false end # Records that the element has been loaded. def element_loaded(element_name) element_name = self.class.get_element(element_name).name @loaded_elements[element_name] = true end # Returns true if the element has been loaded by the mapper. def element_loaded?(element) element = self.class.get_element(element).name return @loaded_elements[element] end # Apply element checks for given element name and value. (See also #element, :check attribute). # Checks may be defined by the DataType, or be given as an element attribute. # The check can be a Regexp, that will be checked against the value, or a Proc, which is expected to # return true if the check is succesful, and false otherwise. # Will raise a Model::FormatError when a check is not succesful. # If the :check attribute is an Hash, the Hash keys will be used as messages, which will be passed # to the FormatError. def _check(name, val) element = self.class.elements[name] element.type.check(val) if (element.type.respond_to?(:check)) if (checks = element.attributes[:check]) checks = {(_("'%s' is not in the correct format") % element.label) => checks} unless checks.is_a?(Hash) checks.each do |msg, check| test = case check when Regexp val == nil || val.empty? ? true : check.match(val) when Proc check.call(val) end raise FormatError.new(element, val, msg) unless test end end end # Converts the object to the instance of a subclass for which this model is polymorphic. def polymorphic_become(model) return self if self.is_a?(model) unless self.class.polymorphic_models && self.class.polymorphic_models[model] sup = model.superclass while sup < Spider::Model::BaseModel && !self.class.polymorphic_models[sup] sup = sup.superclass end raise ModelException, "#{self.class} is not polymorphic for #{model}" unless self.class.polymorphic_models[sup] sup_poly = polymorphic_become(sup) return sup_poly.polymorphic_become(model) end el = self.class.polymorphic_models[model][:through] obj = model.new(el => self) obj = Spider::Model.identity_mapper.get(obj) if Spider::Model.identity_mapper obj.element_loaded(el) return obj end def become(model) return self if self.class == model obj = polymorphic_become(model) rescue ModelException return obj end # Converts the object to the instance of a subclass. This will instantiate the model # passed as an argument, and set each value of the current object on the new one. # No checks are made that this makes sense, so the method will fail if the "subclass" does # not contain all of the current model's elements. def subclass(model) obj = model.new self.class.elements_array.each do |el| obj.set(el, self.get(el)) if element_has_value?(el) && model.elements[el.name] end return obj end # Returns the current autoload status def autoload? @_autoload end # Enables or disables autoloading. # An autoloading object will try to load all missing elements on first access. # (see also Element#lazy_groups) def autoload=(val) autoload(val, false) end # Sets autoload mode # The first parameter the value of autoload to be set; it can be true, false or :save_mode (see #save_mode)) # the second bool parameter specifies if the value should be propagated on all child objects. def autoload(a, traverse=true) #:nodoc: return if @_tmp_autoload_walk @_tmp_autoload_walk = true @_autoload = a if (traverse) self.class.elements_array.select{ |el| el.model? && \ (element_has_value?(el.name) || el.attributes[:extended_model])}.each do |el| val = get(el) val.autoload = a if val.respond_to?(:autoload=) end end @_tmp_autoload_walk = nil end # Disables autoload. # If a block is given, the current autoload setting will be restored after yielding. def no_autoload prev_autoload = autoload? self.autoload = false if block_given? yield self.autoload = prev_autoload end return prev_autoload end # Sets autoload to :save_mode; elements will be autoloaded only one by one, so that # any already set data will not be overwritten # If a block is given, the current autoload setting will be restored after yielding. def save_mode prev_autoload = autoload? self.autoload = :save_mode if (block_given?) yield self.autoload = prev_autoload end return prev_autoload end ############################################################## # Methods for getting information about element values # ############################################################## # Returns true if other is_a?(self.class), and has the same values for this class' primary keys. def ==(other) return false unless other return false unless other.is_a?(self.class) self.class.primary_keys.each do |k| return false unless get(k) == other.get(k) end return true end ############################################################## # Iterators # ############################################################## # Iterates over elements and yields name-value pairs def each # :yields: element_name, element_value self.class.elements.each do |name, el| yield name, get(name) end end # Iterates over non-nil elements, yielding name-value pairs def each_val # :yields: element_name, element_value self.class.elements.select{ |name, el| element_has_value?(name) }.each do |name, el| yield name, get(name) end end # Returns an array of current primary key values def primary_keys self.class.primary_keys.map{ |k| val = get(k) k.model? && val ? val.primary_keys : val } end # Returns an hash of primary keys names and values def primary_keys_hash h = {} self.class.primary_keys.each{ |k| h[k.name] = get(k) } h end # Returns a string with the primary keys joined by ',' def keys_string self.class.primary_keys.map{ |pk| self.get(pk) }.join(',') end # Returns true if the element instance variable is set #-- # FIXME: should probably try to get away without this method # it is the only method that relies on the mapper def element_has_value?(element) element = self.class.get_element(element) if (element.integrated?) return false unless obj = instance_variable_get(:"@#{element.integrated_from.name}") return obj.element_has_value?(element.integrated_from_element) end if (element.attributes[:computed_from]) element.attributes[:computed_from].each{ |el| return false unless element_has_value?(el) } return true end ivar = nil ivar = instance_variable_get(:"@#{element.name}") if instance_variable_defined?(:"@#{element.name}") return nil == ivar ? false : true # FIXME: is this needed? # if (!mapper.mapped?(element) # return send("#{element_name}?") if (respond_to?("#{element_name}?")) # return get(element) == nil ? false : true if (!mapper.mapped?(element)) # end end # Returns true if the element value has been modified since instantiating or loading def element_modified?(element) element = self.class.get_element(element) set_mod = @modified_elements[element.name] return set_mod if set_mod if (element.integrated?) return false unless integrated = get_no_load(element.integrated_from) return integrated.element_modified?(element.integrated_from_element) end if element_has_value?(element) && (val = get(element)).respond_to?(:modified?) return val.modified? end return false end # Returns true if any of elements has been modified def elements_modified?(*elements) elements = elements[0] if elements[0].is_a?(Array) elements.each{ |el| return true if element_modified?(el) } return false end # Returns true if any element, or any child object, has been modified def modified? return true unless @modified_elements.reject{ |key, val| !val }.empty? self.class.elements_array.select{ |el| !el.model? && element_has_value?(el) && el.type.is_a?(Spider::DataType) }.each do |el| return true if get(el).modified? end return false end def in_storage? return false unless primary_keys_set? return self.class.load(primary_keys_hash) end # Given elements are set as modified def set_modified(request) #:nodoc: request.each do |key, val| # FIXME: go deep @modified_elements[key] = true end end # Resets modified elements def reset_modified_elements(*elements) #:nodoc: if (elements.length > 0) elements.each{ |el_name| @modified_elements.delete(el_name) } else @modified_elements = {} end end # Returns true if all primary keys have a value; false if some primary key # is not set or the model has no primary key def primary_keys_set? primary_keys = self.class.primary_keys return false unless primary_keys.length > 0 primary_keys.each do |el| if (el.integrated?) return false unless (int_obj = instance_variable_get(:"@#{el.integrated_from.name}")) #return false unless int_obj.instance_variable_get(:"@#{el.integrated_from_element}") return false unless int_obj.element_has_value?(el.integrated_from_element) else return false unless self.instance_variable_get(:"@#{el.name}") end end return true end # Returns true if no element has a value def empty? return @_has_values end # Sets all values of obj on the current object def merge!(obj, only=nil) obj.class.elements_array.select{ |el| (only || obj.element_has_value?(el)) && !el.integrated? && !el.attributes[:computed_from] }.each do |el| next if only && !only.key?(el.name) val = obj.get_no_load(el) set_loaded_value(el, val, false) end end # Returns a deep copy of the object def clone obj = self.class.new obj.merge!(self) return obj end # Returns a new instance with the same primary keys def get_new obj = nil Spider::Model.no_identity_mapper do obj = self.class.new self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } end return obj end # Returns a new static instance with the same primary keys def get_new_static obj = self.class.static self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } return obj end # Returns a condition based on the current primary keys def keys_to_condition c = Condition.and self.class.primary_keys.each do |key| val = get(key) if (key.model?) c[key.name] = val.keys_to_condition else c[key.name] = val end end return c end ################################################# # Object observers methods # ################################################# # The given block will be called whenever a value is modified. # The block will be passed three arguments: the object, the element name, and the previous value # Example: # obj.observe_all_values do |instance, element_name, old_val| # puts "#{element_name} for object #{instance} has changed from #{old_val} to #{instance.get(element_name) }" def observe_all_values(&proc) @all_values_observers ||= [] @all_values_observers << proc end def observe_element(element_name, &proc) @value_observers ||= {} @value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.observer_all_values(&proc) self.all_values_observers << proc end def self.observe_element(element_name, &proc) self.value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.value_observers @value_observers ||= {} end def self.all_values_observers @all_values_observers ||= [] end # Calls the observers for element_name def notify_observers(element_name, new_val) #:nodoc: if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(self, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(self, element_name, new_val) } end end # Calls the observers for element_name def self.notify_observers(element_name, new_val) if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(self, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(self, element_name, new_val) } end end ############################################################## # Storage, mapper and schema loading (instance methods) # ############################################################## # Returns the current @storage, or instantiates the default calling Spider::BaseModel.storage def storage return @storage || self.class.storage end # Instantiates the storage for the instance. # Accepts a string (url or named storage) which will be passed to Spider::BaseModel.get_storage # Example: # obj.use_storage('my_named_db') # obj.use_storage('db:oracle://username:password@XE') def use_storage(storage) @storage = self.class.get_storage(storage) @mapper = self.class.get_mapper(@storage) end # Returns the current mapper, or instantiates a new one (base on the current storage, if set) def mapper @storage ||= nil if (@storage) @mapper ||= self.class.get_mapper(@storage) else @mapper ||= self.class.mapper end return @mapper end # Sets the current mapper def mapper=(mapper) @mapper = mapper end ############################################################## # Saving and loading from storage methods # ############################################################## # Saves the object to the storage # (see Mapper#save) def save if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else save! end end self end def save! mapper.save(self) self end # Saves the object and all child objects to the storage # (see Mapper#save_all) def save_all mapper.save_all(self) self end def insert if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self, :save, :force => :insert) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else insert! end end self end # Inserts the object in the storage # Note: if the object is already present in the storage and unique indexes are enforced, # this will raise an error. # (See Mapper#insert). def insert! mapper.insert(self) reset_modified_elements end # Updates the object in the storage # Note: the update will silently fail if the object is not present in the storage # (see Mapper#update). def update mapper.update(self) reset_modified_elements end # Deletes the object from the storage # (see Mapper#delete). def delete if @unit_of_work @unit_of_work.add(self, :delete) return end before_delete unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self, :delete) if @unit_of_work @unit_of_work.commit @unit_of_work.stop if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else delete! end end def delete! mapper.delete(self) end def before_delete end def before_save end def use_unit_of_work had_uow = true unless Spider.current[:unit_of_work] had_wow = false @unit_of_work = Spider::Model.start_unit_of_work end unless Spider::Model.identity_mapper @uow_identity_mapper = Spider::Model::IdentityMapper.new Spider.current[:identity_mapper] = @uow_identity_mapper @uow_identity_mapper.put(self) if self.primary_keys_set? end # Spider.current[:unit_of_work].add(self) Spider.current[:unit_of_work] return had_uow end # Loads the object from the storage # Acceptable arguments are: # * a Query object, or # * a Request object, or a Hash, which will be converted to a Request, or # * a list of elements to request # It will then construct a Condition with current primary keys, and call Mapper#load # Note that an error will be raised by the Mapper if not all primary keys are set. def load(*params) if (params[0].is_a? Query) query = params[0] else return false unless primary_keys_set? query = Query.new if (params[0].is_a?(Request)) query.request = params.shift elsif (params[0].is_a?(Hash)) query.request = Request.new(params.shift) end elements = params.length > 0 ? params : self.class.elements.keys return true unless elements.select{ |el| !element_loaded?(el) }.length > 0 elements.each do |name| query.request[name] = true end query.condition.conjunction = :and self.class.primary_keys.each do |key| query.condition[key.name] = get(key.name) end end #clear_values() return mapper.load(self, query) end # Sets all values to nil def clear_values() self.class.elements.each_key do |element_name| instance_variable_set(:"@#{element_name}", nil) end end def remove_association(element, object) mapper.delete_element_associations(self, element, object) end # Method that will be called by the mapper before a query. May be overridden to preprocess the query. # Must return the modified query. Note: to prepare conditions, use prepare_condition, since it will # be called on subconditions as well. def self.prepare_query(query) query end ############################################################## # Method missing # ############################################################## # Tries the method on integrated models def method_missing(method, *args) #:nodoc: # UNUSED # case method.to_s # when /load_by_(.+)/ # element = $1 # if !self.class.elements[element.to_sym].attributes[:primary_key] # raise ModelException, "load_by_ called for element #{element} which is not a primary key" # elsif self.class.primary_keys.length > 1 # raise ModelException, "can't call #{method} because #{element} is not the only primary key" # end # query = Query.new # query.condition[element.to_sym] = args[0] # load(query) # else if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| obj = send(name) if (obj.respond_to?(method)) return obj.send(method, *args) end end end raise NoMethodError, "undefined method `#{method}' for #{self.class}" #super # end end def respond_to?(symbol, include_private=false) return true if super if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| if (model.method_defined?(symbol)) return true end end end return false end # Returns a descriptive string for the object. # By default this method returns the value of the first String element, if any; otherwise, # the string representation of the first element of any type. # Descendant classes may well provide a better representation. def to_s desc_elements = self.class.elements_array.select{ |el| el.attributes[:desc] } unless desc_elements.empty? return desc_elements.sort{ |a, b| ad = a.attributes[:desc]; bd = b.attributes[:desc] if ad == true && bd == true 0 elsif bd == true -1 elsif ad == true 1 else ad <=> bd end }.map{ |el| self.get(el).to_s }.join(' ') end self.class.each_element do |el| if ((el.type == String || el.type == Text) && !el.primary_key?) v = get(el) return v ? v.to_s : '' end end el = self.class.elements_array[0] if element_has_value?(el) v = get(el) return v ? v.to_s : '' end return '' end # A compact representation of the object. # Note: inspect will not autoload the object. def inspect self.class.name+': {' + self.class.elements_array.select{ |el| (element_loaded?(el) || element_has_value?(el)) && !el.hidden? } \ .map{ |el| ":#{el.name} => #{get(el.name).to_s}"}.join(',') + '}' end # Returns a JSON representation of the object. # # The tree will be traversed outputting all encountered objects; when an already seen object # is met, the primary keys will be output (as a single value if one, as an array if many) and traversing # will stop. # # For more fine-grained control of the output, it is better to use the #cut method and call to_json on it. def to_json(state=nil, &proc) require 'json' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') if (@tmp_json_seen && !block_given?) pks = self.class.primary_keys.map{ |k| get(k).to_json } pks = pks[0] if pks.length == 1 return pks.to_json end @tmp_json_seen = true json = "" #Spider::Model.with_identity_mapper do |im| self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", true) end if (block_given?) select_elements = Proc.new{ true } else select_elements = Proc.new{ |name, el| !el.hidden? # && # #!el.attributes[:integrated_model] && # (element_has_value?(el) || (el.integrated? && element_has_value?(el.integrated_from))) } end json = "{" + self.class.elements.select(&select_elements).map{ |name, el| if (block_given?) val = yield(self, el) val ? "#{name.to_json}: #{val.to_json}" : nil else val = get(name) if (el.type == 'text' || el.type == 'longText') val = ic.iconv(val + ' ')[0..-2] end val = val.to_json "#{name.to_json}: #{val}" end }.select{ |pair| pair}.join(',') + "}" @tmp_json_seen = false self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", false) end #end return json end # Returns a part of the object tree, converted to Hashes, Arrays and Strings. # Arguments can be: # * a String, followed by a list of elements; the String will be sprintf'd with element values # or # * a depth Fixnum; depth 0 means obj.to_s will be returned, depth 1 will return an hash containing the # object's element values converted to string, and so on # or # * a Hash, whith element names as keys, and depths, or Hashes, or Procs as values; each element # will be traversed up to the depth given, or recursively according to the has; or, if a Proc is given, # it will be called with the current object and element name as arguments # or # * a list of elements; this is equivalent to passing a hash of the elements with depth 0. # # Examples: # obj.inspect # => Zoo::Animal: {:name => Llama, :family => Camelidae, :friends => Sheep, Camel} # obj.cut(0) # => 'Llama' # obj.cut(:name, :friends) # => {:name => 'Llama', :friends => 'Sheep, Camel'} # obj.cut(:name => 0, :friends => 1) # => {:name => 'Llama', :friends => [ # {:name => 'Sheep', :family => 'Bovidae', :friends => 'Llama'}, # {:name => 'Camel', :family => 'Camelidae', :friens => 'Dromedary, LLama'} # ]} # obj.cut(:name => 0, :friends => {:name => 0}) # => {:name => 'Llama', :friends => [{:name => 'Sheep'}, {:name => 'Camel'}]} # objs.cut(:name => 0, :friends => lambda{ |instance, element| # instance.get(element).name.upcase # }) # => {:name => 'Llama', :friends => ['SHEEP', 'CAMEL']} # obj.cut("Hi, i'm a %s and my friends are %s", :name, :friends) # => "Hi, i'm a Llama and my friends are Sheep, Camel" def cut(*params, &proc) h = {} if (params[0].is_a?(String)) return sprintf(params[0], *params[1..-1].map{ |el| get(el) }) elsif (params[0].is_a?(Fixnum)) p = params.shift if (p < 1) if (block_given?) return proc.call(self) else return self.to_s end end lev = p where = {} self.class.elements_array.each { |el| where[el.name] = lev-1} end if (params[0].is_a?(Hash)) where ||= {} params[0].each{ |k, v| where[k.to_sym] = v} else where ||= {} params.each{ |p| where[p] = 0 if p.is_a?(Symbol)} end Spider::Model.with_identity_mapper do |im| where.keys.each do |name| next unless where[name] if (where[name].is_a?(Proc)) val = where[name].call(self, name) else el = self.class.elements[name] if el val = get(el) val = val.cut(where[name], &proc) if el.model? && val else raise ModelException, "Element #{name} does not exist" unless self.respond_to?(name) val = self.send(name) val = val.cut(where[name], &proc) if val.is_a?(BaseModel) end end h[name] = val end end return h end # Returns a element_name => value Hash def to_hash() h = {} self.class.elements.select{ |name, el| element_loaded? el }.each do |name, el| h[name] = get(name) end return h end # Returns a yaml representation of the object. Will try to autoload all elements, unless autoload is false; # foreign keys will be expressed as an array if multiple, as a single primary key value otherwise def to_yaml(params={}) require 'yaml' return YAML::dump(to_yaml_h(params)) end def to_yaml_h(params={}) h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next if params[:except] && params[:except].include?(el.name) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else h[el.name] = get(el) end end h end def self.from_yaml(yaml) h = YAML::load(yaml) obj = self.static h.each do |key, value| el = elements[key.to_sym] if (el.multiple?) el_obj = el.model.static el.model.primary_keys.each do |pk| el_obj.set(pk, value.unshift) end obj.set(el, el_obj) else obj.set(el, value) end end return obj end def dump_to_hash h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next unless mapper.have_references?(el) || (el.junction? && el.model.attributes[:sub_model] == self.class) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else val = get(el) if val case val.class.name.to_sym when :Date, :DateTime, :Time val = val.strftime end end h[el.name] = val end end h end def dump_to_all_data_hash(options={}, h={}, seen={}) Spider::Model.with_identity_mapper do |im| clname = self.class.name.to_sym seen[clname] ||= {} return if seen[clname][self.primary_keys] seen[clname][self.primary_keys] = true h[clname] ||= [] h[clname] << self.dump_to_hash self.class.elements_array.each do |el| next unless el.model? next if el.model < Spider::Model::InlineModel next if options[:models] && !options[:models].include?(el.type) next if options[:except_models] && options[:except_models].include?(el.type) el_clname == el.type.name.to_sym next if options[:elements] && (options[:elements][el_clname] && !options[:elements][el_clname].include?(el.name)) next if options[:except_elements] && (options[:except_elements][el_clname] && options[:except_elements][el_clname].include?(el.name)) val = self.get(el) next unless val val = [val] unless val.is_a?(Enumerable) val.each do |v| v.dump_to_all_data_hash(options, h, seen) end end end h end def self.in_transaction self.storage.in_transaction yield self.storage.commit_or_continue end def self.dump_element(el) remove_elements = [] method = case el.attributes[:association] when :many :many when :choice :choice when :multiple_choice :multiple_choice when :tree :tree else :element end type = el.type attributes = el.attributes.clone if (method == :many || method == :multiple_choice) attributes.delete(:multiple) end attributes.delete(:association) if method != :element if (attributes[:association_type]) attributes[:through] = attributes[:association_type] unless attributes[:anonymous_model] attributes.delete(:association_type) end attributes.delete(:lazy) if attributes[:lazy] == :default if (method == :tree) delete_attrs = [:queryset_module, :multiple] delete_attrs.each{ |a| attributes.delete(a) } remove_elements += [attributes[:reverse], attributes[:tree_left], attributes[:tree_right], attributes[:tree_depth]] type = nil end return { :name => el.name, :type => type, :attributes => attributes, :method => method, :remove_elements => remove_elements } end def self.prepare_to_code modules = self.name.split('::')[0..-2] included = (self.included_modules - Spider::Model::BaseModel.included_modules).select do |m| m.name !~ /^#{Regexp.quote(self.name)}/ end local_name = self.name.split('::')[-1] superklass = self.superclass.name elements = [] remove_elements = [] self.elements_array.each do |el| next if el.integrated? next if (el.reverse && el.model.elements[el.reverse] && \ (el.model.elements[el.reverse].attributes[:add_reverse] || \ el.model.elements[el.reverse].attributes[:add_multiple_reverse])) el_hash = dump_element(el) return nil unless el_hash elements << el_hash remove_elements += el_hash[:remove_elements] end elements.reject!{ |el| remove_elements.include?(el[:name]) } return { :modules => modules, :included => included, :attributes => self.attributes, :elements => elements, :local_name => local_name, :superclass => superklass, :use_storage => @use_storage, :additional_code => [] } end def self.to_code(options={}) c = prepare_to_code str = "" indent = 0 append = lambda do |val| str += " "*indent str += val str end str += c[:modules].map{ |m| "module #{m}" }.join('; ') + "\n" str += "\n" indent = 4 append.call "class #{c[:local_name]} < #{c[:superclass]}\n" indent += 4 c[:included].each do |i| append.call "include #{i.name}\n" end c[:attributes].each do |k, v| append.call "attribute :#{k}, #{v.inspect}" end str += "\n" c[:elements].each do |el| append.call("#{el[:method].to_s} #{el[:name].inspect}") str += ", #{el[:type]}" if el[:type] str += ", #{el[:attributes].inspect[1..-2]}\n" if el[:attributes] && !el[:attributes].empty? end str += "\n" append.call "use_storage '#{c[:use_storage]}'\n" if c[:use_storage] c[:additional_code].each do |block| block.each_line do |line| append.call line end str += "\n" end indent -= 4 append.call("end\n") str += c[:modules].map{ "end" }.join(';') return str end end end; end
# Copyright (c) 2013 AppNeta, Inc. # All rights reserved. module Oboe module Sinatra module Base def self.included(klass) ::Oboe::Util.method_alias(klass, :dispatch!, ::Sinatra::Base) ::Oboe::Util.method_alias(klass, :handle_exception!, ::Sinatra::Base) end def dispatch_with_oboe if Oboe.tracing? report_kvs = {} report_kvs[:Controller] = self.class report_kvs[:Action] = env['PATH_INFO'] # Fall back to the raw tracing API so we can pass KVs # back on exit (a limitation of the Oboe::API.trace # block method) This removes the need for an info # event to send additonal KVs ::Oboe::API.log_entry('sinatra', {}) begin dispatch_without_oboe ensure ::Oboe::API.log_exit('sinatra', report_kvs) end else dispatch_without_oboe end end def handle_exception_with_oboe(boom) Oboe::API.log_exception(nil, boom) if Oboe.tracing? handle_exception_without_oboe(boom) end end end end if defined?(::Sinatra) require 'oboe/inst/rack' require 'oboe/frameworks/sinatra/templates' Oboe.logger.info "[oboe/loading] Instrumenting Sinatra" if Oboe::Config[:verbose] Oboe::Loading.load_access_key Oboe::Inst.load_instrumentation ::Sinatra::Base.use Oboe::Rack # When in TEST environment, we load this instrumentation regardless. # Otherwise, only when Padrino isn't around. unless defined?(::Padrino) and not (ENV['RACK_ENV'] == "test") # Padrino has 'enhanced' routes and rendering so the Sinatra # instrumentation won't work anyways. Only load for pure Sinatra apps. ::Oboe::Util.send_include(::Sinatra::Base, ::Oboe::Sinatra::Base) ::Oboe::Util.send_include(::Sinatra::Templates, ::Oboe::Sinatra::Templates) # Report __Init after fork when in Heroku Oboe::API.report_init unless Oboe.heroku? end end Add support for RUM in sinatra # Copyright (c) 2013 AppNeta, Inc. # All rights reserved. module Oboe module Sinatra module Base def self.included(klass) ::Oboe::Util.method_alias(klass, :dispatch!, ::Sinatra::Base) ::Oboe::Util.method_alias(klass, :handle_exception!, ::Sinatra::Base) end def dispatch_with_oboe if Oboe.tracing? report_kvs = {} report_kvs[:Controller] = self.class report_kvs[:Action] = env['PATH_INFO'] # Fall back to the raw tracing API so we can pass KVs # back on exit (a limitation of the Oboe::API.trace # block method) This removes the need for an info # event to send additonal KVs ::Oboe::API.log_entry('sinatra', {}) begin dispatch_without_oboe ensure ::Oboe::API.log_exit('sinatra', report_kvs) end else dispatch_without_oboe end end def handle_exception_with_oboe(boom) Oboe::API.log_exception(nil, boom) if Oboe.tracing? handle_exception_without_oboe(boom) end @@rum_xhr_tmpl = File.read(File.dirname(__FILE__) + '/rails/helpers/rum/rum_ajax_header.js.erb') @@rum_hdr_tmpl = File.read(File.dirname(__FILE__) + '/rails/helpers/rum/rum_header.js.erb') @@rum_ftr_tmpl = File.read(File.dirname(__FILE__) + '/rails/helpers/rum/rum_footer.js.erb') def oboe_rum_header Oboe.logger.warn "Testing" return unless Oboe::Config.rum_id if Oboe.tracing? if request.xhr? return ERB.new(@@rum_xhr_tmpl).result else return ERB.new(@@rum_hdr_tmpl).result end end rescue Exception => e Oboe.logger.warn "oboe_rum_header: #{e.message}." return "" end def oboe_rum_footer return unless Oboe::Config.rum_id if Oboe.tracing? # Even though the footer template is named xxxx.erb, there are no ERB tags in it so we'll # skip that step for now return @@rum_ftr_tmpl end rescue Exception => e Oboe.logger.warn "oboe_rum_footer: #{e.message}." return "" end end end end if defined?(::Sinatra) require 'oboe/inst/rack' require 'oboe/frameworks/sinatra/templates' Oboe.logger.info "[oboe/loading] Instrumenting Sinatra" if Oboe::Config[:verbose] Oboe::Loading.load_access_key Oboe::Inst.load_instrumentation ::Sinatra::Base.use Oboe::Rack # When in TEST environment, we load this instrumentation regardless. # Otherwise, only when Padrino isn't around. unless defined?(::Padrino) and not (ENV['RACK_ENV'] == "test") # Padrino has 'enhanced' routes and rendering so the Sinatra # instrumentation won't work anyways. Only load for pure Sinatra apps. ::Oboe::Util.send_include(::Sinatra::Base, ::Oboe::Sinatra::Base) ::Oboe::Util.send_include(::Sinatra::Templates, ::Oboe::Sinatra::Templates) # Report __Init after fork when in Heroku Oboe::API.report_init unless Oboe.heroku? end end
require 'spiderfw/model/mixins/state_machine' require 'spiderfw/model/element' require 'spiderfw/model/integrated_element' require 'iconv' module Spider; module Model # The main class for interacting with data. # When not dealing with legacy storages, subclasses should use Managed instead, which provides an id and # other conveniences. # # Each BaseModel subclass defines a model; instances can be used as "data objects": # they will interact with the Mapper loading and saving the values associated with the BaseModel's defined elements. # # Each element defines an instance variable, a getter and a setter. If the instance is set to #autoload, # when a getter is first called the mapper will fetch the value from the Storage . # # Elements can be of one of the base types (Spider::Model.base_types), of a DataType, or other models. In the last # case, they define a relationship between models. # # Basic usage: # model Food < BaseModel # element :name, String # end # model Animal < BaseModel # element :name, String # many :friends, Animal # choice :favorite_food, Food # end # # salmon = Food.new(:name => 'Salmon') # salmon.save # cat = Animal.new(:name => 'Cat', :favorite_food = salmon) # weasel = Animal.new(:name => 'Weasel', :friends => [cat]) # weasel.save # cat.friends << weasel # cat.save # # wizzy = Animal.load(:name => 'Weasel') # p wizzy.friends # => 'Cat' # p wizzy.friends[0].favorite_food # => 'Salmon' # # bear = Animal.new(:name => 'Bear', :favorite_food = salmon) # bear.save # salmon_lovers = Animal.where{ favorite_food == salmon } # p salmon_lovers.length # => 2 # p salmon_lovers[0].name # => 'Cat' class BaseModel include Spider::Logger include DataTypes include Spider::QueryFuncs include EventSource # include StateMachine # The BaseModel class itself. Used when dealing with proxy objects. attr_reader :model # An Hash of loaded elements attr_reader :loaded_elements # Model instance or QuerySet containing the object attr_accessor :_parent # If _parent is a model instance, which element points to this one attr_accessor :_parent_element # If this object is used as a superclass in class_table_inheritance, points to the current subclass attr_accessor :_subclass_object # This object won't be put into the identity mapper attr_accessor :_no_identity_mapper class <<self # An Hash of model attributes. They can be used freely. attr_reader :attributes # An array of element names, in definition order. attr_reader :elements_order # An Hash of integrated models => corresponding integrated element name. attr_reader :integrated_models # An Hash of polymorphic models => polymorphic params attr_reader :polymorphic_models # An Array of named sequences. attr_reader :sequences end # Copies this class' elements to the subclass. def self.inherited(subclass) #:nodoc: # FIXME: might need to clone every element @subclasses ||= [] @subclasses << subclass each_element do |el| subclass.add_element(el.clone) unless el.attributes[:local_pk] end subclass.instance_variable_set("@mapper_procs_subclass", @mapper_procs_subclass.clone) if @mapper_procs_subclass subclass.instance_variable_set("@mapper_modules", @mapper_modules.clone) if @mapper_modules subclass.instance_variable_set("@extended_models", @extended_models.clone) if @extended_models em = subclass.const_set(:ElementMethods, Module.new) subclass.send(:include, em) super end def self.subclasses @subclasses || [] end # Returns the parent Spider::App of the module def self.app return @app if @app app = self while (!app.include?(Spider::App)) app = app.parent_module end @app = app end ####################################### # Model definition methods # ####################################### # Defines an element. # Arguments are element name (a Symbol), element type, and a Hash of attributes. # # Type may be a Class: a base type (see Spider::Model.base_types), a DataType subclass, # or a BaseModel subclass; or an Array or a Hash, in which case an InlineModel will be created. # # An Element instance will be available in Model::BaseModel.elements; getter and setter methods will be defined on # the class. # # If a block is passed to this method, type will be 'extended': a custom junction association will be created, # effectively adding elements to the type only in this model's context. # Example: # class Animal < BaseModel # element :name, String # element :friends, Animal, :multiple => true do # element :how_much, String # end # end # cat = Animal.new(:name => 'Cat') # dog = Animal.new(:name => 'Dog') # cat.friends << dog # cat.friend[0].how_much = 'Not very much' # # Returns the created Element. # # Some used attributes: # :primary_key:: (bool) The element is a primary key # :length:: (number) Maximum length of the element (if meaningful) # :required:: (bool) The element must always have a value # :multiple:: (bool) defines a 1|n -> n relationship # :label:: (string) a short description, used by the UI # :association:: (symbol) A named association (such as :choice, :multiple_choice, etc.) # :lazy:: (bool, array or symbol) If true, the element will be placed in the :default lazy group; # if a symbol or an array of symbols is passed, the element will be placed in those groups. # (see Element#lazy_groups) # :reverse:: (symbol) The reverse element in the relationship to the other model # :add_reverse:: (symbol) Adds an element on the other model, and sets it as the association reverse. # :add_multiple_reverse:: (symbol) Adds a multiple element on the other model, and sets it as the association reverse. # :element_position:: (number) inserts the element at the specified position in the elements order # :auto:: (bool) Informative: the value is set automatically through some mechanism # :autoincrement:: (bool) The value (which must be a Fixnum) will be autoincremented by the mapper # :integrate:: (bool or symbol) type's elements will be available to this class # as if they were defined here (see #integrate) # :integrated_from:: (symbol) the name of the element from which this element is integrated # :integrated_from_element:: (symbol) the name of the element of the child object from which this element is integrated # :hidden:: (bool) a hint that the element shouldn't be shown by the UI # :computed_from:: (array of symbols) the element is not mapped; its value is computed # by the class from the given elements. # :unmapped:: (bool) the element is not mapped. # :sortable:: (bool or Array of symbols) specifies that an unmapped element can be used for sorting. # The model must provide a meaningful order using the prepare_query method. # :check:: (a Proc, or a Regexp, or a Hash of messages => Regexp|Proc). See #check # :through:: (a BaseModel subclass) model representing the many to many relationship. # :read_only:: (bool) hint to the UI that the element should not be user modifiable. # :owned:: (bool) only this model holds references to type # :condition:: (hash or Condition) Restricts an association always adding the condition. # :order:: (true or Fixnum) When doing queries, sort by this element. More than one element can have the # :order attribute; if it is a Fixnum, it will mean the position in the ordering. # :default:: (Proc or value) default value for the element. If it is a Proc, it will be passed # the object. # :desc:: (true or Fixnum) Use this element for the to_s string. Multiple elements # with the :desc attribute will be joined by spaces; order may be specified if # a Fixnum is used for the parameter # # Other attributes may be used by DataTypes (see #DataType::ClassMethods.take_attributes), and other code. # See also Element. def self.element(name, type, attributes={}, &proc) name = name.to_sym @elements ||= {} @elements_order ||= [] raise "Element called #{name} already exists in #{self}" if @elements[name] if type.class == Class default_attributes = case type.name when 'String' {:length => 255} else {} end else default_attributes = {} end attributes = default_attributes.merge(attributes) # if (type.class == Class && Model.base_type(type)) # type = Model.base_type(type) # els if (type.class <= Hash) type = create_inline_model(name, type, attributes) attributes[:inline] = true end if (attributes[:integrated_from]) if (attributes[:integrated_from].class == String) parts = attributes[:integrated_from].split('.') attributes[:integrated_from] = @elements[parts[0].to_sym] attributes[:integrated_from_element] = parts[1].to_sym if parts[1] elsif (attributes[:integrated_from].is_a?(Symbol)) attributes[:integrated_from] = @elements[attributes[:integrated_from]] end if (!attributes[:integrated_from_element]) attributes[:integrated_from_element] = name end end if (attributes[:condition] && !attributes[:condition].is_a?(Condition)) attributes[:condition] = Condition.new(attributes[:condition]) end if attributes[:computed_from] && !attributes[:computed_from].is_a?(Enumerable) attributes[:computed_from] = [attributes[:computed_from]] end type.set_element_attributes(attributes) if type < Spider::DataType orig_type = type assoc_type = nil if (proc || attributes[:junction] || (attributes[:multiple] && (!attributes[:add_reverse]) && (!attributes[:has_single_reverse]) && \ # FIXME! the first check is needed when the referenced class has not been parsed yet # but now it assumes that the reverse is not multiple if it is not defined (attributes[:has_single_reverse] == false || !attributes[:reverse] || (!type.elements[attributes[:reverse]] || type.elements[attributes[:reverse]].multiple?)))) attributes[:anonymous_model] = true attributes[:owned] = true unless attributes[:owned] != nil first_model = self.first_definer(name, type) assoc_type_name = Spider::Inflector.camelize(name) create_junction = true if (attributes[:through]) assoc_type = attributes[:through] create_junction = false elsif (first_model.const_defined?(assoc_type_name) ) assoc_type = first_model.const_get(assoc_type_name) if (!assoc_type.attributes[:sub_model]) # other kind of inline model assoc_type_name += 'Junction' create_junction = false if (first_model.const_defined?(assoc_type_name)) else create_junction = false end end attributes[:junction] = true attributes[:junction_id] = :id unless attributes.has_key?(:junction_id) if (attributes[:junction_our_element]) self_name = attributes[:junction_our_element] else self_name = first_model.short_name.gsub('/', '_').downcase.to_sym end attributes[:reverse] = self_name unless attributes[:junction_their_element] other_name = Spider::Inflector.underscore(orig_type.short_name == self.short_name ? orig_type.name : orig_type.short_name).gsub('/', '_').downcase.to_sym other_name = :"#{other_name}_ref" if (orig_type.elements[other_name]) attributes[:junction_their_element] = other_name end other_name = attributes[:junction_their_element] if (create_junction) assoc_type = first_model.const_set(assoc_type_name, Class.new(BaseModel)) assoc_type.attributes[:sub_model] = self assoc_type.attributes[:sub_model_element] = name assoc_type.element(attributes[:junction_id], Fixnum, :primary_key => true, :autoincrement => true, :hidden => true) if attributes[:junction_id] assoc_type.element(self_name, self, :hidden => true, :reverse => name, :association => :choice, :junction_reference => true) # FIXME: must check if reverse exists? # FIXME! fix in case of clashes with existent elements assoc_type.element(other_name, orig_type, :association => :choice, :junction_reference => true) assoc_type.integrate(other_name, :hidden => true, :no_pks => true) # FIXME: in some cases we want the integrated elements if (proc) # to be hidden, but the integrated el instead attributes[:extended] = true attributes[:keep_junction] = true assoc_type.class_eval(&proc) end end orig_type.referenced_by_junctions << [assoc_type, other_name] attributes[:keep_junction] = true if (attributes[:through] && attributes[:keep_junction] != false) attributes[:association_type] = assoc_type if attributes[:polymorph] assoc_type.elements[attributes[:junction_their_element]].attributes[:polymorph] = attributes[:polymorph] attributes.delete(:polymorph) end end add_element(Element.new(name, type, attributes)) if (attributes[:add_reverse] && attributes[:add_reverse].is_a?(Symbol)) attributes[:add_reverse] = {:name => attributes[:add_reverse]} end if (attributes[:add_multiple_reverse] && attributes[:add_multiple_reverse].is_a?(Symbol)) attributes[:add_multiple_reverse] = {:name => attributes[:add_multiple_reverse]} end if (attributes[:add_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_reverse][:name] rev = attributes[:add_reverse].merge(:reverse => name, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:keep_junction] = false rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end elsif (attributes[:add_multiple_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_multiple_reverse][:name] rev = attributes[:add_multiple_reverse].merge(:reverse => name, :multiple => true, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end end if (attributes[:lazy] == nil) # if attributes[:primary_key] # attributes[:lazy] = true # els if (type < BaseModel && (attributes[:multiple] || attributes[:polymorph])) # FIXME: we can load eagerly single relations if we can do a join attributes[:lazy] = true else attributes[:lazy_check_owner] = true if type < BaseModel attributes[:lazy] = :default end end # class element getter unless respond_to?(name) (class << self; self; end).instance_eval do define_method("#{name}") do @elements[name] end end end define_element_methods(name) attr_reader "#{name}_junction" if attributes[:junction] && !attributes[:keep_junction] if (attributes[:integrate]) integrate_params = attributes[:integrate].is_a?(Hash) ? attributes[:integrate] : {} integrate(name, integrate_params) end if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |imod, iel| imod.integrate_element(iel, self.elements[name]) unless imod.elements[name] end end if (@subclasses) @subclasses.each do |sub| next if sub.elements[name] # if subclass already defined an element with this name, don't overwrite it sub.elements[name] = @elements[name].clone sub.elements_order << name end end element_defined(@elements[name]) @elements[name].model? return @elements[name] end def self.define_element_methods(name) ivar = :"@#{ name }" unless self.const_defined?(:ElementMethods) em = self.const_set(:ElementMethods, Module.new) include em end element_methods = self.const_get(:ElementMethods) #instance variable getter element_methods.send(:define_method, name) do element = self.class.elements[name] raise "Internal error! Element method #{name} exists, but element not found" unless element return element.attributes[:fixed] if element.attributes[:fixed] if (element.integrated?) integrated = get(element.integrated_from.name) return integrated.send(element.integrated_from_element) if integrated return nil end if element_has_value?(name) || element_loaded?(name) val = instance_variable_get(ivar) val.set_parent(self, name) if val && element.model? && !val._parent # FIXME!!! return val end # Spider.logger.debug("Element not loaded #{name} (i'm #{self.class} #{self.object_id})") if autoload? && primary_keys_set? if (autoload? == :save_mode) mapper.load_element!(self, element) else mapper.load_element(self, element) end val = instance_variable_get(ivar) end if !val && element.model? && (element.multiple? || element.attributes[:extended_model]) val = instance_variable_set(ivar, instantiate_element(name)) end if !val && element.attributes[:default] if element.attributes[:default].is_a?(Proc) val = element.attributes[:default].call(self) else val = element.attributes[:default] end val = element.model.new(val) if element.model? && !val.is_a?(BaseModel) end val.set_parent(self, name) if element.model? && val && val.respond_to?(:parent) && !val._parent # FIXME!!! return val end alias_method :"#{name}?", name if self.elements[name].type <= Spider::DataTypes::Bool #instance_variable_setter element_methods.send(:define_method, "#{name}=") do |val| element = self.class.elements[name] raise "Internal error! Element method #{name}= exists, but element not found" unless element return if element.attributes[:fixed] was_loaded = element_loaded?(element) #@_autoload = false unless element.primary_key? if (element.integrated?) integrated_obj = get(element.integrated_from) unless integrated_obj integrated_obj = instantiate_element(element.integrated_from.name) set(element.integrated_from, integrated_obj) end #integrated_obj.autoload = false begin res = integrated_obj.send("#{element.integrated_from_element}=", val) rescue IdentityMapperException set(element.integrated_from, Spider::Model.get(integrated_obj)) get(element.integrated_from).merge!(integrated_obj) end if !element.primary_key? && integrated_obj.element_modified?(name) @modified_elements[name] = true end return res end if (val && element.model?) if (element.multiple?) unless (val.is_a?(QuerySet)) qs = instantiate_element(name) if (val.is_a?(Enumerable)) val.each do |row| row = element.type.new(row) unless row.is_a?(BaseModel) qs << row end else qs << val end val = qs end else val = element.model.get(val) unless val.is_a?(BaseModel) end end val = prepare_child(element.name, val) _check(name, val) notify_observers(name, val) @_has_values = true unless @_primary_keys_set if self.class.elements[element.name].primary_key? && primary_keys_set? @_primary_keys_set = true if Spider::Model.identity_mapper Spider::Model.identity_mapper.put(self, true, true) else Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work end end end old_val = instance_variable_get(ivar) @modified_elements[name] = true if !element.primary_key? && (!was_loaded || val != old_val) instance_variable_set(ivar, val) set_reverse(element, val) if element.model? if val && element.model? && !self.class.attributes[:no_type_check] klass = val.is_a?(QuerySet) ? val.model : val.class if val && !(klass <= element.type || klass <= element.model) raise TypeError, "Object #{val} (#{klass}) is of the wrong type for element #{element.name} in #{self.class} (expected #{element.model})" end end val #extend_element(name) end end def self.add_element(el) @elements ||= {} @elements[el.name] = el @elements_order ||= [] if (el.attributes[:element_position]) @elements_order.insert(el.attributes[:element_position], el.name) else @elements_order << el.name end @primary_keys ||= [] if el.attributes[:primary_key] && !@primary_keys.include?(el) @primary_keys << el end end # Removes a defined element def self.remove_element(el) return unless @elements el = el.name if el.is_a?(Element) element = @elements[el] if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |mod, iel| i = mod.elements[el] mod.remove_element(el) if i && i.integrated? && i.integrated_from.name == iel end end self.elements_array.select{ |e| e.integrated? && e.integrated_from.name == el}.each{ |e| remove_element(e) } self.const_get(:ElementMethods).send(:remove_method, :"#{el}") rescue NameError self.const_get(:ElementMethods).send(:remove_method, :"#{el}=") rescue NameError @elements.delete(el) @elements_order.delete(el) @primary_keys.delete_if{ |pk| pk.name == el} # if (@subclasses) # @subclasses.each do |sub| # sub.remove_element(el) # end # end end def self.element_defined(el) if (@on_element_defined && @on_element_defined[el.name]) @on_element_defined[el.name].each do |proc| proc.call(el) end end end def self.on_element_defined(el_name, &proc) @on_element_defined ||= {} @on_element_defined[el_name] ||= [] @on_element_defined[el_name] << proc end # Integrates an element: any call to the child object's elements will be passed to the child. # The element must not be multiple. # Example: # class Address < BaseModel # element :street, String # element :area_code, String # end # class Person < BaseModel # element :name, String # element :address, Address # integrate :address # end # p = Person.new(...) # p.street == p.address.street def self.integrate(element_name, params={}) params ||= {} elements[element_name].attributes[:integrated_model] = true model = elements[element_name].type self.attributes[:integrated_models] ||= {} self.attributes[:integrated_models][model] = element_name params[:except] ||= [] model.each_element do |el| next if params[:except].include?(el.name) next if elements[el.name] unless params[:overwrite] # don't overwrite existing elements integrate_element(element_name, el, params) end model.attributes[:integrated_from_elements] ||= [] model.attributes[:integrated_from_elements] << [self, element_name] end def self.integrate_element(element_name, element_element, params={}) el = element_element integrated_attributes = {} integrated_attributes[:primary_key] = false if params[:no_pks] integrated_attributes[:hidden] = params[:hidden] unless (params[:hidden].nil?) integrated_attributes[:primary_key] = false unless (params[:keep_pks]) # attributes.delete(:required) # attributes.delete(:integrate) # attributes.delete(:local_pk) integrated_attributes[:local_pk] = false integrated_attributes[:lazy] = element_name name = params[:mapping] && params[:mapping][el.name] ? params[:mapping][el.name] : el.name add_element(IntegratedElement.new(name, self, element_name, el.name, integrated_attributes)) define_element_methods(name) end def self.remove_integrate(element_name) element = element_name.is_a?(Element) ? element_name : self.elements[element_name] model = element.model self.elements_array.select{ |el| el.attributes[:integrated_from] && el.attributes[:integrated_from].name == element.name }.each do |el| self.remove_element(el) end model.attributes[:integrated_from_elements].reject!{ |item| item[0] == self } end # Sets additional attributes on the element # # _Warning:_ for attributes which are parsed by the BaseModel during element definition, # this will not have the desired effect; remove and redefine the element instead. def self.element_attributes(element_name, attributes) elements[element_name].attributes = elements[element_name].attributes.merge(attributes) if attributes[:primary_key] && !@primary_keys.include?(elements[element_name]) @primary_keys << elements[element_name] elsif !attributes[:primary_key] @primary_keys.delete(elements[element_name]) end end # Defines a multiple element. Equivalent to calling # element(name, type, :multiple => true, :association => :many, ...) def self.many(name, type, attributes={}, &proc) attributes[:multiple] = true attributes[:association] ||= :many element(name, type, attributes, &proc) end # Defines an element with choice association. Shorthand for # element(name, type, :association => :choice, ...) def self.choice(name, type, attributes={}, &proc) attributes[:association] = :choice element(name, type, attributes, &proc) end # Defines a multiple element with :multiple_choice association. Shorthand for # many(name, type, :association => :multiple_choice, ...) def self.multiple_choice(name, type, attributes={}, &proc) attributes[:association] = :multiple_choice many(name, type, attributes, &proc) end def self.element_query(name, element_name, attributes={}) orig_element = self.elements[element_name] set_el_query = lambda do orig_element = self.elements[element_name] attributes = attributes.merge(orig_element.attributes) attributes[:unmapped] = true attributes[:element_query] = element_name attributes[:association] = :element_query attributes[:lazy] = true attributes.delete(:add_reverse) attributes.delete(:add_multiple_reverse) if (orig_element.attributes[:condition]) cond = orig_element.attributes[:condition].clone cond = cond.and(attributes[:condition]) if attributes[:condition] attributes[:condition] = cond end element(name, orig_element.type, attributes) end if (orig_element) set_el_query.call else on_element_defined(element_name, &set_el_query) end end # Saves the element definition and evals it when first needed, avoiding problems with classes not # available yet when the model is defined. # FIXME: remove? def self.define_elements(&proc) #:nodoc: @elements_definition = proc end # Creates an inline model def self.create_inline_model(name, hash, attributes={}) #:nodoc: model = self.const_set(Spider::Inflector.camelize(name), Class.new(InlineModel)) model.instance_eval do if attributes[:inline_model] attributes[:inline_model].each do |el| element(el[0], el[1], el[2] || {}) end else hash.each do |key, val| key = key.to_s if key.is_a?(Symbol) element(:id, key.class, :primary_key => true) if (val.class == Hash) # TODO: allow passing of multiple values like {:element1 => 'el1', :element2 => 'el2'} else element(:desc, val.class, :desc => true) end break end end end model.data = hash return model end # An array of other models this class points to. def self.submodels elements.select{ |name, el| el.model? }.map{ |name, el| el.model } end def self.extend_model(model, params={}) #:nodoc: if (model == superclass) # first undo table per class inheritance @elements = {} @elements_order = [] @extended_models.delete(model.superclass) if @extended_models end primary_keys.each{ |k| remove_element(k) } if (params[:replace_pks]) model.primary_keys.each{ |k| remove_element(k) } integrated_name = params[:name] if (!integrated_name) integrated_name = (self.parent_module == model.parent_module) ? model.short_name : model.name integrated_name = Spider::Inflector.underscore(integrated_name).gsub('/', '_') end integrated_name = integrated_name.to_sym @extended_models ||= {} @extended_models[model] = integrated_name attributes = {} attributes[:hidden] = true unless (params[:hide_integrated] == false) attributes[:delete_cascade] = params[:delete_cascade] attributes[:extended_model] = true attributes[:add_reverse] = params[:reverse] integrated = element(integrated_name, model, attributes) integrate_options = {:keep_pks => true}.merge((params[:integrate_options] || {})) integrate(integrated_name, integrate_options) model.elements_array.select{ |el| el.attributes[:local_pk] }.each{ |el| remove_element(el.name) } unless (params[:no_local_pk] || !elements_array.select{ |el| el.attributes[:local_pk] }.empty?) # FIXME: check if :id is already defined pk_name = @elements[:id] ? :"id_#{self.short_name.downcase}" : :id element(pk_name, Fixnum, :autoincrement => true, :local_pk => true, :hidden => true) end model.polymorphic(self, :through => integrated_name) end # Externalizes the superclass elements making the superclass an external integrated element. # Parameters may be: # * :name (symbol) name of the created element # * :delete_cascade (bool) delete cascade the superclass instance. True by default. # * :no_local_pk (bool) do not define an id for this class def self.class_table_inheritance(params={}) self.extend_model(superclass, params) end # Makes the class use the superclass storage def self.inherit_storage self.attributes[:inherit_storage] = true (class << self; self; end).instance_eval do define_method(:storage) do superclass.storage end end end # Sets a fixed condition. def self.condition(condition) self.attributes[:condition] = condition end # #-- # TODO: document me def self.group(name, &proc) #:nodoc: proxy = Class.new(ProxyModel).proxy(name.to_s+'_', self) proxy.instance_eval(&proc) proxy.each_element do |el| element(name.to_s+'_'+el.name.to_s, el.type, el.attributes.clone) end define_method(name) do @proxies ||= {} return @proxies[name] ||= proxy.new end end # Add a subclass, allowing polymorphic queries on it. def self.polymorphic(model, options) through = options[:through] || Spider::Inflector.underscore(self.name).gsub('/', '_') through = through.to_sym @polymorphic_models ||= {} @polymorphic_models[model] = {:through => through} end # Sets or gets class attributes (a Hash). # If given a hash of attributes, will merge them with class attributes. # Model attributes are generally empty, and can be used by apps. def self.attributes(val=nil) @attributes ||= {} if (val) @attributes.merge!(val) end @attributes end # Sets a model attribute. See #self.attributes def self.attribute(name, value) @attributes ||= {} @attributes[name] = value end # Adds a sequence to the model. def self.sequence(name) @sequences ||= [] @sequences << name end # Model sequences. def self.sequences @sequences ||= [] end # Does nothing. This method is to keep note of elements created in other models. def self._added_elements(&proc) end def self.referenced_by_junctions @referenced_by_junctions ||= [] end ##################################################### # Methods returning information about the model # ##################################################### # Underscored local name (without namespaces) def self.short_name return Inflector.underscore(self.name.match(/([^:]+)$/)[1]) end # False for BaseModel (true for Spider::Model::Managed). def self.managed? return false end # Name def self.to_s self.name end # Sets the singolar and/or the plural label for the model # Returns the singlular label def self.label(sing=nil, plur=nil) @label = sing if sing @label_plural = plur if plur _(@label || self.name || '') end # Sets/retrieves the plural form for the label def self.label_plural(val=nil) @label_plural = val if (val) _(@label_plural || self.name || '') end def self.auto_primary_keys? self.primary_keys.select{ |k| !k.autogenerated? }.empty? end def self.containing_module par = self.parent_module while par <= BaseModel par = par.parent_module end par end def self.get_element(el) el = el.name if el.is_a?(Element) el = el.to_sym raise "No element called #{el} in #{self}" unless @elements[el] @elements[el] end def self.junction? !!self.attributes[:sub_model] end ######################################################## # Methods returning information about the elements # ######################################################## # An Hash of Elements, indexed by name. def self.elements @elements end # An array of the model's Elements. def self.elements_array @elements_order.map{ |key| @elements[key] } end # Yields each element in order. def self.each_element return unless @elements_order @elements_order.each do |name| yield elements[name] end end # Returns true if the model has given element name. def self.has_element?(name) return elements[name] ? true : false end # An array of elements with primary_key attribute set. def self.primary_keys @primary_keys end # Returns the model actually defining element_name; that could be the model # itself, a superclass, or an integrated model. def self.first_definer(element_name, type) if (@extended_models && @extended_models[self.superclass] && self.superclass.elements[element_name] && self.superclass.elements[element_name].type == type) return self.superclass.first_definer(element_name, type) end if (self.attributes[:integrated_models]) self.attributes[:integrated_models].keys.each do |mod| return mod.first_definer(element_name, type) if (mod.elements[element_name] && mod.elements[element_name].type == type) end end return self end # Returns true if the element with given name is associated with the passed # association. # This method should be used instead of querying the element's association directly, # since subclasses and mixins may extend this method to provide association equivalence. def self.element_association?(element_name, association) return true if elements[element_name].association = association end # An Hash of extended models => element name of the extended model element def self.extended_models @extended_models ||= {} end ############################################################## # Storage, mapper and loading (Class methods) # ############################################################## # The given module will be mixed in any mapper used by the class. def self.mapper_include(mod) @mapper_modules ||= [] @mapper_modules << mod end def self.mapper_include_for(params, mod) @mapper_modules_for ||= [] @mapper_modules_for << [params, mod] end # The given proc will be mixed in the mapper used by this class # Note that the proc will be converted to a Module, so any overridden methods will still have # access to the super method. def self.with_mapper(*params, &proc) # @mapper_procs ||= [] # @mapper_procs << proc mod = Module.new(&proc) mapper_include(mod) end # FIXME: remove def self.with_mapper_subclasses(*params, &proc) #:nodoc: @mapper_procs_subclass ||= [] @mapper_procs_subclass << proc end # Like #with_mapper, but will mixin the block only if the mapper matches params. # Possible params are: # - a String, matching the class' use_storage def self.with_mapper_for(*params, &proc) @mapper_procs_for ||= [] @mapper_procs_for << [params, proc] end # Sets the url or the name of the storage to use def self.use_storage(name=nil) @use_storage = name if name @use_storage end # Returns the current default storage for the class # The storage to use can be set with #use_storage def self.storage return @storage if @storage if (!@use_storage && self.attributes[:sub_model]) @use_storage = self.attributes[:sub_model].use_storage end return @use_storage ? get_storage(@use_storage) : get_storage end # Returns an instancethe storage corresponding to the storage_string if it is given, # or of the default storage otherwise. # The storage string can be a storage url (see #Storage.get_storage), or a named storage # defined in configuration #-- # Mixin! def self.get_storage(storage_string='default') storage_regexp = /([\w\d]+?):(.+)/ orig_string = nil if (storage_string !~ storage_regexp) orig_string = storage_string storage_conf = Spider.conf.get('storages')[storage_string] storage_string = storage_conf['url'] if storage_conf if (!storage_string || storage_string !~ storage_regexp) raise ModelException, "No storage '#{orig_string}' found" end end type, url = $1, $2 storage = Storage.get_storage(type, url) storage.instance_name = orig_string storage.configure(storage_conf) if storage_conf return storage end # Returns an instance of the default mapper for the class. def self.mapper @mapper ||= get_mapper(storage) end # Returns an instance of the mapper for the given storage def self.get_mapper(storage) # map_class = self.attributes[:inherit_storage] ? superclass : self mapper = storage.get_mapper(self) if (@mapper_modules) @mapper_modules.each{ |mod| mapper.extend(mod) } end if (@mapper_modules_for) @mapper_modules_for.each do |params, mod| if params.is_a?(String) mapper.extend(mod) if self.use_storage == params end end end if (@mapper_procs) @mapper_procs.each{ |proc| mapper.instance_eval(&proc) } end if (@mapper_procs_for) @mapper_procs_for.each do |params, proc| if (params.length == 1 && params[0].class == String) mapper.instance_eval(&proc) if (self.use_storage == params[0]) end end end if (@mapper_procs_subclass) @mapper_procs_subclass.each{ |proc| mapper.instance_eval(&proc) } end return mapper end # Syncs the schema with the storage. def self.sync_schema(options={}) options = ({ :force => false, :drop_fields => false, :update_sequences => false, :no_foreign_key_constraints => true }).merge(options) Spider::Model.sync_schema(self, options[:force], options) end # Executes #self.where, and calls QuerySet#load on the result. # Returns nil if the result is empty, the QuerySet otherwise # See #self.where for parameter syntax def self.find(*params, &proc) qs = self.where(*params, &proc) return qs.empty? ? nil : qs end # Executes #self.where, returning the first result. # See #self.where for parameter syntax. def self.load(*params, &proc) qs = self.where(*params, &proc) qs.limit = 1 return qs[0] end # Returns a queryset without conditions def self.all return self.where end # Constructs a Query based on params, and returns a QuerySet # Allowed parameters are: # * a Query object # * a Condition and an (optional) Request, or anything that can be parsed by Condition.new and Request.new # If a block is provided, it is passed to Condition.parse_block. # Examples: # felines = Animals.where({:family => 'felines'}) # felines = Animals.where({:family => 'felines'}, [:name, :description]) # cool_animals = Animals.where{ (has_fangs == true) | (has_claws == true)} # See also Condition#parse_block def self.where(*params, &proc) if (params[0] && params[0].is_a?(Query)) query = params[0] qs = QuerySet.new(self, query) elsif(proc) qs = QuerySet.new(self) qs.autoload = true qs.where(&proc) else condition = Condition.and(params[0]) request = Request.new(params[1]) query = Query.new(condition, request) qs = QuerySet.new(self, query) end return qs end # Returns the condition for a "free" text query # Examples: # condition = News.free_query_condition('animals') # animal_news = News.where(condition) def self.free_query_condition(q) c = Condition.or self.elements_array.each do |el| if (el.type == String || el.type == Text) c.set(el.name, 'ilike', '%'+q+'%') end end return c end # Returns the number of objects in storage def self.count(condition=nil) mapper.count(condition) end # Can be defined to provide functionality to this model's querysets. def self.extend_queryset(qs) end ################################################# # Instance methods # ################################################# # The constructor may take: # * an Hash of values, that will be set on the new instance; or # * a BaseModel instance; its values will be set on the new instance; or # * a single value; it will be set on the first primary key. def initialize(values=nil) @_autoload = true @_has_values = false @loaded_elements = {} @modified_elements = {} @value_observers = nil @all_values_observers = nil @_extra = {} @model = self.class @_primary_keys_set = false set_values(values) if values # if primary_keys_set? # @_primary_keys_set = true # if Spider::Model.identity_mapper # Spider::Model.identity_mapper.put(self, true) # else # Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work # end # else # #nil # end end # Returns an instance of the Model with #autoload set to false def self.static(values=nil) obj = self.new obj.autoload = false obj.set_values(values) if values return obj end def self.create(values) obj = self.static(values) obj.insert return obj end def self.get(values) return self.new(values) unless Spider::Model.identity_mapper values = [values] unless values.is_a?(Hash) || values.is_a?(Array) if values.is_a?(Array) vals = {} self.primary_keys.each_with_index do |k, i| vals[k.name] = values[i] end values = vals end curr = Spider::Model.identity_mapper.get(self, values) return curr if curr obj = self.new(values) Spider::Model.identity_mapper.put(obj) obj end def set_values(values) if (values.is_a? Hash) values.keys.select{ |k| k = k.name if k.is_a?(Element) self.class.elements[k.to_sym] && self.class.elements[k.to_sym].primary_key? }.each do |k| set!(k, values[k]) end values.each do |key, val| set!(key, val) end elsif (values.is_a? BaseModel) values.each_val do |name, val| set(name, val) if self.class.has_element?(name) end elsif (values.is_a? Array) self.class.primary_keys.each_index do |i| set(self.class.primary_keys[i], values[i]) end # Single unset key, single value elsif ((empty_keys = self.class.primary_keys.select{ |key| !element_has_value?(key) }).length == 1) set(empty_keys[0], values) else raise ArgumentError, "Don't know how to construct a #{self.class} from #{values.inspect}" end end # Returns the instance's IdentityMapper def identity_mapper return Spider::Model.identity_mapper if Spider::Model.identity_mapper @identity_mapper ||= IdentityMapper.new end # Sets the instance's IdentityMapper. def identity_mapper=(im) @identity_mapper = im end # Returns a new instance for given element name. def instantiate_element(name) element = self.class.elements[name] if (element.model?) if (element.multiple?) val = QuerySet.static(element.model) else val = element.type.new val.autoload = autoload? end end val = prepare_child(name, val) instance_variable_set("@#{name}", val) set_reverse(element, val) if element.model? val end # Prepares an object that is being set as a child. def prepare_child(name, obj) return obj if obj.nil? element = self.class.elements[name] if (element.model?) # convert between junction and real type if needed if element.attributes[:junction] if obj.is_a?(QuerySet) obj.no_autoload do if (element.attributes[:keep_junction] && obj.model == element.type) qs = QuerySet.new(element.model) obj.each{ |el_obj| qs << {element.reverse => self, element.attributes[:junction_their_element] => el_obj} } obj = qs elsif (!element.attributes[:keep_junction] && obj.model == element.model) instance_variable_set("@#{element.name}_junction", obj) qs = QuerySet.new(element.type, obj.map{ |el_obj| el_obj.get(element.attributes[:junction_their_element])}) obj = qs end end else if (!element.attributes[:keep_junction] && obj.class == element.model) obj = obj.get(element.attributes[:junction_their_element]) end end end self.class.elements_array.select{ |el| el.attributes[:fixed] }.each do |el| if el.integrated_from == element obj.set(el.integrated_from_element, el.attributes[:fixed]) end end obj.identity_mapper = self.identity_mapper if obj.respond_to?(:identity_mapper) if (element.multiple? && element.attributes[:junction] && element.attributes[:keep_junction]) obj.append_element = element.attributes[:junction_their_element] end if (element.attributes[:set] && element.attributes[:set].is_a?(Hash)) element.attributes[:set].each{ |k, v| obj.set(k, v) } obj.reset_modified_elements(*element.attributes[:set].keys) # FIXME: is it always ok to not set the element as modified? But otherwise sub objects # are always saved (and that's definitely no good) end if element.type == self.class.superclass && self.class.extended_models[element.type] && self.class.extended_models[element.type] == element.name obj._subclass_object = self end else obj = prepare_value(element, obj) end return obj end # Returns all children that can be reached from the current path. # Path is expressed as a dotted String. def all_children(path) children = [] no_autoload do el = path.shift if self.class.elements[el] && element_has_value?(el) && children = get(el) if path.length >= 1 children = children.all_children(path) end end end return children end # Sets the object currently containing this one (BaseModel or QuerySet) def set_parent(obj, element) @_parent = obj @_parent_element = element end def set_reverse(element, obj) return unless element.model? && obj if element.has_single_reverse? && (!element.attributes[:junction] || element.attributes[:keep_junction]) unless element.multiple? val = obj.get_no_load(element.reverse) return if val && val.object_id == self.object_id end obj.set(element.reverse, self) end end ################################################# # Get and set # ################################################# # Returns an element. # The element may be a symbol, or a dotted path String. # Will call the associated getter. # cat.get('favorite_food.name') def get(element) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) sub_val = send(first) return nil unless sub_val return sub_val.get(rest) end return send(element) end # Returns an element without autoloading it. def get_no_load(element) res = nil no_autoload do res = get(element) end return res end # Sets an element. # The element can be a symbol, or a dotted path String. # Will call the associated setter. # cat.set('favorite_food.name', 'Salmon') def set(element, value, options={}) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) first_val = send(first) unless first_val if (options[:instantiate]) first_val = instantiate_element(first.to_sym) set(first, first_val) else raise "Element #{first} is nil, can't set #{element}" end end return first_val.set(rest, value, options) end return send("#{element}=", value) end # Sets an element, instantiating intermediate objects if needed def set!(element, value, options={}) options[:instantiate] = true set(element, value, options) end # Calls #get on element; whenever no getter responds, returns the extra data. # See #[]= def [](element) element = element.name if element.is_a?(Element) begin get(element) rescue NoMethodError return @_extra[element] end end # If element is a model's element, calls #set. # Otherwise, stores the value in an "extra" hash, where it will be accessible by #[] def []=(element, value) element = element.name if element.is_a?(Element) if (self.class.elements[element]) set(element, value) else @_extra[element] = value end end # Sets each value of a Hash. def set_hash(hash) hash.each { |key, val| set(key, val) } end # Prepares a value going to be set on the object. Will convert the value to the # appropriate type. def self.prepare_value(element, value) element = self.class.elements[element] unless element.is_a?(Element) if (element.type < Spider::DataType) value = element.type.from_value(value) unless value.is_a?(element.type) if value element.type.take_attributes.each do |a| if element.attributes[a].is_a?(Proc) value.attributes[a] = value.instance_eval(&element.attributes[a]) else value.attributes[a] = element.attributes[a] end end value = value.prepare end elsif element.model? value.autoload(autoload?, true) if value && value.respond_to?(:autolad) else case element.type.name when 'Date', 'DateTime' return nil if value.is_a?(String) && value.empty? parsed = nil if (value.is_a?(String)) begin parsed = element.type.strptime(value, "%Y-%m-%dT%H:%M:%S") rescue parsed = nil parsed ||= element.type.lparse(value, :short) rescue parsed = nil parsed ||= element.type.parse(value) rescue ArgumentError => exc raise FormatError.new(element, value, _("'%s' is not a valid date")) end value = parsed end when 'String' when 'Spider::DataTypes::Text' value = value.to_s when 'Fixnum' value = value.to_i end end value end def prepare_value(element, value) self.class.prepare_value(element, value) end # Sets a value without calling the associated setter; used by the mapper. def set_loaded_value(element, value, mark_loaded=true) element_name = element.is_a?(Element) ? element.name : element element = self.class.elements[element_name] if (element.integrated?) get(element.integrated_from).set_loaded_value(element.integrated_from_element, value) else value = prepare_child(element.name, value) current = instance_variable_get("@#{element_name}") current.set_parent(nil, nil) if current && current.is_a?(BaseModel) value.set_parent(self, element.name) if value.is_a?(BaseModel) instance_variable_set("@#{element_name}", value) end value.loaded = true if (value.is_a?(QuerySet)) element_loaded(element_name) if mark_loaded set_reverse(element, value) if element.model? @modified_elements[element_name] = false end # Records that the element has been loaded. def element_loaded(element_name) element_name = self.class.get_element(element_name).name @loaded_elements[element_name] = true end # Returns true if the element has been loaded by the mapper. def element_loaded?(element) element = self.class.get_element(element).name return @loaded_elements[element] end # Apply element checks for given element name and value. (See also #element, :check attribute). # Checks may be defined by the DataType, or be given as an element attribute. # The check can be a Regexp, that will be checked against the value, or a Proc, which is expected to # return true if the check is succesful, and false otherwise. # Will raise a Model::FormatError when a check is not succesful. # If the :check attribute is an Hash, the Hash keys will be used as messages, which will be passed # to the FormatError. def _check(name, val) element = self.class.elements[name] element.type.check(val) if (element.type.respond_to?(:check)) if (checks = element.attributes[:check]) checks = {(_("'%s' is not in the correct format") % element.label) => checks} unless checks.is_a?(Hash) checks.each do |msg, check| test = case check when Regexp val == nil || val.empty? ? true : check.match(val) when Proc check.call(val) end raise FormatError.new(element, val, msg) unless test end end end # Converts the object to the instance of a subclass for which this model is polymorphic. def polymorphic_become(model) return self if self.is_a?(model) unless self.class.polymorphic_models && self.class.polymorphic_models[model] sup = model.superclass while sup < Spider::Model::BaseModel && !self.class.polymorphic_models[sup] sup = sup.superclass end raise ModelException, "#{self.class} is not polymorphic for #{model}" unless self.class.polymorphic_models[sup] sup_poly = polymorphic_become(sup) return sup_poly.polymorphic_become(model) end el = self.class.polymorphic_models[model][:through] obj = model.new(el => self) obj = Spider::Model.identity_mapper.get(obj) if Spider::Model.identity_mapper obj.element_loaded(el) return obj end def become(model) return self if self.class == model obj = polymorphic_become(model) rescue ModelException return obj end # Converts the object to the instance of a subclass. This will instantiate the model # passed as an argument, and set each value of the current object on the new one. # No checks are made that this makes sense, so the method will fail if the "subclass" does # not contain all of the current model's elements. def subclass(model) obj = model.new self.class.elements_array.each do |el| obj.set(el, self.get(el)) if element_has_value?(el) && model.elements[el.name] end return obj end # Returns the current autoload status def autoload? @_autoload end # Enables or disables autoloading. # An autoloading object will try to load all missing elements on first access. # (see also Element#lazy_groups) def autoload=(val) autoload(val, false) end # Sets autoload mode # The first parameter the value of autoload to be set; it can be true, false or :save_mode (see #save_mode)) # the second bool parameter specifies if the value should be propagated on all child objects. def autoload(a, traverse=true) #:nodoc: return if @_tmp_autoload_walk @_tmp_autoload_walk = true @_autoload = a if (traverse) self.class.elements_array.select{ |el| el.model? && \ (element_has_value?(el.name) || el.attributes[:extended_model])}.each do |el| val = get(el) val.autoload = a if val.respond_to?(:autoload=) end end @_tmp_autoload_walk = nil end # Disables autoload. # If a block is given, the current autoload setting will be restored after yielding. def no_autoload prev_autoload = autoload? self.autoload = false if block_given? yield self.autoload = prev_autoload end return prev_autoload end # Sets autoload to :save_mode; elements will be autoloaded only one by one, so that # any already set data will not be overwritten # If a block is given, the current autoload setting will be restored after yielding. def save_mode prev_autoload = autoload? self.autoload = :save_mode if (block_given?) yield self.autoload = prev_autoload end return prev_autoload end ############################################################## # Methods for getting information about element values # ############################################################## # Returns true if other is_a?(self.class), and has the same values for this class' primary keys. def ==(other) return false unless other return false unless other.is_a?(self.class) self.class.primary_keys.each do |k| return false unless get(k) == other.get(k) end return true end ############################################################## # Iterators # ############################################################## # Iterates over elements and yields name-value pairs def each # :yields: element_name, element_value self.class.elements.each do |name, el| yield name, get(name) end end # Iterates over non-nil elements, yielding name-value pairs def each_val # :yields: element_name, element_value self.class.elements.select{ |name, el| element_has_value?(name) }.each do |name, el| yield name, get(name) end end # Returns an array of current primary key values def primary_keys self.class.primary_keys.map{ |k| val = get(k) k.model? && val ? val.primary_keys : val } end # Returns an hash of primary keys names and values def primary_keys_hash h = {} self.class.primary_keys.each{ |k| h[k.name] = get(k) } h end # Returns a string with the primary keys joined by ',' def keys_string self.class.primary_keys.map{ |pk| self.get(pk) }.join(',') end # Returns true if the element instance variable is set #-- # FIXME: should probably try to get away without this method # it is the only method that relies on the mapper def element_has_value?(element) element = self.class.get_element(element) if (element.integrated?) return false unless obj = instance_variable_get(:"@#{element.integrated_from.name}") return obj.element_has_value?(element.integrated_from_element) end if (element.attributes[:computed_from]) element.attributes[:computed_from].each{ |el| return false unless element_has_value?(el) } return true end ivar = nil ivar = instance_variable_get(:"@#{element.name}") if instance_variable_defined?(:"@#{element.name}") return nil == ivar ? false : true # FIXME: is this needed? # if (!mapper.mapped?(element) # return send("#{element_name}?") if (respond_to?("#{element_name}?")) # return get(element) == nil ? false : true if (!mapper.mapped?(element)) # end end # Returns true if the element value has been modified since instantiating or loading def element_modified?(element) element = self.class.get_element(element) set_mod = @modified_elements[element.name] return set_mod if set_mod if (element.integrated?) return false unless integrated = get_no_load(element.integrated_from) return integrated.element_modified?(element.integrated_from_element) end if element_has_value?(element) && (val = get(element)).respond_to?(:modified?) return val.modified? end return false end # Returns true if any of elements has been modified def elements_modified?(*elements) elements = elements[0] if elements[0].is_a?(Array) elements.each{ |el| return true if element_modified?(el) } return false end # Returns true if any element, or any child object, has been modified def modified? return true unless @modified_elements.reject{ |key, val| !val }.empty? self.class.elements_array.select{ |el| !el.model? && element_has_value?(el) && el.type.is_a?(Spider::DataType) }.each do |el| return true if get(el).modified? end return false end def in_storage? return false unless primary_keys_set? return self.class.load(primary_keys_hash) end # Given elements are set as modified def set_modified(request) #:nodoc: request.each do |key, val| # FIXME: go deep @modified_elements[key] = true end end # Resets modified elements def reset_modified_elements(*elements) #:nodoc: if (elements.length > 0) elements.each{ |el_name| @modified_elements.delete(el_name) } else @modified_elements = {} end end # Returns true if all primary keys have a value; false if some primary key # is not set or the model has no primary key def primary_keys_set? primary_keys = self.class.primary_keys return false unless primary_keys.length > 0 primary_keys.each do |el| if (el.integrated?) return false unless (int_obj = instance_variable_get(:"@#{el.integrated_from.name}")) #return false unless int_obj.instance_variable_get(:"@#{el.integrated_from_element}") return false unless int_obj.element_has_value?(el.integrated_from_element) else return false unless self.instance_variable_get(:"@#{el.name}") end end return true end # Returns true if no element has a value def empty? return @_has_values end # Sets all values of obj on the current object def merge!(obj, only=nil) return self if obj.object_id == self.object_id obj.class.elements_array.select{ |el| (only || obj.element_has_value?(el)) && !el.integrated? && !el.attributes[:computed_from] }.each do |el| next if only && !only.key?(el.name) val = obj.element_has_value?(el.name) ? obj.get_no_load(el) : nil our_val = self.element_has_value?(el.name) ? self.get_no_load(el) : nil next if our_val == val if el.model? && only && only[el.name].is_a?(Hash) && our_val \ && val.is_a?(BaseModel) && our_val.is_a?(BaseModel) val = our_val.merge!(val, only[el.name]) else Spider.logger.warn("Element #{el.name} overwritten in #{obj.inspect}") if our_val && our_val != val end set_loaded_value(el, val, false) unless val.nil? && element.multiple? end self end def merge_hash(h) h.each do |k, v| self.set(k.to_sym, v) end end # Returns a deep copy of the object def clone obj = self.class.new obj.merge!(self) return obj end # Returns a new instance with the same primary keys def get_new obj = nil Spider::Model.no_identity_mapper do obj = self.class.new obj._no_identity_mapper = true self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } end return obj end # Returns a new static instance with the same primary keys def get_new_static obj = nil Spider::Model.no_identity_mapper do obj = self.class.static obj._no_identity_mapper = true self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } end return obj end # Returns a condition based on the current primary keys def keys_to_condition c = Condition.and self.class.primary_keys.each do |key| val = get(key) if (key.model?) c[key.name] = val.keys_to_condition else c[key.name] = val end end return c end ################################################# # Object observers methods # ################################################# # The given block will be called whenever a value is modified. # The block will be passed three arguments: the object, the element name, and the previous value # Example: # obj.observe_all_values do |instance, element_name, old_val| # puts "#{element_name} for object #{instance} has changed from #{old_val} to #{instance.get(element_name) }" def observe_all_values(&proc) @all_values_observers ||= [] @all_values_observers << proc end def observe_element(element_name, &proc) @value_observers ||= {} @value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.observer_all_values(&proc) self.all_values_observers << proc end def self.observe_element(element_name, &proc) self.value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.value_observers @value_observers ||= {} end def self.all_values_observers @all_values_observers ||= [] end # Calls the observers for element_name def notify_observers(element_name, new_val) #:nodoc: if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(self, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(self, element_name, new_val) } end self.class.notify_observers(element_name, new_val, self) end # Calls the observers for element_name def self.notify_observers(element_name, new_val, obj=nil) if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(obj, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(obj, element_name, new_val) } end end ############################################################## # Storage, mapper and schema loading (instance methods) # ############################################################## # Returns the current @storage, or instantiates the default calling Spider::BaseModel.storage def storage return @storage || self.class.storage end # Instantiates the storage for the instance. # Accepts a string (url or named storage) which will be passed to Spider::BaseModel.get_storage # Example: # obj.use_storage('my_named_db') # obj.use_storage('db:oracle://username:password@XE') def use_storage(storage) @storage = self.class.get_storage(storage) @mapper = self.class.get_mapper(@storage) end # Returns the current mapper, or instantiates a new one (base on the current storage, if set) def mapper @storage ||= nil if (@storage) @mapper ||= self.class.get_mapper(@storage) else @mapper ||= self.class.mapper end return @mapper end # Sets the current mapper def mapper=(mapper) @mapper = mapper end ############################################################## # Saving and loading from storage methods # ############################################################## # Saves the object to the storage # (see Mapper#save) def save if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless unit_of_work_available? if unit_of_work_available? Spider.current[:unit_of_work].add(self) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else save! end end self end def save! mapper.save(self) self end # Saves the object and all child objects to the storage # (see Mapper#save_all) def save_all mapper.save_all(self) self end def insert if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless unit_of_work_available? if unit_of_work_available? Spider.current[:unit_of_work].add(self, :save, :force => :insert) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else insert! end end self end def unit_of_work_available? Spider.current[:unit_of_work] && !Spider.current[:unit_of_work].running? end # Inserts the object in the storage # Note: if the object is already present in the storage and unique indexes are enforced, # this will raise an error. # (See Mapper#insert). def insert! mapper.insert(self) reset_modified_elements end # Updates the object in the storage # Note: the update will silently fail if the object is not present in the storage # (see Mapper#update). def update mapper.update(self) reset_modified_elements end # Deletes the object from the storage # (see Mapper#delete). def delete if @unit_of_work @unit_of_work.add(self, :delete) return end before_delete unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self, :delete) if @unit_of_work @unit_of_work.commit @unit_of_work.stop if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else delete! end end def delete! mapper.delete(self) end def before_delete end def before_save end def use_unit_of_work had_uow = true unless Spider.current[:unit_of_work] had_wow = false @unit_of_work = Spider::Model.start_unit_of_work end unless Spider::Model.identity_mapper @uow_identity_mapper = Spider::Model::IdentityMapper.new Spider.current[:identity_mapper] = @uow_identity_mapper @uow_identity_mapper.put(self) if self.primary_keys_set? end # Spider.current[:unit_of_work].add(self) Spider.current[:unit_of_work] return had_uow end # Loads the object from the storage # Acceptable arguments are: # * a Query object, or # * a Request object, or a Hash, which will be converted to a Request, or # * a list of elements to request # It will then construct a Condition with current primary keys, and call Mapper#load # Note that an error will be raised by the Mapper if not all primary keys are set. def load(*params) if (params[0].is_a? Query) query = params[0] else return false unless primary_keys_set? query = Query.new if (params[0].is_a?(Request)) query.request = params.shift elsif (params[0].is_a?(Hash)) query.request = Request.new(params.shift) end elements = params.length > 0 ? params : self.class.elements.keys return true unless elements.select{ |el| !element_loaded?(el) }.length > 0 elements.each do |name| query.request[name] = true end query.condition.conjunction = :and self.class.primary_keys.each do |key| query.condition[key.name] = get(key.name) end end #clear_values() return mapper.load(self, query) end # Sets all values to nil def clear_values() self.class.elements.each_key do |element_name| instance_variable_set(:"@#{element_name}", nil) end end def remove_association(element, object) mapper.delete_element_associations(self, element, object) end # Method that will be called by the mapper before a query. May be overridden to preprocess the query. # Must return the modified query. Note: to prepare conditions, use prepare_condition, since it will # be called on subconditions as well. def self.prepare_query(query) query end ############################################################## # Method missing # ############################################################## # Tries the method on integrated models def method_missing(method, *args) #:nodoc: # UNUSED # case method.to_s # when /load_by_(.+)/ # element = $1 # if !self.class.elements[element.to_sym].attributes[:primary_key] # raise ModelException, "load_by_ called for element #{element} which is not a primary key" # elsif self.class.primary_keys.length > 1 # raise ModelException, "can't call #{method} because #{element} is not the only primary key" # end # query = Query.new # query.condition[element.to_sym] = args[0] # load(query) # else if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| obj = send(name) if (obj.respond_to?(method)) return obj.send(method, *args) end end end raise NoMethodError, "undefined method `#{method}' for #{self.class}" #super # end end def respond_to?(symbol, include_private=false) return true if super if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| if (model.method_defined?(symbol)) return true end end end return false end # Returns a descriptive string for the object. # By default this method returns the value of the first String element, if any; otherwise, # the string representation of the first element of any type. # Descendant classes may well provide a better representation. def to_s desc_elements = self.class.elements_array.select{ |el| el.attributes[:desc] } unless desc_elements.empty? return desc_elements.sort{ |a, b| ad = a.attributes[:desc]; bd = b.attributes[:desc] if ad == true && bd == true 0 elsif bd == true -1 elsif ad == true 1 else ad <=> bd end }.map{ |el| self.get(el).to_s }.join(' ') end self.class.each_element do |el| if ((el.type == String || el.type == Text) && !el.primary_key?) v = get(el) return v ? v.to_s : '' end end el = self.class.elements_array[0] if element_has_value?(el) v = get(el) return v ? v.to_s : '' end return '' end # A compact representation of the object. # Note: inspect will not autoload the object. def inspect self.class.name+': {' + self.class.elements_array.select{ |el| (element_loaded?(el) || element_has_value?(el)) && !el.hidden? } \ .map{ |el| ":#{el.name} => #{get(el.name).to_s}"}.join(',') + '}' end # Returns a JSON representation of the object. # # The tree will be traversed outputting all encountered objects; when an already seen object # is met, the primary keys will be output (as a single value if one, as an array if many) and traversing # will stop. # # For more fine-grained control of the output, it is better to use the #cut method and call to_json on it. def to_json(state=nil, &proc) require 'json' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') if (@tmp_json_seen && !block_given?) pks = self.class.primary_keys.map{ |k| get(k).to_json } pks = pks[0] if pks.length == 1 return pks.to_json end @tmp_json_seen = true json = "" #Spider::Model.with_identity_mapper do |im| self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", true) end if (block_given?) select_elements = Proc.new{ true } else select_elements = Proc.new{ |name, el| !el.hidden? # && # #!el.attributes[:integrated_model] && # (element_has_value?(el) || (el.integrated? && element_has_value?(el.integrated_from))) } end json = "{" + self.class.elements.select(&select_elements).map{ |name, el| if (block_given?) val = yield(self, el) val ? "#{name.to_json}: #{val.to_json}" : nil else val = get(name) if (el.type == 'text' || el.type == 'longText') val = ic.iconv(val + ' ')[0..-2] end val = val.to_json "#{name.to_json}: #{val}" end }.select{ |pair| pair}.join(',') + "}" @tmp_json_seen = false self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", false) end #end return json end # Returns a part of the object tree, converted to Hashes, Arrays and Strings. # Arguments can be: # * a String, followed by a list of elements; the String will be sprintf'd with element values # or # * a depth Fixnum; depth 0 means obj.to_s will be returned, depth 1 will return an hash containing the # object's element values converted to string, and so on # or # * a Hash, whith element names as keys, and depths, or Hashes, or Procs as values; each element # will be traversed up to the depth given, or recursively according to the has; or, if a Proc is given, # it will be called with the current object and element name as arguments # or # * a list of elements; this is equivalent to passing a hash of the elements with depth 0. # # Examples: # obj.inspect # => Zoo::Animal: {:name => Llama, :family => Camelidae, :friends => Sheep, Camel} # obj.cut(0) # => 'Llama' # obj.cut(:name, :friends) # => {:name => 'Llama', :friends => 'Sheep, Camel'} # obj.cut(:name => 0, :friends => 1) # => {:name => 'Llama', :friends => [ # {:name => 'Sheep', :family => 'Bovidae', :friends => 'Llama'}, # {:name => 'Camel', :family => 'Camelidae', :friens => 'Dromedary, LLama'} # ]} # obj.cut(:name => 0, :friends => {:name => 0}) # => {:name => 'Llama', :friends => [{:name => 'Sheep'}, {:name => 'Camel'}]} # objs.cut(:name => 0, :friends => lambda{ |instance, element| # instance.get(element).name.upcase # }) # => {:name => 'Llama', :friends => ['SHEEP', 'CAMEL']} # obj.cut("Hi, i'm a %s and my friends are %s", :name, :friends) # => "Hi, i'm a Llama and my friends are Sheep, Camel" def cut(*params, &proc) h = {} if (params[0].is_a?(String)) return sprintf(params[0], *params[1..-1].map{ |el| get(el) }) elsif (params[0].is_a?(Fixnum)) p = params.shift if (p < 1) if (block_given?) return proc.call(self) else return self.to_s end end lev = p where = {} self.class.elements_array.each { |el| where[el.name] = lev-1} end if (params[0].is_a?(Hash)) where ||= {} params[0].each{ |k, v| where[k.to_sym] = v} else where ||= {} params.each{ |p| where[p] = 0 if p.is_a?(Symbol)} end Spider::Model.with_identity_mapper do |im| where.keys.each do |name| next unless where[name] if (where[name].is_a?(Proc)) val = where[name].call(self, name) else el = self.class.elements[name] if el val = get(el) val = val.cut(where[name], &proc) if el.model? && val else raise ModelException, "Element #{name} does not exist" unless self.respond_to?(name) val = self.send(name) val = val.cut(where[name], &proc) if val.is_a?(BaseModel) end end h[name] = val end end return h end # Returns a element_name => value Hash def to_hash() h = {} self.class.elements.select{ |name, el| element_loaded? el }.each do |name, el| h[name] = get(name) end return h end # Returns a yaml representation of the object. Will try to autoload all elements, unless autoload is false; # foreign keys will be expressed as an array if multiple, as a single primary key value otherwise def to_yaml(params={}) require 'yaml' return YAML::dump(to_yaml_h(params)) end def to_yaml_h(params={}) h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next if params[:except] && params[:except].include?(el.name) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else h[el.name] = get(el) end end h end def self.from_yaml(yaml) h = YAML::load(yaml) obj = self.static h.each do |key, value| el = elements[key.to_sym] if (el.multiple?) el_obj = el.model.static el.model.primary_keys.each do |pk| el_obj.set(pk, value.unshift) end obj.set(el, el_obj) else obj.set(el, value) end end return obj end def dump_to_hash h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next unless mapper.have_references?(el) || (el.junction? && el.model.attributes[:sub_model] == self.class) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else val = get(el) if val case val.class.name.to_sym when :Date, :DateTime, :Time val = val.strftime end end h[el.name] = val end end h end def dump_to_all_data_hash(options={}, h={}, seen={}) Spider::Model.with_identity_mapper do |im| clname = self.class.name.to_sym seen[clname] ||= {} return if seen[clname][self.primary_keys] seen[clname][self.primary_keys] = true h[clname] ||= [] h[clname] << self.dump_to_hash self.class.elements_array.each do |el| next unless el.model? next if el.model < Spider::Model::InlineModel next if options[:models] && !options[:models].include?(el.type) next if options[:except_models] && options[:except_models].include?(el.type) el_clname == el.type.name.to_sym next if options[:elements] && (options[:elements][el_clname] && !options[:elements][el_clname].include?(el.name)) next if options[:except_elements] && (options[:except_elements][el_clname] && options[:except_elements][el_clname].include?(el.name)) val = self.get(el) next unless val val = [val] unless val.is_a?(Enumerable) val.each do |v| v.dump_to_all_data_hash(options, h, seen) end end end h end def self.in_transaction self.storage.in_transaction yield self.storage.commit_or_continue end def self.dump_element(el) remove_elements = [] method = case el.attributes[:association] when :many :many when :choice :choice when :multiple_choice :multiple_choice when :tree :tree else :element end type = el.type attributes = el.attributes.clone if (method == :many || method == :multiple_choice) attributes.delete(:multiple) end attributes.delete(:association) if method != :element if (attributes[:association_type]) attributes[:through] = attributes[:association_type] unless attributes[:anonymous_model] attributes.delete(:association_type) end attributes.delete(:lazy) if attributes[:lazy] == :default if (method == :tree) delete_attrs = [:queryset_module, :multiple] delete_attrs.each{ |a| attributes.delete(a) } remove_elements += [attributes[:reverse], attributes[:tree_left], attributes[:tree_right], attributes[:tree_depth]] type = nil end return { :name => el.name, :type => type, :attributes => attributes, :method => method, :remove_elements => remove_elements } end def self.prepare_to_code modules = self.name.split('::')[0..-2] included = (self.included_modules - Spider::Model::BaseModel.included_modules).select do |m| m.name !~ /^#{Regexp.quote(self.name)}/ end local_name = self.name.split('::')[-1] superklass = self.superclass.name elements = [] remove_elements = [] self.elements_array.each do |el| next if el.integrated? next if (el.reverse && el.model.elements[el.reverse] && \ (el.model.elements[el.reverse].attributes[:add_reverse] || \ el.model.elements[el.reverse].attributes[:add_multiple_reverse])) el_hash = dump_element(el) return nil unless el_hash elements << el_hash remove_elements += el_hash[:remove_elements] end elements.reject!{ |el| remove_elements.include?(el[:name]) } return { :modules => modules, :included => included, :attributes => self.attributes, :elements => elements, :local_name => local_name, :superclass => superklass, :use_storage => @use_storage, :additional_code => [] } end def self.to_code(options={}) c = prepare_to_code str = "" indent = 0 append = lambda do |val| str += " "*indent str += val str end str += c[:modules].map{ |m| "module #{m}" }.join('; ') + "\n" str += "\n" indent = 4 append.call "class #{c[:local_name]} < #{c[:superclass]}\n" indent += 4 c[:included].each do |i| append.call "include #{i.name}\n" end c[:attributes].each do |k, v| append.call "attribute :#{k}, #{v.inspect}" end str += "\n" c[:elements].each do |el| append.call("#{el[:method].to_s} #{el[:name].inspect}") str += ", #{el[:type]}" if el[:type] str += ", #{el[:attributes].inspect[1..-2]}\n" if el[:attributes] && !el[:attributes].empty? end str += "\n" append.call "use_storage '#{c[:use_storage]}'\n" if c[:use_storage] c[:additional_code].each do |block| block.each_line do |line| append.call line end str += "\n" end indent -= 4 append.call("end\n") str += c[:modules].map{ "end" }.join(';') return str end end end; end Added BaseModel.from_hash_dump require 'spiderfw/model/mixins/state_machine' require 'spiderfw/model/element' require 'spiderfw/model/integrated_element' require 'iconv' module Spider; module Model # The main class for interacting with data. # When not dealing with legacy storages, subclasses should use Managed instead, which provides an id and # other conveniences. # # Each BaseModel subclass defines a model; instances can be used as "data objects": # they will interact with the Mapper loading and saving the values associated with the BaseModel's defined elements. # # Each element defines an instance variable, a getter and a setter. If the instance is set to #autoload, # when a getter is first called the mapper will fetch the value from the Storage . # # Elements can be of one of the base types (Spider::Model.base_types), of a DataType, or other models. In the last # case, they define a relationship between models. # # Basic usage: # model Food < BaseModel # element :name, String # end # model Animal < BaseModel # element :name, String # many :friends, Animal # choice :favorite_food, Food # end # # salmon = Food.new(:name => 'Salmon') # salmon.save # cat = Animal.new(:name => 'Cat', :favorite_food = salmon) # weasel = Animal.new(:name => 'Weasel', :friends => [cat]) # weasel.save # cat.friends << weasel # cat.save # # wizzy = Animal.load(:name => 'Weasel') # p wizzy.friends # => 'Cat' # p wizzy.friends[0].favorite_food # => 'Salmon' # # bear = Animal.new(:name => 'Bear', :favorite_food = salmon) # bear.save # salmon_lovers = Animal.where{ favorite_food == salmon } # p salmon_lovers.length # => 2 # p salmon_lovers[0].name # => 'Cat' class BaseModel include Spider::Logger include DataTypes include Spider::QueryFuncs include EventSource # include StateMachine # The BaseModel class itself. Used when dealing with proxy objects. attr_reader :model # An Hash of loaded elements attr_reader :loaded_elements # Model instance or QuerySet containing the object attr_accessor :_parent # If _parent is a model instance, which element points to this one attr_accessor :_parent_element # If this object is used as a superclass in class_table_inheritance, points to the current subclass attr_accessor :_subclass_object # This object won't be put into the identity mapper attr_accessor :_no_identity_mapper class <<self # An Hash of model attributes. They can be used freely. attr_reader :attributes # An array of element names, in definition order. attr_reader :elements_order # An Hash of integrated models => corresponding integrated element name. attr_reader :integrated_models # An Hash of polymorphic models => polymorphic params attr_reader :polymorphic_models # An Array of named sequences. attr_reader :sequences end # Copies this class' elements to the subclass. def self.inherited(subclass) #:nodoc: # FIXME: might need to clone every element @subclasses ||= [] @subclasses << subclass each_element do |el| subclass.add_element(el.clone) unless el.attributes[:local_pk] end subclass.instance_variable_set("@mapper_procs_subclass", @mapper_procs_subclass.clone) if @mapper_procs_subclass subclass.instance_variable_set("@mapper_modules", @mapper_modules.clone) if @mapper_modules subclass.instance_variable_set("@extended_models", @extended_models.clone) if @extended_models em = subclass.const_set(:ElementMethods, Module.new) subclass.send(:include, em) super end def self.subclasses @subclasses || [] end # Returns the parent Spider::App of the module def self.app return @app if @app app = self while (!app.include?(Spider::App)) app = app.parent_module end @app = app end ####################################### # Model definition methods # ####################################### # Defines an element. # Arguments are element name (a Symbol), element type, and a Hash of attributes. # # Type may be a Class: a base type (see Spider::Model.base_types), a DataType subclass, # or a BaseModel subclass; or an Array or a Hash, in which case an InlineModel will be created. # # An Element instance will be available in Model::BaseModel.elements; getter and setter methods will be defined on # the class. # # If a block is passed to this method, type will be 'extended': a custom junction association will be created, # effectively adding elements to the type only in this model's context. # Example: # class Animal < BaseModel # element :name, String # element :friends, Animal, :multiple => true do # element :how_much, String # end # end # cat = Animal.new(:name => 'Cat') # dog = Animal.new(:name => 'Dog') # cat.friends << dog # cat.friend[0].how_much = 'Not very much' # # Returns the created Element. # # Some used attributes: # :primary_key:: (bool) The element is a primary key # :length:: (number) Maximum length of the element (if meaningful) # :required:: (bool) The element must always have a value # :multiple:: (bool) defines a 1|n -> n relationship # :label:: (string) a short description, used by the UI # :association:: (symbol) A named association (such as :choice, :multiple_choice, etc.) # :lazy:: (bool, array or symbol) If true, the element will be placed in the :default lazy group; # if a symbol or an array of symbols is passed, the element will be placed in those groups. # (see Element#lazy_groups) # :reverse:: (symbol) The reverse element in the relationship to the other model # :add_reverse:: (symbol) Adds an element on the other model, and sets it as the association reverse. # :add_multiple_reverse:: (symbol) Adds a multiple element on the other model, and sets it as the association reverse. # :element_position:: (number) inserts the element at the specified position in the elements order # :auto:: (bool) Informative: the value is set automatically through some mechanism # :autoincrement:: (bool) The value (which must be a Fixnum) will be autoincremented by the mapper # :integrate:: (bool or symbol) type's elements will be available to this class # as if they were defined here (see #integrate) # :integrated_from:: (symbol) the name of the element from which this element is integrated # :integrated_from_element:: (symbol) the name of the element of the child object from which this element is integrated # :hidden:: (bool) a hint that the element shouldn't be shown by the UI # :computed_from:: (array of symbols) the element is not mapped; its value is computed # by the class from the given elements. # :unmapped:: (bool) the element is not mapped. # :sortable:: (bool or Array of symbols) specifies that an unmapped element can be used for sorting. # The model must provide a meaningful order using the prepare_query method. # :check:: (a Proc, or a Regexp, or a Hash of messages => Regexp|Proc). See #check # :through:: (a BaseModel subclass) model representing the many to many relationship. # :read_only:: (bool) hint to the UI that the element should not be user modifiable. # :owned:: (bool) only this model holds references to type # :condition:: (hash or Condition) Restricts an association always adding the condition. # :order:: (true or Fixnum) When doing queries, sort by this element. More than one element can have the # :order attribute; if it is a Fixnum, it will mean the position in the ordering. # :default:: (Proc or value) default value for the element. If it is a Proc, it will be passed # the object. # :desc:: (true or Fixnum) Use this element for the to_s string. Multiple elements # with the :desc attribute will be joined by spaces; order may be specified if # a Fixnum is used for the parameter # # Other attributes may be used by DataTypes (see #DataType::ClassMethods.take_attributes), and other code. # See also Element. def self.element(name, type, attributes={}, &proc) name = name.to_sym @elements ||= {} @elements_order ||= [] raise "Element called #{name} already exists in #{self}" if @elements[name] if type.class == Class default_attributes = case type.name when 'String' {:length => 255} else {} end else default_attributes = {} end attributes = default_attributes.merge(attributes) # if (type.class == Class && Model.base_type(type)) # type = Model.base_type(type) # els if (type.class <= Hash) type = create_inline_model(name, type, attributes) attributes[:inline] = true end if (attributes[:integrated_from]) if (attributes[:integrated_from].class == String) parts = attributes[:integrated_from].split('.') attributes[:integrated_from] = @elements[parts[0].to_sym] attributes[:integrated_from_element] = parts[1].to_sym if parts[1] elsif (attributes[:integrated_from].is_a?(Symbol)) attributes[:integrated_from] = @elements[attributes[:integrated_from]] end if (!attributes[:integrated_from_element]) attributes[:integrated_from_element] = name end end if (attributes[:condition] && !attributes[:condition].is_a?(Condition)) attributes[:condition] = Condition.new(attributes[:condition]) end if attributes[:computed_from] && !attributes[:computed_from].is_a?(Enumerable) attributes[:computed_from] = [attributes[:computed_from]] end type.set_element_attributes(attributes) if type < Spider::DataType orig_type = type assoc_type = nil if (proc || attributes[:junction] || (attributes[:multiple] && (!attributes[:add_reverse]) && (!attributes[:has_single_reverse]) && \ # FIXME! the first check is needed when the referenced class has not been parsed yet # but now it assumes that the reverse is not multiple if it is not defined (attributes[:has_single_reverse] == false || !attributes[:reverse] || (!type.elements[attributes[:reverse]] || type.elements[attributes[:reverse]].multiple?)))) attributes[:anonymous_model] = true attributes[:owned] = true unless attributes[:owned] != nil first_model = self.first_definer(name, type) assoc_type_name = Spider::Inflector.camelize(name) create_junction = true if (attributes[:through]) assoc_type = attributes[:through] create_junction = false elsif (first_model.const_defined?(assoc_type_name) ) assoc_type = first_model.const_get(assoc_type_name) if (!assoc_type.attributes[:sub_model]) # other kind of inline model assoc_type_name += 'Junction' create_junction = false if (first_model.const_defined?(assoc_type_name)) else create_junction = false end end attributes[:junction] = true attributes[:junction_id] = :id unless attributes.has_key?(:junction_id) if (attributes[:junction_our_element]) self_name = attributes[:junction_our_element] else self_name = first_model.short_name.gsub('/', '_').downcase.to_sym end attributes[:reverse] = self_name unless attributes[:junction_their_element] other_name = Spider::Inflector.underscore(orig_type.short_name == self.short_name ? orig_type.name : orig_type.short_name).gsub('/', '_').downcase.to_sym other_name = :"#{other_name}_ref" if (orig_type.elements[other_name]) attributes[:junction_their_element] = other_name end other_name = attributes[:junction_their_element] if (create_junction) assoc_type = first_model.const_set(assoc_type_name, Class.new(BaseModel)) assoc_type.attributes[:sub_model] = self assoc_type.attributes[:sub_model_element] = name assoc_type.element(attributes[:junction_id], Fixnum, :primary_key => true, :autoincrement => true, :hidden => true) if attributes[:junction_id] assoc_type.element(self_name, self, :hidden => true, :reverse => name, :association => :choice, :junction_reference => true) # FIXME: must check if reverse exists? # FIXME! fix in case of clashes with existent elements assoc_type.element(other_name, orig_type, :association => :choice, :junction_reference => true) assoc_type.integrate(other_name, :hidden => true, :no_pks => true) # FIXME: in some cases we want the integrated elements if (proc) # to be hidden, but the integrated el instead attributes[:extended] = true attributes[:keep_junction] = true assoc_type.class_eval(&proc) end end orig_type.referenced_by_junctions << [assoc_type, other_name] attributes[:keep_junction] = true if (attributes[:through] && attributes[:keep_junction] != false) attributes[:association_type] = assoc_type if attributes[:polymorph] assoc_type.elements[attributes[:junction_their_element]].attributes[:polymorph] = attributes[:polymorph] attributes.delete(:polymorph) end end add_element(Element.new(name, type, attributes)) if (attributes[:add_reverse] && attributes[:add_reverse].is_a?(Symbol)) attributes[:add_reverse] = {:name => attributes[:add_reverse]} end if (attributes[:add_multiple_reverse] && attributes[:add_multiple_reverse].is_a?(Symbol)) attributes[:add_multiple_reverse] = {:name => attributes[:add_multiple_reverse]} end if (attributes[:add_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_reverse][:name] rev = attributes[:add_reverse].merge(:reverse => name, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:keep_junction] = false rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end elsif (attributes[:add_multiple_reverse]) unless (orig_type.elements[attributes[:add_reverse]]) attributes[:reverse] ||= attributes[:add_multiple_reverse][:name] rev = attributes[:add_multiple_reverse].merge(:reverse => name, :multiple => true, :added_reverse => true, :delete_cascade => attributes[:reverse_delete_cascade]) rev_name = rev.delete(:name) if assoc_type rev[:junction] = true rev[:through] = assoc_type rev[:junction_their_element] = self_name rev[:junction_our_element] = other_name end orig_type.element(rev_name, self, rev) end end if (attributes[:lazy] == nil) # if attributes[:primary_key] # attributes[:lazy] = true # els if (type < BaseModel && (attributes[:multiple] || attributes[:polymorph])) # FIXME: we can load eagerly single relations if we can do a join attributes[:lazy] = true else attributes[:lazy_check_owner] = true if type < BaseModel attributes[:lazy] = :default end end # class element getter unless respond_to?(name) (class << self; self; end).instance_eval do define_method("#{name}") do @elements[name] end end end define_element_methods(name) attr_reader "#{name}_junction" if attributes[:junction] && !attributes[:keep_junction] if (attributes[:integrate]) integrate_params = attributes[:integrate].is_a?(Hash) ? attributes[:integrate] : {} integrate(name, integrate_params) end if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |imod, iel| imod.integrate_element(iel, self.elements[name]) unless imod.elements[name] end end if (@subclasses) @subclasses.each do |sub| next if sub.elements[name] # if subclass already defined an element with this name, don't overwrite it sub.elements[name] = @elements[name].clone sub.elements_order << name end end element_defined(@elements[name]) @elements[name].model? return @elements[name] end def self.define_element_methods(name) ivar = :"@#{ name }" unless self.const_defined?(:ElementMethods) em = self.const_set(:ElementMethods, Module.new) include em end element_methods = self.const_get(:ElementMethods) #instance variable getter element_methods.send(:define_method, name) do element = self.class.elements[name] raise "Internal error! Element method #{name} exists, but element not found" unless element return element.attributes[:fixed] if element.attributes[:fixed] if (element.integrated?) integrated = get(element.integrated_from.name) return integrated.send(element.integrated_from_element) if integrated return nil end if element_has_value?(name) || element_loaded?(name) val = instance_variable_get(ivar) val.set_parent(self, name) if val && element.model? && !val._parent # FIXME!!! return val end # Spider.logger.debug("Element not loaded #{name} (i'm #{self.class} #{self.object_id})") if autoload? && primary_keys_set? if (autoload? == :save_mode) mapper.load_element!(self, element) else mapper.load_element(self, element) end val = instance_variable_get(ivar) end if !val && element.model? && (element.multiple? || element.attributes[:extended_model]) val = instance_variable_set(ivar, instantiate_element(name)) end if !val && element.attributes[:default] if element.attributes[:default].is_a?(Proc) val = element.attributes[:default].call(self) else val = element.attributes[:default] end val = element.model.new(val) if element.model? && !val.is_a?(BaseModel) end val.set_parent(self, name) if element.model? && val && val.respond_to?(:parent) && !val._parent # FIXME!!! return val end alias_method :"#{name}?", name if self.elements[name].type <= Spider::DataTypes::Bool #instance_variable_setter element_methods.send(:define_method, "#{name}=") do |val| element = self.class.elements[name] raise "Internal error! Element method #{name}= exists, but element not found" unless element return if element.attributes[:fixed] was_loaded = element_loaded?(element) #@_autoload = false unless element.primary_key? if (element.integrated?) integrated_obj = get(element.integrated_from) unless integrated_obj integrated_obj = instantiate_element(element.integrated_from.name) set(element.integrated_from, integrated_obj) end #integrated_obj.autoload = false begin res = integrated_obj.send("#{element.integrated_from_element}=", val) rescue IdentityMapperException set(element.integrated_from, Spider::Model.get(integrated_obj)) get(element.integrated_from).merge!(integrated_obj) end if !element.primary_key? && integrated_obj.element_modified?(name) @modified_elements[name] = true end return res end if (val && element.model?) if (element.multiple?) unless (val.is_a?(QuerySet)) qs = instantiate_element(name) if (val.is_a?(Enumerable)) val.each do |row| row = element.type.new(row) unless row.is_a?(BaseModel) qs << row end else qs << val end val = qs end else val = element.model.get(val) unless val.is_a?(BaseModel) end end val = prepare_child(element.name, val) _check(name, val) notify_observers(name, val) @_has_values = true unless @_primary_keys_set if self.class.elements[element.name].primary_key? && primary_keys_set? @_primary_keys_set = true if Spider::Model.identity_mapper Spider::Model.identity_mapper.put(self, true, true) else Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work end end end old_val = instance_variable_get(ivar) @modified_elements[name] = true if !element.primary_key? && (!was_loaded || val != old_val) instance_variable_set(ivar, val) set_reverse(element, val) if element.model? if val && element.model? && !self.class.attributes[:no_type_check] klass = val.is_a?(QuerySet) ? val.model : val.class if val && !(klass <= element.type || klass <= element.model) raise TypeError, "Object #{val} (#{klass}) is of the wrong type for element #{element.name} in #{self.class} (expected #{element.model})" end end val #extend_element(name) end end def self.add_element(el) @elements ||= {} @elements[el.name] = el @elements_order ||= [] if (el.attributes[:element_position]) @elements_order.insert(el.attributes[:element_position], el.name) else @elements_order << el.name end @primary_keys ||= [] if el.attributes[:primary_key] && !@primary_keys.include?(el) @primary_keys << el end end # Removes a defined element def self.remove_element(el) return unless @elements el = el.name if el.is_a?(Element) element = @elements[el] if self.attributes[:integrated_from_elements] self.attributes[:integrated_from_elements].each do |mod, iel| i = mod.elements[el] mod.remove_element(el) if i && i.integrated? && i.integrated_from.name == iel end end self.elements_array.select{ |e| e.integrated? && e.integrated_from.name == el}.each{ |e| remove_element(e) } self.const_get(:ElementMethods).send(:remove_method, :"#{el}") rescue NameError self.const_get(:ElementMethods).send(:remove_method, :"#{el}=") rescue NameError @elements.delete(el) @elements_order.delete(el) @primary_keys.delete_if{ |pk| pk.name == el} # if (@subclasses) # @subclasses.each do |sub| # sub.remove_element(el) # end # end end def self.element_defined(el) if (@on_element_defined && @on_element_defined[el.name]) @on_element_defined[el.name].each do |proc| proc.call(el) end end end def self.on_element_defined(el_name, &proc) @on_element_defined ||= {} @on_element_defined[el_name] ||= [] @on_element_defined[el_name] << proc end # Integrates an element: any call to the child object's elements will be passed to the child. # The element must not be multiple. # Example: # class Address < BaseModel # element :street, String # element :area_code, String # end # class Person < BaseModel # element :name, String # element :address, Address # integrate :address # end # p = Person.new(...) # p.street == p.address.street def self.integrate(element_name, params={}) params ||= {} elements[element_name].attributes[:integrated_model] = true model = elements[element_name].type self.attributes[:integrated_models] ||= {} self.attributes[:integrated_models][model] = element_name params[:except] ||= [] model.each_element do |el| next if params[:except].include?(el.name) next if elements[el.name] unless params[:overwrite] # don't overwrite existing elements integrate_element(element_name, el, params) end model.attributes[:integrated_from_elements] ||= [] model.attributes[:integrated_from_elements] << [self, element_name] end def self.integrate_element(element_name, element_element, params={}) el = element_element integrated_attributes = {} integrated_attributes[:primary_key] = false if params[:no_pks] integrated_attributes[:hidden] = params[:hidden] unless (params[:hidden].nil?) integrated_attributes[:primary_key] = false unless (params[:keep_pks]) # attributes.delete(:required) # attributes.delete(:integrate) # attributes.delete(:local_pk) integrated_attributes[:local_pk] = false integrated_attributes[:lazy] = element_name name = params[:mapping] && params[:mapping][el.name] ? params[:mapping][el.name] : el.name add_element(IntegratedElement.new(name, self, element_name, el.name, integrated_attributes)) define_element_methods(name) end def self.remove_integrate(element_name) element = element_name.is_a?(Element) ? element_name : self.elements[element_name] model = element.model self.elements_array.select{ |el| el.attributes[:integrated_from] && el.attributes[:integrated_from].name == element.name }.each do |el| self.remove_element(el) end model.attributes[:integrated_from_elements].reject!{ |item| item[0] == self } end # Sets additional attributes on the element # # _Warning:_ for attributes which are parsed by the BaseModel during element definition, # this will not have the desired effect; remove and redefine the element instead. def self.element_attributes(element_name, attributes) elements[element_name].attributes = elements[element_name].attributes.merge(attributes) if attributes[:primary_key] && !@primary_keys.include?(elements[element_name]) @primary_keys << elements[element_name] elsif !attributes[:primary_key] @primary_keys.delete(elements[element_name]) end end # Defines a multiple element. Equivalent to calling # element(name, type, :multiple => true, :association => :many, ...) def self.many(name, type, attributes={}, &proc) attributes[:multiple] = true attributes[:association] ||= :many element(name, type, attributes, &proc) end # Defines an element with choice association. Shorthand for # element(name, type, :association => :choice, ...) def self.choice(name, type, attributes={}, &proc) attributes[:association] = :choice element(name, type, attributes, &proc) end # Defines a multiple element with :multiple_choice association. Shorthand for # many(name, type, :association => :multiple_choice, ...) def self.multiple_choice(name, type, attributes={}, &proc) attributes[:association] = :multiple_choice many(name, type, attributes, &proc) end def self.element_query(name, element_name, attributes={}) orig_element = self.elements[element_name] set_el_query = lambda do orig_element = self.elements[element_name] attributes = attributes.merge(orig_element.attributes) attributes[:unmapped] = true attributes[:element_query] = element_name attributes[:association] = :element_query attributes[:lazy] = true attributes.delete(:add_reverse) attributes.delete(:add_multiple_reverse) if (orig_element.attributes[:condition]) cond = orig_element.attributes[:condition].clone cond = cond.and(attributes[:condition]) if attributes[:condition] attributes[:condition] = cond end element(name, orig_element.type, attributes) end if (orig_element) set_el_query.call else on_element_defined(element_name, &set_el_query) end end # Saves the element definition and evals it when first needed, avoiding problems with classes not # available yet when the model is defined. # FIXME: remove? def self.define_elements(&proc) #:nodoc: @elements_definition = proc end # Creates an inline model def self.create_inline_model(name, hash, attributes={}) #:nodoc: model = self.const_set(Spider::Inflector.camelize(name), Class.new(InlineModel)) model.instance_eval do if attributes[:inline_model] attributes[:inline_model].each do |el| element(el[0], el[1], el[2] || {}) end else hash.each do |key, val| key = key.to_s if key.is_a?(Symbol) element(:id, key.class, :primary_key => true) if (val.class == Hash) # TODO: allow passing of multiple values like {:element1 => 'el1', :element2 => 'el2'} else element(:desc, val.class, :desc => true) end break end end end model.data = hash return model end # An array of other models this class points to. def self.submodels elements.select{ |name, el| el.model? }.map{ |name, el| el.model } end def self.extend_model(model, params={}) #:nodoc: if (model == superclass) # first undo table per class inheritance @elements = {} @elements_order = [] @extended_models.delete(model.superclass) if @extended_models end primary_keys.each{ |k| remove_element(k) } if (params[:replace_pks]) model.primary_keys.each{ |k| remove_element(k) } integrated_name = params[:name] if (!integrated_name) integrated_name = (self.parent_module == model.parent_module) ? model.short_name : model.name integrated_name = Spider::Inflector.underscore(integrated_name).gsub('/', '_') end integrated_name = integrated_name.to_sym @extended_models ||= {} @extended_models[model] = integrated_name attributes = {} attributes[:hidden] = true unless (params[:hide_integrated] == false) attributes[:delete_cascade] = params[:delete_cascade] attributes[:extended_model] = true attributes[:add_reverse] = params[:reverse] integrated = element(integrated_name, model, attributes) integrate_options = {:keep_pks => true}.merge((params[:integrate_options] || {})) integrate(integrated_name, integrate_options) model.elements_array.select{ |el| el.attributes[:local_pk] }.each{ |el| remove_element(el.name) } unless (params[:no_local_pk] || !elements_array.select{ |el| el.attributes[:local_pk] }.empty?) # FIXME: check if :id is already defined pk_name = @elements[:id] ? :"id_#{self.short_name.downcase}" : :id element(pk_name, Fixnum, :autoincrement => true, :local_pk => true, :hidden => true) end model.polymorphic(self, :through => integrated_name) end # Externalizes the superclass elements making the superclass an external integrated element. # Parameters may be: # * :name (symbol) name of the created element # * :delete_cascade (bool) delete cascade the superclass instance. True by default. # * :no_local_pk (bool) do not define an id for this class def self.class_table_inheritance(params={}) self.extend_model(superclass, params) end # Makes the class use the superclass storage def self.inherit_storage self.attributes[:inherit_storage] = true (class << self; self; end).instance_eval do define_method(:storage) do superclass.storage end end end # Sets a fixed condition. def self.condition(condition) self.attributes[:condition] = condition end # #-- # TODO: document me def self.group(name, &proc) #:nodoc: proxy = Class.new(ProxyModel).proxy(name.to_s+'_', self) proxy.instance_eval(&proc) proxy.each_element do |el| element(name.to_s+'_'+el.name.to_s, el.type, el.attributes.clone) end define_method(name) do @proxies ||= {} return @proxies[name] ||= proxy.new end end # Add a subclass, allowing polymorphic queries on it. def self.polymorphic(model, options) through = options[:through] || Spider::Inflector.underscore(self.name).gsub('/', '_') through = through.to_sym @polymorphic_models ||= {} @polymorphic_models[model] = {:through => through} end # Sets or gets class attributes (a Hash). # If given a hash of attributes, will merge them with class attributes. # Model attributes are generally empty, and can be used by apps. def self.attributes(val=nil) @attributes ||= {} if (val) @attributes.merge!(val) end @attributes end # Sets a model attribute. See #self.attributes def self.attribute(name, value) @attributes ||= {} @attributes[name] = value end # Adds a sequence to the model. def self.sequence(name) @sequences ||= [] @sequences << name end # Model sequences. def self.sequences @sequences ||= [] end # Does nothing. This method is to keep note of elements created in other models. def self._added_elements(&proc) end def self.referenced_by_junctions @referenced_by_junctions ||= [] end ##################################################### # Methods returning information about the model # ##################################################### # Underscored local name (without namespaces) def self.short_name return Inflector.underscore(self.name.match(/([^:]+)$/)[1]) end # False for BaseModel (true for Spider::Model::Managed). def self.managed? return false end # Name def self.to_s self.name end # Sets the singolar and/or the plural label for the model # Returns the singlular label def self.label(sing=nil, plur=nil) @label = sing if sing @label_plural = plur if plur _(@label || self.name || '') end # Sets/retrieves the plural form for the label def self.label_plural(val=nil) @label_plural = val if (val) _(@label_plural || self.name || '') end def self.auto_primary_keys? self.primary_keys.select{ |k| !k.autogenerated? }.empty? end def self.containing_module par = self.parent_module while par <= BaseModel par = par.parent_module end par end def self.get_element(el) el = el.name if el.is_a?(Element) el = el.to_sym raise "No element called #{el} in #{self}" unless @elements[el] @elements[el] end def self.junction? !!self.attributes[:sub_model] end ######################################################## # Methods returning information about the elements # ######################################################## # An Hash of Elements, indexed by name. def self.elements @elements end # An array of the model's Elements. def self.elements_array @elements_order.map{ |key| @elements[key] } end # Yields each element in order. def self.each_element return unless @elements_order @elements_order.each do |name| yield elements[name] end end # Returns true if the model has given element name. def self.has_element?(name) return elements[name] ? true : false end # An array of elements with primary_key attribute set. def self.primary_keys @primary_keys end # Returns the model actually defining element_name; that could be the model # itself, a superclass, or an integrated model. def self.first_definer(element_name, type) if (@extended_models && @extended_models[self.superclass] && self.superclass.elements[element_name] && self.superclass.elements[element_name].type == type) return self.superclass.first_definer(element_name, type) end if (self.attributes[:integrated_models]) self.attributes[:integrated_models].keys.each do |mod| return mod.first_definer(element_name, type) if (mod.elements[element_name] && mod.elements[element_name].type == type) end end return self end # Returns true if the element with given name is associated with the passed # association. # This method should be used instead of querying the element's association directly, # since subclasses and mixins may extend this method to provide association equivalence. def self.element_association?(element_name, association) return true if elements[element_name].association = association end # An Hash of extended models => element name of the extended model element def self.extended_models @extended_models ||= {} end ############################################################## # Storage, mapper and loading (Class methods) # ############################################################## # The given module will be mixed in any mapper used by the class. def self.mapper_include(mod) @mapper_modules ||= [] @mapper_modules << mod end def self.mapper_include_for(params, mod) @mapper_modules_for ||= [] @mapper_modules_for << [params, mod] end # The given proc will be mixed in the mapper used by this class # Note that the proc will be converted to a Module, so any overridden methods will still have # access to the super method. def self.with_mapper(*params, &proc) # @mapper_procs ||= [] # @mapper_procs << proc mod = Module.new(&proc) mapper_include(mod) end # FIXME: remove def self.with_mapper_subclasses(*params, &proc) #:nodoc: @mapper_procs_subclass ||= [] @mapper_procs_subclass << proc end # Like #with_mapper, but will mixin the block only if the mapper matches params. # Possible params are: # - a String, matching the class' use_storage def self.with_mapper_for(*params, &proc) @mapper_procs_for ||= [] @mapper_procs_for << [params, proc] end # Sets the url or the name of the storage to use def self.use_storage(name=nil) @use_storage = name if name @use_storage end # Returns the current default storage for the class # The storage to use can be set with #use_storage def self.storage return @storage if @storage if (!@use_storage && self.attributes[:sub_model]) @use_storage = self.attributes[:sub_model].use_storage end return @use_storage ? get_storage(@use_storage) : get_storage end # Returns an instancethe storage corresponding to the storage_string if it is given, # or of the default storage otherwise. # The storage string can be a storage url (see #Storage.get_storage), or a named storage # defined in configuration #-- # Mixin! def self.get_storage(storage_string='default') storage_regexp = /([\w\d]+?):(.+)/ orig_string = nil if (storage_string !~ storage_regexp) orig_string = storage_string storage_conf = Spider.conf.get('storages')[storage_string] storage_string = storage_conf['url'] if storage_conf if (!storage_string || storage_string !~ storage_regexp) raise ModelException, "No storage '#{orig_string}' found" end end type, url = $1, $2 storage = Storage.get_storage(type, url) storage.instance_name = orig_string storage.configure(storage_conf) if storage_conf return storage end # Returns an instance of the default mapper for the class. def self.mapper @mapper ||= get_mapper(storage) end # Returns an instance of the mapper for the given storage def self.get_mapper(storage) # map_class = self.attributes[:inherit_storage] ? superclass : self mapper = storage.get_mapper(self) if (@mapper_modules) @mapper_modules.each{ |mod| mapper.extend(mod) } end if (@mapper_modules_for) @mapper_modules_for.each do |params, mod| if params.is_a?(String) mapper.extend(mod) if self.use_storage == params end end end if (@mapper_procs) @mapper_procs.each{ |proc| mapper.instance_eval(&proc) } end if (@mapper_procs_for) @mapper_procs_for.each do |params, proc| if (params.length == 1 && params[0].class == String) mapper.instance_eval(&proc) if (self.use_storage == params[0]) end end end if (@mapper_procs_subclass) @mapper_procs_subclass.each{ |proc| mapper.instance_eval(&proc) } end return mapper end # Syncs the schema with the storage. def self.sync_schema(options={}) options = ({ :force => false, :drop_fields => false, :update_sequences => false, :no_foreign_key_constraints => true }).merge(options) Spider::Model.sync_schema(self, options[:force], options) end # Executes #self.where, and calls QuerySet#load on the result. # Returns nil if the result is empty, the QuerySet otherwise # See #self.where for parameter syntax def self.find(*params, &proc) qs = self.where(*params, &proc) return qs.empty? ? nil : qs end # Executes #self.where, returning the first result. # See #self.where for parameter syntax. def self.load(*params, &proc) qs = self.where(*params, &proc) qs.limit = 1 return qs[0] end # Returns a queryset without conditions def self.all return self.where end # Constructs a Query based on params, and returns a QuerySet # Allowed parameters are: # * a Query object # * a Condition and an (optional) Request, or anything that can be parsed by Condition.new and Request.new # If a block is provided, it is passed to Condition.parse_block. # Examples: # felines = Animals.where({:family => 'felines'}) # felines = Animals.where({:family => 'felines'}, [:name, :description]) # cool_animals = Animals.where{ (has_fangs == true) | (has_claws == true)} # See also Condition#parse_block def self.where(*params, &proc) if (params[0] && params[0].is_a?(Query)) query = params[0] qs = QuerySet.new(self, query) elsif(proc) qs = QuerySet.new(self) qs.autoload = true qs.where(&proc) else condition = Condition.and(params[0]) request = Request.new(params[1]) query = Query.new(condition, request) qs = QuerySet.new(self, query) end return qs end # Returns the condition for a "free" text query # Examples: # condition = News.free_query_condition('animals') # animal_news = News.where(condition) def self.free_query_condition(q) c = Condition.or self.elements_array.each do |el| if (el.type == String || el.type == Text) c.set(el.name, 'ilike', '%'+q+'%') end end return c end # Returns the number of objects in storage def self.count(condition=nil) mapper.count(condition) end # Can be defined to provide functionality to this model's querysets. def self.extend_queryset(qs) end ################################################# # Instance methods # ################################################# # The constructor may take: # * an Hash of values, that will be set on the new instance; or # * a BaseModel instance; its values will be set on the new instance; or # * a single value; it will be set on the first primary key. def initialize(values=nil) @_autoload = true @_has_values = false @loaded_elements = {} @modified_elements = {} @value_observers = nil @all_values_observers = nil @_extra = {} @model = self.class @_primary_keys_set = false set_values(values) if values # if primary_keys_set? # @_primary_keys_set = true # if Spider::Model.identity_mapper # Spider::Model.identity_mapper.put(self, true) # else # Spider::Model.unit_of_work.add(self) if Spider::Model.unit_of_work # end # else # #nil # end end # Returns an instance of the Model with #autoload set to false def self.static(values=nil) obj = self.new obj.autoload = false obj.set_values(values) if values return obj end def self.create(values) obj = self.static(values) obj.insert return obj end def self.get(values) return self.new(values) unless Spider::Model.identity_mapper values = [values] unless values.is_a?(Hash) || values.is_a?(Array) if values.is_a?(Array) vals = {} self.primary_keys.each_with_index do |k, i| vals[k.name] = values[i] end values = vals end curr = Spider::Model.identity_mapper.get(self, values) return curr if curr obj = self.new(values) Spider::Model.identity_mapper.put(obj) obj end def set_values(values) if (values.is_a? Hash) values.keys.select{ |k| k = k.name if k.is_a?(Element) self.class.elements[k.to_sym] && self.class.elements[k.to_sym].primary_key? }.each do |k| set!(k, values[k]) end values.each do |key, val| set!(key, val) end elsif (values.is_a? BaseModel) values.each_val do |name, val| set(name, val) if self.class.has_element?(name) end elsif (values.is_a? Array) self.class.primary_keys.each_index do |i| set(self.class.primary_keys[i], values[i]) end # Single unset key, single value elsif ((empty_keys = self.class.primary_keys.select{ |key| !element_has_value?(key) }).length == 1) set(empty_keys[0], values) else raise ArgumentError, "Don't know how to construct a #{self.class} from #{values.inspect}" end end # Returns the instance's IdentityMapper def identity_mapper return Spider::Model.identity_mapper if Spider::Model.identity_mapper @identity_mapper ||= IdentityMapper.new end # Sets the instance's IdentityMapper. def identity_mapper=(im) @identity_mapper = im end # Returns a new instance for given element name. def instantiate_element(name) element = self.class.elements[name] if (element.model?) if (element.multiple?) val = QuerySet.static(element.model) else val = element.type.new val.autoload = autoload? end end val = prepare_child(name, val) instance_variable_set("@#{name}", val) set_reverse(element, val) if element.model? val end # Prepares an object that is being set as a child. def prepare_child(name, obj) return obj if obj.nil? element = self.class.elements[name] if (element.model?) # convert between junction and real type if needed if element.attributes[:junction] if obj.is_a?(QuerySet) obj.no_autoload do if (element.attributes[:keep_junction] && obj.model == element.type) qs = QuerySet.new(element.model) obj.each{ |el_obj| qs << {element.reverse => self, element.attributes[:junction_their_element] => el_obj} } obj = qs elsif (!element.attributes[:keep_junction] && obj.model == element.model) instance_variable_set("@#{element.name}_junction", obj) qs = QuerySet.new(element.type, obj.map{ |el_obj| el_obj.get(element.attributes[:junction_their_element])}) obj = qs end end else if (!element.attributes[:keep_junction] && obj.class == element.model) obj = obj.get(element.attributes[:junction_their_element]) end end end self.class.elements_array.select{ |el| el.attributes[:fixed] }.each do |el| if el.integrated_from == element obj.set(el.integrated_from_element, el.attributes[:fixed]) end end obj.identity_mapper = self.identity_mapper if obj.respond_to?(:identity_mapper) if (element.multiple? && element.attributes[:junction] && element.attributes[:keep_junction]) obj.append_element = element.attributes[:junction_their_element] end if (element.attributes[:set] && element.attributes[:set].is_a?(Hash)) element.attributes[:set].each{ |k, v| obj.set(k, v) } obj.reset_modified_elements(*element.attributes[:set].keys) # FIXME: is it always ok to not set the element as modified? But otherwise sub objects # are always saved (and that's definitely no good) end if element.type == self.class.superclass && self.class.extended_models[element.type] && self.class.extended_models[element.type] == element.name obj._subclass_object = self end else obj = prepare_value(element, obj) end return obj end # Returns all children that can be reached from the current path. # Path is expressed as a dotted String. def all_children(path) children = [] no_autoload do el = path.shift if self.class.elements[el] && element_has_value?(el) && children = get(el) if path.length >= 1 children = children.all_children(path) end end end return children end # Sets the object currently containing this one (BaseModel or QuerySet) def set_parent(obj, element) @_parent = obj @_parent_element = element end def set_reverse(element, obj) return unless element.model? && obj if element.has_single_reverse? && (!element.attributes[:junction] || element.attributes[:keep_junction]) unless element.multiple? val = obj.get_no_load(element.reverse) return if val && val.object_id == self.object_id end obj.set(element.reverse, self) end end ################################################# # Get and set # ################################################# # Returns an element. # The element may be a symbol, or a dotted path String. # Will call the associated getter. # cat.get('favorite_food.name') def get(element) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) sub_val = send(first) return nil unless sub_val return sub_val.get(rest) end return send(element) end # Returns an element without autoloading it. def get_no_load(element) res = nil no_autoload do res = get(element) end return res end # Sets an element. # The element can be a symbol, or a dotted path String. # Will call the associated setter. # cat.set('favorite_food.name', 'Salmon') def set(element, value, options={}) element = element.name if element.is_a?(Element) first, rest = element.to_s.split('.', 2) if (rest) first_val = send(first) unless first_val if (options[:instantiate]) first_val = instantiate_element(first.to_sym) set(first, first_val) else raise "Element #{first} is nil, can't set #{element}" end end return first_val.set(rest, value, options) end return send("#{element}=", value) end # Sets an element, instantiating intermediate objects if needed def set!(element, value, options={}) options[:instantiate] = true set(element, value, options) end # Calls #get on element; whenever no getter responds, returns the extra data. # See #[]= def [](element) element = element.name if element.is_a?(Element) begin get(element) rescue NoMethodError return @_extra[element] end end # If element is a model's element, calls #set. # Otherwise, stores the value in an "extra" hash, where it will be accessible by #[] def []=(element, value) element = element.name if element.is_a?(Element) if (self.class.elements[element]) set(element, value) else @_extra[element] = value end end # Sets each value of a Hash. def set_hash(hash) hash.each { |key, val| set(key, val) } end # Prepares a value going to be set on the object. Will convert the value to the # appropriate type. def self.prepare_value(element, value) element = self.class.elements[element] unless element.is_a?(Element) if (element.type < Spider::DataType) value = element.type.from_value(value) unless value.is_a?(element.type) if value element.type.take_attributes.each do |a| if element.attributes[a].is_a?(Proc) value.attributes[a] = value.instance_eval(&element.attributes[a]) else value.attributes[a] = element.attributes[a] end end value = value.prepare end elsif element.model? value.autoload(autoload?, true) if value && value.respond_to?(:autolad) else case element.type.name when 'Date', 'DateTime' return nil if value.is_a?(String) && value.empty? parsed = nil if (value.is_a?(String)) begin parsed = element.type.strptime(value, "%Y-%m-%dT%H:%M:%S") rescue parsed = nil parsed ||= element.type.lparse(value, :short) rescue parsed = nil parsed ||= element.type.parse(value) rescue ArgumentError => exc raise FormatError.new(element, value, _("'%s' is not a valid date")) end value = parsed end when 'String' when 'Spider::DataTypes::Text' value = value.to_s when 'Fixnum' value = value.to_i end end value end def prepare_value(element, value) self.class.prepare_value(element, value) end # Sets a value without calling the associated setter; used by the mapper. def set_loaded_value(element, value, mark_loaded=true) element_name = element.is_a?(Element) ? element.name : element element = self.class.elements[element_name] if (element.integrated?) get(element.integrated_from).set_loaded_value(element.integrated_from_element, value) else value = prepare_child(element.name, value) current = instance_variable_get("@#{element_name}") current.set_parent(nil, nil) if current && current.is_a?(BaseModel) value.set_parent(self, element.name) if value.is_a?(BaseModel) instance_variable_set("@#{element_name}", value) end value.loaded = true if (value.is_a?(QuerySet)) element_loaded(element_name) if mark_loaded set_reverse(element, value) if element.model? @modified_elements[element_name] = false end # Records that the element has been loaded. def element_loaded(element_name) element_name = self.class.get_element(element_name).name @loaded_elements[element_name] = true end # Returns true if the element has been loaded by the mapper. def element_loaded?(element) element = self.class.get_element(element).name return @loaded_elements[element] end # Apply element checks for given element name and value. (See also #element, :check attribute). # Checks may be defined by the DataType, or be given as an element attribute. # The check can be a Regexp, that will be checked against the value, or a Proc, which is expected to # return true if the check is succesful, and false otherwise. # Will raise a Model::FormatError when a check is not succesful. # If the :check attribute is an Hash, the Hash keys will be used as messages, which will be passed # to the FormatError. def _check(name, val) element = self.class.elements[name] element.type.check(val) if (element.type.respond_to?(:check)) if (checks = element.attributes[:check]) checks = {(_("'%s' is not in the correct format") % element.label) => checks} unless checks.is_a?(Hash) checks.each do |msg, check| test = case check when Regexp val == nil || val.empty? ? true : check.match(val) when Proc check.call(val) end raise FormatError.new(element, val, msg) unless test end end end # Converts the object to the instance of a subclass for which this model is polymorphic. def polymorphic_become(model) return self if self.is_a?(model) unless self.class.polymorphic_models && self.class.polymorphic_models[model] sup = model.superclass while sup < Spider::Model::BaseModel && !self.class.polymorphic_models[sup] sup = sup.superclass end raise ModelException, "#{self.class} is not polymorphic for #{model}" unless self.class.polymorphic_models[sup] sup_poly = polymorphic_become(sup) return sup_poly.polymorphic_become(model) end el = self.class.polymorphic_models[model][:through] obj = model.new(el => self) obj = Spider::Model.identity_mapper.get(obj) if Spider::Model.identity_mapper obj.element_loaded(el) return obj end def become(model) return self if self.class == model obj = polymorphic_become(model) rescue ModelException return obj end # Converts the object to the instance of a subclass. This will instantiate the model # passed as an argument, and set each value of the current object on the new one. # No checks are made that this makes sense, so the method will fail if the "subclass" does # not contain all of the current model's elements. def subclass(model) obj = model.new self.class.elements_array.each do |el| obj.set(el, self.get(el)) if element_has_value?(el) && model.elements[el.name] end return obj end # Returns the current autoload status def autoload? @_autoload end # Enables or disables autoloading. # An autoloading object will try to load all missing elements on first access. # (see also Element#lazy_groups) def autoload=(val) autoload(val, false) end # Sets autoload mode # The first parameter the value of autoload to be set; it can be true, false or :save_mode (see #save_mode)) # the second bool parameter specifies if the value should be propagated on all child objects. def autoload(a, traverse=true) #:nodoc: return if @_tmp_autoload_walk @_tmp_autoload_walk = true @_autoload = a if (traverse) self.class.elements_array.select{ |el| el.model? && \ (element_has_value?(el.name) || el.attributes[:extended_model])}.each do |el| val = get(el) val.autoload = a if val.respond_to?(:autoload=) end end @_tmp_autoload_walk = nil end # Disables autoload. # If a block is given, the current autoload setting will be restored after yielding. def no_autoload prev_autoload = autoload? self.autoload = false if block_given? yield self.autoload = prev_autoload end return prev_autoload end # Sets autoload to :save_mode; elements will be autoloaded only one by one, so that # any already set data will not be overwritten # If a block is given, the current autoload setting will be restored after yielding. def save_mode prev_autoload = autoload? self.autoload = :save_mode if (block_given?) yield self.autoload = prev_autoload end return prev_autoload end ############################################################## # Methods for getting information about element values # ############################################################## # Returns true if other is_a?(self.class), and has the same values for this class' primary keys. def ==(other) return false unless other return false unless other.is_a?(self.class) self.class.primary_keys.each do |k| return false unless get(k) == other.get(k) end return true end ############################################################## # Iterators # ############################################################## # Iterates over elements and yields name-value pairs def each # :yields: element_name, element_value self.class.elements.each do |name, el| yield name, get(name) end end # Iterates over non-nil elements, yielding name-value pairs def each_val # :yields: element_name, element_value self.class.elements.select{ |name, el| element_has_value?(name) }.each do |name, el| yield name, get(name) end end # Returns an array of current primary key values def primary_keys self.class.primary_keys.map{ |k| val = get(k) k.model? && val ? val.primary_keys : val } end # Returns an hash of primary keys names and values def primary_keys_hash h = {} self.class.primary_keys.each{ |k| h[k.name] = get(k) } h end # Returns a string with the primary keys joined by ',' def keys_string self.class.primary_keys.map{ |pk| self.get(pk) }.join(',') end # Returns true if the element instance variable is set #-- # FIXME: should probably try to get away without this method # it is the only method that relies on the mapper def element_has_value?(element) element = self.class.get_element(element) if (element.integrated?) return false unless obj = instance_variable_get(:"@#{element.integrated_from.name}") return obj.element_has_value?(element.integrated_from_element) end if (element.attributes[:computed_from]) element.attributes[:computed_from].each{ |el| return false unless element_has_value?(el) } return true end ivar = nil ivar = instance_variable_get(:"@#{element.name}") if instance_variable_defined?(:"@#{element.name}") return nil == ivar ? false : true # FIXME: is this needed? # if (!mapper.mapped?(element) # return send("#{element_name}?") if (respond_to?("#{element_name}?")) # return get(element) == nil ? false : true if (!mapper.mapped?(element)) # end end # Returns true if the element value has been modified since instantiating or loading def element_modified?(element) element = self.class.get_element(element) set_mod = @modified_elements[element.name] return set_mod if set_mod if (element.integrated?) return false unless integrated = get_no_load(element.integrated_from) return integrated.element_modified?(element.integrated_from_element) end if element_has_value?(element) && (val = get(element)).respond_to?(:modified?) return val.modified? end return false end # Returns true if any of elements has been modified def elements_modified?(*elements) elements = elements[0] if elements[0].is_a?(Array) elements.each{ |el| return true if element_modified?(el) } return false end # Returns true if any element, or any child object, has been modified def modified? return true unless @modified_elements.reject{ |key, val| !val }.empty? self.class.elements_array.select{ |el| !el.model? && element_has_value?(el) && el.type.is_a?(Spider::DataType) }.each do |el| return true if get(el).modified? end return false end def in_storage? return false unless primary_keys_set? return self.class.load(primary_keys_hash) end # Given elements are set as modified def set_modified(request) #:nodoc: request.each do |key, val| # FIXME: go deep @modified_elements[key] = true end end # Resets modified elements def reset_modified_elements(*elements) #:nodoc: if (elements.length > 0) elements.each{ |el_name| @modified_elements.delete(el_name) } else @modified_elements = {} end end # Returns true if all primary keys have a value; false if some primary key # is not set or the model has no primary key def primary_keys_set? primary_keys = self.class.primary_keys return false unless primary_keys.length > 0 primary_keys.each do |el| if (el.integrated?) return false unless (int_obj = instance_variable_get(:"@#{el.integrated_from.name}")) #return false unless int_obj.instance_variable_get(:"@#{el.integrated_from_element}") return false unless int_obj.element_has_value?(el.integrated_from_element) else return false unless self.instance_variable_get(:"@#{el.name}") end end return true end # Returns true if no element has a value def empty? return @_has_values end # Sets all values of obj on the current object def merge!(obj, only=nil) return self if obj.object_id == self.object_id obj.class.elements_array.select{ |el| (only || obj.element_has_value?(el)) && !el.integrated? && !el.attributes[:computed_from] }.each do |el| next if only && !only.key?(el.name) val = obj.element_has_value?(el.name) ? obj.get_no_load(el) : nil our_val = self.element_has_value?(el.name) ? self.get_no_load(el) : nil next if our_val == val if el.model? && only && only[el.name].is_a?(Hash) && our_val \ && val.is_a?(BaseModel) && our_val.is_a?(BaseModel) val = our_val.merge!(val, only[el.name]) else Spider.logger.warn("Element #{el.name} overwritten in #{obj.inspect}") if our_val && our_val != val end set_loaded_value(el, val, false) unless val.nil? && element.multiple? end self end def merge_hash(h) h.each do |k, v| self.set(k.to_sym, v) end end # Returns a deep copy of the object def clone obj = self.class.new obj.merge!(self) return obj end # Returns a new instance with the same primary keys def get_new obj = nil Spider::Model.no_identity_mapper do obj = self.class.new obj._no_identity_mapper = true self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } end return obj end # Returns a new static instance with the same primary keys def get_new_static obj = nil Spider::Model.no_identity_mapper do obj = self.class.static obj._no_identity_mapper = true self.class.primary_keys.each{ |k| obj.set(k, self.get(k)) } end return obj end # Returns a condition based on the current primary keys def keys_to_condition c = Condition.and self.class.primary_keys.each do |key| val = get(key) if (key.model?) c[key.name] = val.keys_to_condition else c[key.name] = val end end return c end ################################################# # Object observers methods # ################################################# # The given block will be called whenever a value is modified. # The block will be passed three arguments: the object, the element name, and the previous value # Example: # obj.observe_all_values do |instance, element_name, old_val| # puts "#{element_name} for object #{instance} has changed from #{old_val} to #{instance.get(element_name) }" def observe_all_values(&proc) @all_values_observers ||= [] @all_values_observers << proc end def observe_element(element_name, &proc) @value_observers ||= {} @value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.observer_all_values(&proc) self.all_values_observers << proc end def self.observe_element(element_name, &proc) self.value_observers[element_name] ||= [] @value_observers[element_name] << proc end def self.value_observers @value_observers ||= {} end def self.all_values_observers @all_values_observers ||= [] end # Calls the observers for element_name def notify_observers(element_name, new_val) #:nodoc: if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(self, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(self, element_name, new_val) } end self.class.notify_observers(element_name, new_val, self) end # Calls the observers for element_name def self.notify_observers(element_name, new_val, obj=nil) if @value_observers && @value_observers[element_name] @value_observers[element_name].each{ |proc| proc.call(obj, element_name, new_val) } end if @all_values_observers @all_values_observers.each{ |proc| proc.call(obj, element_name, new_val) } end end ############################################################## # Storage, mapper and schema loading (instance methods) # ############################################################## # Returns the current @storage, or instantiates the default calling Spider::BaseModel.storage def storage return @storage || self.class.storage end # Instantiates the storage for the instance. # Accepts a string (url or named storage) which will be passed to Spider::BaseModel.get_storage # Example: # obj.use_storage('my_named_db') # obj.use_storage('db:oracle://username:password@XE') def use_storage(storage) @storage = self.class.get_storage(storage) @mapper = self.class.get_mapper(@storage) end # Returns the current mapper, or instantiates a new one (base on the current storage, if set) def mapper @storage ||= nil if (@storage) @mapper ||= self.class.get_mapper(@storage) else @mapper ||= self.class.mapper end return @mapper end # Sets the current mapper def mapper=(mapper) @mapper = mapper end ############################################################## # Saving and loading from storage methods # ############################################################## # Saves the object to the storage # (see Mapper#save) def save if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless unit_of_work_available? if unit_of_work_available? Spider.current[:unit_of_work].add(self) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else save! end end self end def save! mapper.save(self) self end # Saves the object and all child objects to the storage # (see Mapper#save_all) def save_all mapper.save_all(self) self end def insert if @unit_of_work @unit_of_work.add(self) return end save_mode do before_save unless unit_of_work_available? if unit_of_work_available? Spider.current[:unit_of_work].add(self, :save, :force => :insert) if @unit_of_work @unit_of_work.commit Spider::Model.stop_unit_of_work if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else insert! end end self end def unit_of_work_available? Spider.current[:unit_of_work] && !Spider.current[:unit_of_work].running? end # Inserts the object in the storage # Note: if the object is already present in the storage and unique indexes are enforced, # this will raise an error. # (See Mapper#insert). def insert! mapper.insert(self) reset_modified_elements end # Updates the object in the storage # Note: the update will silently fail if the object is not present in the storage # (see Mapper#update). def update mapper.update(self) reset_modified_elements end # Deletes the object from the storage # (see Mapper#delete). def delete if @unit_of_work @unit_of_work.add(self, :delete) return end before_delete unless Spider.current[:unit_of_work] if Spider.current[:unit_of_work] Spider.current[:unit_of_work].add(self, :delete) if @unit_of_work @unit_of_work.commit @unit_of_work.stop if @uow_identity_mapper Spider.current[:identity_mapper] = nil @uow_identity_mapper = nil end @unit_of_work = nil end return else delete! end end def delete! mapper.delete(self) end def before_delete end def before_save end def use_unit_of_work had_uow = true unless Spider.current[:unit_of_work] had_wow = false @unit_of_work = Spider::Model.start_unit_of_work end unless Spider::Model.identity_mapper @uow_identity_mapper = Spider::Model::IdentityMapper.new Spider.current[:identity_mapper] = @uow_identity_mapper @uow_identity_mapper.put(self) if self.primary_keys_set? end # Spider.current[:unit_of_work].add(self) Spider.current[:unit_of_work] return had_uow end # Loads the object from the storage # Acceptable arguments are: # * a Query object, or # * a Request object, or a Hash, which will be converted to a Request, or # * a list of elements to request # It will then construct a Condition with current primary keys, and call Mapper#load # Note that an error will be raised by the Mapper if not all primary keys are set. def load(*params) if (params[0].is_a? Query) query = params[0] else return false unless primary_keys_set? query = Query.new if (params[0].is_a?(Request)) query.request = params.shift elsif (params[0].is_a?(Hash)) query.request = Request.new(params.shift) end elements = params.length > 0 ? params : self.class.elements.keys return true unless elements.select{ |el| !element_loaded?(el) }.length > 0 elements.each do |name| query.request[name] = true end query.condition.conjunction = :and self.class.primary_keys.each do |key| query.condition[key.name] = get(key.name) end end #clear_values() return mapper.load(self, query) end # Sets all values to nil def clear_values() self.class.elements.each_key do |element_name| instance_variable_set(:"@#{element_name}", nil) end end def remove_association(element, object) mapper.delete_element_associations(self, element, object) end # Method that will be called by the mapper before a query. May be overridden to preprocess the query. # Must return the modified query. Note: to prepare conditions, use prepare_condition, since it will # be called on subconditions as well. def self.prepare_query(query) query end ############################################################## # Method missing # ############################################################## # Tries the method on integrated models def method_missing(method, *args) #:nodoc: # UNUSED # case method.to_s # when /load_by_(.+)/ # element = $1 # if !self.class.elements[element.to_sym].attributes[:primary_key] # raise ModelException, "load_by_ called for element #{element} which is not a primary key" # elsif self.class.primary_keys.length > 1 # raise ModelException, "can't call #{method} because #{element} is not the only primary key" # end # query = Query.new # query.condition[element.to_sym] = args[0] # load(query) # else if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| obj = send(name) if (obj.respond_to?(method)) return obj.send(method, *args) end end end raise NoMethodError, "undefined method `#{method}' for #{self.class}" #super # end end def respond_to?(symbol, include_private=false) return true if super if (self.class.attributes[:integrated_models]) self.class.attributes[:integrated_models].each do |model, name| if (model.method_defined?(symbol)) return true end end end return false end # Returns a descriptive string for the object. # By default this method returns the value of the first String element, if any; otherwise, # the string representation of the first element of any type. # Descendant classes may well provide a better representation. def to_s desc_elements = self.class.elements_array.select{ |el| el.attributes[:desc] } unless desc_elements.empty? return desc_elements.sort{ |a, b| ad = a.attributes[:desc]; bd = b.attributes[:desc] if ad == true && bd == true 0 elsif bd == true -1 elsif ad == true 1 else ad <=> bd end }.map{ |el| self.get(el).to_s }.join(' ') end self.class.each_element do |el| if ((el.type == String || el.type == Text) && !el.primary_key?) v = get(el) return v ? v.to_s : '' end end el = self.class.elements_array[0] if element_has_value?(el) v = get(el) return v ? v.to_s : '' end return '' end # A compact representation of the object. # Note: inspect will not autoload the object. def inspect self.class.name+': {' + self.class.elements_array.select{ |el| (element_loaded?(el) || element_has_value?(el)) && !el.hidden? } \ .map{ |el| ":#{el.name} => #{get(el.name).to_s}"}.join(',') + '}' end # Returns a JSON representation of the object. # # The tree will be traversed outputting all encountered objects; when an already seen object # is met, the primary keys will be output (as a single value if one, as an array if many) and traversing # will stop. # # For more fine-grained control of the output, it is better to use the #cut method and call to_json on it. def to_json(state=nil, &proc) require 'json' ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') if (@tmp_json_seen && !block_given?) pks = self.class.primary_keys.map{ |k| get(k).to_json } pks = pks[0] if pks.length == 1 return pks.to_json end @tmp_json_seen = true json = "" #Spider::Model.with_identity_mapper do |im| self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", true) end if (block_given?) select_elements = Proc.new{ true } else select_elements = Proc.new{ |name, el| !el.hidden? # && # #!el.attributes[:integrated_model] && # (element_has_value?(el) || (el.integrated? && element_has_value?(el.integrated_from))) } end json = "{" + self.class.elements.select(&select_elements).map{ |name, el| if (block_given?) val = yield(self, el) val ? "#{name.to_json}: #{val.to_json}" : nil else val = get(name) if (el.type == 'text' || el.type == 'longText') val = ic.iconv(val + ' ')[0..-2] end val = val.to_json "#{name.to_json}: #{val}" end }.select{ |pair| pair}.join(',') + "}" @tmp_json_seen = false self.class.elements_array.select{ |el| el.attributes[:integrated_model] }.each do |el| (int = get(el)) && int.instance_variable_set("@tmp_json_seen", false) end #end return json end # Returns a part of the object tree, converted to Hashes, Arrays and Strings. # Arguments can be: # * a String, followed by a list of elements; the String will be sprintf'd with element values # or # * a depth Fixnum; depth 0 means obj.to_s will be returned, depth 1 will return an hash containing the # object's element values converted to string, and so on # or # * a Hash, whith element names as keys, and depths, or Hashes, or Procs as values; each element # will be traversed up to the depth given, or recursively according to the has; or, if a Proc is given, # it will be called with the current object and element name as arguments # or # * a list of elements; this is equivalent to passing a hash of the elements with depth 0. # # Examples: # obj.inspect # => Zoo::Animal: {:name => Llama, :family => Camelidae, :friends => Sheep, Camel} # obj.cut(0) # => 'Llama' # obj.cut(:name, :friends) # => {:name => 'Llama', :friends => 'Sheep, Camel'} # obj.cut(:name => 0, :friends => 1) # => {:name => 'Llama', :friends => [ # {:name => 'Sheep', :family => 'Bovidae', :friends => 'Llama'}, # {:name => 'Camel', :family => 'Camelidae', :friens => 'Dromedary, LLama'} # ]} # obj.cut(:name => 0, :friends => {:name => 0}) # => {:name => 'Llama', :friends => [{:name => 'Sheep'}, {:name => 'Camel'}]} # objs.cut(:name => 0, :friends => lambda{ |instance, element| # instance.get(element).name.upcase # }) # => {:name => 'Llama', :friends => ['SHEEP', 'CAMEL']} # obj.cut("Hi, i'm a %s and my friends are %s", :name, :friends) # => "Hi, i'm a Llama and my friends are Sheep, Camel" def cut(*params, &proc) h = {} if (params[0].is_a?(String)) return sprintf(params[0], *params[1..-1].map{ |el| get(el) }) elsif (params[0].is_a?(Fixnum)) p = params.shift if (p < 1) if (block_given?) return proc.call(self) else return self.to_s end end lev = p where = {} self.class.elements_array.each { |el| where[el.name] = lev-1} end if (params[0].is_a?(Hash)) where ||= {} params[0].each{ |k, v| where[k.to_sym] = v} else where ||= {} params.each{ |p| where[p] = 0 if p.is_a?(Symbol)} end Spider::Model.with_identity_mapper do |im| where.keys.each do |name| next unless where[name] if (where[name].is_a?(Proc)) val = where[name].call(self, name) else el = self.class.elements[name] if el val = get(el) val = val.cut(where[name], &proc) if el.model? && val else raise ModelException, "Element #{name} does not exist" unless self.respond_to?(name) val = self.send(name) val = val.cut(where[name], &proc) if val.is_a?(BaseModel) end end h[name] = val end end return h end # Returns a element_name => value Hash def to_hash() h = {} self.class.elements.select{ |name, el| element_loaded? el }.each do |name, el| h[name] = get(name) end return h end # Returns a yaml representation of the object. Will try to autoload all elements, unless autoload is false; # foreign keys will be expressed as an array if multiple, as a single primary key value otherwise def to_yaml(params={}) require 'yaml' return YAML::dump(to_yaml_h(params)) end def to_yaml_h(params={}) h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next if params[:except] && params[:except].include?(el.name) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else h[el.name] = get(el) end end h end def self.from_yaml(yaml) h = YAML::load(yaml) obj = self.static h.each do |key, value| el = elements[key.to_sym] if (el.multiple?) el_obj = el.model.static el.model.primary_keys.each do |pk| el_obj.set(pk, value.unshift) end obj.set(el, el_obj) else obj.set(el, value) end end return obj end def dump_to_hash h = {} def obj_pks(obj, klass) unless obj return klass.primary_keys.length > 1 ? [] : nil end pks = obj.primary_keys return pks[0] if pks.length == 1 return pks end self.class.elements_array.each do |el| next unless mapper.have_references?(el) || (el.junction? && el.model.attributes[:sub_model] == self.class) if (el.model?) obj = get(el) if !obj h[el.name] = nil elsif (el.multiple?) h[el.name] = obj.map{ |o| obj_pks(o, el.model) } else h[el.name] = obj_pks(obj, el.model) end else val = get(el) if val case val.class.name.to_sym when :Date, :DateTime, :Time val = val.strftime end end h[el.name] = val end end h end def self.from_hash_dump(h) obj = self.static h.each do |key, val| el = self.elements[key.to_sym] next unless el if el.multiple? && val qs = obj.get(el) val.each do |v| v = el.model.from_hash_dump(v) if v.is_a?(Hash) qs << v end else val = el.model.from_hash_dump(val) if val.is_a?(Hash) obj.set(el, val) end end obj end def dump_to_all_data_hash(options={}, h={}, seen={}) Spider::Model.with_identity_mapper do |im| clname = self.class.name.to_sym seen[clname] ||= {} return if seen[clname][self.primary_keys] seen[clname][self.primary_keys] = true h[clname] ||= [] h[clname] << self.dump_to_hash self.class.elements_array.each do |el| next unless el.model? next if el.model < Spider::Model::InlineModel next if options[:models] && !options[:models].include?(el.type) next if options[:except_models] && options[:except_models].include?(el.type) el_clname == el.type.name.to_sym next if options[:elements] && (options[:elements][el_clname] && !options[:elements][el_clname].include?(el.name)) next if options[:except_elements] && (options[:except_elements][el_clname] && options[:except_elements][el_clname].include?(el.name)) val = self.get(el) next unless val val = [val] unless val.is_a?(Enumerable) val.each do |v| v.dump_to_all_data_hash(options, h, seen) end end end h end def self.in_transaction self.storage.in_transaction yield self.storage.commit_or_continue end def self.dump_element(el) remove_elements = [] method = case el.attributes[:association] when :many :many when :choice :choice when :multiple_choice :multiple_choice when :tree :tree else :element end type = el.type attributes = el.attributes.clone if (method == :many || method == :multiple_choice) attributes.delete(:multiple) end attributes.delete(:association) if method != :element if (attributes[:association_type]) attributes[:through] = attributes[:association_type] unless attributes[:anonymous_model] attributes.delete(:association_type) end attributes.delete(:lazy) if attributes[:lazy] == :default if (method == :tree) delete_attrs = [:queryset_module, :multiple] delete_attrs.each{ |a| attributes.delete(a) } remove_elements += [attributes[:reverse], attributes[:tree_left], attributes[:tree_right], attributes[:tree_depth]] type = nil end return { :name => el.name, :type => type, :attributes => attributes, :method => method, :remove_elements => remove_elements } end def self.prepare_to_code modules = self.name.split('::')[0..-2] included = (self.included_modules - Spider::Model::BaseModel.included_modules).select do |m| m.name !~ /^#{Regexp.quote(self.name)}/ end local_name = self.name.split('::')[-1] superklass = self.superclass.name elements = [] remove_elements = [] self.elements_array.each do |el| next if el.integrated? next if (el.reverse && el.model.elements[el.reverse] && \ (el.model.elements[el.reverse].attributes[:add_reverse] || \ el.model.elements[el.reverse].attributes[:add_multiple_reverse])) el_hash = dump_element(el) return nil unless el_hash elements << el_hash remove_elements += el_hash[:remove_elements] end elements.reject!{ |el| remove_elements.include?(el[:name]) } return { :modules => modules, :included => included, :attributes => self.attributes, :elements => elements, :local_name => local_name, :superclass => superklass, :use_storage => @use_storage, :additional_code => [] } end def self.to_code(options={}) c = prepare_to_code str = "" indent = 0 append = lambda do |val| str += " "*indent str += val str end str += c[:modules].map{ |m| "module #{m}" }.join('; ') + "\n" str += "\n" indent = 4 append.call "class #{c[:local_name]} < #{c[:superclass]}\n" indent += 4 c[:included].each do |i| append.call "include #{i.name}\n" end c[:attributes].each do |k, v| append.call "attribute :#{k}, #{v.inspect}" end str += "\n" c[:elements].each do |el| append.call("#{el[:method].to_s} #{el[:name].inspect}") str += ", #{el[:type]}" if el[:type] str += ", #{el[:attributes].inspect[1..-2]}\n" if el[:attributes] && !el[:attributes].empty? end str += "\n" append.call "use_storage '#{c[:use_storage]}'\n" if c[:use_storage] c[:additional_code].each do |block| block.each_line do |line| append.call line end str += "\n" end indent -= 4 append.call("end\n") str += c[:modules].map{ "end" }.join(';') return str end end end; end
module Octokit class Client # Methods for the Commit Statuses API # # @see http://developer.github.com/v3/repos/statuses/ module Statuses COMBINED_STATUS_MEDIA_TYPE = "application/vnd.github.she-hulk-preview+json" # List all statuses for a given commit # # @param repo [String, Repository, Hash] A GitHub repository # @param sha [String] The SHA1 for the commit # @return [Array<Sawyer::Resource>] A list of statuses # @see http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref def statuses(repo, sha, options = {}) get "repos/#{Repository.new(repo)}/statuses/#{sha}", options end alias :list_statuses :statuses # Get the combined status for a ref # # @param repo [String, Repository, Hash] a GitHub repository # @param ref [String] A Sha or Ref to fetch the status of # @return [Sawyer::Resource] The combined status for the commit # @see https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref def combined_status(repo, ref, options = {}) ensure_combined_status_api_media_type(options) get "repos/#{Repository.new(repo)}/commits/#{ref}/status", options end alias :status :combined_status # Create status for a commit # # @param repo [String, Repository, Hash] A GitHub repository # @param sha [String] The SHA1 for the commit # @param state [String] The state: pending, success, failure, error # @param context [String] A context to differentiate this status from others # # @return [Sawyer::Resource] A status # @see http://developer.github.com/v3/repos/statuses/#create-a-status def create_status(repo, sha, state, options = {}) options.merge!(:state => state) post "repos/#{Repository.new(repo)}/statuses/#{sha}", options end private def ensure_combined_status_api_media_type(options = {}) unless options[:accept] options[:accept] = COMBINED_STATUS_MEDIA_TYPE warn_combined_status_preview end options end def warn_combined_status_preview octokit_warn <<-EOS WARNING: The preview version of the combined status API is not yet suitable for production use. You can avoid this message by supplying an appropriate media type in the 'Accept' header. See the blog post for details http://git.io/wtsdaA EOS end end end end Don't document this as an argument module Octokit class Client # Methods for the Commit Statuses API # # @see http://developer.github.com/v3/repos/statuses/ module Statuses COMBINED_STATUS_MEDIA_TYPE = "application/vnd.github.she-hulk-preview+json" # List all statuses for a given commit # # @param repo [String, Repository, Hash] A GitHub repository # @param sha [String] The SHA1 for the commit # @return [Array<Sawyer::Resource>] A list of statuses # @see http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref def statuses(repo, sha, options = {}) get "repos/#{Repository.new(repo)}/statuses/#{sha}", options end alias :list_statuses :statuses # Get the combined status for a ref # # @param repo [String, Repository, Hash] a GitHub repository # @param ref [String] A Sha or Ref to fetch the status of # @return [Sawyer::Resource] The combined status for the commit # @see https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref def combined_status(repo, ref, options = {}) ensure_combined_status_api_media_type(options) get "repos/#{Repository.new(repo)}/commits/#{ref}/status", options end alias :status :combined_status # Create status for a commit # # @param repo [String, Repository, Hash] A GitHub repository # @param sha [String] The SHA1 for the commit # @param state [String] The state: pending, success, failure, error # # @return [Sawyer::Resource] A status # @see http://developer.github.com/v3/repos/statuses/#create-a-status def create_status(repo, sha, state, options = {}) options.merge!(:state => state) post "repos/#{Repository.new(repo)}/statuses/#{sha}", options end private def ensure_combined_status_api_media_type(options = {}) unless options[:accept] options[:accept] = COMBINED_STATUS_MEDIA_TYPE warn_combined_status_preview end options end def warn_combined_status_preview octokit_warn <<-EOS WARNING: The preview version of the combined status API is not yet suitable for production use. You can avoid this message by supplying an appropriate media type in the 'Accept' header. See the blog post for details http://git.io/wtsdaA EOS end end end end
Pod::Spec.new do |s| s.name = 'PlayKit' s.version = '0.1.5' s.summary = 'PlayKit: Kaltura Mobile Player SDK - iOS' s.homepage = 'https://github.com/kaltura/playkit-ios' s.license = { :type => 'AGPLv3', :text => 'AGPLv3' } s.author = { 'Noam Tamim' => 'noam.tamim@kaltura.com', 'Eliza Sapir' => 'eliza.sapir@kaltura.com' } s.source = { :git => 'https://github.com/kaltura/playkit-ios.git', :tag => 'v' + s.version.to_s } s.ios.deployment_target = '8.0' s.subspec 'Core' do |sp| sp.source_files = 'Classes/**/*' sp.dependency 'SwiftyJSON' sp.dependency 'Log' end s.subspec 'IMAPlugin' do |ssp| ssp.source_files = 'Plugins/IMA' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.subspec 'GoogleCastAddon' do |ssp| ssp.source_files = 'Addons/GoogleCast' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited) -framework "GoogleCast"', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'google-cast-sdk' ssp.dependency 'PlayKit/Core' end s.subspec 'YouboraPlugin' do |ssp| ssp.source_files = 'Plugins/Youbora' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited) -framework "YouboraLib" -framework "YouboraPluginAVPlayer"', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'Youbora-AVPlayer/dynamic' ssp.dependency 'PlayKit/Core' end s.subspec 'WidevineClassic' do |ssp| ssp.source_files = 'Widevine' ssp.dependency 'PlayKitWV' ssp.dependency 'PlayKit/Core' ssp.pod_target_xcconfig = { 'ENABLE_BITCODE' => 'NO', 'GCC_PREPROCESSOR_DEFINITIONS'=>'WIDEVINE_ENABLED=1' } end s.subspec 'PhoenixPlugin' do |ssp| ssp.source_files = 'Plugins/Phoenix' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited)', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.subspec 'KalturaStatsPlugin' do |ssp| ssp.source_files = 'Plugins/KalturaStats' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited)', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', ' LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.subspec 'KalturaLiveStatsPlugin' do |ssp| ssp.source_files = 'Plugins/KalturaLiveStats' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited)', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', ' LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.default_subspec = 'Core' end bump v0.1.6.rc2 Pod::Spec.new do |s| s.name = 'PlayKit' s.version = '0.1.6.rc2' s.summary = 'PlayKit: Kaltura Mobile Player SDK - iOS' s.homepage = 'https://github.com/kaltura/playkit-ios' s.license = { :type => 'AGPLv3', :text => 'AGPLv3' } s.author = { 'Noam Tamim' => 'noam.tamim@kaltura.com', 'Eliza Sapir' => 'eliza.sapir@kaltura.com' } s.source = { :git => 'https://github.com/kaltura/playkit-ios.git', :tag => 'v' + s.version.to_s } s.ios.deployment_target = '8.0' s.subspec 'Core' do |sp| sp.source_files = 'Classes/**/*' sp.dependency 'SwiftyJSON' sp.dependency 'Log' end s.subspec 'IMAPlugin' do |ssp| ssp.source_files = 'Plugins/IMA' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.subspec 'GoogleCastAddon' do |ssp| ssp.source_files = 'Addons/GoogleCast' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited) -framework "GoogleCast"', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'google-cast-sdk' ssp.dependency 'PlayKit/Core' end s.subspec 'YouboraPlugin' do |ssp| ssp.source_files = 'Plugins/Youbora' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited) -framework "YouboraLib" -framework "YouboraPluginAVPlayer"', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'Youbora-AVPlayer/dynamic' ssp.dependency 'PlayKit/Core' end s.subspec 'WidevineClassic' do |ssp| ssp.source_files = 'Widevine' ssp.dependency 'PlayKitWV' ssp.dependency 'PlayKit/Core' ssp.pod_target_xcconfig = { 'ENABLE_BITCODE' => 'NO', 'GCC_PREPROCESSOR_DEFINITIONS'=>'WIDEVINE_ENABLED=1' } end s.subspec 'PhoenixPlugin' do |ssp| ssp.source_files = 'Plugins/Phoenix' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited)', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', 'LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.subspec 'KalturaStatsPlugin' do |ssp| ssp.source_files = 'Plugins/KalturaStats' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited)', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', ' LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.subspec 'KalturaLiveStatsPlugin' do |ssp| ssp.source_files = 'Plugins/KalturaLiveStats' ssp.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'OTHER_LDFLAGS' => '$(inherited)', 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**', ' LIBRARY_SEARCH_PATHS' => '$(inherited) "${PODS_ROOT}"/**' } ssp.dependency 'PlayKit/Core' end s.default_subspec = 'Core' end
module Spreewald VERSION = '1.4.0' end Version 1.5.0 module Spreewald VERSION = '1.5.0' end
module OkuribitoRails VERSION = "0.2.3".freeze end Version up. :+1: module OkuribitoRails VERSION = "0.2.4".freeze end
require 'omf-sfa/models/component' require 'omf-sfa/models/ip' require 'omf-sfa/models/epc' module OMF::SFA::Model class ENodeB < Component many_to_one :control_ip, class: Ip many_to_one :pgw_ip, class: Ip many_to_one :mme_ip, class: Ip many_to_one :epc many_to_one :cmc plugin :nested_attributes nested_attributes :control_ip, :pgw_ip, :mme_ip, :epc, :cmc sfa_add_namespace :flex, 'http://nitlab.inf.uth.gr/schema/sfa/rspec/lte/1' sfa_class 'e_node_b', :can_be_referred => true, :expose_id => false, :namespace => :flex sfa :availability, :attr_value => 'now', :attr_name => 'available' sfa :base_model, :namespace => :flex sfa :vendor, :namespace => :flex sfa :mode, :namespace => :flex sfa :center_ul_frequency, :namespace => :flex sfa :center_dl_frequency, :namespace => :flex sfa :channel_bandwidth, :namespace => :flex sfa :number_of_antennas, :namespace => :flex sfa :tx_power, :namespace => :flex sfa :mme_sctp_port, :namespace => :flex sfa :control_ip, :namespace => :flex sfa :pgw_ip, :namespace => :flex sfa :mme_ip, :namespace => :flex def availability self.available_now? end def self.exclude_from_json sup = super [:control_ip_id, :pgw_ip_id, :mme_ip_id, :epc_id, :cmc_id].concat(sup) end def self.include_nested_attributes_to_json sup = super [:leases, :control_ip, :pgw_ip, :mme_ip, :epc, :cmc].concat(sup) end def self.can_be_managed? true end end end add sliver_id on e_node_b manifest require 'omf-sfa/models/component' require 'omf-sfa/models/ip' require 'omf-sfa/models/epc' module OMF::SFA::Model class ENodeB < Component many_to_one :control_ip, class: Ip many_to_one :pgw_ip, class: Ip many_to_one :mme_ip, class: Ip many_to_one :epc many_to_one :cmc plugin :nested_attributes nested_attributes :control_ip, :pgw_ip, :mme_ip, :epc, :cmc sfa_add_namespace :flex, 'http://nitlab.inf.uth.gr/schema/sfa/rspec/lte/1' sfa_class 'e_node_b', :can_be_referred => true, :expose_id => false, :namespace => :flex sfa :availability, :attr_value => 'now', :attr_name => 'available' sfa :base_model, :namespace => :flex sfa :vendor, :namespace => :flex sfa :mode, :namespace => :flex sfa :center_ul_frequency, :namespace => :flex sfa :center_dl_frequency, :namespace => :flex sfa :channel_bandwidth, :namespace => :flex sfa :number_of_antennas, :namespace => :flex sfa :tx_power, :namespace => :flex sfa :mme_sctp_port, :namespace => :flex sfa :control_ip, :namespace => :flex sfa :pgw_ip, :namespace => :flex sfa :mme_ip, :namespace => :flex sfa :sliver_id, :attribute => true def availability self.available_now? end def sliver_id return nil if self.parent.nil? return nil if self.leases.nil? || self.leases.empty? self.leases.first.urn end def self.exclude_from_json sup = super [:control_ip_id, :pgw_ip_id, :mme_ip_id, :epc_id, :cmc_id].concat(sup) end def self.include_nested_attributes_to_json sup = super [:leases, :control_ip, :pgw_ip, :mme_ip, :epc, :cmc].concat(sup) end def self.can_be_managed? true end end end
module OmniAuth module Strategies class PAM include OmniAuth::Strategy option :name, 'pam' option :fields, [:username] option :uid_field, :username # this map is used to return gecos in info option :gecos_map, [:name, :location, :phone, :home_phone, :description] def request_phase OmniAuth::Form.build( :title => (options[:title] || "Authenticate"), :url => callback_path ) do |field| field.text_field 'Username', 'username' field.password_field 'Password', 'password' end.to_response end def callback_phase rpam_opts = Hash.new rpam_opts[:service] = options[:service] unless options[:service].nil? unless Rpam.auth(request['username'], request['password'], rpam_opts) return fail!(:invalid_credentials) end super end def parse_gecos if options[:gecos_map].kind_of?(Array) begin gecos = Etc.getpwnam(uid).gecos.split(',') Hash[options[:gecos_map].zip(gecos)].delete_if { |k, v| v.nil? } rescue end end {} # make sure we return something mergeable end uid do request['username'] end info do { :nickname => uid, :name => uid, :email => "#{uid}#{ options.has_key?(:email) ? options[:email] : ''}" }.merge!(parse_gecos) end end end end OmniAuth.config.add_camelization 'pam', 'PAM' Fix parse_gecos to actually work module OmniAuth module Strategies class PAM include OmniAuth::Strategy option :name, 'pam' option :fields, [:username] option :uid_field, :username # this map is used to return gecos in info option :gecos_map, [:name, :location, :phone, :home_phone, :description] def request_phase OmniAuth::Form.build( :title => (options[:title] || "Authenticate"), :url => callback_path ) do |field| field.text_field 'Username', 'username' field.password_field 'Password', 'password' end.to_response end def callback_phase rpam_opts = Hash.new rpam_opts[:service] = options[:service] unless options[:service].nil? unless Rpam.auth(request['username'], request['password'], rpam_opts) return fail!(:invalid_credentials) end super end def parse_gecos if options[:gecos_map].kind_of?(Array) begin gecos = Etc.getpwnam(uid).gecos.split(',') Hash[options[:gecos_map].zip(gecos)].delete_if { |k, v| v.nil? } rescue end end end uid do request['username'] end info do { :nickname => uid, :name => uid, :email => "#{uid}#{ options.has_key?(:email) ? options[:email] : ''}" }.merge!(parse_gecos || {}) end end end end OmniAuth.config.add_camelization 'pam', 'PAM'
module Oscflow module Client class OscSend end end end osc client methods module Oscflow module Client class OscSend def connect(host="localhost",port=8080) @client = OSC::Client.new( host, port ) puts "Connected to #{host}:#{port}" end def send_data(channel, message) @client.send( OSC::Message.new( "/#{channel}" , message )) end end end end
module ParamsTransformer class Base attr_reader :params, :inputs attr_accessor :inputs def initialize(args) @params = Rails.version[0].to_i > 4 ? args.to_h.with_indifferent_access : HashWithIndifferentAccess.new(args) @inputs = set_inputs after_init(@params) end def transform hash = {} inputs.each do |input| value = instance_variable_get("@#{input.variable_name}") # only set values to nil when they are intended to be nil next if value.nil? && (input.association? || params.keys.exclude?(input.name.to_s)) hash[input.variable_name] = value end hash end def self.input(name, type = nil, options = {}) @@input_definitions ||= {} array = @@input_definitions[self.name].present? ? @@input_definitions[self.name] : [] array << [name, type, options] @@input_definitions[self.name] = array end def self.input_definitions @@input_definitions end private def set_inputs setter = ParamsTransformer::DirectoryParser.new(current_class_name: self.class.name) all_inputs = [] ParamsTransformer::Transformer.input_definitions.each do |class_name, form_inputs| next unless setter.relevant_classes.include?(class_name) form_inputs.each do |form_input| all_inputs << set_input(form_input) end end all_inputs end def set_input(form_input) name = form_input[0] type = form_input[1] options = form_input[2] input_value = params[name] input = ParamsTransformer::Input.new(self, name, type, input_value, options) self.class.__send__(:attr_accessor, input.variable_name) instance_variable_set("@#{input.variable_name.to_s}", input.parsed_value) return input end # METHODS FOR CHILDREN def after_init(args) # this method is optionally implemented by children to # override default initialization behavior end end end update reference to base file to match name change module ParamsTransformer class Base attr_reader :params, :inputs attr_accessor :inputs def initialize(args) @params = Rails.version[0].to_i > 4 ? args.to_h.with_indifferent_access : HashWithIndifferentAccess.new(args) @inputs = set_inputs after_init(@params) end def transform hash = {} inputs.each do |input| value = instance_variable_get("@#{input.variable_name}") # only set values to nil when they are intended to be nil next if value.nil? && (input.association? || params.keys.exclude?(input.name.to_s)) hash[input.variable_name] = value end hash end def self.input(name, type = nil, options = {}) @@input_definitions ||= {} array = @@input_definitions[self.name].present? ? @@input_definitions[self.name] : [] array << [name, type, options] @@input_definitions[self.name] = array end def self.input_definitions @@input_definitions end private def set_inputs setter = ParamsTransformer::DirectoryParser.new(current_class_name: self.class.name) all_inputs = [] ParamsTransformer::Base.input_definitions.each do |class_name, form_inputs| next unless setter.relevant_classes.include?(class_name) form_inputs.each do |form_input| all_inputs << set_input(form_input) end end all_inputs end def set_input(form_input) name = form_input[0] type = form_input[1] options = form_input[2] input_value = params[name] input = ParamsTransformer::Input.new(self, name, type, input_value, options) self.class.__send__(:attr_accessor, input.variable_name) instance_variable_set("@#{input.variable_name.to_s}", input.parsed_value) return input end # METHODS FOR CHILDREN def after_init(args) # this method is optionally implemented by children to # override default initialization behavior end end end
module Paypal module Payment class Response < Base attr_accessor :amount, :ship_to, :description, :note, :items, :notify_url, :insurance_option_offered, :currency_code, :error_code, :transaction_id, :billing_agreement_id def initialize(attributes = {}) attrs = attributes.dup @amount = Common::Amount.new( :total => attrs.delete(:AMT), :item => attrs.delete(:ITEMAMT), :handing => attrs.delete(:HANDLINGAMT), :insurance => attrs.delete(:INSURANCEAMT), :ship_disc => attrs.delete(:SHIPDISCAMT), :shipping => attrs.delete(:SHIPPINGAMT), :tax => attrs.delete(:TAXAMT) ) @ship_to = Payment::Response::ShipTo.new( :name => attrs.delete(:SHIPTONAME), :zip => attrs.delete(:SHIPTOZIP), :street => attrs.delete(:SHIPTOSTREET), :street2 => attrs.delete(:SHIPTOSTREET2), :city => attrs.delete(:SHIPTOCITY), :state => attrs.delete(:SHIPTOSTATE), :country_code => attrs.delete(:SHIPTOCOUNTRYCODE), :country_name => attrs.delete(:SHIPTOCOUNTRYNAME) ) @description = attrs.delete(:DESC) @note = attrs.delete(:NOTETEXT) @notify_url = attrs.delete(:NOTIFYURL) @insurance_option_offered = attrs.delete(:INSURANCEOPTIONOFFERED) == 'true' @currency_code = attrs.delete(:CURRENCYCODE) @error_code = attrs.delete(:ERRORCODE) @transaction_id = attrs.delete(:TRANSACTIONID) @billing_agreement_id = attrs.delete(:BILLINGAGREEMENTID) # items items = [] attrs.keys.each do |_attr_| key, index = _attr_.to_s.scan(/^(.+)(\d)$/).flatten if index items[index.to_i] ||= {} items[index.to_i][key.to_sym] = attrs.delete(:"#{key}#{index}") end end @items = items.collect do |_attr_| Item.new(_attr_) end # warn ignored params attrs.each do |key, value| Paypal.log "Ignored Parameter (#{self.class}): #{key}=#{value}", :warn end end end end end Add error type fields to payment responses. module Paypal module Payment class Response < Base attr_accessor :amount, :ship_to, :description, :note, :items, :notify_url, :insurance_option_offered, :currency_code, :short_message, :long_message, :error_code, :severity_code, :ack, :transaction_id, :billing_agreement_id def initialize(attributes = {}) attrs = attributes.dup @amount = Common::Amount.new( :total => attrs.delete(:AMT), :item => attrs.delete(:ITEMAMT), :handing => attrs.delete(:HANDLINGAMT), :insurance => attrs.delete(:INSURANCEAMT), :ship_disc => attrs.delete(:SHIPDISCAMT), :shipping => attrs.delete(:SHIPPINGAMT), :tax => attrs.delete(:TAXAMT) ) @ship_to = Payment::Response::ShipTo.new( :name => attrs.delete(:SHIPTONAME), :zip => attrs.delete(:SHIPTOZIP), :street => attrs.delete(:SHIPTOSTREET), :street2 => attrs.delete(:SHIPTOSTREET2), :city => attrs.delete(:SHIPTOCITY), :state => attrs.delete(:SHIPTOSTATE), :country_code => attrs.delete(:SHIPTOCOUNTRYCODE), :country_name => attrs.delete(:SHIPTOCOUNTRYNAME) ) @description = attrs.delete(:DESC) @note = attrs.delete(:NOTETEXT) @notify_url = attrs.delete(:NOTIFYURL) @insurance_option_offered = attrs.delete(:INSURANCEOPTIONOFFERED) == 'true' @currency_code = attrs.delete(:CURRENCYCODE) @short_message = attrs.delete(:SHORTMESSAGE) @long_message = attrs.delete(:LONGMESSAGE) @error_code = attrs.delete(:ERRORCODE) @severity_code = attrs.delete(:SEVERITYCODE) @ack = attrs.delete(:ACK) @transaction_id = attrs.delete(:TRANSACTIONID) @billing_agreement_id = attrs.delete(:BILLINGAGREEMENTID) # items items = [] attrs.keys.each do |_attr_| key, index = _attr_.to_s.scan(/^(.+)(\d)$/).flatten if index items[index.to_i] ||= {} items[index.to_i][key.to_sym] = attrs.delete(:"#{key}#{index}") end end @items = items.collect do |_attr_| Item.new(_attr_) end # warn ignored params attrs.each do |key, value| Paypal.log "Ignored Parameter (#{self.class}): #{key}=#{value}", :warn end end end end end
module Phonelib # @private phone analyzing methods module module PhoneAnalyzer # extending with helper methods for analyze include Phonelib::PhoneAnalyzerHelper # array of types not included for validation check in cycle NOT_FOR_CHECK = [:general_desc, :fixed_line, :mobile, :fixed_or_mobile] # parses provided phone if it is valid for country data and # returns result of analyze # # ==== Attributes # # * +phone+ - Phone number for parsing # * +passed_country+ - Country provided for parsing. Must be ISO code of # country (2 letters) like 'US', 'us' or :us for United States def analyze(phone, passed_country) country = country_or_default_country passed_country result = try_to_parse_country(phone, country) case when result && !result.values.find {|e| e[:valid].any? }.nil? # all is good, return result d_result = nil when passed_country.nil? # trying for all countries if no country was passed detected = detect_and_parse phone d_result = detected.empty? ? result || {} : detected when !original_string.start_with?('+') && country_can_double_prefix?(country) # if country allows double prefix trying modified phone d_result = try_to_parse_country(changed_double_prefixed_phone(country, phone), country) end better_result(result, d_result) end private # method checks which result is better to return def better_result(base_result, result = nil) if result.nil? return base_result || {} end if base_result.nil? || base_result.empty? || base_result.values.find {|e| e[:possible].any? }.nil? return result end if result && result.values.find {|e| e[:valid].any? } return result end base_result || {} end # trying to parse phone for single country including international prefix # check for provided country # # ==== Attributes # # * +phone+ - phone for parsing # * +country+ - country to parse phone with def try_to_parse_country(phone, country) data = Phonelib.phone_data[country] return nil unless country && data # if country was provided and it's a valid country, trying to # create e164 representation of phone number, # kind of normalization for parsing e164 = convert_to_e164 phone, data # if phone starts with international prefix of provided # country try to reanalyze without international prefix for # all countries return analyze(e164.delete('+'), nil) if e164[0] == '+' # trying to parse number for provided country parse_single_country e164, data end # method checks if phone is valid against single provided country data # # ==== Attributes # # * +e164+ - e164 representation of phone for parsing # * +data+ - country data for single country for parsing def parse_single_country(e164, data) valid_match = phone_match_data?(e164, data) if valid_match national_and_data(e164, data, valid_match) else possible_match = phone_match_data?(e164, data, true) possible_match && national_and_data(e164, data, possible_match, true) end end # method tries to detect what is the country for provided phone # # ==== Attributes # # * +phone+ - phone number for parsing def detect_and_parse(phone) result = {} Phonelib.phone_data.each do |key, data| parsed = parse_single_country(phone, data) if double_prefix_allowed?(data, phone, parsed && parsed[key]) parsed = parse_single_country(changed_double_prefixed_phone(key, phone), data) end result.merge!(parsed) unless parsed.nil? end result end # Create phone representation in e164 format # # ==== Attributes # # * +phone+ - phone number for parsing # * +data+ - country data to be based on for creating e164 representation def convert_to_e164(phone, data) match = phone.match full_regex_for_data(data, Core::VALID_PATTERN) case when match national_start = phone.length - match.to_a.last.size "#{data[Core::COUNTRY_CODE]}#{phone[national_start..-1]}" when phone.match(cr("^#{data[Core::INTERNATIONAL_PREFIX]}")) phone.sub(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"), '+') else "#{data[Core::COUNTRY_CODE]}#{phone}" end end # returns national number and analyzing results for provided phone number # # ==== Attributes # # * +phone+ - phone number for parsing # * +data+ - country data # * +country_match+ - result of match of phone within full regex # * +not_valid+ - specifies that number is not valid by general desc pattern def national_and_data(phone, data, country_match, not_valid = false) prefix_length = data[Core::COUNTRY_CODE].length prefix_length += [1, 2].map { |i| country_match[i].to_s.size }.inject(:+) result = data.select { |k, _v| k != :types && k != :formats } result[:national] = phone[prefix_length..-1] || '' result[:format] = number_format(result[:national], data[Core::FORMATS]) result.merge! all_number_types(result[:national], data[Core::TYPES], not_valid) result[:valid] = [] if not_valid { result[:id] => result } end # Returns all valid and possible phone number types for currently parsed # phone for provided data hash. # # ==== Attributes # # * +phone+ - phone number for parsing # * +data+ - country data # * +not_valid+ - specifies that number is not valid by general desc pattern def all_number_types(phone, data, not_valid = false) response = { valid: [], possible: [] } types_for_check(data).each do |type| possible, valid = get_patterns(data, type) valid_and_possible, possible_result = number_valid_and_possible?(phone, possible, valid, not_valid) response[:possible] << type if possible_result response[:valid] << type if valid_and_possible end sanitize_fixed_mobile(response) end # Gets matched number formatting rule or default one # # ==== Attributes # # * +national+ - national phone number # * +format_data+ - formatting data from country data def number_format(national, format_data) format_data && format_data.find do |format| (format[Core::LEADING_DIGITS].nil? \ || national.match(cr("^(#{format[Core::LEADING_DIGITS]})"))) \ && national.match(cr("^(#{format[Core::PATTERN]})$")) end || Core::DEFAULT_NUMBER_FORMAT end # Returns possible and valid patterns for validation for provided type # # ==== Attributes # # * +all_patterns+ - hash of all patterns for validation # * +type+ - type of phone to get patterns for def get_patterns(all_patterns, type) type = Core::FIXED_LINE if type == Core::FIXED_OR_MOBILE patterns = all_patterns[type] if patterns.nil? [nil, nil] else [patterns[Core::POSSIBLE_PATTERN], patterns[Core::VALID_PATTERN]] end end end end improving code module Phonelib # @private phone analyzing methods module module PhoneAnalyzer # extending with helper methods for analyze include Phonelib::PhoneAnalyzerHelper # array of types not included for validation check in cycle NOT_FOR_CHECK = [:general_desc, :fixed_line, :mobile, :fixed_or_mobile] # parses provided phone if it is valid for country data and # returns result of analyze # # ==== Attributes # # * +phone+ - Phone number for parsing # * +passed_country+ - Country provided for parsing. Must be ISO code of # country (2 letters) like 'US', 'us' or :us for United States def analyze(phone, passed_country) country = country_or_default_country passed_country result = try_to_parse_country(phone, country) d_result = case when result && result.values.find {|e| e[:valid].any? } # all is good, return result when passed_country.nil? # trying for all countries if no country was passed detect_and_parse phone when !original_string.start_with?('+') && country_can_double_prefix?(country) # if country allows double prefix trying modified phone try_to_parse_country(changed_double_prefixed_phone(country, phone), country) end better_result(result, d_result) end private # method checks which result is better to return def better_result(base_result, result = nil) if result.nil? return base_result || {} end if base_result.nil? || base_result.empty? || base_result.values.find {|e| e[:possible].any? }.nil? return result end if result && result.values.find {|e| e[:valid].any? } return result end base_result || {} end # trying to parse phone for single country including international prefix # check for provided country # # ==== Attributes # # * +phone+ - phone for parsing # * +country+ - country to parse phone with def try_to_parse_country(phone, country) data = Phonelib.phone_data[country] return nil unless country && data # if country was provided and it's a valid country, trying to # create e164 representation of phone number, # kind of normalization for parsing e164 = convert_to_e164 phone, data # if phone starts with international prefix of provided # country try to reanalyze without international prefix for # all countries return analyze(e164.delete('+'), nil) if e164[0] == '+' # trying to parse number for provided country parse_single_country e164, data end # method checks if phone is valid against single provided country data # # ==== Attributes # # * +e164+ - e164 representation of phone for parsing # * +data+ - country data for single country for parsing def parse_single_country(e164, data) valid_match = phone_match_data?(e164, data) if valid_match national_and_data(e164, data, valid_match) else possible_match = phone_match_data?(e164, data, true) possible_match && national_and_data(e164, data, possible_match, true) end end # method tries to detect what is the country for provided phone # # ==== Attributes # # * +phone+ - phone number for parsing def detect_and_parse(phone) result = {} Phonelib.phone_data.each do |key, data| parsed = parse_single_country(phone, data) if double_prefix_allowed?(data, phone, parsed && parsed[key]) parsed = parse_single_country(changed_double_prefixed_phone(key, phone), data) end result.merge!(parsed) unless parsed.nil? end result end # Create phone representation in e164 format # # ==== Attributes # # * +phone+ - phone number for parsing # * +data+ - country data to be based on for creating e164 representation def convert_to_e164(phone, data) match = phone.match full_regex_for_data(data, Core::VALID_PATTERN) case when match national_start = phone.length - match.to_a.last.size "#{data[Core::COUNTRY_CODE]}#{phone[national_start..-1]}" when phone.match(cr("^#{data[Core::INTERNATIONAL_PREFIX]}")) phone.sub(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"), '+') else "#{data[Core::COUNTRY_CODE]}#{phone}" end end # returns national number and analyzing results for provided phone number # # ==== Attributes # # * +phone+ - phone number for parsing # * +data+ - country data # * +country_match+ - result of match of phone within full regex # * +not_valid+ - specifies that number is not valid by general desc pattern def national_and_data(phone, data, country_match, not_valid = false) prefix_length = data[Core::COUNTRY_CODE].length prefix_length += [1, 2].map { |i| country_match[i].to_s.size }.inject(:+) result = data.select { |k, _v| k != :types && k != :formats } result[:national] = phone[prefix_length..-1] || '' result[:format] = number_format(result[:national], data[Core::FORMATS]) result.merge! all_number_types(result[:national], data[Core::TYPES], not_valid) result[:valid] = [] if not_valid { result[:id] => result } end # Returns all valid and possible phone number types for currently parsed # phone for provided data hash. # # ==== Attributes # # * +phone+ - phone number for parsing # * +data+ - country data # * +not_valid+ - specifies that number is not valid by general desc pattern def all_number_types(phone, data, not_valid = false) response = { valid: [], possible: [] } types_for_check(data).each do |type| possible, valid = get_patterns(data, type) valid_and_possible, possible_result = number_valid_and_possible?(phone, possible, valid, not_valid) response[:possible] << type if possible_result response[:valid] << type if valid_and_possible end sanitize_fixed_mobile(response) end # Gets matched number formatting rule or default one # # ==== Attributes # # * +national+ - national phone number # * +format_data+ - formatting data from country data def number_format(national, format_data) format_data && format_data.find do |format| (format[Core::LEADING_DIGITS].nil? \ || national.match(cr("^(#{format[Core::LEADING_DIGITS]})"))) \ && national.match(cr("^(#{format[Core::PATTERN]})$")) end || Core::DEFAULT_NUMBER_FORMAT end # Returns possible and valid patterns for validation for provided type # # ==== Attributes # # * +all_patterns+ - hash of all patterns for validation # * +type+ - type of phone to get patterns for def get_patterns(all_patterns, type) type = Core::FIXED_LINE if type == Core::FIXED_OR_MOBILE patterns = all_patterns[type] if patterns.nil? [nil, nil] else [patterns[Core::POSSIBLE_PATTERN], patterns[Core::VALID_PATTERN]] end end end end
module Piv module Helpers module Application extend ActiveSupport::Concern # TODO: Move to config file API_URL = "https://www.pivotaltracker.com/services/v5/" module ClassMethods attr_accessor :global_dir end def session_in_progress? !!current_session end def current_session Session.current end def client @client ||= Client.new(API_URL) end def global_installer @global_installer ||= MicroCommands::InstallGlobal.new(self.class.global_dir) end def assure_globally_installed global_installer.run :up unless global_installer.done? end end end end Allow Piv::Helpers::Application module to include accessor methods to receive connection during configuration time. also raise an error as part of assuring global installation in the case the connection or global directory configs are missing module Piv class ConfigurationError < StandardError; end module Helpers module Application extend ActiveSupport::Concern module ClassMethods attr_accessor :global_dir, :connection end def session_in_progress? !!current_session end def current_session Session.current end def client @client ||= Client.new(self.class.connection) do |c| c.options.timeout = 4 end end def global_installer @global_installer ||= MicroCommands::InstallGlobal.new(self.class.global_dir) end def assure_globally_installed raise ConfigurationError, "make sure connection and global directory are established" unless self.class.global_dir && self.class.connection global_installer.run :up unless global_installer.done? end end end end
module PngQuantizator VERSION = "0.1.1" end bump version module PngQuantizator VERSION = "0.2.0" end
class Spec::Runner::Options attr_accessor :selenium_configuration, :selenium_app_runner def run_examples_with_selenium_runner(*args) result = run_examples_without_selenium_runner(*args) selenium_app_runner.stop selenium_configuration.stop_driver_if_necessary(passed) result end alias_method_chain :run_examples, :selenium_runner end rspec_options.selenium_configuration = Polonium::Configuration.instance rspec_options.selenium_app_runner = nil Spec::Example::ExampleMethods.before(:all) do unless rspec_options.selenium_app_runner rspec_options.selenium_app_runner = rspec_options.selenium_configuration.create_server_runner rspec_options.selenium_app_runner.start end end CTI/BT - Fix success variable in Options#run_examples. git-svn-id: e4a4d536aa56eeafd4da76318df01900fcfef01f@1120 af276e61-6b34-4dac-905b-574b5f35ef33 class Spec::Runner::Options attr_accessor :selenium_configuration, :selenium_app_runner def run_examples_with_selenium_runner(*args) success = run_examples_without_selenium_runner(*args) selenium_app_runner.stop selenium_configuration.stop_driver_if_necessary(success) success end alias_method_chain :run_examples, :selenium_runner end rspec_options.selenium_configuration = Polonium::Configuration.instance rspec_options.selenium_app_runner = nil Spec::Example::ExampleMethods.before(:all) do unless rspec_options.selenium_app_runner rspec_options.selenium_app_runner = rspec_options.selenium_configuration.create_server_runner rspec_options.selenium_app_runner.start end end
# -*- encoding : utf-8 -*- module PPCurses class ComboBox DOWN_ARROW = '∇' attr_accessor :selected def initialize( label, options) @label = label end def show(screen) screen.attron(A_REVERSE) if @selected screen.addstr("#{@label}:") screen.attroff(A_REVERSE) if @selected screen.addstr(" - select - #{DOWN_ARROW}") end def height 1 end def set_curs_pos(screen) curs_set(INVISIBLE) end def handle_keypress(key) if key == ENTER then # TODO -- open a menu with options... end false end end end Display options, overlay menu window to position of combo box. # -*- encoding : utf-8 -*- module PPCurses class ComboBox DOWN_ARROW = '∇' attr_accessor :selected def initialize( label, options) @label = label @options = options end def show(screen) screen.attron(A_REVERSE) if @selected screen.addstr("#{@label}:") @combo_display_point = screen.cur_point screen.attroff(A_REVERSE) if @selected screen.addstr(" - select - #{DOWN_ARROW}") end def height 1 end def set_curs_pos(screen) curs_set(INVISIBLE) end def handle_keypress(key) if key == ENTER # TODO - Sub menu must handle ENTER options_menu = PPCurses::Menu.new( @options, nil ) options_menu.set_origin(@combo_display_point) options_menu.show options_menu.menu_selection options_menu.close end false end end end
# # File: PpmContextObjs.rb # # These are PrimaryParameters context objects # # ############################################################################## # Everything is contained in Module PpmToGdl module PpmToGdl ########################################################################## # MPpm class describes a PPM object class MPpm attr_accessor :id attr_accessor :name attr_accessor :alias attr_accessor :varType # Type attribute - What portion of decision log value comes from: valid values "PRD, CRP, APM attr_accessor :dataType # DataType attribute -numeric, text, money, etc. attr_accessor :customer attr_accessor :verbose # def initialize(name, als, varType, dataType) # @name = name # @alias = als # @varType = varType # @dataType = dataType # # end # initialize def initialize(name, attributes, verbose=false) $LOG.debug "Ppm::initialize( #{name}, #{attributes} )" @verbose = verbose @name = name @alias = attributes["Name"] @varType = attributes["Type"] #@dataType = "UNKNOWN" @dataType = attributes["Datatype"] #if (attributes.has_key?("Datatype")) @customer = attributes["Customer"] if(@verbose) attributes.each do |k, v| puts "Attrib[ #{k} ]: #{v}" end end case @varType when 'APM' @varType = "app" when 'CRP' @varType = "crd" when 'PRD' @varType = "prd" end # varType case @dataType when 'Boolean' @dataType = "boolean" when 'Date' @dataType = "date" when 'Money' @dataType = "money" when 'Numeric' @dataType = "numeric" when 'Percentage' @dataType = "percentage" when 'Text' @dataType = "text" end # dataType end # initialize end # class Ppm end # module PpmToGdl Adding support for DateTime DataType # # File: PpmContextObjs.rb # # These are PrimaryParameters context objects # # ############################################################################## # Everything is contained in Module PpmToGdl module PpmToGdl ########################################################################## # MPpm class describes a PPM object class MPpm attr_accessor :id attr_accessor :name attr_accessor :alias attr_accessor :varType # Type attribute - What portion of decision log value comes from: valid values "PRD, CRP, APM attr_accessor :dataType # DataType attribute -numeric, text, money, etc. attr_accessor :customer attr_accessor :verbose # def initialize(name, als, varType, dataType) # @name = name # @alias = als # @varType = varType # @dataType = dataType # # end # initialize def initialize(name, attributes, verbose=false) $LOG.debug "Ppm::initialize( #{name}, #{attributes} )" @verbose = verbose @name = name @alias = attributes["Name"] @varType = attributes["Type"] #@dataType = "UNKNOWN" @dataType = attributes["Datatype"] #if (attributes.has_key?("Datatype")) @customer = attributes["Customer"] if(@verbose) attributes.each do |k, v| puts "Attrib[ #{k} ]: #{v}" end end case @varType when 'APM' @varType = "app" when 'CRP' @varType = "crd" when 'PRD' @varType = "prd" end # varType case @dataType when 'Boolean' @dataType = "boolean" when 'Date' @dataType = "date" when 'Money' @dataType = "money" when 'Numeric' @dataType = "numeric" when 'Percentage' @dataType = "percentage" when 'Text' @dataType = "text" when 'DateTime' @dataType = "datetime" end # dataType end # initialize end # class Ppm end # module PpmToGdl
# frozen_string_literal: true # The purpose of the DatasetResolver class is to take a GraphQL AST describing # the attributes and associations that are desired in a query, and then # construct a set of DB queries to fulfill the request correctly and # efficiently. The "correctly" part requires applying the appropriate filters # to the query, while "efficiently" requires some thought about retrieving # only the columns we need from the DB and manually eager-loading the # appropriate associations. require 'prelay/result_array' module Prelay class DatasetResolver ZERO_OR_ONE = 0..1 EMPTY_RESULT_ARRAY = ResultArray.new(EMPTY_ARRAY).freeze def initialize(selections_by_type:) @types = selections_by_type end def resolve records = [] overall_order = nil count = 0 @types.each do |type, ast| ds = type.model.dataset ds = yield(ds) supplemental_columns = [] supplemental_columns << :cursor if need_ordering_in_ruby? ds = apply_query_to_dataset(ds, type: type, supplemental_columns: supplemental_columns) if ast.count_requested? count += ds.unordered.unlimited.count end ds = apply_pagination_to_dataset(ds, type: type) derived_order = ds.opts[:order] overall_order ||= derived_order raise "Trying to merge results from datasets in different orders!" unless overall_order == derived_order records += results_for_dataset(ds, type: type) end # Each individual result set is sorted, now we need to make sure the # union is sorted as well. sort_records_by_order(records, overall_order) if need_ordering_in_ruby? r = ResultArray.new(records) r.total_count = count r end def resolve_singular # TODO: Can just stop iterating through types when we get a match. records = [] @types.each_key do |type| ds = type.model.dataset ds = yield(ds) ds = apply_query_to_dataset(ds, type: type) records += results_for_dataset(ds, type: type) end raise "Too many records!" unless ZERO_OR_ONE === records.length records.first end def resolve_via_association(association, ids) return [EMPTY_RESULT_ARRAY, {}] if ids.none? block = association.sequel_association&.dig(:block) order = association.derived_order records = [] remote_column = association.remote_columns.first # TODO: Multiple columns? overall_order = nil counts = {} @types.each do |type, ast| qualified_remote_column = Sequel.qualify(type.model.table_name, remote_column) ds = type.model.dataset ds = ds.order(order) supplemental_columns = [remote_column] supplemental_columns << :cursor if need_ordering_in_ruby? ds = apply_query_to_dataset(ds, type: type, supplemental_columns: supplemental_columns) ds = block.call(ds) if block ds = ds.where(qualified_remote_column => ids) if ast.count_requested? more_counts = ds.unlimited.unordered.from_self.group_by(remote_column).select_hash(remote_column, Sequel.as(Sequel.function(:count, Sequel.lit('*')), :count)) counts = counts.merge(more_counts) { |k,o,n| o + n } end ds = apply_pagination_to_dataset(ds, type: type) derived_order = ds.opts[:order] overall_order ||= derived_order raise "Trying to merge results from datasets in different orders!" unless overall_order == derived_order if ids.length > 1 && limit = ds.opts[:limit] # Steal Sequel's technique for limiting eager-loaded associations with # a window function. ds = ds. unlimited. unordered. select_append(Sequel.function(:row_number).over(partition: qualified_remote_column, order: ds.opts[:order]).as(:prelay_row_number)). from_self. where { |r| r.<=(:prelay_row_number, limit) } end records += results_for_dataset(ds, type: type) end sort_records_by_order(records, overall_order) if need_ordering_in_ruby? [ResultArray.new(records), counts] end protected def apply_query_to_dataset(ds, type:, supplemental_columns: EMPTY_ARRAY) ast = @types.fetch(type) arguments = ast.arguments table_name = ds.model.table_name if scope = type.dataset_scope ds = scope.call(ds) end ([type] + type.interfaces.keys.reverse).each do |filter_source| filter_source.filters.each do |name, (type, block)| if value = arguments[name] ds = block.call(ds, value) end end end columns = ast.columns + supplemental_columns columns.uniq! if columns.delete(:cursor) order = ds.opts[:order] raise "Can't handle ordering by anything other than a single column!" unless order&.length == 1 exp = unwrap_order_expression(order.first) columns << Sequel.as(exp, :cursor) end selections = (ds.opts[:select] || EMPTY_ARRAY) + columns.map{|c| qualify_column(table_name, c)} if selections.count > 0 ds = ds.select(*selections) end ds end def apply_pagination_to_dataset(ds, type:) ast = @types.fetch(type) arguments = ast.arguments if limit = arguments[:first] || arguments[:last] ds = ds.reverse_order if arguments[:last] # If has_next_page or has_previous_page was requested, bump the limit # by one so we know whether there's another page coming up. limit += 1 if ast.pagination_info_requested? ds = if cursor = arguments[:after] || arguments[:before] values = JSON.parse(Base64.decode64(cursor)) expressions = ds.opts[:order].zip(values).map do |o, v| e = unwrap_order_expression(o) if e.is_a?(Sequel::SQL::Function) && e.name == :ts_rank_cd # Minor hack for full-text search, which returns reals when # Sequel assumes floats are double precision. Sequel.cast(v, :real) elsif e == :created_at Time.at(*v) # value should be an array of two integers, seconds and microseconds. else v end end ds.seek_paginate(limit, after: expressions) else ds.seek_paginate(limit) end end ds end private # If we're loading more than one type, and therefore executing more than # one query, we'll need to sort the combined results in Ruby. In other # words, to get the ten earliest posts + comments, we need to retrieve the # ten earliest posts, the ten earliest comments, concatenate them # together, sort them by their created_at, and take the first ten. def need_ordering_in_ruby? @types.length > 1 end def sort_records_by_order(records, order) records.sort_by!{|r| r.record.values.fetch(:cursor)} o = order.is_a?(Array) ? order.first : order records.reverse! if o.is_a?(Sequel::SQL::OrderedExpression) && o.descending records end def unwrap_order_expression(oe) case oe when Sequel::SQL::OrderedExpression oe.expression else oe end end def qualify_column(table_name, column) case column when Symbol Sequel.qualify(table_name, column) when Sequel::SQL::AliasedExpression Sequel.as(qualify_column(table_name, column.expression), column.aliaz) when Sequel::SQL::QualifiedIdentifier # TODO: Figure out when/how this happens and stop it. raise "Table qualification mismatch: #{column.table.inspect}, #{table_name.inspect}" unless column.table == table_name column else # Could be any arbitrary expression, like a function call or an SQL subquery. column end end def results_for_dataset(ds, type:) objects = ds.all.map{|r| type.new(r)} ResultArray.new(objects).tap { |results| process_associations_for_results(results, type: type) } end def process_associations_for_results(results, type:) return if results.empty? @types.fetch(type).associations.each do |key, (association, relay_processor)| # TODO: Figure out what it means to have multiple columns here. local_column = association.local_columns.first remote_column = association.remote_columns.first ids = results.map{|r| r.record.send(local_column)}.uniq sub_records, counts = relay_processor.to_resolver.resolve_via_association(association, ids) sub_records_hash = {} if association.returns_array? sub_records.each do |r| results_array = sub_records_hash[r.record.send(remote_column)] ||= ResultArray.new([]) results_array << r end counts.each do |id, count| sub_records_hash[id].total_count = count end results.each do |r| associated_records = sub_records_hash[r.record.send(local_column)] || ResultArray.new([]) r.associations[key] = associated_records end else sub_records.each{|r| sub_records_hash[r.record.send(remote_column)] = r} results.each do |r| associated_record = sub_records_hash[r.record.send(local_column)] r.associations[key] = associated_record end end end end end end Add some error checks, just for sanity. # frozen_string_literal: true # The purpose of the DatasetResolver class is to take a GraphQL AST describing # the attributes and associations that are desired in a query, and then # construct a set of DB queries to fulfill the request correctly and # efficiently. The "correctly" part requires applying the appropriate filters # to the query, while "efficiently" requires some thought about retrieving # only the columns we need from the DB and manually eager-loading the # appropriate associations. require 'prelay/result_array' module Prelay class DatasetResolver ZERO_OR_ONE = 0..1 EMPTY_RESULT_ARRAY = ResultArray.new(EMPTY_ARRAY).freeze def initialize(selections_by_type:) @types = selections_by_type end def resolve records = [] overall_order = nil count = 0 @types.each do |type, ast| raise "Unexpected ast!: #{ast.class}" unless ast.is_a?(RelaySelection::ConnectionSelection) raise "Unexpected type!" unless type == ast.type ds = type.model.dataset ds = yield(ds) supplemental_columns = [] supplemental_columns << :cursor if need_ordering_in_ruby? ds = apply_query_to_dataset(ds, type: type, supplemental_columns: supplemental_columns) if ast.count_requested? count += ds.unordered.unlimited.count end ds = apply_pagination_to_dataset(ds, type: type) derived_order = ds.opts[:order] overall_order ||= derived_order raise "Trying to merge results from datasets in different orders!" unless overall_order == derived_order records += results_for_dataset(ds, type: type) end # Each individual result set is sorted, now we need to make sure the # union is sorted as well. sort_records_by_order(records, overall_order) if need_ordering_in_ruby? r = ResultArray.new(records) r.total_count = count r end def resolve_singular # TODO: Can just stop iterating through types when we get a match. records = [] @types.each do |type, ast| raise "Unexpected ast!: #{ast.class}" unless [RelaySelection::FieldSelection, RelaySelection::EdgeSelection].include?(ast.class) raise "Unexpected type!" unless type == ast.type ds = type.model.dataset ds = yield(ds) ds = apply_query_to_dataset(ds, type: type) records += results_for_dataset(ds, type: type) end raise "Too many records!" unless ZERO_OR_ONE === records.length records.first end def resolve_via_association(association, ids) return [EMPTY_RESULT_ARRAY, {}] if ids.none? block = association.sequel_association&.dig(:block) order = association.derived_order records = [] remote_column = association.remote_columns.first # TODO: Multiple columns? overall_order = nil counts = {} @types.each do |type, ast| raise "Unexpected selection!" unless [RelaySelection::ConnectionSelection, RelaySelection::FieldSelection].include?(ast.class) raise "Unexpected type!" unless type == ast.type qualified_remote_column = Sequel.qualify(type.model.table_name, remote_column) ds = type.model.dataset ds = ds.order(order) supplemental_columns = [remote_column] supplemental_columns << :cursor if need_ordering_in_ruby? ds = apply_query_to_dataset(ds, type: type, supplemental_columns: supplemental_columns) ds = block.call(ds) if block ds = ds.where(qualified_remote_column => ids) if ast.count_requested? more_counts = ds.unlimited.unordered.from_self.group_by(remote_column).select_hash(remote_column, Sequel.as(Sequel.function(:count, Sequel.lit('*')), :count)) counts = counts.merge(more_counts) { |k,o,n| o + n } end ds = apply_pagination_to_dataset(ds, type: type) derived_order = ds.opts[:order] overall_order ||= derived_order raise "Trying to merge results from datasets in different orders!" unless overall_order == derived_order if ids.length > 1 && limit = ds.opts[:limit] # Steal Sequel's technique for limiting eager-loaded associations with # a window function. ds = ds. unlimited. unordered. select_append(Sequel.function(:row_number).over(partition: qualified_remote_column, order: ds.opts[:order]).as(:prelay_row_number)). from_self. where { |r| r.<=(:prelay_row_number, limit) } end records += results_for_dataset(ds, type: type) end sort_records_by_order(records, overall_order) if need_ordering_in_ruby? [ResultArray.new(records), counts] end protected def apply_query_to_dataset(ds, type:, supplemental_columns: EMPTY_ARRAY) ast = @types.fetch(type) arguments = ast.arguments table_name = ds.model.table_name if scope = type.dataset_scope ds = scope.call(ds) end ([type] + type.interfaces.keys.reverse).each do |filter_source| filter_source.filters.each do |name, (type, block)| if value = arguments[name] ds = block.call(ds, value) end end end columns = ast.columns + supplemental_columns columns.uniq! if columns.delete(:cursor) order = ds.opts[:order] raise "Can't handle ordering by anything other than a single column!" unless order&.length == 1 exp = unwrap_order_expression(order.first) columns << Sequel.as(exp, :cursor) end selections = (ds.opts[:select] || EMPTY_ARRAY) + columns.map{|c| qualify_column(table_name, c)} if selections.count > 0 ds = ds.select(*selections) end ds end def apply_pagination_to_dataset(ds, type:) ast = @types.fetch(type) arguments = ast.arguments if limit = arguments[:first] || arguments[:last] ds = ds.reverse_order if arguments[:last] # If has_next_page or has_previous_page was requested, bump the limit # by one so we know whether there's another page coming up. limit += 1 if ast.pagination_info_requested? ds = if cursor = arguments[:after] || arguments[:before] values = JSON.parse(Base64.decode64(cursor)) expressions = ds.opts[:order].zip(values).map do |o, v| e = unwrap_order_expression(o) if e.is_a?(Sequel::SQL::Function) && e.name == :ts_rank_cd # Minor hack for full-text search, which returns reals when # Sequel assumes floats are double precision. Sequel.cast(v, :real) elsif e == :created_at Time.at(*v) # value should be an array of two integers, seconds and microseconds. else v end end ds.seek_paginate(limit, after: expressions) else ds.seek_paginate(limit) end end ds end private # If we're loading more than one type, and therefore executing more than # one query, we'll need to sort the combined results in Ruby. In other # words, to get the ten earliest posts + comments, we need to retrieve the # ten earliest posts, the ten earliest comments, concatenate them # together, sort them by their created_at, and take the first ten. def need_ordering_in_ruby? @types.length > 1 end def sort_records_by_order(records, order) records.sort_by!{|r| r.record.values.fetch(:cursor)} o = order.is_a?(Array) ? order.first : order records.reverse! if o.is_a?(Sequel::SQL::OrderedExpression) && o.descending records end def unwrap_order_expression(oe) case oe when Sequel::SQL::OrderedExpression oe.expression else oe end end def qualify_column(table_name, column) case column when Symbol Sequel.qualify(table_name, column) when Sequel::SQL::AliasedExpression Sequel.as(qualify_column(table_name, column.expression), column.aliaz) when Sequel::SQL::QualifiedIdentifier # TODO: Figure out when/how this happens and stop it. raise "Table qualification mismatch: #{column.table.inspect}, #{table_name.inspect}" unless column.table == table_name column else # Could be any arbitrary expression, like a function call or an SQL subquery. column end end def results_for_dataset(ds, type:) objects = ds.all.map{|r| type.new(r)} ResultArray.new(objects).tap { |results| process_associations_for_results(results, type: type) } end def process_associations_for_results(results, type:) return if results.empty? @types.fetch(type).associations.each do |key, (association, relay_processor)| # TODO: Figure out what it means to have multiple columns here. local_column = association.local_columns.first remote_column = association.remote_columns.first ids = results.map{|r| r.record.send(local_column)}.uniq sub_records, counts = relay_processor.to_resolver.resolve_via_association(association, ids) sub_records_hash = {} if association.returns_array? sub_records.each do |r| results_array = sub_records_hash[r.record.send(remote_column)] ||= ResultArray.new([]) results_array << r end counts.each do |id, count| sub_records_hash[id].total_count = count end results.each do |r| associated_records = sub_records_hash[r.record.send(local_column)] || ResultArray.new([]) r.associations[key] = associated_records end else sub_records.each{|r| sub_records_hash[r.record.send(remote_column)] = r} results.each do |r| associated_record = sub_records_hash[r.record.send(local_column)] r.associations[key] = associated_record end end end end end end
Puppet::Type.newtype(:augeas_file) do @doc = 'Manage a file from a template and Augeas changes' newparam(:path, :namevar => true) do desc 'The path to the target file' end newparam(:base) do desc 'The path to the base file' end newparam(:lens) do desc 'The Augeas lens to use' end newparam(:root) do desc "A file system path; all files loaded by Augeas are loaded underneath `root`." defaultto "/" end newparam(:load_path) do desc "Optional colon-separated list or array of directories; these directories are searched for schema definitions. The agent's `$libdir/augeas/lenses` path will always be added to support pluginsync." defaultto "" end newparam(:type_check, :boolean => true) do desc "Whether augeas should perform typechecking. Defaults to false." newvalues(:true, :false) defaultto :false end newparam(:show_diff, :boolean => true) do desc "Whether to display differences when the file changes, defaulting to true. This parameter is useful for files that may contain passwords or other secret data, which might otherwise be included in Puppet reports or other insecure outputs. If the global `show_diff` setting is false, then no diffs will be shown even if this parameter is true." defaultto :true end newparam(:changes) do desc 'The array of changes to apply to the base file' defaultto [] end # This is the actual meat of the code. It forces # augeas to be run and fails or not based on the augeas return # code. newproperty(:returns) do include Puppet::Util desc "The Augeas output. Should not be set." defaultto 0 # Make output a bit prettier def change_to_s(currentvalue, newvalue) "content successfully replaced" end def retrieve provider.need_apply? ? :need_to_run : 0 end # Actually execute the command. def sync @resource.provider.write_changes end end end boolean values Puppet::Type.newtype(:augeas_file) do @doc = 'Manage a file from a template and Augeas changes' newparam(:path, :namevar => true) do desc 'The path to the target file' end newparam(:base) do desc 'The path to the base file' end newparam(:lens) do desc 'The Augeas lens to use' end newparam(:root) do desc "A file system path; all files loaded by Augeas are loaded underneath `root`." defaultto "/" end newparam(:load_path) do desc "Optional colon-separated list or array of directories; these directories are searched for schema definitions. The agent's `$libdir/augeas/lenses` path will always be added to support pluginsync." defaultto "" end newparam(:type_check, :boolean => true) do desc "Whether augeas should perform typechecking. Defaults to false." defaultto :false end newparam(:show_diff, :boolean => true) do desc "Whether to display differences when the file changes, defaulting to true. This parameter is useful for files that may contain passwords or other secret data, which might otherwise be included in Puppet reports or other insecure outputs. If the global `show_diff` setting is false, then no diffs will be shown even if this parameter is true." defaultto :true end newparam(:changes) do desc 'The array of changes to apply to the base file' defaultto [] end # This is the actual meat of the code. It forces # augeas to be run and fails or not based on the augeas return # code. newproperty(:returns) do include Puppet::Util desc "The Augeas output. Should not be set." defaultto 0 # Make output a bit prettier def change_to_s(currentvalue, newvalue) "content successfully replaced" end def retrieve provider.need_apply? ? :need_to_run : 0 end # Actually execute the command. def sync @resource.provider.write_changes end end end
require 'yaml' require 'puppet' require File.expand_path(File.join(File.dirname(__FILE__), 'soap')) module Transip class Client def self.config_file @config_file ||= File.expand_path(File.join(Puppet.settings[:confdir], 'transip.yaml')) end def self.credentials @credentials ||= YAML.load_file(config_file) end def self.domainclient @domainclient ||= Transip::Soap.new(username: credentials['username'], key_file: credentials['key_file'], mode: :readwrite) end def self.domain_names @domain_names ||= domainclient.request(:get_domain_names)[:item] rescue Savon::SOAPFault raise Puppet::Error, 'Unable to get domain names' end def self.to_entry(dnsentry) %i[name content type expire].each_with_object({}) do |i, memo| memo[i] = dnsentry[i.to_s] end end def self.to_dnsentry(entry) # Transip::DnsEntry.new(entry[:name], entry[:expire], entry[:type], entry[:content]) entry.dup end def self.entries(domainname) to_array(domainclient.request(:get_info, domain_name: domainname).to_hash[:domain]) # rescue Transip::ApiError # raise Puppet::Error, "Unable to get entries for #{domainname}" end def self.to_array(domain) domain['dnsEntries'].map { |e| to_entry(e) } end def self.all_entries puts "domain names in all_entries: #{domain_names}\n" dnsentries = domainclient.request(:batch_get_info, domain_names: domain_names) puts "dnsentries: #{dnsentries.inspect}\n" # dnsentries = domainclient.request(:batch_get_info, domain_names: domain_names).map(&:to_hash) # dnsentries.each_with_object({}) do |domain, memo| # d = domain[:domain] # memo[d['name']] = to_array(d) # end # rescue Transip::ApiError # raise Puppet::Error, 'Unable to get entries for all domains' {} end def self.set_entries(domain, entries) dnsentries = entries.map { |e| to_dnsentry(e) } domainclient.request(:set_dns_entries, domain_name: domain, dns_entries: dnsentries) # rescue Transip::ApiError # raise Puppet::Error, "Unable to set entries for #{domain}" end end end debug require 'yaml' require 'puppet' require File.expand_path(File.join(File.dirname(__FILE__), 'soap')) module Transip class Client def self.config_file @config_file ||= File.expand_path(File.join(Puppet.settings[:confdir], 'transip.yaml')) end def self.credentials @credentials ||= YAML.load_file(config_file) end def self.domainclient @domainclient ||= Transip::Soap.new(username: credentials['username'], key_file: credentials['key_file'], mode: :readwrite) end def self.domain_names @domain_names ||= domainclient.request(:get_domain_names) rescue Savon::SOAPFault raise Puppet::Error, 'Unable to get domain names' end def self.to_entry(dnsentry) %i[name content type expire].each_with_object({}) do |i, memo| memo[i] = dnsentry[i.to_s] end end def self.to_dnsentry(entry) # Transip::DnsEntry.new(entry[:name], entry[:expire], entry[:type], entry[:content]) entry.dup end def self.entries(domainname) to_array(domainclient.request(:get_info, domain_name: domainname).to_hash[:domain]) # rescue Transip::ApiError # raise Puppet::Error, "Unable to get entries for #{domainname}" end def self.to_array(domain) domain['dnsEntries'].map { |e| to_entry(e) } end def self.all_entries puts "domain names in all_entries: #{domain_names}\n" dnsentries = domainclient.request(:batch_get_info, domain_names: domain_names) puts "dnsentries: #{dnsentries.inspect}\n" # dnsentries = domainclient.request(:batch_get_info, domain_names: domain_names).map(&:to_hash) # dnsentries.each_with_object({}) do |domain, memo| # d = domain[:domain] # memo[d['name']] = to_array(d) # end # rescue Transip::ApiError # raise Puppet::Error, 'Unable to get entries for all domains' {} end def self.set_entries(domain, entries) dnsentries = entries.map { |e| to_dnsentry(e) } domainclient.request(:set_dns_entries, domain_name: domain, dns_entries: dnsentries) # rescue Transip::ApiError # raise Puppet::Error, "Unable to set entries for #{domain}" end end end
module RailsSettings class Settings < ActiveRecord::Base self.table_name = table_name_prefix + 'settings' class SettingNotFound < RuntimeError; end cattr_accessor :defaults @@defaults = {}.with_indifferent_access belongs_to :thing, polymorphic: true # Support old plugin if defined?(SettingsDefaults::DEFAULTS) @@defaults = SettingsDefaults::DEFAULTS.with_indifferent_access end # get the value field, YAML decoded def value YAML.load(self[:value]) end # set the value field, YAML encoded def value=(new_value) self[:value] = new_value.to_yaml end class << self # get or set a variable with the variable as the called method def method_missing(method, *args) method_name = method.to_s super(method, *args) rescue NoMethodError # set a value for a variable if method_name[-1] == '=' var_name = method_name.sub('=', '') value = args.first self[var_name] = value else # retrieve a value self[method_name] end end # destroy the specified settings record def destroy(var_name) var_name = var_name.to_s obj = object(var_name) raise SettingNotFound, "Setting variable \"#{var_name}\" not found" if obj.nil? obj.destroy true end # retrieve all settings as a hash (optionally starting with a given namespace) def get_all(starting_with = nil) vars = thing_scoped.select('var, value') vars = vars.where("var LIKE '#{starting_with}%'") if starting_with result = {} vars.each do |record| result[record.var] = record.value end result.with_indifferent_access end def where(sql = nil) vars = thing_scoped.where(sql) if sql vars end # get a setting value by [] notation def [](var_name) object(var_name).try(:value) || @@defaults[var_name.to_s] end # set a setting value by [] notation def []=(var_name, value) var_name = var_name.to_s record = object(var_name) || thing_scoped.new(var: var_name) record.value = value record.save! value end def merge!(var_name, hash_value) raise ArgumentError unless hash_value.is_a?(Hash) old_value = self[var_name] || {} raise TypeError, "Existing value is not a hash, can't merge!" unless old_value.is_a?(Hash) new_value = old_value.merge(hash_value) self[var_name] = new_value if new_value != old_value new_value end def object(var_name) thing_scoped.where(var: var_name.to_s).first end def thing_scoped unscoped.where('thing_type is NULL and thing_id is NULL') end end end end include defaults in get_all call (PR #56) module RailsSettings class Settings < ActiveRecord::Base self.table_name = table_name_prefix + 'settings' class SettingNotFound < RuntimeError; end cattr_accessor :defaults @@defaults = {}.with_indifferent_access belongs_to :thing, polymorphic: true # Support old plugin if defined?(SettingsDefaults::DEFAULTS) @@defaults = SettingsDefaults::DEFAULTS.with_indifferent_access end # get the value field, YAML decoded def value YAML.load(self[:value]) end # set the value field, YAML encoded def value=(new_value) self[:value] = new_value.to_yaml end class << self # get or set a variable with the variable as the called method def method_missing(method, *args) method_name = method.to_s super(method, *args) rescue NoMethodError # set a value for a variable if method_name[-1] == '=' var_name = method_name.sub('=', '') value = args.first self[var_name] = value else # retrieve a value self[method_name] end end # destroy the specified settings record def destroy(var_name) var_name = var_name.to_s obj = object(var_name) raise SettingNotFound, "Setting variable \"#{var_name}\" not found" if obj.nil? obj.destroy true end # retrieve all settings as a hash (optionally starting with a given namespace) def get_all(starting_with = nil) vars = thing_scoped.select('var, value') vars = vars.where("var LIKE '#{starting_with}%'") if starting_with result = {} vars.each do |record| result[record.var] = record.value end vars.merge! @@defaults.slice(*(@@defaults.keys - result.keys)) result.with_indifferent_access end def where(sql = nil) vars = thing_scoped.where(sql) if sql vars end # get a setting value by [] notation def [](var_name) object(var_name).try(:value) || @@defaults[var_name.to_s] end # set a setting value by [] notation def []=(var_name, value) var_name = var_name.to_s record = object(var_name) || thing_scoped.new(var: var_name) record.value = value record.save! value end def merge!(var_name, hash_value) raise ArgumentError unless hash_value.is_a?(Hash) old_value = self[var_name] || {} raise TypeError, "Existing value is not a hash, can't merge!" unless old_value.is_a?(Hash) new_value = old_value.merge(hash_value) self[var_name] = new_value if new_value != old_value new_value end def object(var_name) thing_scoped.where(var: var_name.to_s).first end def thing_scoped unscoped.where('thing_type is NULL and thing_id is NULL') end end end end
module SSHKit module Custom module DSL VERSION = '0.0.6' end end end bumped version after minor changes module SSHKit module Custom module DSL VERSION = '0.0.7' end end end
require 'active_record' class Object class << self def is_paranoid? false end end end module ActsAsParanoid def acts_as_paranoid(options = {}) raise ArgumentError, "Hash expected, got #{options.class.name}" if not options.is_a?(Hash) and not options.empty? configuration = { :column => "deleted_at", :column_type => "time", :recover_dependent_associations => true, :dependent_recovery_window => 5.seconds } configuration.update(options) unless options.nil? type = case configuration[:column_type] when "time" then "Time.now" when "boolean" then "true" else raise ArgumentError, "'time' or 'boolean' expected for :column_type option, got #{configuration[:column_type]}" end column_reference = "#{self.table_name}.#{configuration[:column]}" class_eval <<-EOV default_scope where("#{column_reference} IS ?", nil) class << self def is_paranoid? true end def with_deleted self.unscoped.where("") #self.unscoped.reload end def only_deleted self.unscoped.where("#{column_reference} IS NOT ?", nil) end def delete_all!(conditions = nil) self.unscoped.delete_all!(conditions) end def delete_all(conditions = nil) update_all ["#{configuration[:column]} = ?", #{type}], conditions end def paranoid_column :"#{configuration[:column]}" end def paranoid_column_type :"#{configuration[:column_type]}" end def dependent_associations self.reflect_on_all_associations.select {|a| a.options[:dependent] == :destroy } end end def paranoid_value self.send(self.class.paranoid_column) end def destroy! before_destroy() if respond_to?(:before_destroy) #{self.name}.delete_all!(:id => self) after_destroy() if respond_to?(:after_destroy) end def destroy run_callbacks :destroy do if paranoid_value == nil #{self.name}.delete_all(:id => self.id) else #{self.name}.delete_all!(:id => self.id) end end end def recover(options = {}) options = { :recursive => #{configuration[:recover_dependent_associations]}, :recovery_window => #{configuration[:dependent_recovery_window]} }.merge(options) self.class.transaction do recover_dependent_associations(options[:recovery_window], options) if options[:recursive] self.update_attribute(self.class.paranoid_column, nil) end end def recover_dependent_associations(window, options) self.class.dependent_associations.each do |association| if association.collection? self.send(association.name).unscoped do self.send(association.name).deleted_around(paranoid_value, window).each do |object| object.recover(options) if object.respond_to?(:recover) end end elsif association.macro == :has_one association.klass.unscoped do object = association.klass.deleted_around(paranoid_value, window).send('find_by_'+association.primary_key_name, self.id) object.recover(options) if object && object.respond_to?(:recover) end else association.klass.unscoped do id = self.send(association.primary_key_name) object = association.klass.deleted_around(paranoid_value, window).find_by_id(id) object.recover(options) if object && object.respond_to?(:recover) end end end end scope :deleted_around, lambda {|value, window| if self.class.is_paranoid? if self.class.paranoid_column_type == 'time' && ![true, false].include?(value) self.where("\#{self.class.paranoid_column} > ? AND \#{self.class.paranoid_column} < ?", (value - window), (value + window)) else self.only_deleted end end } ActiveRecord::Relation.class_eval do alias_method :delete_all!, :delete_all alias_method :destroy!, :destroy end EOV end end # Extend ActiveRecord's functionality ActiveRecord::Base.extend ActsAsParanoid Don't recursively recover if the association isn't paranoid require 'active_record' class Object class << self def is_paranoid? false end end end module ActsAsParanoid def acts_as_paranoid(options = {}) raise ArgumentError, "Hash expected, got #{options.class.name}" if not options.is_a?(Hash) and not options.empty? configuration = { :column => "deleted_at", :column_type => "time", :recover_dependent_associations => true, :dependent_recovery_window => 5.seconds } configuration.update(options) unless options.nil? type = case configuration[:column_type] when "time" then "Time.now" when "boolean" then "true" else raise ArgumentError, "'time' or 'boolean' expected for :column_type option, got #{configuration[:column_type]}" end column_reference = "#{self.table_name}.#{configuration[:column]}" class_eval <<-EOV default_scope where("#{column_reference} IS ?", nil) class << self def is_paranoid? true end def with_deleted self.unscoped.where("") #self.unscoped.reload end def only_deleted self.unscoped.where("#{column_reference} IS NOT ?", nil) end def delete_all!(conditions = nil) self.unscoped.delete_all!(conditions) end def delete_all(conditions = nil) update_all ["#{configuration[:column]} = ?", #{type}], conditions end def paranoid_column :"#{configuration[:column]}" end def paranoid_column_type :"#{configuration[:column_type]}" end def dependent_associations self.reflect_on_all_associations.select {|a| a.options[:dependent] == :destroy } end end def paranoid_value self.send(self.class.paranoid_column) end def destroy! before_destroy() if respond_to?(:before_destroy) #{self.name}.delete_all!(:id => self) after_destroy() if respond_to?(:after_destroy) end def destroy run_callbacks :destroy do if paranoid_value == nil #{self.name}.delete_all(:id => self.id) else #{self.name}.delete_all!(:id => self.id) end end end def recover(options = {}) options = { :recursive => #{configuration[:recover_dependent_associations]}, :recovery_window => #{configuration[:dependent_recovery_window]} }.merge(options) self.class.transaction do recover_dependent_associations(options[:recovery_window], options) if options[:recursive] self.update_attribute(self.class.paranoid_column, nil) end end def recover_dependent_associations(window, options) self.class.dependent_associations.each do |association| if association.collection? && self.send(association.name).is_paranoid? self.send(association.name).unscoped do self.send(association.name).deleted_around(paranoid_value, window).each do |object| object.recover(options) if object.respond_to?(:recover) end end elsif association.macro == :has_one && association.klass.is_paranoid? association.klass.unscoped do object = association.klass.deleted_around(paranoid_value, window).send('find_by_'+association.primary_key_name, self.id) object.recover(options) if object && object.respond_to?(:recover) end elsif association.klass.is_paranoid? association.klass.unscoped do id = self.send(association.primary_key_name) object = association.klass.deleted_around(paranoid_value, window).find_by_id(id) object.recover(options) if object && object.respond_to?(:recover) end end end end scope :deleted_around, lambda {|value, window| if self.class.is_paranoid? if self.class.paranoid_column_type == 'time' && ![true, false].include?(value) self.where("\#{self.class.paranoid_column} > ? AND \#{self.class.paranoid_column} < ?", (value - window), (value + window)) else self.only_deleted end end } ActiveRecord::Relation.class_eval do alias_method :delete_all!, :delete_all alias_method :destroy!, :destroy end EOV end end # Extend ActiveRecord's functionality ActiveRecord::Base.extend ActsAsParanoid
module Rasti class Form module Types class String class << self include Castable def [](format) Class.new(self) do @format = format.is_a?(::String) ? ::Regexp.new(format) : format end end def to_s name || "#{superclass.name}[#{format.inspect}]" end alias_method :inspect, :to_s private attr_reader :format def valid?(value) !value.nil? && value.respond_to?(:to_s) && valid_format?(value) end def valid_format?(value) format.nil? || value.to_s.match?(format) end def transform(value) value.to_s end end end end end end Fixed for Ruby < 2.4 module Rasti class Form module Types class String class << self include Castable def [](format) Class.new(self) do @format = format.is_a?(::String) ? ::Regexp.new(format) : format end end def to_s name || "#{superclass.name}[#{format.inspect}]" end alias_method :inspect, :to_s private attr_reader :format def valid?(value) !value.nil? && value.respond_to?(:to_s) && valid_format?(value) end def valid_format?(value) format.nil? || !value.to_s.match(format).nil? end def transform(value) value.to_s end end end end end end
module Sunspot class IndexQueue # Abstract queue entry interface. All the gory details on actually handling the queue are handled by a # specific implementation class. The default implementation will use ActiveRecord as the backing queue. # # Implementing classes must define attribute readers for +id+, +record_class_name+, +record_id+, +error+, # +attempts+, and +is_delete?+. module Entry autoload :ActiveRecordImpl, File.expand_path('../entry/active_record_impl', __FILE__) autoload :DataMapperImpl, File.expand_path('../entry/data_mapper_impl', __FILE__) autoload :MongoImpl, File.expand_path('../entry/mongo_impl', __FILE__) attr_writer :processed class << self # Set the implementation class to use for the queue. This can be set as either a class object, # full class name, or a symbol representing one of the default implementations. # # # These all set the implementation to use the default ActiveRecord queue. # Sunspot::IndexQueue::Entry.implementation = :active_record # Sunspot::IndexQueue::Entry.implementation = "Sunspot::IndexQueue::Entry::ActiveRecordImpl" # Sunspot::IndexQueue::Entry.implementation = Sunspot::IndexQueue::Entry::ActiveRecordImpl # # Implementations should support pulling entries in batches by a priority where higher priority # entries are processed first. Errors should be automatically retried after an interval specified # by the IndexQueue. The batch size set by the IndexQueue should also be honored. def implementation=(klass) unless klass.is_a?(Class) || klass.nil? class_name = klass.to_s class_name = Sunspot::Util.camel_case(class_name).gsub('/', '::') unless class_name.include?('::') if class_name.include?('::') || !const_defined?("#{class_name}Impl") klass = Sunspot::Util.full_const_get(class_name) else klass = const_get("#{class_name}Impl") end end @implementation = klass end # The implementation class used for the queue. def implementation @implementation ||= ActiveRecordImpl end # Get a count of the queue entries for an IndexQueue. Implementations must implement this method. def total_count(queue) implementation.total_count(queue) end # Get a count of the entries ready to be processed for an IndexQueue. Implementations must implement this method. def ready_count(queue) implementation.ready_count(queue) end # Get a count of the error entries for an IndexQueue. Implementations must implement this method. def error_count(queue) implementation.error_count(queue) end # Get the specified number of error entries for an IndexQueue. Implementations must implement this method. def errors(queue, limit, offset) implementation.errors(queue, limit, offset) end # Get the next batch of entries to process for IndexQueue. Implementations must implement this method. def next_batch!(queue) implementation.next_batch!(queue) end # Reset the entries in the queue to be excuted again immediately and clear any errors. def reset!(queue) implementation.reset!(queue) end # Add an entry the queue. +is_delete+ will be true if the entry is a delete. Implementations must implement this method. def add(klass, id, delete, options = {}) raise NotImplementedError.new("add") end # Add multiple entries to the queue. +delete+ will be true if the entry is a delete. def enqueue(queue, klass, ids, delete, priority) klass = Sunspot::Util.full_const_get(klass.to_s) unless klass.is_a?(Class) unless queue.class_names.empty? || queue.class_names.include?(klass.name) raise ArgumentError.new("Class #{klass.name} is not in the class names allowed for the queue") end priority = priority.to_i if ids.is_a?(Array) ids.each do |id| implementation.add(klass, id, delete, priority) end else implementation.add(klass, ids, delete, priority) end end # Delete entries from the queue. Implementations must implement this method. def delete_entries(entries) implementation.delete_entries(entries) end # Load all records in an array of entries. This can be faster than calling load on each DataAccessor # depending on them implementation def load_all_records(entries) classes = entries.collect{|entry| entry.record_class_name}.uniq.collect{|name| Sunspot::Util.full_const_get(name) rescue nil}.compact map = entries.inject({}){|hash, entry| hash[entry.record_id.to_s] = entry; hash} classes.each do |klass| ids = entries.collect{|entry| entry.record_id} Sunspot::Adapters::DataAccessor.create(klass).load_all(ids).each do |record| entry = map[Sunspot::Adapters::InstanceAdapter.adapt(record).id.to_s] entry.instance_variable_set(:@record, record) if entry end end end end def processed? @processed = false unless defined?(@processed) @processed end # Get the record represented by this entry. def record @record ||= Sunspot::Adapters::DataAccessor.create(Sunspot::Util.full_const_get(record_class_name)).load_all([record_id]).first end # Set the error message on an entry. Implementations must implement this method. def set_error!(error, retry_interval = nil) raise NotImplementedError.new("set_error!") end # Reset an entry to be executed again immediatel and clear any errors. Implementations must implement this method. def reset! raise NotImplementedError.new("reset!") end end end end Added eager loading ability when specified in the searchable declaration. module Sunspot class IndexQueue # Abstract queue entry interface. All the gory details on actually handling the queue are handled by a # specific implementation class. The default implementation will use ActiveRecord as the backing queue. # # Implementing classes must define attribute readers for +id+, +record_class_name+, +record_id+, +error+, # +attempts+, and +is_delete?+. module Entry autoload :ActiveRecordImpl, File.expand_path('../entry/active_record_impl', __FILE__) autoload :DataMapperImpl, File.expand_path('../entry/data_mapper_impl', __FILE__) autoload :MongoImpl, File.expand_path('../entry/mongo_impl', __FILE__) attr_writer :processed class << self # Set the implementation class to use for the queue. This can be set as either a class object, # full class name, or a symbol representing one of the default implementations. # # # These all set the implementation to use the default ActiveRecord queue. # Sunspot::IndexQueue::Entry.implementation = :active_record # Sunspot::IndexQueue::Entry.implementation = "Sunspot::IndexQueue::Entry::ActiveRecordImpl" # Sunspot::IndexQueue::Entry.implementation = Sunspot::IndexQueue::Entry::ActiveRecordImpl # # Implementations should support pulling entries in batches by a priority where higher priority # entries are processed first. Errors should be automatically retried after an interval specified # by the IndexQueue. The batch size set by the IndexQueue should also be honored. def implementation=(klass) unless klass.is_a?(Class) || klass.nil? class_name = klass.to_s class_name = Sunspot::Util.camel_case(class_name).gsub('/', '::') unless class_name.include?('::') if class_name.include?('::') || !const_defined?("#{class_name}Impl") klass = Sunspot::Util.full_const_get(class_name) else klass = const_get("#{class_name}Impl") end end @implementation = klass end # The implementation class used for the queue. def implementation @implementation ||= ActiveRecordImpl end # Get a count of the queue entries for an IndexQueue. Implementations must implement this method. def total_count(queue) implementation.total_count(queue) end # Get a count of the entries ready to be processed for an IndexQueue. Implementations must implement this method. def ready_count(queue) implementation.ready_count(queue) end # Get a count of the error entries for an IndexQueue. Implementations must implement this method. def error_count(queue) implementation.error_count(queue) end # Get the specified number of error entries for an IndexQueue. Implementations must implement this method. def errors(queue, limit, offset) implementation.errors(queue, limit, offset) end # Get the next batch of entries to process for IndexQueue. Implementations must implement this method. def next_batch!(queue) implementation.next_batch!(queue) end # Reset the entries in the queue to be excuted again immediately and clear any errors. def reset!(queue) implementation.reset!(queue) end # Add an entry the queue. +is_delete+ will be true if the entry is a delete. Implementations must implement this method. def add(klass, id, delete, options = {}) raise NotImplementedError.new("add") end # Add multiple entries to the queue. +delete+ will be true if the entry is a delete. def enqueue(queue, klass, ids, delete, priority) klass = Sunspot::Util.full_const_get(klass.to_s) unless klass.is_a?(Class) unless queue.class_names.empty? || queue.class_names.include?(klass.name) raise ArgumentError.new("Class #{klass.name} is not in the class names allowed for the queue") end priority = priority.to_i if ids.is_a?(Array) ids.each do |id| implementation.add(klass, id, delete, priority) end else implementation.add(klass, ids, delete, priority) end end # Delete entries from the queue. Implementations must implement this method. def delete_entries(entries) implementation.delete_entries(entries) end # Load all records in an array of entries. This can be faster than calling load on each DataAccessor # depending on them implementation def load_all_records(entries) classes = entries.collect{|entry| entry.record_class_name}.uniq.collect{|name| Sunspot::Util.full_const_get(name) rescue nil}.compact map = entries.inject({}){|hash, entry| hash[entry.record_id.to_s] = entry; hash} classes.each do |klass| ids = entries.collect{|entry| entry.record_id} adapter = Sunspot::Adapters::DataAccessor.create(klass) adapter.include = klass.sunspot_options[:include] adapter.load_all(ids).each do |record| entry = map[Sunspot::Adapters::InstanceAdapter.adapt(record).id.to_s] entry.instance_variable_set(:@record, record) if entry end end end end def processed? @processed = false unless defined?(@processed) @processed end # Get the record represented by this entry. def record @record ||= Sunspot::Adapters::DataAccessor.create(Sunspot::Util.full_const_get(record_class_name)).load_all([record_id]).first end # Set the error message on an entry. Implementations must implement this method. def set_error!(error, retry_interval = nil) raise NotImplementedError.new("set_error!") end # Reset an entry to be executed again immediatel and clear any errors. Implementations must implement this method. def reset! raise NotImplementedError.new("reset!") end end end end
# -*- coding:utf-8; mode:ruby; -*- module Rbindkeys class BindResolver DEFAULT_DEFAULT_VALUE = :through attr_reader :tree # returned value if no binds hit attr_reader :default_value def initialize default_value = DEFAULT_DEFAULT_VALUE @tree = {} @default_value = default_value end end end write skeleton methods # -*- coding:utf-8; mode:ruby; -*- module Rbindkeys class BindResolver DEFAULT_DEFAULT_VALUE = :through attr_reader :tree # returned value if no binds hit attr_reader :default_value def initialize default_value = DEFAULT_DEFAULT_VALUE @tree = {} @default_value = default_value end def bind input, output end def resolve key_code, key_code_set end end end
module SwaggerUiEngine VERSION = '1.0.2'.freeze SWAGGER_UI_VERSION = '2.2.10'.freeze end Update gem version module SwaggerUiEngine VERSION = '1.1.0'.freeze SWAGGER_UI_VERSION = '2.2.10'.freeze end
# Extensions to RDF core classes to support reasoning require 'rdf' module RDF class URI class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform an entailment on this term. # # @param [Symbol] method A registered entailment method # @yield term # @yieldparam [Term] term # @return [Array<Term>] def entail(method, &block) self.send(@@entailments.fetch(method), &block) end ## # Determine if the domain of a property term is consistent with the specified resource in `queryable`. # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def domain_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "domain_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end ## # Determine if the range of a property term is consistent with the specified resource in `queryable`. # # Specific entailment regimes should insert themselves before this to apply the appropriate semantic condition # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def range_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "range_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end end class Node class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform an entailment on this term. # # @param [Symbol] method A registered entailment method # @yield term # @yieldparam [Term] term # @return [Array<Term>] def entail(method, &block) self.send(@@entailments.fetch(method), &block) end ## # Determine if the domain of a property term is consistent with the specified resource in `queryable`. # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def domain_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "domain_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end ## # Determine if the range of a property term is consistent with the specified resource in `queryable`. # # Specific entailment regimes should insert themselves before this to apply the appropriate semantic condition # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def range_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "range_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end end class Statement class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform an entailment on this term. # # @param [Symbol] method A registered entailment method # @yield term # @yieldparam [Term] term # @return [Array<Term>] def entail(method, &block) self.send(@@entailments.fetch(method), &block) end end module Enumerable class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform entailments on this enumerable in a single pass, yielding entailed statements. # # For best results, either run rules separately expanding the enumberated graph, or run repeatedly until no new statements are added to the enumerable containing both original and entailed statements. As `:subClassOf` and `:subPropertyOf` entailments are implicitly recursive, this may not be necessary except for extreme cases. # # @overload entail # @param [Array<Symbol>] *rules # Registered entailment method(s). # # @yield statement # @yieldparam [RDF::Statement] statement # @return [void] # # @overload entail # @param [Array<Symbol>] *rules Registered entailment method(s) # @return [Enumerator] def entail(*rules, &block) if block_given? rules = %w(subClassOf subPropertyOf domain range).map(&:to_sym) if rules.empty? self.each do |statement| rules.each {|rule| statement.entail(rule, &block)} end else # Otherwise, return an Enumerator with the entailed statements this = self RDF::Queryable::Enumerator.new do |yielder| this.entail(*rules) {|y| yielder << y} end end end end module Mutable class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end # Return a new mutable, composed of original and entailed statements # # @param [Array<Symbol>] rules Registered entailment method(s) # @return [RDF::Mutable] # @see [RDF::Enumerable#entail] def entail(*rules, &block) self.dup.entail!(*rules) end # Add entailed statements to the mutable # # @param [Array<Symbol>] rules Registered entailment method(s) # @return [RDF::Mutable] # @see [RDF::Enumerable#entail] def entail!(*rules, &block) rules = %w(subClassOf subPropertyOf domain range).map(&:to_sym) if rules.empty? statements = [] self.each do |statement| rules.each do |rule| statement.entail(rule) do |st| statements << st end end end self.insert(*statements) self end end module Queryable # Lint a queryable, presuming that it has already had RDFS entailment expansion. # @return [Hash{Symbol => Hash{Symbol => Array<String>}}] messages found for classes and properties by term def lint messages = {} # Check for defined classes in known vocabularies self.query(predicate: RDF.type) do |stmt| require 'byebug'; byebug if stmt.object.node? vocab = RDF::Vocabulary.find(stmt.object) term = (RDF::Vocabulary.find_term(stmt.object) rescue nil) if vocab pname = term ? term.pname : stmt.object.pname # Must be a defined term, not in RDF or RDFS vocabularies if term && term.class? # Warn against using a deprecated term superseded = term.attributes[:'schema:supersededBy'] superseded = superseded.pname if superseded.respond_to?(:pname) (messages[:class] ||= {})[pname] = ["Term is superseded by #{superseded}"] if superseded else (messages[:class] ||= {})[pname] = ["No class definition found"] unless vocab.nil? || [RDF::RDFV, RDF::RDFS].include?(vocab) end end # Check for defined predicates in known vocabularies and domain/range resource_types = {} self.each_statement do |stmt| vocab = RDF::Vocabulary.find(stmt.predicate) term = (RDF::Vocabulary.find_term(stmt.predicate) rescue nil) if vocab pname = term ? term.pname : stmt.predicate.pname # Must be a valid statement begin stmt.validate! rescue ((messages[:statement] ||= {})[pname] ||= []) << "Triple #{stmt.to_ntriples} is invalid" end # Must be a defined property if term && term.property? # Warn against using a deprecated term superseded = term.attributes[:'schema:supersededBy'] superseded = superseded.pname if superseded.respond_to?(:pname) (messages[:property] ||= {})[pname] = ["Term is superseded by #{superseded}"] if superseded else ((messages[:property] ||= {})[pname] ||= []) << "No property definition found" unless vocab.nil? next end # See if type of the subject is in the domain of this predicate resource_types[stmt.subject] ||= self.query(subject: stmt.subject, predicate: RDF.type). map {|s| (t = (RDF::Vocabulary.find_term(s.object) rescue nil)) && t.entail(:subClassOf)}. flatten. uniq. compact unless term.domain_compatible?(stmt.subject, self, types: resource_types[stmt.subject]) require 'byebug'; byebug if term.domain.any?(&:node?) ((messages[:property] ||= {})[pname] ||= []) << if !term.domain.empty? "Subject #{show_resource(stmt.subject)} not compatible with domain (#{Array(term.domain).map {|d| d.pname|| d}.join(',')})" else "Subject #{show_resource(stmt.subject)} not compatible with domainIncludes (#{term.domainIncludes.map {|d| d.pname|| d}.join(',')})" end end # Make sure that if ranges are defined, the object has an appropriate type resource_types[stmt.object] ||= self.query(subject: stmt.object, predicate: RDF.type). map {|s| (t = (RDF::Vocabulary.find_term(s.object) rescue nil)) && t.entail(:subClassOf)}. flatten. uniq. compact if stmt.object.resource? unless term.range_compatible?(stmt.object, self, types: resource_types[stmt.object]) ((messages[:property] ||= {})[pname] ||= []) << if !term.range.empty? "Object #{show_resource(stmt.object)} not compatible with range (#{Array(term.range).map {|d| d.pname|| d}.join(',')})" else "Object #{show_resource(stmt.object)} not compatible with rangeIncludes (#{term.rangeIncludes.map {|d| d.pname|| d}.join(',')})" end end end messages[:class].each {|k, v| messages[:class][k] = v.uniq} if messages[:class] messages[:property].each {|k, v| messages[:property][k] = v.uniq} if messages[:property] messages end private # Show resource in diagnostic output def show_resource(resource) if resource.node? resource.to_ntriples + '(' + self.query(subject: resource, predicate: RDF.type). map {|s| s.object.uri? ? s.object.pname : s.object.to_ntriples} .join(',') + ')' else resource.to_ntriples end end end end Remove debugging statements. # Extensions to RDF core classes to support reasoning require 'rdf' module RDF class URI class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform an entailment on this term. # # @param [Symbol] method A registered entailment method # @yield term # @yieldparam [Term] term # @return [Array<Term>] def entail(method, &block) self.send(@@entailments.fetch(method), &block) end ## # Determine if the domain of a property term is consistent with the specified resource in `queryable`. # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def domain_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "domain_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end ## # Determine if the range of a property term is consistent with the specified resource in `queryable`. # # Specific entailment regimes should insert themselves before this to apply the appropriate semantic condition # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def range_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "range_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end end class Node class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform an entailment on this term. # # @param [Symbol] method A registered entailment method # @yield term # @yieldparam [Term] term # @return [Array<Term>] def entail(method, &block) self.send(@@entailments.fetch(method), &block) end ## # Determine if the domain of a property term is consistent with the specified resource in `queryable`. # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def domain_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "domain_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end ## # Determine if the range of a property term is consistent with the specified resource in `queryable`. # # Specific entailment regimes should insert themselves before this to apply the appropriate semantic condition # # @param [RDF::Resource] resource # @param [RDF::Queryable] queryable # @param [Hash{Symbol => Object}] options ({}) # @option options [Array<RDF::Vocabulary::Term>] :types # Fully entailed types of resource, if not provided, they are queried def range_compatible?(resource, queryable, options = {}) %w(owl rdfs schema).map {|r| "range_compatible_#{r}?".to_sym}.all? do |meth| !self.respond_to?(meth) || self.send(meth, resource, queryable, options) end end end class Statement class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform an entailment on this term. # # @param [Symbol] method A registered entailment method # @yield term # @yieldparam [Term] term # @return [Array<Term>] def entail(method, &block) self.send(@@entailments.fetch(method), &block) end end module Enumerable class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end ## # Perform entailments on this enumerable in a single pass, yielding entailed statements. # # For best results, either run rules separately expanding the enumberated graph, or run repeatedly until no new statements are added to the enumerable containing both original and entailed statements. As `:subClassOf` and `:subPropertyOf` entailments are implicitly recursive, this may not be necessary except for extreme cases. # # @overload entail # @param [Array<Symbol>] *rules # Registered entailment method(s). # # @yield statement # @yieldparam [RDF::Statement] statement # @return [void] # # @overload entail # @param [Array<Symbol>] *rules Registered entailment method(s) # @return [Enumerator] def entail(*rules, &block) if block_given? rules = %w(subClassOf subPropertyOf domain range).map(&:to_sym) if rules.empty? self.each do |statement| rules.each {|rule| statement.entail(rule, &block)} end else # Otherwise, return an Enumerator with the entailed statements this = self RDF::Queryable::Enumerator.new do |yielder| this.entail(*rules) {|y| yielder << y} end end end end module Mutable class << self @@entailments = {} ## # Add an entailment method. The method accepts no arguments, and returns or yields an array of values associated with the particular entailment method # @param [Symbol] method # @param [Proc] proc def add_entailment(method, proc) @@entailments[method] = proc end end # Return a new mutable, composed of original and entailed statements # # @param [Array<Symbol>] rules Registered entailment method(s) # @return [RDF::Mutable] # @see [RDF::Enumerable#entail] def entail(*rules, &block) self.dup.entail!(*rules) end # Add entailed statements to the mutable # # @param [Array<Symbol>] rules Registered entailment method(s) # @return [RDF::Mutable] # @see [RDF::Enumerable#entail] def entail!(*rules, &block) rules = %w(subClassOf subPropertyOf domain range).map(&:to_sym) if rules.empty? statements = [] self.each do |statement| rules.each do |rule| statement.entail(rule) do |st| statements << st end end end self.insert(*statements) self end end module Queryable # Lint a queryable, presuming that it has already had RDFS entailment expansion. # @return [Hash{Symbol => Hash{Symbol => Array<String>}}] messages found for classes and properties by term def lint messages = {} # Check for defined classes in known vocabularies self.query(predicate: RDF.type) do |stmt| vocab = RDF::Vocabulary.find(stmt.object) term = (RDF::Vocabulary.find_term(stmt.object) rescue nil) if vocab pname = term ? term.pname : stmt.object.pname # Must be a defined term, not in RDF or RDFS vocabularies if term && term.class? # Warn against using a deprecated term superseded = term.attributes[:'schema:supersededBy'] superseded = superseded.pname if superseded.respond_to?(:pname) (messages[:class] ||= {})[pname] = ["Term is superseded by #{superseded}"] if superseded else (messages[:class] ||= {})[pname] = ["No class definition found"] unless vocab.nil? || [RDF::RDFV, RDF::RDFS].include?(vocab) end end # Check for defined predicates in known vocabularies and domain/range resource_types = {} self.each_statement do |stmt| vocab = RDF::Vocabulary.find(stmt.predicate) term = (RDF::Vocabulary.find_term(stmt.predicate) rescue nil) if vocab pname = term ? term.pname : stmt.predicate.pname # Must be a valid statement begin stmt.validate! rescue ((messages[:statement] ||= {})[pname] ||= []) << "Triple #{stmt.to_ntriples} is invalid" end # Must be a defined property if term && term.property? # Warn against using a deprecated term superseded = term.attributes[:'schema:supersededBy'] superseded = superseded.pname if superseded.respond_to?(:pname) (messages[:property] ||= {})[pname] = ["Term is superseded by #{superseded}"] if superseded else ((messages[:property] ||= {})[pname] ||= []) << "No property definition found" unless vocab.nil? next end # See if type of the subject is in the domain of this predicate resource_types[stmt.subject] ||= self.query(subject: stmt.subject, predicate: RDF.type). map {|s| (t = (RDF::Vocabulary.find_term(s.object) rescue nil)) && t.entail(:subClassOf)}. flatten. uniq. compact unless term.domain_compatible?(stmt.subject, self, types: resource_types[stmt.subject]) ((messages[:property] ||= {})[pname] ||= []) << if !term.domain.empty? "Subject #{show_resource(stmt.subject)} not compatible with domain (#{Array(term.domain).map {|d| d.pname|| d}.join(',')})" else "Subject #{show_resource(stmt.subject)} not compatible with domainIncludes (#{term.domainIncludes.map {|d| d.pname|| d}.join(',')})" end end # Make sure that if ranges are defined, the object has an appropriate type resource_types[stmt.object] ||= self.query(subject: stmt.object, predicate: RDF.type). map {|s| (t = (RDF::Vocabulary.find_term(s.object) rescue nil)) && t.entail(:subClassOf)}. flatten. uniq. compact if stmt.object.resource? unless term.range_compatible?(stmt.object, self, types: resource_types[stmt.object]) ((messages[:property] ||= {})[pname] ||= []) << if !term.range.empty? "Object #{show_resource(stmt.object)} not compatible with range (#{Array(term.range).map {|d| d.pname|| d}.join(',')})" else "Object #{show_resource(stmt.object)} not compatible with rangeIncludes (#{term.rangeIncludes.map {|d| d.pname|| d}.join(',')})" end end end messages[:class].each {|k, v| messages[:class][k] = v.uniq} if messages[:class] messages[:property].each {|k, v| messages[:property][k] = v.uniq} if messages[:property] messages end private # Show resource in diagnostic output def show_resource(resource) if resource.node? resource.to_ntriples + '(' + self.query(subject: resource, predicate: RDF.type). map {|s| s.object.uri? ? s.object.pname : s.object.to_ntriples} .join(',') + ')' else resource.to_ntriples end end end end
module Recommender module ViewHelper %w[view like dislike favorite buy basket].each do |action| define_method "track_#{action}" do |item, user_id, options = {}| options = options.merge(event: action, object_type: item.class.to_s.downcase, object_id: item.id, user_id: user_id) get_tracking_code options end end def track_recommendation_click source_id, destination_id, user_id, klass script = " window.track_recommendation = window.track_recommendation || []; window.track_recommendation.push([ { event: \"trackClick\", type: \"#{klass}\", source: \"#{source_id}\", destination: \"#{destination_id}\", user: \"#{user_id}\" }, ]); " end def get_recommendation_include content_tag :script do "(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = '//static.#{Recommender.config.domain}/script/v1.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();".html_safe end end def get_tracking_code options = {} user_id = options.delete(:user_id) object_id = options.delete(:object_id) object_type = options.delete(:object_type) event = options.delete(:event) use_script = options[:script] == nil ? true : options[:script] script = " window.track_recommendation = window.track_recommendation || []; window.track_recommendation.push([ { event: \"setAccount\", value: \"#{Recommender.config.user_id}\" }, { event: \"#{event}\", object: \"#{object_id}\", type: \"#{object_type}\", user: \"#{user_id}\" } ]); ".html_safe return script unless use_script content_tag :script, script end end end html safe module Recommender module ViewHelper %w[view like dislike favorite buy basket].each do |action| define_method "track_#{action}" do |item, user_id, options = {}| options = options.merge(event: action, object_type: item.class.to_s.downcase, object_id: item.id, user_id: user_id) get_tracking_code options end end def track_recommendation_click source_id, destination_id, user_id, klass "window.track_recommendation = window.track_recommendation || []; window.track_recommendation.push([ { event: \"trackClick\", type: \"#{klass}\", source: \"#{source_id}\", destination: \"#{destination_id}\", user: \"#{user_id}\" }, ]);".html_safe end def get_recommendation_include content_tag :script do "(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = '//static.#{Recommender.config.domain}/script/v1.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();".html_safe end end def get_tracking_code options = {} user_id = options.delete(:user_id) object_id = options.delete(:object_id) object_type = options.delete(:object_type) event = options.delete(:event) use_script = options[:script] == nil ? true : options[:script] script = " window.track_recommendation = window.track_recommendation || []; window.track_recommendation.push([ { event: \"setAccount\", value: \"#{Recommender.config.user_id}\" }, { event: \"#{event}\", object: \"#{object_id}\", type: \"#{object_type}\", user: \"#{user_id}\" } ]); ".html_safe return script unless use_script content_tag :script, script end end end
require 'active_support/inflector' require 'httparty' require 'json' module TargetProcess class APIClient def get(path, options={}) options.merge!(format: 'json') options = {body: options} response = perform(:get, path, options) normalize_response(response.parsed_response) end def post(path, attr_hash) content = prepare_data(attr_hash).to_json options = {body: content, headers: {'Content-Type' => 'application/json'}} response = perform(:post, path, options) normalize_response(response.parsed_response) end def delete(path) perform(:delete, path).response end private def perform(type, path, options={}) auth = { username: TargetProcess.configuration.username, password: TargetProcess.configuration.password } options.merge!(basic_auth: auth) check_for_api_errors HTTParty.send(type, generate_url(path), options) end def check_for_api_errors(response) if response['Error'] raise APIError.parse(response) else response end end def generate_url(path) if TargetProcess.configuration.api_url[-1] == "/" TargetProcess.configuration.api_url + path else TargetProcess.configuration.api_url + "/" + path end end def normalize_response(hash) hash = Hash[hash.map {|k, v| [k.underscore.to_sym, v] }] hash.each do |k,v| hash[k] = case v when Hash normalize_response(v) when Array v.collect! { |el| normalize_response(el) } when /Date\((\d+)-(\d+)\)/ ::Time.at($1.to_i/1000) else v end end end def json_date(time) "\/Date(#{time.to_i}000+0#{time.utc_offset/3600}00)\/" end def prepare_data(hash) hash = Hash[hash.map {|k, v| [k.to_s.camelize.to_sym, v] }] hash.each { |k,v| hash[k] = json_date(v) if v.is_a?(::Time) } end end end HTTP Error 411 when GET request use body HTTP Error 411 when GET request use body instead query require 'active_support/inflector' require 'httparty' require 'json' module TargetProcess class APIClient def get(path, options={}) options.merge!(format: 'json') options = {query: options} response = perform(:get, path, options) normalize_response(response.parsed_response) end def post(path, attr_hash) content = prepare_data(attr_hash).to_json options = {body: content, headers: {'Content-Type' => 'application/json'}} response = perform(:post, path, options) normalize_response(response.parsed_response) end def delete(path) perform(:delete, path).response end private def perform(type, path, options={}) auth = { username: TargetProcess.configuration.username, password: TargetProcess.configuration.password } options.merge!(basic_auth: auth) check_for_api_errors HTTParty.send(type, generate_url(path), options) end def check_for_api_errors(response) if response['Error'] raise APIError.parse(response) else response end end def generate_url(path) if TargetProcess.configuration.api_url[-1] == "/" TargetProcess.configuration.api_url + path else TargetProcess.configuration.api_url + "/" + path end end def normalize_response(hash) hash = Hash[hash.map {|k, v| [k.underscore.to_sym, v] }] hash.each do |k,v| hash[k] = case v when Hash normalize_response(v) when Array v.collect! { |el| normalize_response(el) } when /Date\((\d+)-(\d+)\)/ ::Time.at($1.to_i/1000) else v end end end def json_date(time) "\/Date(#{time.to_i}000+0#{time.utc_offset/3600}00)\/" end def prepare_data(hash) hash = Hash[hash.map {|k, v| [k.to_s.camelize.to_sym, v] }] hash.each { |k,v| hash[k] = json_date(v) if v.is_a?(::Time) } end end end
task :get_daily_specs => :environment do require 'ruby-debug' analyze_daily_raw_specs end task :import_daily_attributes => :environment do # get historical data on raw product attributes data and write to daily specs raw = true import_data(raw) end task :import_daily_factors => :environment do # get historical factors data and write to daily specs raw = false import_data(raw) end def import_data(raw) directory = "/optemo/snapshots/slicehost" # loop over the files in the directory, unzipping gzipped files Dir.foreach(directory) do |entry| if entry =~ /\.gz/ %x[gunzip #{directory}/#{entry}] end end # loop over each daily snapshot of the database (.sql file), # import it into the temp database, then get attributes for and write them to DailySpecs Dir.foreach(directory) do |snapshot| if snapshot =~ /\.sql/ date = Date.parse(snapshot.chomp(File.extname(snapshot))) puts 'making records for date' + date.to_s # import data from the snapshot to the temp database puts "mysql -u oana -pcleanslate -h jaguar temp < #{directory}/#{snapshot}" %x[mysql -u oana -pcleanslate -h jaguar temp < #{directory}/#{snapshot}] ActiveRecord::Base.establish_connection(:adapter => "mysql2", :database => "temp", :host => "jaguar", :username => "oana", :password => "cleanslate") case raw when true specs = get_instock_attributes() when false specs = get_instock_factors() end ActiveRecord::Base.establish_connection(:development) update_daily_specs(date, specs, raw) end end end # collects factor values for instock cameras # assumes an active connection to the temp database # output: an array of hashes of the selected factors, one entry per product def get_instock_factors() specs = [] instock = Product.find_all_by_product_type_and_instock("camera_bestbuy", 1) instock.each do |p| sku = p.sku pid = p.id price_factor = ContSpec.find_by_product_id_and_name(pid,"price_factor") maxresolution_factor = ContSpec.find_by_product_id_and_name(pid,"maxresolution_factor") opticalzoom_factor = ContSpec.find_by_product_id_and_name(pid,"opticalzoom_factor") # if any of the expected features do not have values in the DB, don't create a new spec for that product if maxresolution_factor.nil? or opticalzoom_factor.nil? or price_factor.nil? print "found nil factors for " print pid next end # The onsale and featured factor data in ContSpecs was not consistently computed, so has to be recomputed # calculate featured factor featured_spec = BinSpec.find_by_product_id_and_name(pid, "featured") if featured_spec.nil? featured_factor = 0 else featured_factor = 1 end # calculate onsale factor regularprice_spec = ContSpec.find_by_product_id_and_name(pid, "price") saleprice_spec = ContSpec.find_by_product_id_and_name(pid, "saleprice") if (regularprice_spec.nil? or saleprice_spec.nil?) print next else regularprice = regularprice_spec.value saleprice = saleprice_spec.value end onsale_factor = (regularprice > saleprice ? (regularprice - saleprice)/regularprice : 0) new_spec = {:sku => sku, :price_factor => price_factor.value, :maxresolution_factor => maxresolution_factor.value, :opticalzoom_factor => opticalzoom_factor.value, :onsale_factor => onsale_factor, :featured_factor => featured_factor} specs << new_spec end return specs end # collects values of certain specs for instock cameras # assumes an active connection to the temp database # output: an array of hashes of the selected specs, one entry per product def get_instock_attributes() specs = [] instock = Product.find_all_by_product_type_and_instock("camera_bestbuy", 1) instock.each do |p| sku = p.sku pid = p.id saleprice = ContSpec.find_by_product_id_and_name(pid,"saleprice") maxresolution = ContSpec.find_by_product_id_and_name(pid,"maxresolution") opticalzoom = ContSpec.find_by_product_id_and_name(pid,"opticalzoom") #orders = ContSpec.find_by_product_id_and_name(pid,"orders") brand = CatSpec.find_by_product_id_and_name(pid,"brand") # if any of the expected features do not have values in the DB, don't create a new spec for that product if maxresolution.nil? or opticalzoom.nil? or brand.nil? print "found nil raw features for " print pid next end # featured and onsale may be nil when the value is not missing value but should be of 0 featured = BinSpec.find_by_product_id_and_name(pid,"featured") # if nil -> 0, else value onsale = BinSpec.find_by_product_id_and_name(pid,"onsale") featured = featured.nil? ? 0 : 1 onsale = onsale.nil? ? 0 : 1 new_spec = {:sku => sku, :saleprice => saleprice.value, :maxresolution => maxresolution.value, :opticalzoom => opticalzoom.value, :orders => orders.value, :brand => brand.value, :featured => featured, :onsale => onsale} specs << new_spec end return specs end def update_daily_specs(date, specs, raw) product_type = "camera_bestbuy" specs.each do |attributes| sku = attributes[:sku] if raw == true add_daily_spec(sku, "cont", "saleprice", attributes[:saleprice], product_type, date) add_daily_spec(sku, "cont", "maxresolution", attributes[:maxresolution], product_type, date) add_daily_spec(sku, "cont", "opticalzoom", attributes[:opticalzoom], product_type, date) add_daily_spec(sku, "cont", "orders", attributes[:orders], product_type, date) add_daily_spec(sku, "cat", "brand", attributes[:brand], product_type, date) add_daily_spec(sku, "bin", "featured", attributes[:featured], product_type, date) add_daily_spec(sku, "bin", "onsale", attributes[:onsale], product_type, date) elsif raw == false add_daily_spec(sku, "cont", "price_factor", attributes[:price_factor], product_type, date) add_daily_spec(sku, "cont", "maxresolution_factor", attributes[:maxresolution_factor], product_type, date) add_daily_spec(sku, "cont", "opticalzoom_factor", attributes[:opticalzoom_factor], product_type, date) add_daily_spec(sku, "cont", "onsale_factor", attributes[:onsale_factor], product_type, date) add_daily_spec(sku, "cont", "featured_factor", attributes[:featured_factor], product_type, date) end end end def add_daily_spec(sku, spec_type, name, value, product_type, date) case spec_type when "cont" ds = DailySpec.new(:spec_type => spec_type, :sku => sku, :name => name, :value_flt => value, :product_type => product_type, :date => date) when "cat" ds = DailySpec.new(:spec_type => spec_type, :sku => sku, :name => name, :value_txt => value, :product_type => product_type, :date => date) when "bin" ds = DailySpec.new(:spec_type => spec_type, :sku => sku, :name => name, :value_bin => value, :product_type => product_type, :date => date) end ds.save end def analyze_daily_raw_specs product_type = "camera_bestbuy" output_name = "./log/Daily_Data/raw_specs.txt" out_file = File.open(output_name,'w') factors = get_cumulative_data(product_type) factors.keys.each do |date| # for each date appearing in the factors and each sku # query the database to get historical attributes stored in daily specs factors[date].each do |daily_product| sku = daily_product["sku"] feature_records = DailySpec.find_all_by_date_and_sku(date, sku) if feature_records.empty? next end feature_records.each do |record| value = case record.spec_type when "cat" record.value_txt.sub(/ /, '_') when "bin" record.value_bin == true ? 1 : 0 when "cont" record.value_flt end daily_product[record.name] = value end # output a specification of the product to file output_line = [ date, sku, daily_product["daily_sales"], daily_product["saleprice"], daily_product["maxresolution"], daily_product["opticalzoom"], daily_product["brand"], daily_product["featured"], daily_product["onsale"], product_type ].join(" ") out_file.write(output_line + "\n") end end end # Use the cumulative data file and extract factor values for products of the type given as input def get_cumulative_data(product_type) factors = {} data_path = "./log/Daily_Data/" fname = "Cumullative_Data.txt" f = File.open(data_path + fname, 'r') lines = f.readlines lines.each do |line| if line =~ /#{product_type}/ a = line.split date = a[0] factors[date] = [] if factors[date].nil? factors[date] << {"sku" => a[1], "utility" => a[2], "daily_sales" => a[3], "product_type" => a[4], "saleprice_factor" => a[5], "maxresolution_factor" => a[6], "opticalzoom_factor" => a[7], "brand_factor" => a[8], "onsale_factor" => a[9], "orders_factor" => a[10]} end end return factors end modified the import_daily_data file task :get_daily_specs => :environment do require 'ruby-debug' write_instock_skus_into_file #analyze_daily_raw_specs end task :import_daily_attributes => :environment do # get historical data on raw product attributes data and write to daily specs raw = true import_data(raw) end task :import_daily_factors => :environment do # get historical factors data and write to daily specs raw = false import_data(raw) end def import_data(raw) directory = "/mysql_backup/slicehost" #directory = "/Users/Monir/optemo/mysql_backup" # loop over the files in the directory, unzipping gzipped files Dir.foreach(directory) do |entry| if entry =~ /\.gz/ %x[gunzip #{directory}/#{entry}] end end # loop over each daily snapshot of the database (.sql file), # import it into the temp database, then get attributes for and write them to DailySpecs Dir.foreach(directory) do |snapshot| if snapshot =~ /\.sql/ date = Date.parse(snapshot.chomp(File.extname(snapshot))) puts 'making records for date ' + date.to_s # import data from the snapshot to the temp database puts "mysql -u monir -pm_222978 -h jaguar temp < #{directory}/#{snapshot}" %x[mysql -u monir -pm_222978 -h jaguar temp < #{directory}/#{snapshot}] #username and password cannot be company's (optemo, tiny******) ActiveRecord::Base.establish_connection(:adapter => "mysql2", :database => "temp", :host => "jaguar", :username => "monir", :password => "m_222978") case raw when true specs = get_instock_attributes(date) when false specs = get_instock_factors(date) end ActiveRecord::Base.establish_connection(:development) update_daily_specs(date, specs, raw) end end end # collects factor values for instock cameras # assumes an active connection to the temp database # output: an array of hashes of the selected factors, one entry per product def get_instock_factors() specs = [] #instock = Product.find_all_by_product_type_and_instock("camera_bestbuy", 1) instock.each do |p| sku = p.sku pid = p.id price_factor = ContSpec.find_by_product_id_and_name(pid,"price_factor") maxresolution_factor = ContSpec.find_by_product_id_and_name(pid,"maxresolution_factor") opticalzoom_factor = ContSpec.find_by_product_id_and_name(pid,"opticalzoom_factor") # if any of the expected features do not have values in the DB, don't create a new spec for that product if maxresolution_factor.nil? or opticalzoom_factor.nil? or price_factor.nil? print "found nil factors for " print pid next end # The onsale and featured factor data in ContSpecs was not consistently computed, so has to be recomputed # calculate featured factor featured_spec = BinSpec.find_by_product_id_and_name(pid, "featured") if featured_spec.nil? featured_factor = 0 else featured_factor = 1 end # calculate onsale factor regularprice_spec = ContSpec.find_by_product_id_and_name(pid, "price") saleprice_spec = ContSpec.find_by_product_id_and_name(pid, "saleprice") if (regularprice_spec.nil? or saleprice_spec.nil?) print next else regularprice = regularprice_spec.value saleprice = saleprice_spec.value end onsale_factor = (regularprice > saleprice ? (regularprice - saleprice)/regularprice : 0) new_spec = {:sku => sku, :price_factor => price_factor.value, :maxresolution_factor => maxresolution_factor.value, :opticalzoom_factor => opticalzoom_factor.value, :onsale_factor => onsale_factor, :featured_factor => featured_factor} specs << new_spec end return specs end # collects values of certain specs for instock cameras # assumes an active connection to the temp database # output: an array of hashes of the selected specs, one entry per product def get_instock_attributes(date) specs = [] product_type="camera_bestbuy" cont_specs = get_cont_specs(product_type).reject{|e| e=~/[a-z]+_[factor|fr]/} cont_specs.each do |r| puts "#{r}" end cat_specs = get_cat_specs(product_type).reject{|e| e=~/[a-z]+_[factor|fr]/} cat_specs.each do |r| puts "#{r}" end bin_specs = get_bin_specs(product_type).reject{|e| e=~/[a-z]+_[factor|fr]/} bin_specs.each do |r| puts "#{r}" end instock = Product.find_all_by_instock_and_product_type(1, product_type) instock.each do |p| sku = p.sku pid = p.id ContSpec.find_all_by_product_id(pid).each do |row| if (cont_specs.include?(row.name)) specs << {sku: sku, name: row.name, spec_type: "cont", value_flt: row.value, product_type: product_type, date: date} end end CatSpec.find_all_by_product_id(pid).each do |row| if (cat_specs.include?(row.name)) specs << {sku: sku, name: row.name, spec_type: "cat", value_txt: row.value, product_type: product_type, date: date} end end BinSpec.find_all_by_product_id(pid).each do |row| if (bin_specs.include?(row.name)) row.value = 0 if row.value == nil specs << {sku: sku, name: row.name, spec_type: "bin", value_bin: row.value, product_type: product_type, date: date} end end end return specs end def get_cont_specs(product_type="camera_bestbuy") # product_type="camera_bestbuy" #@cont_specs||= AllDailySpec.find_by_sql("select DISTINCT name from all_daily_specs where spec_type= 'cont'").map(&:name) @cont_specs||= ContSpec.find_by_sql("select DISTINCT name from cont_specs where product_type= '#{product_type}'").map(&:name) end def get_cat_specs(product_type="camera_bestbuy") #@cat_specs ||= AllDailySpec.find_by_sql("select DISTINCT name from all_daily_specs where spec_type = 'cat'").map(&:name) @cat_specs||= CatSpec.find_by_sql("select DISTINCT name from cat_specs where product_type= '#{product_type}'").map(&:name) end def get_bin_specs(product_type="camera_bestbuy") #@bin_specs ||= AllDailySpec.find_by_sql("select DISTINCT name from all_daily_specs where spec_type= 'bin'").map(&:name) @bin_specs||= BinSpec.find_by_sql("select DISTINCT name from bin_specs where product_type= '#{product_type}'").map(&:name) end def update_daily_specs(date, specs, raw) alldailyspecs= [] specs.each do |attributes| alldailyspecs << AllDailySpec.new(attributes) end AllDailySpec.import alldailyspecs end def analyze_daily_raw_specs product_type = "camera_bestbuy" output_name = "./log/Daily_Data/all_raw_data.txt" out_file = File.open(output_name,'w') features = get_all_features() features.delete("title") features.delete("model") puts "features #{features}" factors = get_cumulative_data(product_type,features) out_file.write("sku date "+ features.keys.join(" ") + "\n") factors.keys.each do |date| # for each date appearing in the factors and each sku # query the database to get historical attributes stored in daily specs factors[date].each do |daily_product| sku = daily_product["sku"] #puts "date #{date} sku #{sku}" feature_records = AllDailySpec.find_all_by_date_and_sku(date, sku) next if feature_records.empty? feature_records.each do |record| value = case record.spec_type when "cat" record.value_txt.gsub(/\s+/, '_') when "bin" record.value_bin == true ? 1 : 0 when "cont" record.value_flt end daily_product[record.name] = value end # output a specification of the product to file output_line= [date, sku] output_line = features.keys.inject(output_line){|res,ele| res<< (daily_product[ele]||features[ele])}.join(" ") #puts "output_line #{output_line}" out_file.write(output_line + "\n") end end end def get_cumulative_data(product_type, features) factors = {} data_path = "./log/Daily_Data/" fname = "cumullative_data_#{product_type}.txt" f = File.open(data_path + fname, 'r') lines = f.readlines lines.each do |line| a = line.split date = Date.parse(a[0] + " "+a[1]+ " "+a[2]) #puts "date_analyize #{date}" factors[date] = [] if factors[date].nil? factors[date] << {"sku" => a[3]}.merge(features) end return factors end def get_all_features features={} get_cont_specs.each do |r| features[r] = 0 #puts "#{r}" end get_cat_specs.each do |r| features[r]="NA" #puts "#{r}" end get_bin_specs.each do |r| features[r]=0 #puts "#{r}" end features end def write_instock_skus_into_file(produtct_type= "camera_bestbuy") output_name = "../log/Daily_Data/cumullative_data_#{product_type}.txt" out_file = File.open(output_name,'w') puts "hi" records = AllDailySpec.find_by_sql("select * from all_daily_specs where date >= '2011-08-01' and date <= '2011-12-31' and name='store_orders' order by date") puts "size #{records.size}" records.each do |re| line=[] line << re.date line << re.sku line << re.value_flt puts "line #{line.join(" ")}" out_file.write(line.join(" ")+"\n") end end #ORIGINAL CODE #def analyze_daily_raw_specs # product_type = "camera_bestbuy" # output_name = "./log/Daily_Data/raw_specs.txt" # out_file = File.open(output_name,'w') # # factors = get_cumulative_data(product_type) # # factors.keys.each do |date| # # for each date appearing in the factors and each sku # # query the database to get historical attributes stored in daily specs # factors[date].each do |daily_product| # sku = daily_product["sku"] # feature_records = DailySpec.find_all_by_date_and_sku(date, sku) # if feature_records.empty? # next # end # feature_records.each do |record| # value = # case record.spec_type # when "cat" # record.value_txt.sub(/ /, '_') # when "bin" # record.value_bin == true ? 1 : 0 # when "cont" # record.value_flt # end # daily_product[record.name] = value # end # # output a specification of the product to file # output_line = [ # date, # sku, # daily_product["daily_sales"], # daily_product["saleprice"], # daily_product["maxresolution"], # daily_product["opticalzoom"], # daily_product["brand"], # daily_product["featured"], # daily_product["onsale"], # product_type # ].join(" ") # out_file.write(output_line + "\n") # end # end #end # ORIGINAL CODE # Use the cumulative data file and extract factor values for products of the type given as input #def get_cumulative_data(product_type) # factors = {} # data_path = "./log/Daily_Data/" # fname = "Cumullative_Data.txt" # f = File.open(data_path + fname, 'r') # lines = f.readlines # lines.each do |line| # if line =~ /#{product_type}/ # a = line.split # date = a[0] # factors[date] = [] if factors[date].nil? # factors[date] << {"sku" => a[1], "utility" => a[2], "daily_sales" => a[3], "product_type" => a[4], "saleprice_factor" => a[5], "maxresolution_factor" => a[6], "opticalzoom_factor" => a[7], "brand_factor" => a[8], "onsale_factor" => a[9], "orders_factor" => a[10]} # end # end # return factors #end ######ORIGINAL CODE ###### #def update_daily_specs(date, specs, raw) # product_type = "camera_bestbuy" # specs.each do |attributes| # sku = attributes[:sku] # if raw == true # add_daily_spec(sku, "cont", "saleprice", attributes[:saleprice], product_type, date) # add_daily_spec(sku, "cont", "maxresolution", attributes[:maxresolution], product_type, date) # add_daily_spec(sku, "cont", "opticalzoom", attributes[:opticalzoom], product_type, date) # add_daily_spec(sku, "cont", "orders", attributes[:orders], product_type, date) # add_daily_spec(sku, "cat", "brand", attributes[:brand], product_type, date) # add_daily_spec(sku, "bin", "featured", attributes[:featured], product_type, date) # add_daily_spec(sku, "bin", "onsale", attributes[:onsale], product_type, date) # elsif raw == false # add_daily_spec(sku, "cont", "price_factor", attributes[:price_factor], product_type, date) # add_daily_spec(sku, "cont", "maxresolution_factor", attributes[:maxresolution_factor], product_type, date) # add_daily_spec(sku, "cont", "opticalzoom_factor", attributes[:opticalzoom_factor], product_type, date) # add_daily_spec(sku, "cont", "onsale_factor", attributes[:onsale_factor], product_type, date) # add_daily_spec(sku, "cont", "featured_factor", attributes[:featured_factor], product_type, date) # end # end #end ####ORIGINAL CODE ###### #def get_instock_attributes() # specs = [] # # instock = Product.find_all_by_product_type_and_instock("camera_bestbuy", 1) # instock.each do |p| # sku = p.sku # pid = p.id # saleprice = ContSpec.find_by_product_id_and_name(pid,"saleprice") # maxresolution = ContSpec.find_by_product_id_and_name(pid,"maxresolution") # opticalzoom = ContSpec.find_by_product_id_and_name(pid,"opticalzoom") # #orders = ContSpec.find_by_product_id_and_name(pid,"orders") # brand = CatSpec.find_by_product_id_and_name(pid,"brand") # # # if any of the expected features do not have values in the DB, don't create a new spec for that product # if maxresolution.nil? or opticalzoom.nil? or brand.nil? # print "found nil raw features for " # print pid # next # end # # featured and onsale may be nil when the value is not missing value but should be of 0 # featured = BinSpec.find_by_product_id_and_name(pid,"featured") # if nil -> 0, else value # onsale = BinSpec.find_by_product_id_and_name(pid,"onsale") # featured = featured.nil? ? 0 : 1 # onsale = onsale.nil? ? 0 : 1 # # new_spec = {:sku => sku, :saleprice => saleprice.value, :maxresolution => maxresolution.value, # :opticalzoom => opticalzoom.value, :brand => brand.value, # :featured => featured, :onsale => onsale} # # specs << new_spec # end # return specs #end def add_daily_spec(sku, spec_type, name, value, product_type, date) case spec_type when "cont" ds = AllDailySpec.new(:spec_type => spec_type, :sku => sku, :name => name, :value_flt => value, :product_type => product_type, :date => date) when "cat" ds = AllDailySpec.new(:spec_type => spec_type, :sku => sku, :name => name, :value_txt => value, :product_type => product_type, :date => date) when "bin" ds = AllDailySpec.new(:spec_type => spec_type, :sku => sku, :name => name, :value_bin => value, :product_type => product_type, :date => date) end ds.save end
# frozen_string_literal: true module ReviewBot class Notification def initialize(pull_request:, suggested_reviewers:) @pull_request = pull_request @suggested_reviewers = suggested_reviewers end attr_reader :pull_request, :suggested_reviewers def message [ %(• ##{pull_request.html_url} \ <#{pull_request.html_url}|#{pull_request.title}> \ needs a *#{needed_review_type}* from), suggested_reviewers.map(&:slack_emoji).join(' ') ].join(' ') end private def needed_review_type pull_request.needs_first_review? ? 'first review' : 'second review' end end end fix: i am dumb # frozen_string_literal: true module ReviewBot class Notification def initialize(pull_request:, suggested_reviewers:) @pull_request = pull_request @suggested_reviewers = suggested_reviewers end attr_reader :pull_request, :suggested_reviewers def message [ %(• ##{pull_request.id} <#{pull_request.html_url}|#{pull_request.title}> needs a *#{needed_review_type}* from), suggested_reviewers.map(&:slack_emoji).join(' ') ].join(' ') end private def needed_review_type pull_request.needs_first_review? ? 'first review' : 'second review' end end end
# frozen_string_literal: true require "English" # We will start reviewing commit from this one. FROM_SHA = "bef0fe19d3a5d1e215a4fbadd496ad61699e63f9" # Performs the given command, and optionally spits the output as it comes. def spawn_cmd(cmd:, output: true) status = 0 PTY.spawn(cmd) do |stdout, _, pid| if output # rubocop:disable Lint/HandleExceptions begin stdout.each { |line| print line } rescue Errno::EIO # End of output end # rubocop:enable Lint/HandleExceptions end Process.wait(pid) status = $CHILD_STATUS.exitstatus end status end # Returns true if the `git-validation` command is available. def git_validation? spawn_cmd(cmd: "which git-validation", output: false).zero? end # Returns the first commit to be considered by git-validation. def from FROM_SHA end namespace :test do desc "Run git-validate on the source code" task git: :environment do unless git_validation? puts "[TEST] The git-validation command could not be found" exit 1 end path = Rails.root puts "cd #{path} && git-validation -range #{from}..HEAD" status = spawn_cmd(cmd: "cd #{path} && git-validation -range #{from}..HEAD") exit status end end lib: use TRAVIS_COMMIT_RANGE for git-validation This should cover pretty much all cases in Travis, and it will simplify what we've been doing so far. Signed-off-by: Miquel Sabaté Solà <b4d70704b9e7df580cab34510621dbd0aacb2dfd@suse.com> # frozen_string_literal: true require "English" # We will start reviewing commit from this one. FROM_SHA = "bef0fe19d3a5d1e215a4fbadd496ad61699e63f9" # Performs the given command, and optionally spits the output as it comes. def spawn_cmd(cmd:, output: true) status = 0 PTY.spawn(cmd) do |stdout, _, pid| if output # rubocop:disable Lint/HandleExceptions begin stdout.each { |line| print line } rescue Errno::EIO # End of output end # rubocop:enable Lint/HandleExceptions end Process.wait(pid) status = $CHILD_STATUS.exitstatus end status end # Returns true if the `git-validation` command is available. def git_validation? spawn_cmd(cmd: "which git-validation", output: false).zero? end # Returns the range of commits to be considered by git-validation. def range return ENV["TRAVIS_COMMIT_RANGE"] if ENV["TRAVIS_COMMIT_RANGE"].present? "#{FROM_SHA}..HEAD" end namespace :test do desc "Run git-validate on the source code" task git: :environment do unless git_validation? puts "[TEST] The git-validation command could not be found" exit 1 end path = Rails.root puts "cd #{path} && git-validation -range #{range}" status = spawn_cmd(cmd: "cd #{path} && git-validation -range #{range}") exit status end end
require 'rest_client' require 'json' require 'set' require 'cgi' require 'base64' require File.expand_path('../version', __FILE__) unless defined?(RightApi::Client::VERSION) require File.expand_path('../helper', __FILE__) require File.expand_path('../resource', __FILE__) require File.expand_path('../resource_detail', __FILE__) require File.expand_path('../resources', __FILE__) require File.expand_path('../errors', __FILE__) require File.expand_path('../exceptions', __FILE__) # RightApiClient has the generic get/post/delete/put calls that are used by resources module RightApi class Client include Helper DEFAULT_OPEN_TIMEOUT = nil DEFAULT_TIMEOUT = -1 DEFAULT_MAX_ATTEMPTS = 5 ROOT_RESOURCE = '/api/session' OAUTH_ENDPOINT = '/api/oauth2' ROOT_INSTANCE_RESOURCE = '/api/session/instance' DEFAULT_API_URL = 'https://my.rightscale.com' # permitted parameters for initializing AUTH_PARAMS = %w[ email password_base64 password instance_token refresh_token access_token cookies account_id api_url api_version timeout open_timeout max_attempts enable_retry rest_client_class ] # @return [String] OAuth 2.0 refresh token if provided attr_reader :refresh_token # @return [String] OAuth 2.0 access token, if present attr_reader :access_token # @return [Time] expiry timestamp for OAuth 2.0 access token attr_reader :access_token_expires_at attr_accessor :account_id # @return [String] Base API url, e.g. https://us-3.rightscale.com attr_accessor :api_url # @return [String] instance API token as included in user-data attr_reader :instance_token # @return [Hash] collection of API cookies # @deprecated please use OAuth 2.0 refresh tokens instead of password-based authentication attr_reader :cookies # @return [Hash] debug information about the last request and response attr_reader :last_request # @return [Integer] number of seconds to wait for socket open attr_reader :open_timeout # @return [Integer] number of seconds to wait for API response attr_reader :timeout # @return [Integer] number of times to retry idempotent requests (iff enable_retry == true) attr_reader :max_attempts # @return [Boolean] whether to retry idempotent requests that fail attr_reader :enable_retry # Instantiate a new Client. def initialize(args) raise 'This API client is only compatible with Ruby 1.8.7 and upwards.' if (RUBY_VERSION < '1.8.7') @api_url, @api_version = DEFAULT_API_URL, API_VERSION @open_timeout, @timeout, @max_attempts = DEFAULT_OPEN_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS @enable_retry = false # Initializing all instance variables from hash args.each { |key,value| instance_variable_set("@#{key}", value) if AUTH_PARAMS.include?(key.to_s) } if args.is_a? Hash raise 'This API client is only compatible with the RightScale API 1.5 and upwards.' if (Float(@api_version) < 1.5) # allow a custom resource-style REST client (for special logging, etc.) @rest_client_class ||= ::RestClient::Resource @rest_client = @rest_client_class.new(@api_url, :open_timeout => @open_timeout, :timeout => @timeout) @last_request = {} # There are five options for login: # - user email/password (using plaintext or base64-obfuscated password) # - user OAuth refresh token # - instance API token # - existing user-supplied cookies # - existing user-supplied OAuth access token # # The latter two options are not really login; they imply that the user logged in out of band. # See config/login.yml.example for more info. login() unless @cookies || @access_token timestamp_cookies # Add the top level links for instance_facing_calls if @instance_token resource_type, path, data = self.do_get(ROOT_INSTANCE_RESOURCE) instance_href = get_href_from_links(data['links']) cloud_href = instance_href.split('/instances')[0] define_instance_method(:get_instance) do |*params| type, instance_path, instance_data = self.do_get(ROOT_INSTANCE_RESOURCE) RightApi::ResourceDetail.new(self, type, instance_path, instance_data) end Helper::INSTANCE_FACING_RESOURCES.each do |meth| define_instance_method(meth) do |*args| obj_path = cloud_href + '/' + meth.to_s # Following are special cases that need to over-ride the obj_path obj_path = '/api/backups' if meth == :backups obj_path = instance_href + '/live/tasks' if meth == :live_tasks if has_id(*args) obj_path = add_id_and_params_to_path(obj_path, *args) RightApi::Resource.process(self, get_singular(meth), obj_path) else RightApi::Resources.new(self, obj_path, meth.to_s) end end end else # Session is the root resource that has links to all the base resources define_instance_method(:session) do |*params| RightApi::Resources.new(self, ROOT_RESOURCE, 'session') end # Allow the base resources to be accessed directly get_associated_resources(self, session.index.links, nil) end end def to_s "#<RightApi::Client #{api_url}>" end # Log HTTP calls to file (file can be STDOUT as well) def log(file) RestClient.log = file end # Given a path returns a RightApiClient::Resource instance. # def resource(path, params={}) r = Resource.process_detailed(self, *do_get(path, params)) # note that process_detailed will make a best-effort to return an already # detailed resource or array of detailed resources but there may still be # legacy cases where #show is still needed. calling #show on an already # detailed resource is a no-op. r.respond_to?(:show) ? r.show : r end # Seems #resource tends to expand (call index) on Resources instances, # so this is a workaround. # def resources(type, path) Resources.new(self, path, type) end protected # Users shouldn't need to call the following methods directly def retry_request(is_read_only = false) attempts = 0 begin yield rescue OpenSSL::SSL::SSLError => e raise e unless @enable_retry # These errors pertain to the SSL handshake. Since no data has been # exchanged its always safe to retry raise e if attempts >= @max_attempts attempts += 1 retry rescue Errno::ECONNRESET, RestClient::ServerBrokeConnection, RestClient::RequestTimeout => e raise e unless @enable_retry # Packetloss related. # There are two timeouts on the ssl negotiation and data read with different # times. Unfortunately the standard timeout class is used for both and the # exceptions are caught and reraised so you can't distinguish between them. # Unfortunate since ssl negotiation timeouts should always be retryable # whereas data may not. if is_read_only raise e if attempts >= @max_attempts attempts += 1 retry else raise e end rescue ApiError => e if re_login?(e) # Session is expired or invalid login() retry else raise e end end end def login account_href = "/api/accounts/#{@account_id}" params, path = if @refresh_token [ {'grant_type' => 'refresh_token', 'refresh_token'=>@refresh_token}, OAUTH_ENDPOINT ] elsif @instance_token [ { 'instance_token' => @instance_token, 'account_href' => account_href }, ROOT_INSTANCE_RESOURCE ] elsif @password_base64 [ { 'email' => @email, 'password' => Base64.decode64(@password_base64), 'account_href' => account_href }, ROOT_RESOURCE ] else [ { 'email' => @email, 'password' => @password, 'account_href' => account_href }, ROOT_RESOURCE ] end response = nil attempts = 0 begin response = @rest_client[path].post(params, 'X-Api-Version' => @api_version) do |response, request, result, &block| if [301, 302, 307].include?(response.code) update_api_url(response) response.follow_redirection(request, result, &block) else response.return!(request, result) end end rescue Errno::ECONNRESET, RestClient::RequestTimeout, OpenSSL::SSL::SSLError, RestClient::ServerBrokeConnection raise unless @enable_retry raise if attempts >= @max_attempts attempts += 1 retry end if path == OAUTH_ENDPOINT update_access_token(response) else update_cookies(response) end end # Returns the request headers def headers h = { 'X-Api-Version' => @api_version, :accept => :json, } if @account_id h['X-Account'] = @account_id end if @access_token h['Authorization'] = "Bearer #{@access_token}" elsif @cookies h[:cookies] = @cookies end h end def update_last_request(request, response) @last_request[:request] = request @last_request[:response] = response end # Generic get # params are NOT read only def do_get(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request(true) do # Return content type so the resulting resource object knows what kind of resource it is. resource_type, body = @rest_client[path].get(headers) do |response, request, result, &block| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 # Get the resource_type from the content_type, the resource_type # will be used later to add relevant methods to relevant resources type = if result.content_type.index('rightscale') get_resource_type(result.content_type) else '' end [type, response.body] when 301, 302 update_api_url(response) response.follow_redirection(request, result, &block) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :get, path, params, req, res) end data = if resource_type == 'text' { 'text' => body } else JSON.parse(body, :allow_nan => true) end [resource_type, path, data] end # Generic post def do_post(path, params={}) login if need_login? params = fix_array_of_hashes(params) req, res, resource_type, body = nil begin retry_request do @rest_client[path].post(params, headers) do |response, request, result| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 201, 202 # Create and return the resource href = response.headers[:location] relative_href = href.split(@api_url)[-1] # Return the resource that was just created # Determine the resource_type from the href (eg. api/clouds/id). # This is based on the assumption that we can determine the resource_type without doing a do_get resource_type = get_singular(relative_href.split('/')[-2]) RightApi::Resource.process(self, resource_type, relative_href) when 204 nil when 200..299 # This is needed for the tags Resource -- which returns a 200 and has a content type # therefore, ResourceDetail objects needs to be returned if response.code == 200 && response.headers[:content_type].index('rightscale') resource_type = get_resource_type(response.headers[:content_type]) data = JSON.parse(response, :allow_nan => true) # Resource_tag is returned after querying tags.by_resource or tags.by_tags. # You cannot do a show on a resource_tag, but that is basically what we want to do data.map { |obj| RightApi::ResourceDetail.new(self, resource_type, path, obj) } else response.return!(request, result) end when 301, 302 update_api_url(response) do_post(path, params) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue ApiError => e raise wrap(e, :post, path, params, req, res) end end # Generic delete def do_delete(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request do @rest_client[path].delete(headers) do |response, request, result| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 when 204 nil when 301, 302 update_api_url(response) do_delete(path, params) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :delete, path, params, req, res) end end # Generic put def do_put(path, params={}) login if need_login? params = fix_array_of_hashes(params) req, res, resource_type, body = nil begin retry_request do @rest_client[path].put(params, headers) do |response, request, result| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 204 nil when 301, 302 update_api_url(response) do_put(path, params) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :put, path, params, req, res) end end # Determine whether the client needs a fresh round of authentication based on state of # cookies/tokens and their expiration timestamps. # # @return [Boolean] true if re-login is suggested def need_login? (@refresh_token && @refresh_token_expires_at && @refresh_token_expires_at - Time.now < 900) || (@cookies.respond_to?(:empty?) && @cookies.empty?) end # Determine whether an exception can be fixed by logging in again. # # @return [Boolean] true if re-login is appropriate def re_login?(e) auth_error = (e.message.index('403') && e.message =~ %r(.*Session cookie is expired or invalid)) || e.message.index('401') renewable_creds = (@instance_token || (@email && (@password || @password_base64)) || @refresh_token) auth_error && renewable_creds end # @param [String] content_type an HTTP Content-Type header # @return [String] the resource_type associated with content_type def get_resource_type(content_type) content_type.scan(/\.rightscale\.(.*)\+json/)[0][0] end # Makes sure the @cookies have a timestamp. # def timestamp_cookies return unless @cookies class << @cookies; attr_accessor :timestamp; end @cookies.timestamp = Time.now end # Sets the @access_token and @access_token_expires_at # def update_access_token(response) h = JSON.load(response) @access_token = String(h['access_token']) @access_token_expires_at = Time.at(Time.now.to_i + Integer(h['expires_in'])) end # Sets the @cookies (and timestamp it). # def update_cookies(response) return unless response.cookies (@cookies ||= {}).merge!(response.cookies) timestamp_cookies end # # A helper class for error details # class ErrorDetails attr_reader :method, :path, :params, :request, :response def initialize(me, pt, ps, rq, rs) @method = me @path = pt @params = ps @request = rq @response = rs end def code @response ? @response.code : nil end end # Adds details (path, params) to an error. Returns the error. # def wrap(error, method, path, params, request, response) class << error; attr_accessor :_details; end error._details = ErrorDetails.new(method, path, params, request, response) error end private def update_api_url(response) # Update the rest client url if we are redirected to another endpoint uri = URI.parse(response.headers[:location]) @api_url = "#{uri.scheme}://#{uri.host}" # note that the legacy code did not use the proper timeout values upon # redirect (i.e. always set :timeout => -1) but that seems like an # oversight; always use configured timeout values regardless of redirect. @rest_client = @rest_client_class.new( @api_url, :open_timeout => @open_timeout, :timeout => @timeout) end end end Use modules to override log_request require 'rest_client' require 'json' require 'set' require 'cgi' require 'base64' require File.expand_path('../version', __FILE__) unless defined?(RightApi::Client::VERSION) require File.expand_path('../helper', __FILE__) require File.expand_path('../resource', __FILE__) require File.expand_path('../resource_detail', __FILE__) require File.expand_path('../resources', __FILE__) require File.expand_path('../errors', __FILE__) require File.expand_path('../exceptions', __FILE__) module PostOverride def post(payload, additional_headers={}, &block) headers = (options[:headers] || {}).merge(additional_headers) requestor = ::RestClient::Request.new(options.merge( :method => :post, :url => url, :payload => payload, :headers => headers) ) requestor.extend(LogOverride) requestor.execute(&block) end end module LogOverride def log_request if RestClient.log out = [] out << "RestClient.#{method} #{url.inspect}" if !payload.nil? if (payload.short_inspect.include? "email") || (payload.short_inspect.include? "password") out << "<hidden credentials>" else out << payload.short_inspect end end out << processed_headers.to_a.sort.map { |(k, v)| [k.inspect, v.inspect].join("=>") }.join(", ") RestClient.log << out.join(', ') + "\n" end end end # RightApiClient has the generic get/post/delete/put calls that are used by resources module RightApi class Client include Helper DEFAULT_OPEN_TIMEOUT = nil DEFAULT_TIMEOUT = -1 DEFAULT_MAX_ATTEMPTS = 5 ROOT_RESOURCE = '/api/session' OAUTH_ENDPOINT = '/api/oauth2' ROOT_INSTANCE_RESOURCE = '/api/session/instance' DEFAULT_API_URL = 'https://my.rightscale.com' # permitted parameters for initializing AUTH_PARAMS = %w[ email password_base64 password instance_token refresh_token access_token cookies account_id api_url api_version timeout open_timeout max_attempts enable_retry rest_client_class ] # @return [String] OAuth 2.0 refresh token if provided attr_reader :refresh_token # @return [String] OAuth 2.0 access token, if present attr_reader :access_token # @return [Time] expiry timestamp for OAuth 2.0 access token attr_reader :access_token_expires_at attr_accessor :account_id # @return [String] Base API url, e.g. https://us-3.rightscale.com attr_accessor :api_url # @return [String] instance API token as included in user-data attr_reader :instance_token # @return [Hash] collection of API cookies # @deprecated please use OAuth 2.0 refresh tokens instead of password-based authentication attr_reader :cookies # @return [Hash] debug information about the last request and response attr_reader :last_request # @return [Integer] number of seconds to wait for socket open attr_reader :open_timeout # @return [Integer] number of seconds to wait for API response attr_reader :timeout # @return [Integer] number of times to retry idempotent requests (iff enable_retry == true) attr_reader :max_attempts # @return [Boolean] whether to retry idempotent requests that fail attr_reader :enable_retry # Instantiate a new Client. def initialize(args) raise 'This API client is only compatible with Ruby 1.8.7 and upwards.' if (RUBY_VERSION < '1.8.7') @api_url, @api_version = DEFAULT_API_URL, API_VERSION @open_timeout, @timeout, @max_attempts = DEFAULT_OPEN_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS @enable_retry = false # Initializing all instance variables from hash args.each { |key,value| instance_variable_set("@#{key}", value) if AUTH_PARAMS.include?(key.to_s) } if args.is_a? Hash raise 'This API client is only compatible with the RightScale API 1.5 and upwards.' if (Float(@api_version) < 1.5) # allow a custom resource-style REST client (for special logging, etc.) @rest_client_class ||= ::RestClient::Resource ::RestClient.log = STDOUT @rest_client = @rest_client_class.new(@api_url, :open_timeout => @open_timeout, :timeout => @timeout) @last_request = {} # There are five options for login: # - user email/password (using plaintext or base64-obfuscated password) # - user OAuth refresh token # - instance API token # - existing user-supplied cookies # - existing user-supplied OAuth access token # # The latter two options are not really login; they imply that the user logged in out of band. # See config/login.yml.example for more info. login() unless @cookies || @access_token timestamp_cookies # Add the top level links for instance_facing_calls if @instance_token resource_type, path, data = self.do_get(ROOT_INSTANCE_RESOURCE) instance_href = get_href_from_links(data['links']) cloud_href = instance_href.split('/instances')[0] define_instance_method(:get_instance) do |*params| type, instance_path, instance_data = self.do_get(ROOT_INSTANCE_RESOURCE) RightApi::ResourceDetail.new(self, type, instance_path, instance_data) end Helper::INSTANCE_FACING_RESOURCES.each do |meth| define_instance_method(meth) do |*args| obj_path = cloud_href + '/' + meth.to_s # Following are special cases that need to over-ride the obj_path obj_path = '/api/backups' if meth == :backups obj_path = instance_href + '/live/tasks' if meth == :live_tasks if has_id(*args) obj_path = add_id_and_params_to_path(obj_path, *args) RightApi::Resource.process(self, get_singular(meth), obj_path) else RightApi::Resources.new(self, obj_path, meth.to_s) end end end else # Session is the root resource that has links to all the base resources define_instance_method(:session) do |*params| RightApi::Resources.new(self, ROOT_RESOURCE, 'session') end # Allow the base resources to be accessed directly get_associated_resources(self, session.index.links, nil) end end def to_s "#<RightApi::Client #{api_url}>" end # Log HTTP calls to file (file can be STDOUT as well) def log(file) RestClient.log = file end # Given a path returns a RightApiClient::Resource instance. # def resource(path, params={}) r = Resource.process_detailed(self, *do_get(path, params)) # note that process_detailed will make a best-effort to return an already # detailed resource or array of detailed resources but there may still be # legacy cases where #show is still needed. calling #show on an already # detailed resource is a no-op. r.respond_to?(:show) ? r.show : r end # Seems #resource tends to expand (call index) on Resources instances, # so this is a workaround. # def resources(type, path) Resources.new(self, path, type) end protected # Users shouldn't need to call the following methods directly def retry_request(is_read_only = false) attempts = 0 begin yield rescue OpenSSL::SSL::SSLError => e raise e unless @enable_retry # These errors pertain to the SSL handshake. Since no data has been # exchanged its always safe to retry raise e if attempts >= @max_attempts attempts += 1 retry rescue Errno::ECONNRESET, RestClient::ServerBrokeConnection, RestClient::RequestTimeout => e raise e unless @enable_retry # Packetloss related. # There are two timeouts on the ssl negotiation and data read with different # times. Unfortunately the standard timeout class is used for both and the # exceptions are caught and reraised so you can't distinguish between them. # Unfortunate since ssl negotiation timeouts should always be retryable # whereas data may not. if is_read_only raise e if attempts >= @max_attempts attempts += 1 retry else raise e end rescue ApiError => e if re_login?(e) # Session is expired or invalid login() retry else raise e end end end def login account_href = "/api/accounts/#{@account_id}" params, path = if @refresh_token [ {'grant_type' => 'refresh_token', 'refresh_token'=>@refresh_token}, OAUTH_ENDPOINT ] elsif @instance_token [ { 'instance_token' => @instance_token, 'account_href' => account_href }, ROOT_INSTANCE_RESOURCE ] elsif @password_base64 [ { 'email' => @email, 'password' => Base64.decode64(@password_base64), 'account_href' => account_href }, ROOT_RESOURCE ] else [ { 'email' => @email, 'password' => @password, 'account_href' => account_href }, ROOT_RESOURCE ] end response = nil attempts = 0 begin @rester = @rest_client[path] @rester.extend(PostOverride) response = @rester.post(params, 'X-Api-Version' => @api_version) do |response, request, result, &block| if [301, 302, 307].include?(response.code) update_api_url(response) response.follow_redirection(request, result, &block) else response.return!(request, result) end end rescue Errno::ECONNRESET, RestClient::RequestTimeout, OpenSSL::SSL::SSLError, RestClient::ServerBrokeConnection raise unless @enable_retry raise if attempts >= @max_attempts attempts += 1 retry end if path == OAUTH_ENDPOINT update_access_token(response) else update_cookies(response) end end # Returns the request headers def headers h = { 'X-Api-Version' => @api_version, :accept => :json, } if @account_id h['X-Account'] = @account_id end if @access_token h['Authorization'] = "Bearer #{@access_token}" elsif @cookies h[:cookies] = @cookies end h end def update_last_request(request, response) @last_request[:request] = request @last_request[:response] = response end # Generic get # params are NOT read only def do_get(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request(true) do # Return content type so the resulting resource object knows what kind of resource it is. resource_type, body = @rest_client[path].get(headers) do |response, request, result, &block| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 # Get the resource_type from the content_type, the resource_type # will be used later to add relevant methods to relevant resources type = if result.content_type.index('rightscale') get_resource_type(result.content_type) else '' end [type, response.body] when 301, 302 update_api_url(response) response.follow_redirection(request, result, &block) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :get, path, params, req, res) end data = if resource_type == 'text' { 'text' => body } else JSON.parse(body, :allow_nan => true) end [resource_type, path, data] end # Generic post def do_post(path, params={}) login if need_login? params = fix_array_of_hashes(params) req, res, resource_type, body = nil begin retry_request do @rest_client[path].post(params, headers) do |response, request, result| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 201, 202 # Create and return the resource href = response.headers[:location] relative_href = href.split(@api_url)[-1] # Return the resource that was just created # Determine the resource_type from the href (eg. api/clouds/id). # This is based on the assumption that we can determine the resource_type without doing a do_get resource_type = get_singular(relative_href.split('/')[-2]) RightApi::Resource.process(self, resource_type, relative_href) when 204 nil when 200..299 # This is needed for the tags Resource -- which returns a 200 and has a content type # therefore, ResourceDetail objects needs to be returned if response.code == 200 && response.headers[:content_type].index('rightscale') resource_type = get_resource_type(response.headers[:content_type]) data = JSON.parse(response, :allow_nan => true) # Resource_tag is returned after querying tags.by_resource or tags.by_tags. # You cannot do a show on a resource_tag, but that is basically what we want to do data.map { |obj| RightApi::ResourceDetail.new(self, resource_type, path, obj) } else response.return!(request, result) end when 301, 302 update_api_url(response) do_post(path, params) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue ApiError => e raise wrap(e, :post, path, params, req, res) end end # Generic delete def do_delete(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request do @rest_client[path].delete(headers) do |response, request, result| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 when 204 nil when 301, 302 update_api_url(response) do_delete(path, params) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :delete, path, params, req, res) end end # Generic put def do_put(path, params={}) login if need_login? params = fix_array_of_hashes(params) req, res, resource_type, body = nil begin retry_request do @rest_client[path].put(params, headers) do |response, request, result| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 204 nil when 301, 302 update_api_url(response) do_put(path, params) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :put, path, params, req, res) end end # Determine whether the client needs a fresh round of authentication based on state of # cookies/tokens and their expiration timestamps. # # @return [Boolean] true if re-login is suggested def need_login? (@refresh_token && @refresh_token_expires_at && @refresh_token_expires_at - Time.now < 900) || (@cookies.respond_to?(:empty?) && @cookies.empty?) end # Determine whether an exception can be fixed by logging in again. # # @return [Boolean] true if re-login is appropriate def re_login?(e) auth_error = (e.message.index('403') && e.message =~ %r(.*Session cookie is expired or invalid)) || e.message.index('401') renewable_creds = (@instance_token || (@email && (@password || @password_base64)) || @refresh_token) auth_error && renewable_creds end # @param [String] content_type an HTTP Content-Type header # @return [String] the resource_type associated with content_type def get_resource_type(content_type) content_type.scan(/\.rightscale\.(.*)\+json/)[0][0] end # Makes sure the @cookies have a timestamp. # def timestamp_cookies return unless @cookies class << @cookies; attr_accessor :timestamp; end @cookies.timestamp = Time.now end # Sets the @access_token and @access_token_expires_at # def update_access_token(response) h = JSON.load(response) @access_token = String(h['access_token']) @access_token_expires_at = Time.at(Time.now.to_i + Integer(h['expires_in'])) end # Sets the @cookies (and timestamp it). # def update_cookies(response) return unless response.cookies (@cookies ||= {}).merge!(response.cookies) timestamp_cookies end # # A helper class for error details # class ErrorDetails attr_reader :method, :path, :params, :request, :response def initialize(me, pt, ps, rq, rs) @method = me @path = pt @params = ps @request = rq @response = rs end def code @response ? @response.code : nil end end # Adds details (path, params) to an error. Returns the error. # def wrap(error, method, path, params, request, response) class << error; attr_accessor :_details; end error._details = ErrorDetails.new(method, path, params, request, response) error end private def update_api_url(response) # Update the rest client url if we are redirected to another endpoint uri = URI.parse(response.headers[:location]) @api_url = "#{uri.scheme}://#{uri.host}" # note that the legacy code did not use the proper timeout values upon # redirect (i.e. always set :timeout => -1) but that seems like an # oversight; always use configured timeout values regardless of redirect. @rest_client = @rest_client_class.new( @api_url, :open_timeout => @open_timeout, :timeout => @timeout) end end end
namespace :webify do desc 'Shows a WebifyRuby gem version' task :current_version do puts "You are running WebifyRuby v.#{WebifyRuby::VERSION} so far." end end Task fix namespace :webify do desc 'Shows a WebifyRuby gem version' task :current_version do require '../webify_ruby/version.rb' puts "You are running WebifyRuby v.#{WebifyRuby::VERSION} so far." end end
require 'pp' require 'ripper-tags/parser' module RipperTags class FileFinder attr_reader :options def initialize(options) @options = options end def exclude_patterns @exclude ||= Array(options.exclude).map { |pattern| if pattern.index('*') Regexp.new(Regexp.escape(pattern).gsub('\\*', '[^/]+')) else pattern end } end def exclude_file?(file) base = File.basename(file) exclude_patterns.any? {|ex| case ex when Regexp then base =~ ex else base == ex end } || exclude_patterns.any? {|ex| case ex when Regexp then file =~ ex else file.include?(ex) end } end def include_file?(file) (options.all_files || file =~ /\.rb\z/) && !exclude_file?(file) end def find_files(list, depth = 0) list.each do |file| if File.directory?(file) if options.recursive files = Dir.entries(file).map { |name| File.join(file, name) unless '.' == name || '..' == name }.compact find_files(files, depth + 1) {|f| yield f } end else yield file if include_file?(file) end end end def each_file return to_enum(__method__) unless block_given? find_files(options.files) {|f| yield f } end end class DataReader attr_reader :options attr_accessor :read_mode def initialize(options) @options = options @read_mode = defined?(::Encoding) ? 'r:utf-8' : 'r' end def file_finder FileFinder.new(options) end def read_file(filename) str = File.open(filename, read_mode) {|f| f.read } normalize_encoding(str) end def normalize_encoding(str) if str.respond_to?(:encode!) # strip invalid byte sequences str.encode!('utf-16', :invalid => :replace, :undef => :replace) str.encode!('utf-8') else str end end def each_tag return to_enum(__method__) unless block_given? file_finder.each_file do |file| begin $stderr.puts "Parsing file #{file}" if options.verbose extractor = tag_extractor(file) rescue => err if options.force $stderr.puts "Error parsing `#{file}': #{err.message}" else raise err end else extractor.tags.each do |tag| yield tag end end end end def debug_dump(obj) pp(obj, $stderr) end def parse_file(contents, filename) sexp = Parser.new(contents, filename).parse debug_dump(sexp) if options.debug sexp end def tag_extractor(file) file_contents = read_file(file) debug_dump(Ripper.sexp(file_contents)) if options.verbose_debug sexp = parse_file(file_contents, file) Visitor.new(sexp, file, file_contents) end end end Avoid generating unnecessary arrays when finding files recursively require 'pp' require 'ripper-tags/parser' module RipperTags class FileFinder attr_reader :options def initialize(options) @options = options end def exclude_patterns @exclude ||= Array(options.exclude).map { |pattern| if pattern.index('*') Regexp.new(Regexp.escape(pattern).gsub('\\*', '[^/]+')) else pattern end } end def exclude_file?(file) base = File.basename(file) exclude_patterns.any? {|ex| case ex when Regexp then base =~ ex else base == ex end } || exclude_patterns.any? {|ex| case ex when Regexp then file =~ ex else file.include?(ex) end } end def include_file?(file) (options.all_files || file =~ /\.rb\z/) && !exclude_file?(file) end def resolve_file(file) if File.directory?(file) if options.recursive Dir.entries(file).each do |name| unless '.' == name || '..' == name resolve_file(File.join(file, name)) { |f| yield f } end end end else yield file if include_file?(file) end end def each_file return to_enum(__method__) unless block_given? options.files.each do |file| resolve_file(file) { |f| yield f } end end end class DataReader attr_reader :options attr_accessor :read_mode def initialize(options) @options = options @read_mode = defined?(::Encoding) ? 'r:utf-8' : 'r' end def file_finder FileFinder.new(options) end def read_file(filename) str = File.open(filename, read_mode) {|f| f.read } normalize_encoding(str) end def normalize_encoding(str) if str.respond_to?(:encode!) # strip invalid byte sequences str.encode!('utf-16', :invalid => :replace, :undef => :replace) str.encode!('utf-8') else str end end def each_tag return to_enum(__method__) unless block_given? file_finder.each_file do |file| begin $stderr.puts "Parsing file #{file}" if options.verbose extractor = tag_extractor(file) rescue => err if options.force $stderr.puts "Error parsing `#{file}': #{err.message}" else raise err end else extractor.tags.each do |tag| yield tag end end end end def debug_dump(obj) pp(obj, $stderr) end def parse_file(contents, filename) sexp = Parser.new(contents, filename).parse debug_dump(sexp) if options.debug sexp end def tag_extractor(file) file_contents = read_file(file) debug_dump(Ripper.sexp(file_contents)) if options.verbose_debug sexp = parse_file(file_contents, file) Visitor.new(sexp, file, file_contents) end end end
require 'awesome_print' module TentValidator module Runner class CLI TRANSLATE_KEYS = { :current_value => :actual }.freeze def self.run(options = {}) instance = self.new(options) instance.run end def initialize(options = {}) end def run @valid = [] @invalid = [] puts "Running Protocol Validations..." results = Runner.run do |results| print_results(results.as_json) end print "\n" validator_complete(results.as_json) print "\n" if @invalid.any? puts green("#{@valid.uniq.size} validations valid\t") + red("#{@invalid.uniq.size} failed") else puts green("#{@valid.uniq.size} validations valid\t0 failed") end print "\n" exit(1) unless @valid end def print_results(results, parent_names = []) results.each_pair do |name, children| next if name == :results child_results = children[:results] child_results.each do |r| id = r.object_id.to_s valid = result_valid?(r) if valid next if @valid.index(id) @valid << id print green(".") else next if @invalid.index(id) @invalid << id print red("F") end end print_results(children, parent_names + [name]) end end def validator_complete(results, parent_names = []) parent_names.reject! { |n| n == "" } results.each_pair do |name, children| next if name == :results child_results = children[:results] child_results.each do |r| next if result_valid?(r) print "\n" puts red((parent_names + [name]).join(" ")) print "\n" actual = r.as_json[:actual] puts "REQUEST:" puts "#{actual[:request_method]} #{actual[:request_url]}" puts actual[:request_headers].inject([]) { |m, (k,v)| m << "#{k}: #{v}"; m }.join("\n") print "\n" puts actual[:request_body] print "\n" puts "RESPONSE:" puts actual[:response_status] puts actual[:response_headers].inject([]) { |m, (k,v)| m << "#{k}: #{v}"; m }.join("\n") print "\n" puts actual[:response_body] print "\n" puts "DIFF:" r.as_json[:expected].each_pair do |key, val| next if val[:valid] puts key ap val[:diff].map { |i| translate_keys(i.dup) } end end validator_complete(children, parent_names + [name]) end end def result_valid?(result) valid = result.as_json[:expected].inject(true) { |memo, (k,v)| memo = false if v.has_key?(:valid) && !v[:valid] memo } end def translate_keys(hash) TRANSLATE_KEYS.each_pair do |from, to| next unless hash.has_key?(from) hash[to] = hash[from] hash.delete(from) end hash end def green(text); color(text, "\e[32m"); end def red(text); color(text, "\e[31m"); end def yellow(text); color(text, "\e[33m"); end def blue(text); color(text, "\e[34m"); end def color(text, color_code) "#{color_code}#{text}\e[0m" end end end end Update cli: print response body as json require 'awesome_print' module TentValidator module Runner class CLI TRANSLATE_KEYS = { :current_value => :actual }.freeze def self.run(options = {}) instance = self.new(options) instance.run end def initialize(options = {}) end def run @valid = [] @invalid = [] puts "Running Protocol Validations..." results = Runner.run do |results| print_results(results.as_json) end print "\n" validator_complete(results.as_json) print "\n" if @invalid.any? puts green("#{@valid.uniq.size} validations valid\t") + red("#{@invalid.uniq.size} failed") else puts green("#{@valid.uniq.size} validations valid\t0 failed") end print "\n" exit(1) unless @valid end def print_results(results, parent_names = []) results.each_pair do |name, children| next if name == :results child_results = children[:results] child_results.each do |r| id = r.object_id.to_s valid = result_valid?(r) if valid next if @valid.index(id) @valid << id print green(".") else next if @invalid.index(id) @invalid << id print red("F") end end print_results(children, parent_names + [name]) end end def validator_complete(results, parent_names = []) parent_names.reject! { |n| n == "" } results.each_pair do |name, children| next if name == :results child_results = children[:results] child_results.each do |r| next if result_valid?(r) print "\n" puts red((parent_names + [name]).join(" ")) print "\n" actual = r.as_json[:actual] puts "REQUEST:" puts "#{actual[:request_method]} #{actual[:request_url]}" puts actual[:request_headers].inject([]) { |m, (k,v)| m << "#{k}: #{v}"; m }.join("\n") print "\n" puts actual[:request_body] print "\n" puts "RESPONSE:" puts actual[:response_status] puts actual[:response_headers].inject([]) { |m, (k,v)| m << "#{k}: #{v}"; m }.join("\n") print "\n" puts Yajl::Encoder.encode(actual[:response_body]) print "\n" puts "DIFF:" r.as_json[:expected].each_pair do |key, val| next if val[:valid] puts key ap val[:diff].map { |i| translate_keys(i.dup) } end end validator_complete(children, parent_names + [name]) end end def result_valid?(result) valid = result.as_json[:expected].inject(true) { |memo, (k,v)| memo = false if v.has_key?(:valid) && !v[:valid] memo } end def translate_keys(hash) TRANSLATE_KEYS.each_pair do |from, to| next unless hash.has_key?(from) hash[to] = hash[from] hash.delete(from) end hash end def green(text); color(text, "\e[32m"); end def red(text); color(text, "\e[31m"); end def yellow(text); color(text, "\e[33m"); end def blue(text); color(text, "\e[34m"); end def color(text, color_code) "#{color_code}#{text}\e[0m" end end end end
module ROM class Session # @api public class Environment < ROM::Environment include Proxy attr_reader :environment private :environment attr_reader :tracker private :tracker attr_reader :memory private :memory def initialize(environment, tracker) @environment = environment @tracker = tracker initialize_memory end # @api public def [](name) memory[name] end # @api private def commit tracker.commit end private # @api private def initialize_memory @memory = Hash.new { |memory, name| memory[name] = build_relation(name) } end # @api private def build_relation(name) Session::Relation.build(environment[name], tracker, tracker.identity_map(name)) end end # Registry end # Session end # ROM Simplify Session::Environment a little and add docs module ROM class Session # Session-specific environment wrapping ROM's environment # # It works exactly the same as ROM::Environment except it returns # session relations # # @api public class Environment < ROM::Environment include Proxy attr_reader :environment, :tracker, :memory private :environment, :tracker, :memory # @api private def initialize(environment, tracker) @environment = environment @tracker = tracker initialize_memory end # Return a relation identified by name # # @param [Symbol] name of a relation # # @return [Session::Relation] rom's relation wrapped by session # # @api public def [](name) memory[name] end # @api private def commit tracker.commit end private # @api private def initialize_memory @memory = Hash.new { |memory, name| memory[name] = build_relation(name) } end # @api private def build_relation(name) Session::Relation.build(environment[name], tracker, tracker.identity_map(name)) end end # Environment end # Session end # ROM
module TentD module Model module PostBuilder extend self def build_attributes(env, options = {}) data = env['data'] current_user = env['current_user'] type, base_type = Type.find_or_create(data['type']) unless type raise CreateFailure.new("Invalid type: #{data['type'].inspect}") end received_at_timestamp = TentD::Utils.timestamp published_at_timestamp = (data['published_at'] || received_at_timestamp).to_i attrs = { :user_id => current_user.id, :entity_id => current_user.entity_id, :entity => current_user.entity, :type => type.type, :type_id => type.id, :type_base_id => base_type.id, :version_published_at => published_at_timestamp, :version_received_at => received_at_timestamp, :published_at => published_at_timestamp, :received_at => received_at_timestamp, :content => data['content'], } if options[:public_id] attrs[:public_id] = options[:public_id] end if data['version'] && Array === data['version']['parents'] attrs[:version_parents] = data['version']['parents'] attrs[:version_parents].each_with_index do |item, index| unless item['version'] raise CreateFailure.new("/version/parents/#{index}/version is required") end unless item['post'] raise CreateFailure.new("/version/parents/#{index}/post is required") end end elsif options[:version] unless options[:notification] raise CreateFailure.new("Parent version not specified") end end if Hash === data['permissions'] if data['permissions']['public'] == true attrs[:public] = true else attrs[:public] = false if Array === data['permissions']['entities'] attrs[:permissions_entities] = data['permissions']['entities'] end end end if Array === data['mentions'] && data['mentions'].any? attrs[:mentions] = data['mentions'].map do |m| m['entity'] = attrs[:entity] unless m.has_key?('entity') m end end if Array === data['refs'] && data['refs'].any? attrs[:refs] = data['refs'].map do |ref| ref['entity'] = attrs[:entity] unless ref.has_key?('entity') ref end end if options[:notification] attrs[:attachments] = data['attachments'] if Array === data['attachments'] else if Array === data['attachments'] data['attachments'] = data['attachments'].inject([]) do |memo, attachment| next memo unless attachment.has_key?('digest') if attachment['model'] = Attachment.where(:digest => attachment['digest']).first memo << attachment end memo end attrs[:attachments] = data['attachments'].map do |attachment| { :digest => attachment['digest'], :size => attachment['model'].size, :name => attachment['name'], :category => attachment['category'], :content_type => attachment['content_type'] } end end if Array === env['attachments'] attrs[:attachments] = env['attachments'].inject(attrs[:attachments] || Array.new) do |memo, attachment| memo << { :digest => TentD::Utils.hex_digest(attachment[:tempfile]), :size => attachment[:tempfile].size, :name => attachment[:name], :category => attachment[:category], :content_type => attachment[:content_type] } memo end end end attrs end def create_from_env(env, options = {}) attrs = build_attributes(env, options) post = Post.create(attrs) if Array === env['data']['mentions'] post.create_mentions(env['data']['mentions']) end unless options[:notification] if Array === env['data']['attachments'] env['data']['attachments'].each do |attachment| PostsAttachment.create( :attachment_id => attachment['model'].id, :content_type => attachment['content_type'], :post_id => post.id ) end end if Array === env['attachments'] post.create_attachments(env['attachments']) end end if Array === attrs[:version_parents] post.create_version_parents(attrs[:version_parents]) end unless options[:notification] post.queue_delivery end post end def create_attachments(post, attachments) attachments.each_with_index do |attachment, index| data = attachment[:tempfile].read attachment[:tempfile].rewind PostsAttachment.create( :attachment_id => Attachment.find_or_create( TentD::Utils::Hash.slice(post.attachments[index], 'digest', 'size').merge(:data => data) ).id, :post_id => post.id, :content_type => attachment[:content_type] ) end end def create_mentions(post, mentions) mentions.map do |mention| mention_attrs = { :user_id => post.user_id, :post_id => post.id } if mention['entity'] mention_attrs[:entity_id] = Entity.first_or_create(mention['entity']).id mention_attrs[:entity] = mention['entity'] else mention_attrs[:entity_id] = post.entity_id mention_attrs[:entity] = post.entity end if mention['type'] mention_attrs[:type_id] = Type.find_or_create_full(mention['type']).id mention_attrs[:type] = mention['type'] end mention_attrs[:post] = mention['post'] if mention.has_key?('post') mention_attrs[:public] = mention['public'] if mention.has_key?('public') Mention.create(mention_attrs) end end def create_version_parents(post, version_parents) version_parents.each do |item| item['post'] ||= post.public_id _parent = Post.where(:user_id => post.user_id, :public_id => item['post'], :version => item['version']).first Parent.create( :post_id => post.id, :parent_post_id => _parent ? _parent.id : nil, :version => item['version'], :post => item['post'] ) end end end end end Fix PostBuilder when raising CreateFailure module TentD module Model module PostBuilder extend self CreateFailure = Post::CreateFailure def build_attributes(env, options = {}) data = env['data'] current_user = env['current_user'] type, base_type = Type.find_or_create(data['type']) unless type raise CreateFailure.new("Invalid type: #{data['type'].inspect}") end received_at_timestamp = TentD::Utils.timestamp published_at_timestamp = (data['published_at'] || received_at_timestamp).to_i attrs = { :user_id => current_user.id, :entity_id => current_user.entity_id, :entity => current_user.entity, :type => type.type, :type_id => type.id, :type_base_id => base_type.id, :version_published_at => published_at_timestamp, :version_received_at => received_at_timestamp, :published_at => published_at_timestamp, :received_at => received_at_timestamp, :content => data['content'], } if options[:public_id] attrs[:public_id] = options[:public_id] end if data['version'] && Array === data['version']['parents'] attrs[:version_parents] = data['version']['parents'] attrs[:version_parents].each_with_index do |item, index| unless item['version'] raise CreateFailure.new("/version/parents/#{index}/version is required") end unless item['post'] raise CreateFailure.new("/version/parents/#{index}/post is required") end end elsif options[:version] unless options[:notification] raise CreateFailure.new("Parent version not specified") end end if Hash === data['permissions'] if data['permissions']['public'] == true attrs[:public] = true else attrs[:public] = false if Array === data['permissions']['entities'] attrs[:permissions_entities] = data['permissions']['entities'] end end end if Array === data['mentions'] && data['mentions'].any? attrs[:mentions] = data['mentions'].map do |m| m['entity'] = attrs[:entity] unless m.has_key?('entity') m end end if Array === data['refs'] && data['refs'].any? attrs[:refs] = data['refs'].map do |ref| ref['entity'] = attrs[:entity] unless ref.has_key?('entity') ref end end if options[:notification] attrs[:attachments] = data['attachments'] if Array === data['attachments'] else if Array === data['attachments'] data['attachments'] = data['attachments'].inject([]) do |memo, attachment| next memo unless attachment.has_key?('digest') if attachment['model'] = Attachment.where(:digest => attachment['digest']).first memo << attachment end memo end attrs[:attachments] = data['attachments'].map do |attachment| { :digest => attachment['digest'], :size => attachment['model'].size, :name => attachment['name'], :category => attachment['category'], :content_type => attachment['content_type'] } end end if Array === env['attachments'] attrs[:attachments] = env['attachments'].inject(attrs[:attachments] || Array.new) do |memo, attachment| memo << { :digest => TentD::Utils.hex_digest(attachment[:tempfile]), :size => attachment[:tempfile].size, :name => attachment[:name], :category => attachment[:category], :content_type => attachment[:content_type] } memo end end end attrs end def create_from_env(env, options = {}) attrs = build_attributes(env, options) post = Post.create(attrs) if Array === env['data']['mentions'] post.create_mentions(env['data']['mentions']) end unless options[:notification] if Array === env['data']['attachments'] env['data']['attachments'].each do |attachment| PostsAttachment.create( :attachment_id => attachment['model'].id, :content_type => attachment['content_type'], :post_id => post.id ) end end if Array === env['attachments'] post.create_attachments(env['attachments']) end end if Array === attrs[:version_parents] post.create_version_parents(attrs[:version_parents]) end unless options[:notification] post.queue_delivery end post end def create_attachments(post, attachments) attachments.each_with_index do |attachment, index| data = attachment[:tempfile].read attachment[:tempfile].rewind PostsAttachment.create( :attachment_id => Attachment.find_or_create( TentD::Utils::Hash.slice(post.attachments[index], 'digest', 'size').merge(:data => data) ).id, :post_id => post.id, :content_type => attachment[:content_type] ) end end def create_mentions(post, mentions) mentions.map do |mention| mention_attrs = { :user_id => post.user_id, :post_id => post.id } if mention['entity'] mention_attrs[:entity_id] = Entity.first_or_create(mention['entity']).id mention_attrs[:entity] = mention['entity'] else mention_attrs[:entity_id] = post.entity_id mention_attrs[:entity] = post.entity end if mention['type'] mention_attrs[:type_id] = Type.find_or_create_full(mention['type']).id mention_attrs[:type] = mention['type'] end mention_attrs[:post] = mention['post'] if mention.has_key?('post') mention_attrs[:public] = mention['public'] if mention.has_key?('public') Mention.create(mention_attrs) end end def create_version_parents(post, version_parents) version_parents.each do |item| item['post'] ||= post.public_id _parent = Post.where(:user_id => post.user_id, :public_id => item['post'], :version => item['version']).first Parent.create( :post_id => post.id, :parent_post_id => _parent ? _parent.id : nil, :version => item['version'], :post => item['post'] ) end end end end end
module Route53Aliaser class Aliaser attr_reader :config def initialize(config = Configuration.new) @config = config end def stale? config.cache.fetch(config.source_key).nil? end def call unless stale? # NOOP if we haven't expired config.logger.debug "Route53Aliaser: NOOP because cache is fresh" return end target_ips = get_ips(config.target_record, config.target_key) source_ips = get_ips(config.source_record, config.source_key) if target_ips == source_ips config.logger.debug "Route53Aliaser: No Route 53 Update required (Target IPs match the Source IPs)" else config.logger.info "Route53Aliaser: IPs for #{config.target_record} #{target_ips} differ from #{config.source_record} #{source_ips}; will attempt to update" rt53 = Route53Updater.new(config) rt53.update_target(config.target_record, source_ips, config.zone_id) end end private def get_ips(zone, key) ips = retrieve_ips_from_cache(key) if ips.empty? ips, ttl = get_ips_and_ttl_from_dns(zone) cache_results(key, zone, ips, ttl) end ips end def retrieve_ips_from_cache(key) cached_value = config.cache.fetch(key) if cached_value cached_value.split(',') else [] end end def get_ips_and_ttl_from_dns(zone) ips, ttl = [], 0 resources = Resolv::DNS.new.getresources(zone, Resolv::DNS::Resource::IN::A) if resources && resources.size > 0 ips = resources.collect{|res| res.address.to_s}.sort ttl = resources.first.ttl end return ips, ttl rescue ResolvError => e config.logger.error e return ips, ttl end def cache_results(key, zone, ips, ttl) unless ips.empty? config.cache.write(key, ips.join(','), expires_in: ttl.seconds, race_condition_ttl: 10 ) config.logger.debug "Route53Aliaser Caching #{key}: #{ips} for #{ttl} seconds (ttl)" else config.logger.error "Route53Aliaser NOT Caching #{key} because no IPs were found." end end end end Formatting in logs module Route53Aliaser class Aliaser attr_reader :config def initialize(config = Configuration.new) @config = config end def stale? config.cache.fetch(config.source_key).nil? end def call unless stale? # NOOP if we haven't expired config.logger.debug "Route53Aliaser: NOOP because cache is fresh" return end target_ips = get_ips(config.target_record, config.target_key) source_ips = get_ips(config.source_record, config.source_key) if target_ips == source_ips config.logger.debug "Route53Aliaser: No Route 53 Update required (Target IPs match the Source IPs)" else config.logger.info "Route53Aliaser: IPs for #{config.target_record} #{target_ips} differ from #{config.source_record} #{source_ips}; will attempt to update" rt53 = Route53Updater.new(config) rt53.update_target(config.target_record, source_ips, config.zone_id) end end private def get_ips(zone, key) ips = retrieve_ips_from_cache(key) if ips.empty? ips, ttl = get_ips_and_ttl_from_dns(zone) cache_results(key, zone, ips, ttl) end ips end def retrieve_ips_from_cache(key) cached_value = config.cache.fetch(key) if cached_value cached_value.split(',') else [] end end def get_ips_and_ttl_from_dns(zone) ips, ttl = [], 0 resources = Resolv::DNS.new.getresources(zone, Resolv::DNS::Resource::IN::A) if resources && resources.size > 0 ips = resources.collect{|res| res.address.to_s}.sort ttl = resources.first.ttl end return ips, ttl rescue ResolvError => e config.logger.error e return ips, ttl end def cache_results(key, zone, ips, ttl) unless ips.empty? config.cache.write(key, ips.join(','), expires_in: ttl.seconds, race_condition_ttl: 10 ) config.logger.debug "Route53Aliaser: Caching #{key}: #{ips} for #{ttl} seconds (ttl)" else config.logger.error "Route53Aliaser: NOT Caching #{key} because no IPs were found." end end end end
module RubberbandFlamethrower # Benchmarks a call to the fire method (which inserts a batch of random data into Elastic Search) # @param [Integer] how_many - how many randomly generated data objects to insert # @param [Integer] starting_id - starting id for randomly generated data objects, will increment from this number # @param [String] server_url - url of the Elastic Search server # @param [String] index - name of the Elastic Search index to insert data into # @param [String] type - name of the Elastic Search type to insert data into def self.fire(how_many=5000, starting_id=1, server_url="http://localhost:9200", index="twitter", type="tweet") require File.dirname(__FILE__)+"/rubberband_flamethrower/flamethrower.rb" flamethrower = Flamethrower.new time = Benchmark.measure do flamethrower.fire(how_many, starting_id, server_url, index, type, 1) end puts "\nFinished Inserting #{how_many} documents into Elastic Search." puts " user system total real" puts time end # Benchmarks a series of calls to the fire method (which inserts a batch of random data into Elastic Search) # @param [Integer] how_many_batches - how many batches to run # @param [Integer] per_batch - how many randomly generated data objects to insert # @param [Integer] starting_id - starting id for randomly generated data objects, will increment from this number # @param [String] server_url - url of the Elastic Search server # @param [String] index - name of the Elastic Search index to insert data into # @param [String] type - name of the Elastic Search type to insert data into def self.auto(how_many_batches=3, per_batch=5000, starting_id=1, server_url="http://localhost:9200", index="twitter", type="tweet") require File.dirname(__FILE__)+"/rubberband_flamethrower/flamethrower.rb" flamethrower = Flamethrower.new Benchmark.bm(8) do |x| how_many_batches.to_i.times do |i| x.report("set #{i+1}:") { flamethrower.fire(per_batch, starting_id, server_url, index, type) } starting_id = starting_id.to_i + per_batch.to_i end end end # Displays help menu of the available help menu commands def self.help puts "Rubberband Flamethrower is a gem for inserting faked data into an Elastic Search server" puts "and providing basic benchmarks. It creates and inserts fake data objects with three" puts "fields (message, username, and post_date) and reports timing information.\n" puts "Flamethrower Commands Available:\n" puts "flamethrower fire #benchmark a batch insert of data to an elastic search server" puts "flamethrower auto #benchmark a series of batch inserts to an elastic search server" puts "flamethrower help #display this help message" puts "\nThe fire and auto commands can be configured by passing arguments." puts "The parameters accepted by the `flamethrower fire` command all have a default value if" puts "left blank. Here are the parameters in order with their default values:" puts "(how_many=500, starting_id=1, server_url=http://localhost:9200, index=twitter, type=tweet)\n" puts "Command Examples Using Parameters:" puts "flamethrower fire 10000 #To Insert 10,000 instead of 500" puts "flamethrower fire 5000 5001 #To Insert 5,000 starting with the ID 5001" puts "flamethrower fire 2000 1 \"http://es.com:9200\" #To Insert 2,000 starting with the ID 1 to" puts "\t\t\ta server located at http://es.com:9200" puts "flamethrower fire 500 1 \"http://localhost:9200\" \"facebook\" \"message\" #To put your" puts "\t\t\tdocuments into an index named \"facebook\" instead of \"twitter\" with a type of" puts "\t\t\t\"message\" instead of \"tweet\"" end end updating help, changing default batch to 500 module RubberbandFlamethrower # Benchmarks a call to the fire method (which inserts a batch of random data into Elastic Search) # @param [Integer] how_many - how many randomly generated data objects to insert # @param [Integer] starting_id - starting id for randomly generated data objects, will increment from this number # @param [String] server_url - url of the Elastic Search server # @param [String] index - name of the Elastic Search index to insert data into # @param [String] type - name of the Elastic Search type to insert data into def self.fire(how_many=500, starting_id=1, server_url="http://localhost:9200", index="twitter", type="tweet") require File.dirname(__FILE__)+"/rubberband_flamethrower/flamethrower.rb" flamethrower = Flamethrower.new time = Benchmark.measure do flamethrower.fire(how_many, starting_id, server_url, index, type, 1) end puts "\nFinished Inserting #{how_many} documents into Elastic Search." puts " user system total real" puts time end # Benchmarks a series of calls to the fire method (which inserts a batch of random data into Elastic Search) # @param [Integer] how_many_batches - how many batches to run # @param [Integer] per_batch - how many randomly generated data objects to insert # @param [Integer] starting_id - starting id for randomly generated data objects, will increment from this number # @param [String] server_url - url of the Elastic Search server # @param [String] index - name of the Elastic Search index to insert data into # @param [String] type - name of the Elastic Search type to insert data into def self.auto(how_many_batches=3, per_batch=500, starting_id=1, server_url="http://localhost:9200", index="twitter", type="tweet") require File.dirname(__FILE__)+"/rubberband_flamethrower/flamethrower.rb" flamethrower = Flamethrower.new Benchmark.bm(8) do |x| how_many_batches.to_i.times do |i| x.report("set #{i+1}:") { flamethrower.fire(per_batch, starting_id, server_url, index, type) } starting_id = starting_id.to_i + per_batch.to_i end end end # Displays help menu of the available help menu commands def self.help puts "Rubberband Flamethrower is a gem for inserting faked data into an Elastic Search server" puts "and providing basic benchmarks. It creates and inserts fake data objects with three" puts "fields (message, username, and post_date) and reports timing information." puts "\n\nFlamethrower Commands Available:\n\n" puts "flamethrower fire #benchmark a batch insert of data to an elastic search server" puts "flamethrower auto #benchmark a series of batch inserts to an elastic search server" puts "flamethrower help #display this help message" puts "\n\nThe fire and auto commands can be configured by passing arguments." puts "The parameters accepted by fire and auto all have a default value if left blank." puts "\n\n\"fire\" parameters in order with their default values:" puts "(how_many=500, starting_id=1, server_url=http://localhost:9200, index=twitter, type=tweet)" puts "\n\n\"auto\" parameters in order with their default values:" puts "(how_many_batches=3, per_batch=500, starting_id=1, server_url=http://localhost:9200, index=twitter, type=tweet)" puts "\n\nUsage Examples With Parameters:" puts "flamethrower fire 10000 #To Insert 10,000 instead of 500" puts "flamethrower fire 5000 5001 #To Insert 5,000 starting with the ID 5001" puts "flamethrower fire 2000 1 \"http://es.com:9200\" #Elastic Search Node located at http://es.com:9200" puts "flamethrower fire 500 1 \"http://localhost:9200\" \"facebook\" \"message\" puts "\t#Insert into an index named \"facebook\" instead of \"twitter\"" puts "\t#with a type of \"message\" instead of \"tweet\"" end end
# encoding: utf-8 module Rubocop module Cop class UnlessElse < Cop ERROR_MESSAGE = 'Never use unless with else. Rewrite these with the ' + 'positive case first.' def self.portable? true end def inspect(file, source, tokens, sexp) on_node(:if, sexp) do |s| if s.src.keyword.to_source == 'unless' && s.src.else add_offence(:convention, s.src.line, ERROR_MESSAGE) end end end end end end Handle the possibility of encountering a ternary op # encoding: utf-8 module Rubocop module Cop class UnlessElse < Cop ERROR_MESSAGE = 'Never use unless with else. Rewrite these with the ' + 'positive case first.' def self.portable? true end def inspect(file, source, tokens, sexp) on_node(:if, sexp) do |s| next unless s.src.respond_to?(:keyword) if s.src.keyword.to_source == 'unless' && s.src.else add_offence(:convention, s.src.line, ERROR_MESSAGE) end end end end end end
class SystemUtils @@debug=true @@level=5 attr_reader :debug,:level,:last_error def SystemUtils.debug_output object if SystemUtils.debug == true p object end end def SystemUtils.log_output(object,level) if SystemUtils.level < level p :Error p object.to_s end end def SystemUtils.log_error(object) SystemUtils.log_output(object,10) end def SystemUtils.symbolize_keys(hash) hash.inject({}){|result, (key, value)| new_key = case key when String then key.to_sym else key end new_value = case value when Hash then symbolize_keys(value) when Array then newval=Array.new value.each do |array_val| if array_val.is_a?(Hash) array_val = SystemUtils.symbolize_keys(array_val) end newval.push(array_val) end newval else value end result[new_key] = new_value result } end def SystemUtils.log_exception(e) e_str = e.to_s() e.backtrace.each do |bt | e_str += bt + " \n" end @@last_error = e_str p e_str SystemUtils.log_output(e_str,10) end def SystemUtils.last_error return @@last_error end def SystemUtils.level return @@level end def SystemUtils.debug return @@debug end def SystemUtils.run_system(cmd) @@last_error="" begin cmd = cmd + " 2>&1" res= %x<#{cmd}> SystemUtils.debug_output res return res rescue Exception=>e SystemUtils.log_exception(e) return "Error: " +e.to_s end end def DNSHosting.get_default_domain if File.exists?(SysConfig.DefaultDomainnameFile) return File.read(SysConfig.DefaultDomainnameFile) else return "engines" end end end wrong static was DNSHosting c n p error class SystemUtils @@debug=true @@level=5 attr_reader :debug,:level,:last_error def SystemUtils.debug_output object if SystemUtils.debug == true p object end end def SystemUtils.log_output(object,level) if SystemUtils.level < level p :Error p object.to_s end end def SystemUtils.log_error(object) SystemUtils.log_output(object,10) end def SystemUtils.symbolize_keys(hash) hash.inject({}){|result, (key, value)| new_key = case key when String then key.to_sym else key end new_value = case value when Hash then symbolize_keys(value) when Array then newval=Array.new value.each do |array_val| if array_val.is_a?(Hash) array_val = SystemUtils.symbolize_keys(array_val) end newval.push(array_val) end newval else value end result[new_key] = new_value result } end def SystemUtils.log_exception(e) e_str = e.to_s() e.backtrace.each do |bt | e_str += bt + " \n" end @@last_error = e_str p e_str SystemUtils.log_output(e_str,10) end def SystemUtils.last_error return @@last_error end def SystemUtils.level return @@level end def SystemUtils.debug return @@debug end def SystemUtils.run_system(cmd) @@last_error="" begin cmd = cmd + " 2>&1" res= %x<#{cmd}> SystemUtils.debug_output res return res rescue Exception=>e SystemUtils.log_exception(e) return "Error: " +e.to_s end end def SystemUtils.get_default_domain if File.exists?(SysConfig.DefaultDomainnameFile) return File.read(SysConfig.DefaultDomainnameFile) else return "engines" end end end
module S3Uploader KILO_SIZE = 1024.0 def self.upload_directory(source, bucket, options = {}) options = { :destination_dir => '', :threads => 5, :s3_key => ENV['S3_KEY'], :s3_secret => ENV['S3_SECRET'], :public => false, :region => 'us-east-1', :metadata => {} }.merge(options) log = options[:logger] || Logger.new(STDOUT) raise 'Source must be a directory' unless File.directory?(source) if options[:connection] connection = options[:connection] else raise "Missing access keys" if options[:s3_key].nil? or options[:s3_secret].nil? connection = Fog::Storage.new({ :provider => 'AWS', :aws_access_key_id => options[:s3_key], :aws_secret_access_key => options[:s3_secret], :region => options[:region] }) end source = source.chop if source.end_with?('/') if options[:destination_dir] != '' and !options[:destination_dir].end_with?('/') options[:destination_dir] = "#{options[:destination_dir]}/" end total_size = 0 files = Queue.new Dir.glob("#{source}/**/*").select{ |f| !File.directory?(f) }.each do |f| files << f total_size += File.size(f) end directory = connection.directories.new(:key => bucket) start = Time.now total_files = files.size file_number = 0 @mutex = Mutex.new threads = [] options[:threads].times do |i| threads[i] = Thread.new { until files.empty? @mutex.synchronize do file_number += 1 Thread.current["file_number"] = file_number end file = files.pop rescue nil if file key = file.gsub(source, '')[1..-1] dest = "#{options[:destination_dir]}#{key}" log.info("[#{Thread.current["file_number"]}/#{total_files}] Uploading #{key} to s3://#{bucket}/#{dest}") directory.files.create( :key => dest, :body => File.open(file), :public => options[:public], :metadata => options[:metadata] ) end end } end threads.each { |t| t.join } finish = Time.now elapsed = finish.to_f - start.to_f mins, secs = elapsed.divmod 60.0 log.info("Uploaded %d (%.#{0}f KB) in %d:%04.2f" % [total_files, total_size / KILO_SIZE, mins.to_i, secs]) end end allow users to specify the path_style config option. this will allow uploads to buckets with full stops in their names without throwing an ssl error. reference: https://github.com/fog/fog/issues/2381 module S3Uploader KILO_SIZE = 1024.0 def self.upload_directory(source, bucket, options = {}) options = { :destination_dir => '', :threads => 5, :s3_key => ENV['S3_KEY'], :s3_secret => ENV['S3_SECRET'], :public => false, :region => 'us-east-1', :metadata => {}, :path_style => false }.merge(options) log = options[:logger] || Logger.new(STDOUT) raise 'Source must be a directory' unless File.directory?(source) if options[:connection] connection = options[:connection] else raise "Missing access keys" if options[:s3_key].nil? or options[:s3_secret].nil? connection = Fog::Storage.new({ :provider => 'AWS', :aws_access_key_id => options[:s3_key], :aws_secret_access_key => options[:s3_secret], :region => options[:region], :path_style => options[:path_style] }) end source = source.chop if source.end_with?('/') if options[:destination_dir] != '' and !options[:destination_dir].end_with?('/') options[:destination_dir] = "#{options[:destination_dir]}/" end total_size = 0 files = Queue.new Dir.glob("#{source}/**/*").select{ |f| !File.directory?(f) }.each do |f| files << f total_size += File.size(f) end directory = connection.directories.new(:key => bucket) start = Time.now total_files = files.size file_number = 0 @mutex = Mutex.new threads = [] options[:threads].times do |i| threads[i] = Thread.new { until files.empty? @mutex.synchronize do file_number += 1 Thread.current["file_number"] = file_number end file = files.pop rescue nil if file key = file.gsub(source, '')[1..-1] dest = "#{options[:destination_dir]}#{key}" log.info("[#{Thread.current["file_number"]}/#{total_files}] Uploading #{key} to s3://#{bucket}/#{dest}") directory.files.create( :key => dest, :body => File.open(file), :public => options[:public], :metadata => options[:metadata] ) end end } end threads.each { |t| t.join } finish = Time.now elapsed = finish.to_f - start.to_f mins, secs = elapsed.divmod 60.0 log.info("Uploaded %d (%.#{0}f KB) in %d:%04.2f" % [total_files, total_size / KILO_SIZE, mins.to_i, secs]) end end
module Satellite class Configuration include ActiveSupport::Configurable config_accessor :provider config_accessor :omniauth_args do [] end config_accessor :provider_root_url config_accessor :warden_config_blocks do [] end config_accessor :enable_auto_login do true end config_accessor :user_class do User = Class.new{include Satellite::User} end config_accessor :anonymous_user_class do AnonymousUser = Class.new{include Satellite::AnonymousUser} end config_accessor :path_prefix do "/auth" end def enable_auto_login? !!self.enable_auto_login end def omniauth(provider, *args) self.provider = provider self.omniauth_args = args end def warden(&block) self.warden_config_blocks << block end def provider config.provider || (raise ConfigurationError.new("You must configure Satellite omniauth")) end def provider_root_url=(url) URI.parse(url) config.provider_root_url = url rescue URI::Error raise ConfigurationError.new("Provider root url invalid") end def finalize!(app) @configured ||= begin configure_omniauth!(app) configure_warden!(app) true end end private def configure_omniauth!(app) config = self app.middleware.use OmniAuth::Builder do |builder| opts = config.omniauth_args.extract_options! provider config.provider, *config.omniauth_args, opts.merge(path_prefix: config.path_prefix) end end def configure_warden!(app) app.middleware.use Warden::Manager do |warden| warden.default_strategies :satellite warden.default_scope = :satellite warden.failure_app = Satellite::SessionsController.action(:failure) warden_config_blocks.each {|block| block.call warden } end end end end adds a way to setup omniauth config.full_host module Satellite class Configuration include ActiveSupport::Configurable config_accessor :provider config_accessor :omniauth_args do [] end config_accessor :provider_root_url config_accessor :warden_config_blocks do [] end config_accessor :enable_auto_login do true end config_accessor :full_host config_accessor :user_class do User = Class.new{include Satellite::User} end config_accessor :anonymous_user_class do AnonymousUser = Class.new{include Satellite::AnonymousUser} end config_accessor :path_prefix do "/auth" end def enable_auto_login? !!self.enable_auto_login end def omniauth(provider, *args) self.provider = provider self.omniauth_args = args end def warden(&block) self.warden_config_blocks << block end def provider config.provider || (raise ConfigurationError.new("You must configure Satellite omniauth")) end def provider_root_url=(url) URI.parse(url) config.provider_root_url = url rescue URI::Error raise ConfigurationError.new("Provider root url invalid") end def finalize!(app) @configured ||= begin configure_omniauth!(app) configure_warden!(app) true end end private def configure_omniauth!(app) config = self app.middleware.use OmniAuth::Builder do |builder| opts = config.omniauth_args.extract_options! provider config.provider, *config.omniauth_args, opts.merge(omniauth_config_options) end end def omniauth_config_options path_prefix: config.path_prefix full_host: config.full_host end def configure_warden!(app) app.middleware.use Warden::Manager do |warden| warden.default_strategies :satellite warden.default_scope = :satellite warden.failure_app = Satellite::SessionsController.action(:failure) warden_config_blocks.each {|block| block.call warden } end end end end
module Platforms VERSION = '1.0.0' unless defined? ::Platforms::VERSION DATE = '2015-06-06' unless defined? ::Platforms::DATE end Release 1.0.1 module Platforms VERSION = '1.0.1' unless defined? ::Platforms::VERSION DATE = '2015-06-19' unless defined? ::Platforms::DATE end
module SeedPacket class Environment attr_accessor :environment def initialize(environment) self.environment = environment end def seeding_allowed? environment != 'test' end def samples_allowed? !%w{production test}.include?(environment) end def scrubbing_allowed? %w{development test}.include?(environment) end end end Bugfix: Fix problem when environment was a symbol module SeedPacket class Environment attr_accessor :environment def initialize(environment) self.environment = environment.to_s end def seeding_allowed? environment != 'test' end def samples_allowed? !%w{production test}.include?(environment) end def scrubbing_allowed? %w{development test}.include?(environment) end end end
class ServerSettings VERSION = "0.0.7" end Bump version 0.1.0 class ServerSettings VERSION = "0.1.0" end
module Serverspec module Type class Service < Base def enabled?(level=3) backend.check_enabled(@name, level) end def running?(under) if under check_method = "check_running_under_#{under}".to_sym unless backend.respond_to?(check_method) raise ArgumentError.new("`be_running` matcher doesn't support #{@under}") end backend.send(check_method, @name) else backend.check_running(@name) end end def monitored_by?(monitor) check_method = "check_monitored_by_#{monitor}".to_sym raise ArgumentError.new("`be_monitored_by` matcher doesn't support #{monitor}") unless monitor && backend.respond_to?(check_method) backend.send(check_method, @name) end def has_property?(property) backend.check_svcprops(@name, property) end end end end clear empty line module Serverspec module Type class Service < Base def enabled?(level=3) backend.check_enabled(@name, level) end def running?(under) if under check_method = "check_running_under_#{under}".to_sym unless backend.respond_to?(check_method) raise ArgumentError.new("`be_running` matcher doesn't support #{@under}") end backend.send(check_method, @name) else backend.check_running(@name) end end def monitored_by?(monitor) check_method = "check_monitored_by_#{monitor}".to_sym unless monitor && backend.respond_to?(check_method) raise ArgumentError.new("`be_monitored_by` matcher doesn't support #{monitor}") end backend.send(check_method, @name) end def has_property?(property) backend.check_svcprops(@name, property) end end end end
module ActiveResource class Base def encode(options = {}) same = dup same.attributes = {self.class.element_name => same.attributes} if self.class.format.extension == 'json' same.send("to_#{self.class.format.extension}", options) end end module Formats module JsonFormat def decode(json) data = ActiveSupport::JSON.decode(json) if data.is_a?(Hash) && data.keys.size == 1 data.values.first else data end end end end end module ActiveModel module Serializers module JSON def as_json(options = nil) root = options[:root] if options.try(:key?, :root) if include_root_in_json root = self.class.model_name.element if root == true { root => serializable_hash(options) } else serializable_hash(options) end end end end end Scope as_json patch to ActiveResource::Base instead of ActiveModel. module ActiveResource class Base def encode(options = {}) same = dup same.attributes = {self.class.element_name => same.attributes} if self.class.format.extension == 'json' same.send("to_#{self.class.format.extension}", options) end def as_json(options = nil) root = options[:root] if options.try(:key?, :root) if include_root_in_json root = self.class.model_name.element if root == true { root => serializable_hash(options) } else serializable_hash(options) end end end module Formats module JsonFormat def decode(json) data = ActiveSupport::JSON.decode(json) if data.is_a?(Hash) && data.keys.size == 1 data.values.first else data end end end end end
module Sidekiq module History VERSION = "0.0.6" end end Version 0.0.7. module Sidekiq module History VERSION = "0.0.7" end end
module SillyMobilizer VERSION = "0.0.1" end Update lib/silly_mobilizer/version.rb Updated version module SillyMobilizer VERSION = "0.1.1" end
# This is needed to make Sidekiq think it's working in a server capacity. module Sidekiq class CLI end end # Sidekiq requires its processor to be available if configuring server middleware. require 'sidekiq/processor' require 'torque_box/sidekiq_service' Sidekiq requires the Sidekiq::Shutdown class to be available now, but it's currently defined in the CLI class that we don't use. # This is needed to make Sidekiq think it's working in a server capacity. module Sidekiq class Shutdown < RuntimeError; end class CLI; end end # Sidekiq requires its processor to be available if configuring server middleware. require 'sidekiq/processor' require 'torque_box/sidekiq_service'
module SimpleCalendar VERSION = "1.1.8" end Version bump module SimpleCalendar VERSION = "1.1.9" end
module SmalrubyEditor VERSION = '0.1.15' end 0.1.16 module SmalrubyEditor VERSION = '0.1.16' end
module SmarterListing VERSION = '0.2.2' end release version v0.2.3 module SmarterListing VERSION = '0.2.3' end
module Softcover module EpubUtils # Returns the name of the cover file. # We support (in order) JPG/JPEG, PNG, and TIFF. def cover_img extensions = %w[jpg jpeg png tiff] extensions.each do |ext| origin = "images/cover.#{ext}" target = "#{images_dir}/cover.#{ext}" if File.exist?(origin) FileUtils.cp(origin, target) return File.basename(target) end end return false end # Returns true when producing a cover. # We include a cover when not producing an Amazon-specific book # as long as there's a cover image. (When uploading a book to # Amazon KDP, the cover gets uploaded separately, so the MOBI file itself # should have not have a cover.) def cover?(options={}) !options[:amazon] && cover_img end def cover_filename xhtml("cover.#{html_extension}") end # Transforms foo.html to foo.xhtml def xhtml(filename) filename.sub('.html', '.xhtml') end def cover_img_path path("#{images_dir}/#{cover_img}") end def images_dir path('epub/OEBPS/images') end def nav_filename xhtml("nav.#{html_extension}") end def escape(string) CGI.escape_html(string) end # Returns a content.opf file based on a valid template. def content_opf_template(escaped_title, copyright, author, uuid, cover_id, toc_chapters, manifest_chapters, images) if cover_id cover_meta = %(<meta name="cover" content="#{cover_id}"/>) cover_html = %(<item id="cover" href="#{cover_filename}" media-type="application/xhtml+xml"/>) cover_ref = '<itemref idref="cover" linear="no" />' else cover_meta = cover_html = cover_ref = '' end %(<?xml version="1.0" encoding="UTF-8"?> <package unique-identifier="BookID" version="3.0" xmlns="http://www.idpf.org/2007/opf"> <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:opf="http://www.idpf.org/2007/opf"> <dc:title>#{escaped_title}</dc:title> <dc:language>en</dc:language> <dc:rights>Copyright (c) #{copyright} #{escape(author)}</dc:rights> <dc:creator>#{escape(author)}</dc:creator> <dc:publisher>Softcover</dc:publisher> <dc:identifier id="BookID">urn:uuid:#{uuid}</dc:identifier> <meta property="dcterms:modified">#{Time.now.strftime('%Y-%m-%dT%H:%M:%S')}Z</meta> #{cover_meta} </metadata> <manifest> <item href="#{nav_filename}" id="nav" media-type="application/xhtml+xml" properties="nav"/> <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/> <item id="page-template.xpgt" href="styles/page-template.xpgt" media-type="application/vnd.adobe-page-template+xml"/> <item id="pygments.css" href="styles/pygments.css" media-type="text/css"/> <item id="softcover.css" href="styles/softcover.css" media-type="text/css"/> <item id="epub.css" href="styles/epub.css" media-type="text/css"/> <item id="custom.css" href="styles/custom.css" media-type="text/css"/> <item id="custom_epub.css" href="styles/custom_epub.css" media-type="text/css"/> #{cover_html} #{manifest_chapters.join("\n")} #{images.join("\n")} </manifest> <spine toc="ncx"> #{cover_ref} #{toc_chapters.join("\n")} </spine> </package> ) end # Returns a toc.ncx file based on a valid template. def toc_ncx_template(escaped_title, uuid, chapter_nav) %(<?xml version="1.0" encoding="UTF-8"?> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"> <head> <meta name="dtb:uid" content="urn:uuid:#{uuid}"/> <meta name="dtb:depth" content="2"/> <meta name="dtb:totalPageCount" content="0"/> <meta name="dtb:maxPageNumber" content="0"/> </head> <docTitle> <text>#{escaped_title}</text> </docTitle> <navMap> #{chapter_nav.join("\n")} </navMap> </ncx> ) end # Returns the navigation HTML based on a valid template. def nav_html_template(escaped_title, nav_list) %(<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"> <head> <meta charset="UTF-8" /> <title>#{escaped_title}</title> </head> <body> <nav epub:type="toc"> <h1>#{escaped_title}</h1> <ol> #{nav_list.join("\n")} </ol> </nav> </body> </html> ) end end module Builders class Epub < Builder include Softcover::Output include Softcover::EpubUtils def build!(options={}) @preview = options[:preview] Softcover::Builders::Html.new.build! if manifest.markdown? opts = options.merge({ source: :polytex, origin: :markdown }) self.manifest = Softcover::BookManifest.new(opts) end remove_html remove_images create_directories write_mimetype write_container_xml write_ibooks_xml copy_image_files write_html(options) write_contents(options) create_style_files(options) write_toc write_nav make_epub(options) move_epub end # Returns true if generating a book preview. def preview? !!@preview end # Removes HTML. # All the HTML is generated, so this clears out any unused files. def remove_html FileUtils.rm(Dir.glob(path('epub/OEBPS/*.html'))) FileUtils.rm(Dir.glob(path('epub/OEBPS/*.xhtml'))) end # Removes images in case they are stale. def remove_images rm_r images_dir end def create_directories mkdir('epub') mkdir(path('epub/OEBPS')) mkdir(path('epub/OEBPS/styles')) mkdir(path('epub/META-INF')) mkdir(images_dir) mkdir('ebooks') end # Writes the mimetype file. # This is required by the EPUB standard. def write_mimetype File.write(path('epub/mimetype'), 'application/epub+zip') end # Writes the container XML file. # This is required by the EPUB standard. def write_container_xml File.write(path('epub/META-INF/container.xml'), container_xml) end # Writes iBooks-specific XML. # This allows proper display of monospace fonts in code samples, among # other things. def write_ibooks_xml xml_filename = 'com.apple.ibooks.display-options.xml' File.write(path("epub/META-INF/#{xml_filename}"), ibooks_xml) end # Writes the content.opf file. # This is required by the EPUB standard. def write_contents(options={}) File.write(path('epub/OEBPS/content.opf'), content_opf(options)) end # Returns the chapters to write. def chapters preview? ? manifest.preview_chapters : manifest.chapters end # Writes the HTML for the EPUB. # Included is a math detector that processes the page with MathJax # (via page.js) so that math can be included in EPUB (and thence MOBI). def write_html(options={}) texmath_dir = File.join(images_dir, 'texmath') mkdir images_dir mkdir texmath_dir if cover?(options) File.write(path("epub/OEBPS/#{cover_filename}"), cover_page) end pngs = [] chapters.each_with_index do |chapter, i| target_filename = path("epub/OEBPS/#{xhtml(chapter.fragment_name)}") File.open(target_filename, 'w') do |f| content = File.read(path("html/#{chapter.fragment_name}")) doc = strip_attributes(Nokogiri::HTML(content)) # Use xhtml in references. doc.css('a.hyperref').each do |ref_node| ref_node['href'] = ref_node['href'].sub('.html', xhtml('.html')) end body = doc.at_css('body') if body.nil? $stderr.puts "\nError: Document not built due to empty chapter" $stderr.puts "Chapters must include a title using the Markdown" $stderr.puts " # This is a chapter" $stderr.puts "or the LaTeX" $stderr.puts " \\chapter{This is a chapter}" exit(1) end inner_html = body.children.to_xhtml if math?(inner_html) html = html_with_math(chapter, images_dir, texmath_dir, pngs, options) html ||= inner_html # handle case of spurious math detection else html = inner_html end f.write(chapter_template("Chapter #{i}", html)) end end # Clean up unused PNGs. png_files = Dir[path("#{texmath_dir}/*.png")] (png_files - pngs).each do |f| if File.exist?(f) puts "Removing unused PNG #{f}" unless options[:silent] FileUtils.rm(f) end end end # Returns HTML for HTML source that includes math. # As a side-effect, html_with_math creates PNGs corresponding to any # math in the given source. The technique involves using PhantomJS to # hit the HTML source for each page containing math to create SVGs # for every math element. Since ereader support for SVGs is spotty, # they are then converted to PNGs using Inkscape. The filenames are # SHAs of their contents, which arranges both for unique filenames # and for automatic disk caching. def html_with_math(chapter, images_dir, texmath_dir, pngs, options={}) content = File.read(File.join("html", "#{chapter.slug}.#{html_extension}")) pagejs = "#{File.dirname(__FILE__)}/utils/page.js" url = "file://#{Dir.pwd}/html/#{chapter.slug}.#{html_extension}" cmd = "#{phantomjs} #{pagejs} #{url}" silence { silence_stream(STDERR) { system cmd } } # Sometimes in tests the phantomjs_source.html file is missing. # It shouldn't ever happen, but it does no harm to skip it. return nil unless File.exist?('phantomjs_source.html') raw_source = File.read('phantomjs_source.html') source = strip_attributes(Nokogiri::HTML(raw_source)) rm 'phantomjs_source.html' # Remove the first body div, which is the hidden MathJax SVGs. if (mathjax_svgs = source.at_css('body div')) mathjax_svgs.remove else # There's not actually any math, so return nil. return nil end # Remove all the unneeded raw TeX displays. source.css('script').each(&:remove) # Remove all the MathJax preview spans. source.css('MathJax_Preview').each(&:remove) # Suck out all the SVGs svgs = source.css('div#book svg') frames = source.css('span.MathJax_SVG') svgs.zip(frames).each do |svg, frame| # Save the SVG file. svg['viewBox'] = svg['viewbox'] svg.remove_attribute('viewbox') # Workaround for bug in Inkscape 0.91 on MacOS X: # extract height/width from svg attributes and move them to style attr svg_height = svg['height'] # in ex svg_width = svg['width'] # in ex svg['style'] += ' height:'+svg_height+';' + ' width:'+svg_width+';' svg.remove_attribute('height') svg.remove_attribute('width') # /Workaround first_child = frame.children.first first_child.replace(svg) unless svg == first_child output = svg.to_xhtml svg_filename = File.join(texmath_dir, "#{digest(output)}.svg") svg_abspath = File.join("#{Dir.pwd}", svg_filename) File.write(svg_filename, output) # Convert to PNG named: png_filename = svg_filename.sub('.svg', '.png') png_abspath = svg_abspath.sub('.svg', '.png') pngs << png_filename # # Settings for texmath images in ePub / mobi ex2em_height_scaling = 0.51 # =1ex/1em for math png height ex2em_valign_scaling = 0.481482 # =1ex/1em for math png vertical-align ex2px_scale_factor = 20 # =1ex/1px scaling for SVG-->PNG conv. # These are used a three-step process below: Compute, Convert, Replace # STEP1: compute height and vertical-align in `ex` units svg_height_in_ex = Float(svg_height.gsub('ex','')) # MathJax sets SVG height in `ex` units but we want `em` units for PNG png_height = (svg_height_in_ex * ex2em_height_scaling).to_s + 'em' # Extract vertical-align css proprty for inline math equations: if svg.parent.parent.attr('class') == "inline_math" vertical_align = svg['style'].scan(/vertical-align: (.*?);/) vertical_align = vertical_align.flatten.first if vertical_align valign_in_ex = Float(vertical_align.gsub('ex','')) png_valign = (valign_in_ex * ex2em_valign_scaling).to_s + 'em' else png_valign = "0em" end else # No vertical align for displayed math png_valign = nil end # STEP2: Generate PNG from each SVG (unless PNG exists already). unless File.exist?(png_filename) unless options[:silent] || options[:quiet] puts "Creating #{png_filename}" end # Generate png from the MathJax_SVG using Inkscape # Use the -d option to get a sensible size: # Resolution for bitmaps and rasterized filters cmd = "#{inkscape} #{svg_abspath} -o #{png_abspath} -d 2" if options[:silent] silence { silence_stream(STDERR) { system cmd } } else puts cmd silence_stream(STDERR) { system cmd } end end rm svg_filename # STEP 3: Replace svg element with an equivalent png. png = Nokogiri::XML::Node.new('img', source) png['src'] = File.join('images', 'texmath', File.basename(png_filename)) png['alt'] = png_filename.sub('.png', '') png['style'] = 'height:' + png_height + ';' if png_valign png['style'] += ' vertical-align:' + png_valign + ';' end svg.replace(png) end # Make references relative. source.css('a.hyperref').each do |ref_node| ref_node['href'] = ref_node['href'].sub('.html', xhtml('_fragment.html')) end source.at_css('div#book').children.to_xhtml end # Returns the PhantomJS executable (if available). def phantomjs @phantomjs ||= executable(dependency_filename(:phantomjs)) end # Returns the Inkscape executable (if available). def inkscape @inkscape ||= executable(dependency_filename(:inkscape)) end # Strip attributes that are invalid in EPUB documents. def strip_attributes(doc) attrs = %w[data-tralics-id data-label data-number data-chapter role aria-readonly target] doc.tap do attrs.each do |attr| doc.xpath("//@#{attr}").remove end end end # Returns true if a string appears to have LaTeX math. # We detect math via opening math commands: \(, \[, and \begin{equation} # This gives a false positive when math is included in verbatim # environments and nowhere else, but it does little harm (requiring only # an unnecessary call to page.js). def math?(string) !!string.match(/(?:\\\(|\\\[|\\begin{equation})/) end def create_style_files(options) html_styles = File.join('html', 'stylesheets') epub_styles = File.join('epub', 'OEBPS', 'styles') FileUtils.cp(File.join(html_styles, 'pygments.css'), epub_styles) File.write(File.join(epub_styles, 'softcover.css'), clean_book_id(path("#{html_styles}/softcover.css"))) # Copy over the EPUB-specific CSS. template_dir = Softcover::Utils.template_dir(options) epub_css = File.join(template_dir, epub_styles, 'epub.css') FileUtils.cp(epub_css, epub_styles) # Copy over custom CSS. File.write(File.join(epub_styles, 'custom.css'), clean_book_id(path("#{html_styles}/custom.css"))) end # Removes the '#book' CSS id. # For some reason, EPUB books hate the #book ids in the stylesheet # (i.e., such books fail to validate), so remove them. def clean_book_id(filename) File.read(filename).gsub(/#book /, '') end # Copies the image files from the HTML version of the document. def copy_image_files # Copy over all images to guarantee the same directory structure. FileUtils.cp_r(File.join('html', 'images'), File.join('epub', 'OEBPS')) # Parse the full HTML file with Nokogiri to get images actually used. html = File.read(manifest.full_html_file) html_image_filenames = Nokogiri::HTML(html).css('img').map do |node| node.attributes['src'].value end # Form the corresponding EPUB image paths. used_image_filenames = html_image_filenames.map do |filename| "epub/OEBPS/#{filename}" end.to_set # Delete unused images. Dir.glob("epub/OEBPS/images/**/*").each do |image| next if File.directory?(image) rm image unless used_image_filenames.include?(image) end end # Make the EPUB, which is basically just a zipped HTML file. def make_epub(options={}) filename = manifest.filename zfname = filename + '.zip' base_file = "#{zip} -X0 #{zfname} mimetype" fullzip = "#{zip} -rDXg9" meta_info = "#{fullzip} #{zfname} META-INF -x \*.DS_Store -x mimetype" main_info = "#{fullzip} #{zfname} OEBPS -x \*.DS_Store \*.gitkeep" rename = "mv #{zfname} #{filename}.epub" commands = [base_file, meta_info, main_info, rename] command = commands.join(' && ') Dir.chdir('epub') do if Softcover.test? || options[:quiet] || options[:silent] silence { system(command) } else system(command) end end end def zip @zip ||= executable(dependency_filename(:zip)) end # Move the completed EPUB book to the `ebooks` directory. # Note that we handle the case of a preview book as well. def move_epub origin = manifest.filename target = preview? ? origin + '-preview' : origin FileUtils.mv(File.join('epub', "#{origin}.epub"), File.join('ebooks', "#{target}.epub")) end # Writes the Table of Contents. # This is required by the EPUB standard. def write_toc File.write('epub/OEBPS/toc.ncx', toc_ncx) end # Writes the navigation file. # This is required by the EPUB standard. def write_nav File.write("epub/OEBPS/#{nav_filename}", nav_html) end def container_xml %(<?xml version="1.0"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles> <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/> </rootfiles> </container>) end def ibooks_xml %(<?xml version="1.0" encoding="UTF-8"?> <display_options> <platform name="*"> <option name="specified-fonts">true</option> </platform> </display_options>) end # Returns the content configuration file. def content_opf(options={}) man_ch = chapters.map do |chapter| %(<item id="#{chapter.slug}" href="#{xhtml(chapter.fragment_name)}" media-type="application/xhtml+xml"/>) end toc_ch = chapters.map do |chapter| %(<itemref idref="#{chapter.slug}"/>) end image_files = Dir['epub/OEBPS/images/**/*'].select { |f| File.file?(f) } images = image_files.map do |image| ext = File.extname(image).sub('.', '') # e.g., 'png' ext = 'jpeg' if ext == 'jpg' # Strip off the leading 'epub/OEBPS'. sep = File::SEPARATOR href = image.split(sep)[2..-1].join(sep) # Define an id based on the filename. # Prefix with 'img-' in case the filname starts with an # invalid character such as a number. label = File.basename(image).gsub('.', '-') id = "img-#{label}" %(<item id="#{id}" href="#{href}" media-type="image/#{ext}"/>) end manifest.html_title content_opf_template(manifest.html_title, manifest.copyright, manifest.author, manifest.uuid, cover_id(options), toc_ch, man_ch, images) end def cover_page %(<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cover</title> </head> <body> <div id="cover"> <img width="573" height="800" src="images/#{cover_img}" alt="cover" /> </div> </body> </html> ) end def cover_id(options) cover?(options) ? "img-#{cover_img.sub('.', '-')}" : nil end # Returns the Table of Contents for the spine. def toc_ncx chapter_nav = [] if article? article = chapters.first section_names_and_ids(article).each_with_index do |(name, id), n| chapter_nav << %(<navPoint id="#{id}" playOrder="#{n+1}">) chapter_nav << %( <navLabel><text>#{escape(name)}</text></navLabel>) chapter_nav << %( <content src="#{xhtml(article.fragment_name)}##{id}"/>) chapter_nav << %(</navPoint>) end else chapters.each_with_index do |chapter, n| chapter_nav << %(<navPoint id="#{chapter.slug}" playOrder="#{n+1}">) chapter_nav << %( <navLabel><text>#{chapter_name(n)}</text></navLabel>) chapter_nav << %( <content src="#{xhtml(chapter.fragment_name)}"/>) chapter_nav << %(</navPoint>) end end toc_ncx_template(manifest.html_title, manifest.uuid, chapter_nav) end def chapter_name(n) n == 0 ? language_labels["frontmatter"] : strip_html(chapters[n].menu_heading) end # Strip HTML elements from the given text. def strip_html(text) Nokogiri::HTML.fragment(text).content end # Returns the nav HTML content. def nav_html if article? article = chapters.first nav_list = section_names_and_ids(article).map do |name, id| %(<li> <a href="#{xhtml(article.fragment_name)}##{id}">#{name}</a></li>) end else nav_list = manifest.chapters.map do |chapter| element = preview? ? chapter.title : nav_link(chapter) %(<li>#{element}</li>) end end nav_html_template(manifest.html_title, nav_list) end # Returns a navigation link for the chapter. def nav_link(chapter) %(<a href="#{xhtml(chapter.fragment_name)}">#{chapter.html_title}</a>) end # Returns a list of the section names and CSS ids. # Form is [['Beginning', 'sec-beginning'], ['Next', 'sec-next']] def section_names_and_ids(article) # Grab section names and ids from the article. filename = File.join('epub', 'OEBPS', xhtml(article.fragment_name)) doc = Nokogiri::HTML(File.read(filename)) names = doc.css('div.section>h2').map do |s| s.children.children.last.content end ids = doc.css('div.section').map { |s| s.attributes['id'].value } names.zip(ids) end # Returns the HTML template for a chapter. def chapter_template(title, content) %(<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>#{title}</title> <link rel="stylesheet" href="styles/pygments.css" type="text/css" /> <link rel="stylesheet" href="styles/softcover.css" type="text/css" /> <link rel="stylesheet" href="styles/epub.css" type="text/css" /> <link rel="stylesheet" href="styles/custom.css" type="text/css"/> <link rel="stylesheet" href="styles/custom_epub.css" type="text/css"/> <link rel="stylesheet" type="application/vnd.adobe-page-template+xml" href="styles/page-template.xpgt" /> </head> <body> #{content} </body> </html>) end end end end Escape out spaces in directories when building EPUBs module Softcover module EpubUtils # Returns the name of the cover file. # We support (in order) JPG/JPEG, PNG, and TIFF. def cover_img extensions = %w[jpg jpeg png tiff] extensions.each do |ext| origin = "images/cover.#{ext}" target = "#{images_dir}/cover.#{ext}" if File.exist?(origin) FileUtils.cp(origin, target) return File.basename(target) end end return false end # Returns true when producing a cover. # We include a cover when not producing an Amazon-specific book # as long as there's a cover image. (When uploading a book to # Amazon KDP, the cover gets uploaded separately, so the MOBI file itself # should have not have a cover.) def cover?(options={}) !options[:amazon] && cover_img end def cover_filename xhtml("cover.#{html_extension}") end # Transforms foo.html to foo.xhtml def xhtml(filename) filename.sub('.html', '.xhtml') end def cover_img_path path("#{images_dir}/#{cover_img}") end def images_dir path('epub/OEBPS/images') end def nav_filename xhtml("nav.#{html_extension}") end def escape(string) CGI.escape_html(string) end # Returns a content.opf file based on a valid template. def content_opf_template(escaped_title, copyright, author, uuid, cover_id, toc_chapters, manifest_chapters, images) if cover_id cover_meta = %(<meta name="cover" content="#{cover_id}"/>) cover_html = %(<item id="cover" href="#{cover_filename}" media-type="application/xhtml+xml"/>) cover_ref = '<itemref idref="cover" linear="no" />' else cover_meta = cover_html = cover_ref = '' end %(<?xml version="1.0" encoding="UTF-8"?> <package unique-identifier="BookID" version="3.0" xmlns="http://www.idpf.org/2007/opf"> <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:opf="http://www.idpf.org/2007/opf"> <dc:title>#{escaped_title}</dc:title> <dc:language>en</dc:language> <dc:rights>Copyright (c) #{copyright} #{escape(author)}</dc:rights> <dc:creator>#{escape(author)}</dc:creator> <dc:publisher>Softcover</dc:publisher> <dc:identifier id="BookID">urn:uuid:#{uuid}</dc:identifier> <meta property="dcterms:modified">#{Time.now.strftime('%Y-%m-%dT%H:%M:%S')}Z</meta> #{cover_meta} </metadata> <manifest> <item href="#{nav_filename}" id="nav" media-type="application/xhtml+xml" properties="nav"/> <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/> <item id="page-template.xpgt" href="styles/page-template.xpgt" media-type="application/vnd.adobe-page-template+xml"/> <item id="pygments.css" href="styles/pygments.css" media-type="text/css"/> <item id="softcover.css" href="styles/softcover.css" media-type="text/css"/> <item id="epub.css" href="styles/epub.css" media-type="text/css"/> <item id="custom.css" href="styles/custom.css" media-type="text/css"/> <item id="custom_epub.css" href="styles/custom_epub.css" media-type="text/css"/> #{cover_html} #{manifest_chapters.join("\n")} #{images.join("\n")} </manifest> <spine toc="ncx"> #{cover_ref} #{toc_chapters.join("\n")} </spine> </package> ) end # Returns a toc.ncx file based on a valid template. def toc_ncx_template(escaped_title, uuid, chapter_nav) %(<?xml version="1.0" encoding="UTF-8"?> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"> <head> <meta name="dtb:uid" content="urn:uuid:#{uuid}"/> <meta name="dtb:depth" content="2"/> <meta name="dtb:totalPageCount" content="0"/> <meta name="dtb:maxPageNumber" content="0"/> </head> <docTitle> <text>#{escaped_title}</text> </docTitle> <navMap> #{chapter_nav.join("\n")} </navMap> </ncx> ) end # Returns the navigation HTML based on a valid template. def nav_html_template(escaped_title, nav_list) %(<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"> <head> <meta charset="UTF-8" /> <title>#{escaped_title}</title> </head> <body> <nav epub:type="toc"> <h1>#{escaped_title}</h1> <ol> #{nav_list.join("\n")} </ol> </nav> </body> </html> ) end end module Builders class Epub < Builder include Softcover::Output include Softcover::EpubUtils def build!(options={}) @preview = options[:preview] Softcover::Builders::Html.new.build! if manifest.markdown? opts = options.merge({ source: :polytex, origin: :markdown }) self.manifest = Softcover::BookManifest.new(opts) end remove_html remove_images create_directories write_mimetype write_container_xml write_ibooks_xml copy_image_files write_html(options) write_contents(options) create_style_files(options) write_toc write_nav make_epub(options) move_epub end # Returns true if generating a book preview. def preview? !!@preview end # Removes HTML. # All the HTML is generated, so this clears out any unused files. def remove_html FileUtils.rm(Dir.glob(path('epub/OEBPS/*.html'))) FileUtils.rm(Dir.glob(path('epub/OEBPS/*.xhtml'))) end # Removes images in case they are stale. def remove_images rm_r images_dir end def create_directories mkdir('epub') mkdir(path('epub/OEBPS')) mkdir(path('epub/OEBPS/styles')) mkdir(path('epub/META-INF')) mkdir(images_dir) mkdir('ebooks') end # Writes the mimetype file. # This is required by the EPUB standard. def write_mimetype File.write(path('epub/mimetype'), 'application/epub+zip') end # Writes the container XML file. # This is required by the EPUB standard. def write_container_xml File.write(path('epub/META-INF/container.xml'), container_xml) end # Writes iBooks-specific XML. # This allows proper display of monospace fonts in code samples, among # other things. def write_ibooks_xml xml_filename = 'com.apple.ibooks.display-options.xml' File.write(path("epub/META-INF/#{xml_filename}"), ibooks_xml) end # Writes the content.opf file. # This is required by the EPUB standard. def write_contents(options={}) File.write(path('epub/OEBPS/content.opf'), content_opf(options)) end # Returns the chapters to write. def chapters preview? ? manifest.preview_chapters : manifest.chapters end # Writes the HTML for the EPUB. # Included is a math detector that processes the page with MathJax # (via page.js) so that math can be included in EPUB (and thence MOBI). def write_html(options={}) texmath_dir = File.join(images_dir, 'texmath') mkdir images_dir mkdir texmath_dir if cover?(options) File.write(path("epub/OEBPS/#{cover_filename}"), cover_page) end pngs = [] chapters.each_with_index do |chapter, i| target_filename = path("epub/OEBPS/#{xhtml(chapter.fragment_name)}") File.open(target_filename, 'w') do |f| content = File.read(path("html/#{chapter.fragment_name}")) doc = strip_attributes(Nokogiri::HTML(content)) # Use xhtml in references. doc.css('a.hyperref').each do |ref_node| ref_node['href'] = ref_node['href'].sub('.html', xhtml('.html')) end body = doc.at_css('body') if body.nil? $stderr.puts "\nError: Document not built due to empty chapter" $stderr.puts "Chapters must include a title using the Markdown" $stderr.puts " # This is a chapter" $stderr.puts "or the LaTeX" $stderr.puts " \\chapter{This is a chapter}" exit(1) end inner_html = body.children.to_xhtml if math?(inner_html) html = html_with_math(chapter, images_dir, texmath_dir, pngs, options) html ||= inner_html # handle case of spurious math detection else html = inner_html end f.write(chapter_template("Chapter #{i}", html)) end end # Clean up unused PNGs. png_files = Dir[path("#{texmath_dir}/*.png")] (png_files - pngs).each do |f| if File.exist?(f) puts "Removing unused PNG #{f}" unless options[:silent] FileUtils.rm(f) end end end # Escapes spaces in filename directories. # E.g., "Mobile Directory" becomes "Mobile\ Directory". def escape_spaces(name) name.gsub(' ', '\ ') end # Returns HTML for HTML source that includes math. # As a side-effect, html_with_math creates PNGs corresponding to any # math in the given source. The technique involves using PhantomJS to # hit the HTML source for each page containing math to create SVGs # for every math element. Since ereader support for SVGs is spotty, # they are then converted to PNGs using Inkscape. The filenames are # SHAs of their contents, which arranges both for unique filenames # and for automatic disk caching. def html_with_math(chapter, images_dir, texmath_dir, pngs, options={}) content = File.read(File.join("html", "#{chapter.slug}.#{html_extension}")) pagejs = "#{File.dirname(__FILE__)}/utils/page.js" dir = escape_spaces(Dir.pwd) url = "file://" + dir + "/html/#{chapter.slug}.#{html_extension}" cmd = "#{phantomjs} #{pagejs} #{url}" silence { silence_stream(STDERR) { system cmd } } # Sometimes in tests the phantomjs_source.html file is missing. # It shouldn't ever happen, but it does no harm to skip it. return nil unless File.exist?('phantomjs_source.html') raw_source = File.read('phantomjs_source.html') source = strip_attributes(Nokogiri::HTML(raw_source)) rm 'phantomjs_source.html' # Remove the first body div, which is the hidden MathJax SVGs. if (mathjax_svgs = source.at_css('body div')) mathjax_svgs.remove else # There's not actually any math, so return nil. return nil end # Remove all the unneeded raw TeX displays. source.css('script').each(&:remove) # Remove all the MathJax preview spans. source.css('MathJax_Preview').each(&:remove) # Suck out all the SVGs svgs = source.css('div#book svg') frames = source.css('span.MathJax_SVG') svgs.zip(frames).each do |svg, frame| # Save the SVG file. svg['viewBox'] = svg['viewbox'] svg.remove_attribute('viewbox') # Workaround for bug in Inkscape 0.91 on MacOS X: # extract height/width from svg attributes and move them to style attr svg_height = svg['height'] # in ex svg_width = svg['width'] # in ex svg['style'] += ' height:'+svg_height+';' + ' width:'+svg_width+';' svg.remove_attribute('height') svg.remove_attribute('width') # /Workaround first_child = frame.children.first first_child.replace(svg) unless svg == first_child output = svg.to_xhtml svg_filename = File.join(texmath_dir, "#{digest(output)}.svg") svg_abspath = File.join("#{Dir.pwd}", svg_filename) File.write(svg_filename, output) # Convert to PNG named: png_filename = svg_filename.sub('.svg', '.png') png_abspath = svg_abspath.sub('.svg', '.png') pngs << png_filename # # Settings for texmath images in ePub / mobi ex2em_height_scaling = 0.51 # =1ex/1em for math png height ex2em_valign_scaling = 0.481482 # =1ex/1em for math png vertical-align ex2px_scale_factor = 20 # =1ex/1px scaling for SVG-->PNG conv. # These are used a three-step process below: Compute, Convert, Replace # STEP1: compute height and vertical-align in `ex` units svg_height_in_ex = Float(svg_height.gsub('ex','')) # MathJax sets SVG height in `ex` units but we want `em` units for PNG png_height = (svg_height_in_ex * ex2em_height_scaling).to_s + 'em' # Extract vertical-align css proprty for inline math equations: if svg.parent.parent.attr('class') == "inline_math" vertical_align = svg['style'].scan(/vertical-align: (.*?);/) vertical_align = vertical_align.flatten.first if vertical_align valign_in_ex = Float(vertical_align.gsub('ex','')) png_valign = (valign_in_ex * ex2em_valign_scaling).to_s + 'em' else png_valign = "0em" end else # No vertical align for displayed math png_valign = nil end # STEP2: Generate PNG from each SVG (unless PNG exists already). unless File.exist?(png_filename) unless options[:silent] || options[:quiet] puts "Creating #{png_filename}" end # Generate png from the MathJax_SVG using Inkscape # Use the -d option to get a sensible size: # Resolution for bitmaps and rasterized filters cmd = "#{inkscape} #{svg_abspath} -o #{png_abspath} -d 2" if options[:silent] silence { silence_stream(STDERR) { system cmd } } else puts cmd silence_stream(STDERR) { system cmd } end end rm svg_filename # STEP 3: Replace svg element with an equivalent png. png = Nokogiri::XML::Node.new('img', source) png['src'] = File.join('images', 'texmath', File.basename(png_filename)) png['alt'] = png_filename.sub('.png', '') png['style'] = 'height:' + png_height + ';' if png_valign png['style'] += ' vertical-align:' + png_valign + ';' end svg.replace(png) end # Make references relative. source.css('a.hyperref').each do |ref_node| ref_node['href'] = ref_node['href'].sub('.html', xhtml('_fragment.html')) end source.at_css('div#book').children.to_xhtml end # Returns the PhantomJS executable (if available). def phantomjs @phantomjs ||= executable(dependency_filename(:phantomjs)) end # Returns the Inkscape executable (if available). def inkscape @inkscape ||= executable(dependency_filename(:inkscape)) end # Strip attributes that are invalid in EPUB documents. def strip_attributes(doc) attrs = %w[data-tralics-id data-label data-number data-chapter role aria-readonly target] doc.tap do attrs.each do |attr| doc.xpath("//@#{attr}").remove end end end # Returns true if a string appears to have LaTeX math. # We detect math via opening math commands: \(, \[, and \begin{equation} # This gives a false positive when math is included in verbatim # environments and nowhere else, but it does little harm (requiring only # an unnecessary call to page.js). def math?(string) !!string.match(/(?:\\\(|\\\[|\\begin{equation})/) end def create_style_files(options) html_styles = File.join('html', 'stylesheets') epub_styles = File.join('epub', 'OEBPS', 'styles') FileUtils.cp(File.join(html_styles, 'pygments.css'), epub_styles) File.write(File.join(epub_styles, 'softcover.css'), clean_book_id(path("#{html_styles}/softcover.css"))) # Copy over the EPUB-specific CSS. template_dir = Softcover::Utils.template_dir(options) epub_css = File.join(template_dir, epub_styles, 'epub.css') FileUtils.cp(epub_css, epub_styles) # Copy over custom CSS. File.write(File.join(epub_styles, 'custom.css'), clean_book_id(path("#{html_styles}/custom.css"))) end # Removes the '#book' CSS id. # For some reason, EPUB books hate the #book ids in the stylesheet # (i.e., such books fail to validate), so remove them. def clean_book_id(filename) File.read(filename).gsub(/#book /, '') end # Copies the image files from the HTML version of the document. def copy_image_files # Copy over all images to guarantee the same directory structure. FileUtils.cp_r(File.join('html', 'images'), File.join('epub', 'OEBPS')) # Parse the full HTML file with Nokogiri to get images actually used. html = File.read(manifest.full_html_file) html_image_filenames = Nokogiri::HTML(html).css('img').map do |node| node.attributes['src'].value end # Form the corresponding EPUB image paths. used_image_filenames = html_image_filenames.map do |filename| "epub/OEBPS/#{filename}" end.to_set # Delete unused images. Dir.glob("epub/OEBPS/images/**/*").each do |image| next if File.directory?(image) rm image unless used_image_filenames.include?(image) end end # Make the EPUB, which is basically just a zipped HTML file. def make_epub(options={}) filename = manifest.filename zfname = filename + '.zip' base_file = "#{zip} -X0 #{zfname} mimetype" fullzip = "#{zip} -rDXg9" meta_info = "#{fullzip} #{zfname} META-INF -x \*.DS_Store -x mimetype" main_info = "#{fullzip} #{zfname} OEBPS -x \*.DS_Store \*.gitkeep" rename = "mv #{zfname} #{filename}.epub" commands = [base_file, meta_info, main_info, rename] command = commands.join(' && ') Dir.chdir('epub') do if Softcover.test? || options[:quiet] || options[:silent] silence { system(command) } else system(command) end end end def zip @zip ||= executable(dependency_filename(:zip)) end # Move the completed EPUB book to the `ebooks` directory. # Note that we handle the case of a preview book as well. def move_epub origin = manifest.filename target = preview? ? origin + '-preview' : origin FileUtils.mv(File.join('epub', "#{origin}.epub"), File.join('ebooks', "#{target}.epub")) end # Writes the Table of Contents. # This is required by the EPUB standard. def write_toc File.write('epub/OEBPS/toc.ncx', toc_ncx) end # Writes the navigation file. # This is required by the EPUB standard. def write_nav File.write("epub/OEBPS/#{nav_filename}", nav_html) end def container_xml %(<?xml version="1.0"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles> <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/> </rootfiles> </container>) end def ibooks_xml %(<?xml version="1.0" encoding="UTF-8"?> <display_options> <platform name="*"> <option name="specified-fonts">true</option> </platform> </display_options>) end # Returns the content configuration file. def content_opf(options={}) man_ch = chapters.map do |chapter| %(<item id="#{chapter.slug}" href="#{xhtml(chapter.fragment_name)}" media-type="application/xhtml+xml"/>) end toc_ch = chapters.map do |chapter| %(<itemref idref="#{chapter.slug}"/>) end image_files = Dir['epub/OEBPS/images/**/*'].select { |f| File.file?(f) } images = image_files.map do |image| ext = File.extname(image).sub('.', '') # e.g., 'png' ext = 'jpeg' if ext == 'jpg' # Strip off the leading 'epub/OEBPS'. sep = File::SEPARATOR href = image.split(sep)[2..-1].join(sep) # Define an id based on the filename. # Prefix with 'img-' in case the filname starts with an # invalid character such as a number. label = File.basename(image).gsub('.', '-') id = "img-#{label}" %(<item id="#{id}" href="#{href}" media-type="image/#{ext}"/>) end manifest.html_title content_opf_template(manifest.html_title, manifest.copyright, manifest.author, manifest.uuid, cover_id(options), toc_ch, man_ch, images) end def cover_page %(<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cover</title> </head> <body> <div id="cover"> <img width="573" height="800" src="images/#{cover_img}" alt="cover" /> </div> </body> </html> ) end def cover_id(options) cover?(options) ? "img-#{cover_img.sub('.', '-')}" : nil end # Returns the Table of Contents for the spine. def toc_ncx chapter_nav = [] if article? article = chapters.first section_names_and_ids(article).each_with_index do |(name, id), n| chapter_nav << %(<navPoint id="#{id}" playOrder="#{n+1}">) chapter_nav << %( <navLabel><text>#{escape(name)}</text></navLabel>) chapter_nav << %( <content src="#{xhtml(article.fragment_name)}##{id}"/>) chapter_nav << %(</navPoint>) end else chapters.each_with_index do |chapter, n| chapter_nav << %(<navPoint id="#{chapter.slug}" playOrder="#{n+1}">) chapter_nav << %( <navLabel><text>#{chapter_name(n)}</text></navLabel>) chapter_nav << %( <content src="#{xhtml(chapter.fragment_name)}"/>) chapter_nav << %(</navPoint>) end end toc_ncx_template(manifest.html_title, manifest.uuid, chapter_nav) end def chapter_name(n) n == 0 ? language_labels["frontmatter"] : strip_html(chapters[n].menu_heading) end # Strip HTML elements from the given text. def strip_html(text) Nokogiri::HTML.fragment(text).content end # Returns the nav HTML content. def nav_html if article? article = chapters.first nav_list = section_names_and_ids(article).map do |name, id| %(<li> <a href="#{xhtml(article.fragment_name)}##{id}">#{name}</a></li>) end else nav_list = manifest.chapters.map do |chapter| element = preview? ? chapter.title : nav_link(chapter) %(<li>#{element}</li>) end end nav_html_template(manifest.html_title, nav_list) end # Returns a navigation link for the chapter. def nav_link(chapter) %(<a href="#{xhtml(chapter.fragment_name)}">#{chapter.html_title}</a>) end # Returns a list of the section names and CSS ids. # Form is [['Beginning', 'sec-beginning'], ['Next', 'sec-next']] def section_names_and_ids(article) # Grab section names and ids from the article. filename = File.join('epub', 'OEBPS', xhtml(article.fragment_name)) doc = Nokogiri::HTML(File.read(filename)) names = doc.css('div.section>h2').map do |s| s.children.children.last.content end ids = doc.css('div.section').map { |s| s.attributes['id'].value } names.zip(ids) end # Returns the HTML template for a chapter. def chapter_template(title, content) %(<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>#{title}</title> <link rel="stylesheet" href="styles/pygments.css" type="text/css" /> <link rel="stylesheet" href="styles/softcover.css" type="text/css" /> <link rel="stylesheet" href="styles/epub.css" type="text/css" /> <link rel="stylesheet" href="styles/custom.css" type="text/css"/> <link rel="stylesheet" href="styles/custom_epub.css" type="text/css"/> <link rel="stylesheet" type="application/vnd.adobe-page-template+xml" href="styles/page-template.xpgt" /> </head> <body> #{content} </body> </html>) end end end end
require 'thor' require 'yaml' require 'json' require 'travis/worker' require 'vagrant' module Travis class Worker module Cli class Vagrant < Thor namespace "travis:vms" include Cli desc 'update [BOX]', 'Update the worker vms from a base box (BOX defaults to Travis::Worker.config.env)' method_option :reset, :aliases => '-r', :type => :boolean, :default => false, :desc => 'Force reset on virtualbox settings and boxes' method_option :download, :aliases => '-d', :type => :string, :default => false, :desc => 'Copy/download the base box from the given path, storage or URL (will use file.travis.org if -d is given without a string)' def update(box = Travis::Worker.config.env) self.box = box vbox.reset if options[:reset] download_box if download? add_box exit unless up halt rescue => e puts e.message end desc 'download [BOX]', 'Download the box image for a base box (BOX defaults to Travis::Worker.config.env)' def download(box = Travis::Worker.config.env) self.box = box download_box rescue => e puts e.message end desc 'create [BOX]', 'Creates the VirtualBox boxes from a base box (BOX defaults to Travis::Worker.config.env)' method_option :reset, :aliases => '-r', :type => :boolean, :default => false, :desc => 'Force reset on virtualbox settings and boxes' def update(box = Travis::Worker.config.env) self.box = box vbox.reset if options[:reset] add_box exit unless up halt rescue => e puts e.message end protected attr_accessor :box def vbox @vbox ||= Vbox.new('', options) end def config self.class.config end def base_box "boxes/travis-#{box}.box" end def download? !!options[:download] || !File.exists?(base_box) end def download_box # make sure we remove old boxes before downloading new ones. Otherwise wget will append .1, .2 and so on # to the name of the file and import operation will import the old box. MK. run "rm -rf #{base_box}" download_failed! unless run(download_command) end def download_command source =~ /^http:/ ? "wget #{source} -P boxes" : "cp #{source} boxes" end def download_failed! raise "The download command #{download_command} failed, terminating ..." end def source case options[:download] when 'download', NilClass "http://files.travis-ci.org/boxes/provisioned/travis-#{box}.box" else options[:download] end end def add_box vagrant.cli("box", "add", "travis-#{box}", base_box) vagrant.boxes.reload! vagrant.reload! end def up vagrant.cli("up") end def halt vagrant.cli("halt") end def vagrant @vagrant ||= ::Vagrant::Environment.new(:ui_class => ::Vagrant::UI::Colored) end end end end end s/create/update/ require 'thor' require 'yaml' require 'json' require 'travis/worker' require 'vagrant' module Travis class Worker module Cli class Vagrant < Thor namespace "travis:vms" include Cli desc 'update [BOX]', 'Update the worker vms from a base box (BOX defaults to Travis::Worker.config.env)' method_option :reset, :aliases => '-r', :type => :boolean, :default => false, :desc => 'Force reset on virtualbox settings and boxes' method_option :download, :aliases => '-d', :type => :string, :default => false, :desc => 'Copy/download the base box from the given path, storage or URL (will use file.travis.org if -d is given without a string)' def update(box = Travis::Worker.config.env) self.box = box vbox.reset if options[:reset] download_box if download? add_box exit unless up halt rescue => e puts e.message end desc 'download [BOX]', 'Download the box image for a base box (BOX defaults to Travis::Worker.config.env)' def download(box = Travis::Worker.config.env) self.box = box download_box rescue => e puts e.message end desc 'create [BOX]', 'Creates the VirtualBox boxes from a base box (BOX defaults to Travis::Worker.config.env)' method_option :reset, :aliases => '-r', :type => :boolean, :default => false, :desc => 'Force reset on virtualbox settings and boxes' def create(box = Travis::Worker.config.env) self.box = box vbox.reset if options[:reset] add_box exit unless up halt rescue => e puts e.message end protected attr_accessor :box def vbox @vbox ||= Vbox.new('', options) end def config self.class.config end def base_box "boxes/travis-#{box}.box" end def download? !!options[:download] || !File.exists?(base_box) end def download_box # make sure we remove old boxes before downloading new ones. Otherwise wget will append .1, .2 and so on # to the name of the file and import operation will import the old box. MK. run "rm -rf #{base_box}" download_failed! unless run(download_command) end def download_command source =~ /^http:/ ? "wget #{source} -P boxes" : "cp #{source} boxes" end def download_failed! raise "The download command #{download_command} failed, terminating ..." end def source case options[:download] when 'download', NilClass "http://files.travis-ci.org/boxes/provisioned/travis-#{box}.box" else options[:download] end end def add_box vagrant.cli("box", "add", "travis-#{box}", base_box) vagrant.boxes.reload! vagrant.reload! end def up vagrant.cli("up") end def halt vagrant.cli("halt") end def vagrant @vagrant ||= ::Vagrant::Environment.new(:ui_class => ::Vagrant::UI::Colored) end end end end end
require_relative 'view' module Soundcloud2000 module UI class Table < View PADDING = 1 attr_reader :current def initialize(*args) super @sizes = [] @rows = [] @current, @top = 0, 0 events.on(:key) do |key| case key when :up then up when :down then down end end reset end def header(*elements) @header = elements @header end def body(*rows) @rows = rows calculate_widths @rows end def length @rows.size end def body_height height - Array(@header).size end def up if @current > 0 @current -= 1 @top -= 1 if @current < @top draw true else false end end def down if (@current + 1) < length @current += 1 @top += 1 if @current > body_height draw true else false end end def reset super @row = 0 end def draw render do draw_header draw_body end end protected def calculate_widths @rows.each do |row| row.each_with_index do |value, index| current, max = value.length, @sizes[index] || 0 @sizes[index] = current if max < current end end draw end def draw_header if @header color(:blue) do draw_values(@header) end end end def draw_body @rows[@top, body_height + 1].each_with_index do |row, index| color(:white, @top + index == @current ? :inverse : nil) do draw_values(row) end end end def draw_line draw_content(INTERSECTION + LINE_SEPARATOR * (width - 2) + INTERSECTION, 0) end def draw_values(values, padding = PADDING) space = ' ' * [padding, 0].max i = -1 draw_content(values.map { |value| value.ljust(@sizes[i += 1]) }.join(space)) end def draw_content(content, start = 2) @window.setpos(@row += 1, start) @window.addstr(content) end end end end Remove old table code require_relative 'view' module Soundcloud2000 module UI class Table < View PADDING = 1 attr_reader :current def initialize(*args) super @sizes = [] @rows = [] @current, @top = 0, 0 events.on(:key) do |key| case key when :up then up when :down then down end end reset end def header(*elements) @header = elements @header end def body(*rows) @rows = rows calculate_widths @rows end def length @rows.size end def body_height height - Array(@header).size end def up if @current > 0 @current -= 1 @top -= 1 if @current < @top draw true else false end end def down if (@current + 1) < length @current += 1 @top += 1 if @current > body_height draw true else false end end def reset super @row = 0 end def draw render do draw_header draw_body end end protected def rest_width(elements) width - elements.size * PADDING - elements.inject(0) { |sum, size| sum += size } end def calculate_widths @rows.each do |row| row.each_with_index do |value, index| current, max = value.length, @sizes[index] || 0 @sizes[index] = current if max < current end end @sizes[-1] = rest_width(@sizes[0...-1]) draw end def draw_header if @header color(:blue) do draw_values(@header) end end end def draw_body @rows[@top, body_height + 1].each_with_index do |row, index| color(:white, @top + index == @current ? :inverse : nil) do draw_values(row) end end end def draw_values(values) i = -1 draw_row(values.map { |value| value.ljust(@sizes[i += 1]) }.join(' ' * PADDING)) end def draw_row(content) @window.setpos(@row += 1, 0) @window.addstr(content) end end end end
require 'rugged' require 'json' require 'set' # Terminologies: # spectra: { filename => [line, numbers, executed], ... } # mapping: { test_file => spectra } module TTNT class TestToCodeMapping def initialize(repo) @repo = repo raise 'Not in a git repository' unless @repo end def append_from_coverage(test, coverage) spectra = normalize_path(select_project_files(spectra_from_coverage(coverage))) update_mapping_entry(test: test, spectra: spectra) end def read_mapping if File.exists?(mapping_file) JSON.parse(File.read(mapping_file)) else {} end end # Get tests affected from change of file `file` at line number `lineno` def get_tests(file:, lineno:) tests = Set.new read_mapping.each do |test, spectra| lines = spectra[file] next unless lines n = lines.bsearch { |x| x >= lineno } if n == lineno tests << test end end tests end # FIXME: this might not be the responsibility for this class def save_commit_info(sha) unless File.directory?(File.dirname(commit_info_file)) FileUtils.mkdir_p(File.dirname(commit_info_file)) end File.write(commit_info_file, sha) end private def normalized_path(file) File.expand_path(file).sub(@repo.workdir, '') end def normalize_path(spectra) spectra.map do |filename, lines| [normalized_path(filename), lines] end.to_h end def select_project_files(spectra) spectra.select do |filename, lines| filename.start_with?(@repo.workdir) end end def spectra_from_coverage(cov) spectra = Hash.new { |h, k| h[k] = [] } cov.each do |filename, executions| executions.each_with_index do |execution, i| next if execution.nil? || execution == 0 spectra[filename] << i + 1 end end spectra end def update_mapping_entry(test:, spectra:) dir = base_savedir unless File.directory?(dir) FileUtils.mkdir_p(dir) end mapping = read_mapping.merge({ test => spectra }) File.write(mapping_file, mapping.to_json) end def base_savedir "#{@repo.workdir}/.ttnt" end def mapping_file "#{base_savedir}/test_to_code_mapping.json" end def commit_info_file "#{base_savedir}/commit_obj.txt" end end end Write documents for TTNT::TestToCodeMapping require 'rugged' require 'json' require 'set' module TTNT # Mapping from test file to executed code (i.e. coverage without execution count) # # Terminologies: # spectra: { filename => [line, numbers, executed], ... } # mapping: { test_file => spectra } class TestToCodeMapping # @param repo [Rugged::Reposiotry] repository to save test-to-code mapping # (only repo.workdir is used to determine where to save the mapping file) def initialize(repo) @repo = repo raise 'Not in a git repository' unless @repo end # Append the new mapping to test-to-code mapping file. # # @param test [String] test file to which the coverage data is produced # @param coverage [Hash] coverage data generated using `Coverage.start` and `Coverage.result` # @return [void] def append_from_coverage(test, coverage) spectra = normalize_path(select_project_files(spectra_from_coverage(coverage))) update_mapping_entry(test: test, spectra: spectra) end # Read test-to-code mapping from file # # @return [Hash] test-to-code mapping def read_mapping if File.exists?(mapping_file) JSON.parse(File.read(mapping_file)) else {} end end # Get tests affected from change of file `file` at line number `lineno` # # @param file [String] file name which might have effects on some tests # @param lineno [Integer] line number in the file which might have effects on some tests # @return [Set] a set of test files which might be affected by the change in file at lineno def get_tests(file:, lineno:) tests = Set.new read_mapping.each do |test, spectra| lines = spectra[file] next unless lines n = lines.bsearch { |x| x >= lineno } if n == lineno tests << test end end tests end # Save sha as the commit object anchoring has been run on # # @param sha [String] sha of the commit anchoring has been run on # @return [void] # FIXME: this might not be the responsibility for this class def save_commit_info(sha) unless File.directory?(File.dirname(commit_info_file)) FileUtils.mkdir_p(File.dirname(commit_info_file)) end File.write(commit_info_file, sha) end private # Convert absolute path to relative path from the project (git repository) root. # # @param file [String] file name (absolute path) # @return [String] normalized file path def normalized_path(file) File.expand_path(file).sub(@repo.workdir, '') end # Normalize all file names in a spectra. # # @param spectra [Hash] spectra data # @return [Hash] spectra whose keys (file names) are normalized def normalize_path(spectra) spectra.map do |filename, lines| [normalized_path(filename), lines] end.to_h end # Filter out the files outside of the target project using file path. # # @param spectra [Hash] spectra data # @return [Hash] spectra with only files inside the target project def select_project_files(spectra) spectra.select do |filename, lines| filename.start_with?(@repo.workdir) end end # Generate spectra data from Ruby coverage library's data # # @param cov [Hash] coverage data generated using `Coverage.result` # @return [Hash] spectra data def spectra_from_coverage(cov) spectra = Hash.new { |h, k| h[k] = [] } cov.each do |filename, executions| executions.each_with_index do |execution, i| next if execution.nil? || execution == 0 spectra[filename] << i + 1 end end spectra end # Update single test-to-code mapping entry in a file # # @param test [String] target test file # @param spectra [Hash] spectra data for when executing the test file # @return [void] def update_mapping_entry(test:, spectra:) dir = base_savedir unless File.directory?(dir) FileUtils.mkdir_p(dir) end mapping = read_mapping.merge({ test => spectra }) File.write(mapping_file, mapping.to_json) end # Base directory to save TTNT related files # # @return [String] def base_savedir "#{@repo.workdir}/.ttnt" end # File name to save test-to-code mapping # # @return [String] def mapping_file "#{base_savedir}/test_to_code_mapping.json" end # File name to save commit object on which anchoring has been run # # @return [String] def commit_info_file "#{base_savedir}/commit_obj.txt" end end end
require 'lightspeed' require 'spree/core' require 'spree/api' require 'spree/backend' require "spree/product_importer" module SpreeLightspeed class Engine < ::Rails::Engine isolate_namespace SpreeLightspeed config.generators do |g| g.test_framework :rspec, :fixture => false g.assets false g.helper false end config.to_prepare do Dir.glob("#{File.dirname(__FILE__)}/../../app/**/*_decorator*.rb").each do |c| require_dependency(c) end end end end Autoconfig from config/lightspeed.yml require 'lightspeed' require 'spree/core' require 'spree/api' require 'spree/backend' require "spree/product_importer" module SpreeLightspeed class Engine < ::Rails::Engine isolate_namespace SpreeLightspeed config.generators do |g| g.test_framework :rspec, :fixture => false g.assets false g.helper false end config.to_prepare do Dir.glob("#{File.dirname(__FILE__)}/../../app/**/*_decorator*.rb").each do |c| require_dependency(c) end end initializer "lightspeed.config" do |app| path = "#{Rails.root}/config/lightspeed.yml" if File.exists?(path) Lightspeed::Client.config_from_yaml(path, Rails.env) else Rails.logger.error "Please configure Lightspeed via `config/lightspeed.yml`" end end end end
module UcStudentNumber VERSION = "0.1.0" end Change version to 0.0.1 module UcStudentNumber VERSION = "0.0.1" end
module Upmin::ActiveRecord module Query def results return klass.model_class.ransack(search_options).result(distinct: true) end private end end Removes distinct queries module Upmin::ActiveRecord module Query def results return klass.model_class.ransack(search_options).result end private end end
module VagrantPlugins module ChefZero VERSION = "0.2.3" end end Bump version module VagrantPlugins module ChefZero VERSION = "0.2.4" end end
require 'etc' module VagrantPlugins module ProviderKvm module Action class Import include Util include Util::Commands def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant::kvm::action::import") end def call(env) @env = env @env[:ui].info I18n.t("vagrant.actions.vm.import.importing", :name => env[:machine].box.name) provider_config = @env[:machine].provider_config # Ignore unsupported image types args={:image_type => provider_config.image_type} args[:image_type] = 'qcow2' unless args[:image_type] == 'raw' # Add memory attribute when specified if provider_config.memory_size args[:memory] = provider_config.memory_size end # import arguments args = { :image_backing => provider_config.image_backing, :qemu_bin => provider_config.qemu_bin, :cpus => provider_config.core_number, :cpu_model => provider_config.cpu_model, :machine_type => provider_config.machine_type, :network_model => provider_config.network_model, :video_model => provider_config.video_model, :virtio_rng => provider_config.virtio_rng }.merge(args) args[:disk_bus] = provider_config.disk_bus if provider_config.disk_bus # Import the virtual machine storage_path = File.join(@env[:tmp_path],"/storage-pool") box_file = @env[:machine].box.directory.join("box.xml").to_s raise Errors::KvmBadBoxFormat unless File.file?(box_file) # check pool migration neccesary? if @env[:machine].provider.driver.pool_migrate @env[:ui].output "Your vagrant-kvm environment should be fixed. see README" end # repair directories permission home_path = File.expand_path("../../", @env[:tmp_path]) boxes_path = File.expand_path("../boxes/", @env[:tmp_path]) repair_permissions!(home_path, boxes_path) # import box volume volume_name = import_volume(storage_path, box_file, args) # import the box to a new vm env[:machine].id = @env[:machine].provider.driver.import(box_file, volume_name, args) # If we got interrupted, then the import could have been # interrupted and its not a big deal. Just return out. return if @env[:interrupted] # Flag as erroneous and return if import failed raise Vagrant::Errors::VMImportFailure if !@env[:machine].id # Import completed successfully. Continue the chain @app.call(env) end def import_volume(storage_path, box_file, args) @logger.debug "Importing volume. Storage path: #{storage_path} " + "Image Type: #{args[:image_type]}" box_disk = @env[:machine].provider.driver.find_box_disk(box_file) new_disk = File.basename(box_disk, File.extname(box_disk)) + "-" + Time.now.to_i.to_s + ".img" old_path = File.join(File.dirname(box_file), box_disk) new_path = File.join(storage_path, new_disk) # for backward compatibility, we handle both raw and qcow2 box format box = Util::DiskInfo.new(old_path) if box.type == 'raw' || args[:image_type] == 'raw' args[:image_baking] = false @logger.info "Disable disk image with box image as backing file" end if args[:image_type] == 'qcow2' || args[:image_type] == 'raw' # create volume box_name = @env[:machine].config.vm.box driver = @env[:machine].provider.driver userid = Process.uid.to_s groupid = Process.gid.to_s modes = {:dir => '0775', :file => '0664'} label = 'virt_image_t' if driver.host_redhat? # on Redhat/Fedora, permission is controlled # with only SELinux modes = {:dir => '0777',:file => '0666'} secmodel = 'selinux' elsif driver.host_arch? # XXX: should be configurable secmodel = 'dac' elsif driver.host_ubuntu? groupid = Etc.getgrnam('kvm').gid.to_s secmodel='apparmor' elsif driver.host_debian? # XXX: should be configurable groupid = Etc.getgrnam('kvm').gid.to_s secmodel='dac' else # default secmodel='dac' end pool_name = 'vagrant_' + userid + '_' + box_name driver.init_storage_directory( :pool_path => File.dirname(old_path), :pool_name => pool_name, :owner => userid, :group => groupid, :mode => modes[:dir]) driver.create_volume( :disk_name => new_disk, :capacity => box.capacity, :path => new_path, :image_type => args[:image_type], :box_pool => pool_name, :box_path => old_path, :backing => args[:image_backing], :owner => userid, :group => groupid, :mode => modes[:file], :label => label, :secmodel => secmodel) driver.free_storage_pool(pool_name) else @logger.info "Image type #{args[:image_type]} is not supported" end # TODO cleanup if interrupted new_disk end # Repairs $HOME an $HOME/.vagrangt.d/boxes permissions. # # work around for # https://github.com/adrahon/vagrant-kvm/issues/193 # https://github.com/adrahon/vagrant-kvm/issues/163 # https://github.com/adrahon/vagrant-kvm/issues/130 # def repair_permissions!(home_path, boxes_path) # check pathes [home_path, boxes_path].each do |d| s = File::Stat.new(d) @logger.debug("#{d} permission: #{s.mode}") if (s.mode & 1 == 0) env[:ui].info I18n.t("vagrant_kvm.repair_permission",:directory => d, :old_mode => sprintf("%o",s.mode), :new_mode => sprintf("%o", s.mode|1) File.chmod(s.mode | 1, d) end end end def recover(env) if env[:machine].provider.state.id != :not_created return if env["vagrant.error"].is_a?(Vagrant::Errors::VagrantError) # Interrupted, destroy the VM. We note that we don't want to # validate the configuration here, and we don't want to confirm # we want to destroy. destroy_env = env.clone destroy_env[:config_validate] = false destroy_env[:force_confirm_destroy] = true env[:action_runner].run(Action.action_destroy, destroy_env) end end end end end end fix typo fix undefined error reported here. https://github.com/adrahon/vagrant-kvm/issues/201#issuecomment-40050196 Signed-off-by: Hiroshi Miura <ff6fb3ed059786151e736af13627c08d24e9f922@linux.com> require 'etc' module VagrantPlugins module ProviderKvm module Action class Import include Util include Util::Commands def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant::kvm::action::import") end def call(env) @env = env @env[:ui].info I18n.t("vagrant.actions.vm.import.importing", :name => env[:machine].box.name) provider_config = @env[:machine].provider_config # Ignore unsupported image types args={:image_type => provider_config.image_type} args[:image_type] = 'qcow2' unless args[:image_type] == 'raw' # Add memory attribute when specified if provider_config.memory_size args[:memory] = provider_config.memory_size end # import arguments args = { :image_backing => provider_config.image_backing, :qemu_bin => provider_config.qemu_bin, :cpus => provider_config.core_number, :cpu_model => provider_config.cpu_model, :machine_type => provider_config.machine_type, :network_model => provider_config.network_model, :video_model => provider_config.video_model, :virtio_rng => provider_config.virtio_rng }.merge(args) args[:disk_bus] = provider_config.disk_bus if provider_config.disk_bus # Import the virtual machine storage_path = File.join(@env[:tmp_path],"/storage-pool") box_file = @env[:machine].box.directory.join("box.xml").to_s raise Errors::KvmBadBoxFormat unless File.file?(box_file) # check pool migration neccesary? if @env[:machine].provider.driver.pool_migrate @env[:ui].output "Your vagrant-kvm environment should be fixed. see README" end # repair directories permission home_path = File.expand_path("../../", @env[:tmp_path]) boxes_path = File.expand_path("../boxes/", @env[:tmp_path]) repair_permissions!(home_path, boxes_path) # import box volume volume_name = import_volume(storage_path, box_file, args) # import the box to a new vm env[:machine].id = @env[:machine].provider.driver.import(box_file, volume_name, args) # If we got interrupted, then the import could have been # interrupted and its not a big deal. Just return out. return if @env[:interrupted] # Flag as erroneous and return if import failed raise Vagrant::Errors::VMImportFailure if !@env[:machine].id # Import completed successfully. Continue the chain @app.call(env) end def import_volume(storage_path, box_file, args) @logger.debug "Importing volume. Storage path: #{storage_path} " + "Image Type: #{args[:image_type]}" box_disk = @env[:machine].provider.driver.find_box_disk(box_file) new_disk = File.basename(box_disk, File.extname(box_disk)) + "-" + Time.now.to_i.to_s + ".img" old_path = File.join(File.dirname(box_file), box_disk) new_path = File.join(storage_path, new_disk) # for backward compatibility, we handle both raw and qcow2 box format box = Util::DiskInfo.new(old_path) if box.type == 'raw' || args[:image_type] == 'raw' args[:image_baking] = false @logger.info "Disable disk image with box image as backing file" end if args[:image_type] == 'qcow2' || args[:image_type] == 'raw' # create volume box_name = @env[:machine].config.vm.box driver = @env[:machine].provider.driver userid = Process.uid.to_s groupid = Process.gid.to_s modes = {:dir => '0775', :file => '0664'} label = 'virt_image_t' if driver.host_redhat? # on Redhat/Fedora, permission is controlled # with only SELinux modes = {:dir => '0777',:file => '0666'} secmodel = 'selinux' elsif driver.host_arch? # XXX: should be configurable secmodel = 'dac' elsif driver.host_ubuntu? groupid = Etc.getgrnam('kvm').gid.to_s secmodel='apparmor' elsif driver.host_debian? # XXX: should be configurable groupid = Etc.getgrnam('kvm').gid.to_s secmodel='dac' else # default secmodel='dac' end pool_name = 'vagrant_' + userid + '_' + box_name driver.init_storage_directory( :pool_path => File.dirname(old_path), :pool_name => pool_name, :owner => userid, :group => groupid, :mode => modes[:dir]) driver.create_volume( :disk_name => new_disk, :capacity => box.capacity, :path => new_path, :image_type => args[:image_type], :box_pool => pool_name, :box_path => old_path, :backing => args[:image_backing], :owner => userid, :group => groupid, :mode => modes[:file], :label => label, :secmodel => secmodel) driver.free_storage_pool(pool_name) else @logger.info "Image type #{args[:image_type]} is not supported" end # TODO cleanup if interrupted new_disk end # Repairs $HOME an $HOME/.vagrangt.d/boxes permissions. # # work around for # https://github.com/adrahon/vagrant-kvm/issues/193 # https://github.com/adrahon/vagrant-kvm/issues/163 # https://github.com/adrahon/vagrant-kvm/issues/130 # def repair_permissions!(home_path, boxes_path) # check pathes [home_path, boxes_path].each do |d| s = File::Stat.new(d) @logger.debug("#{d} permission: #{s.mode}") if (s.mode & 1 == 0) @env[:ui].info I18n.t("vagrant_kvm.repair_permission",:directory => d, :old_mode => sprintf("%o",s.mode), :new_mode => sprintf("%o", s.mode|1)) File.chmod(s.mode | 1, d) end end end def recover(env) if env[:machine].provider.state.id != :not_created return if env["vagrant.error"].is_a?(Vagrant::Errors::VagrantError) # Interrupted, destroy the VM. We note that we don't want to # validate the configuration here, and we don't want to confirm # we want to destroy. destroy_env = env.clone destroy_env[:config_validate] = false destroy_env[:force_confirm_destroy] = true env[:action_runner].run(Action.action_destroy, destroy_env) end end end end end end
require 'log4r' require 'shellwords' require 'fileutils' require "vagrant/util/subprocess" require Vagrant.source_root.join("plugins/provisioners/shell/provisioner") #require 'pry' module Vagrant module Plugin module V2 class Trigger # @return [Kernel_V2/Config/Trigger] attr_reader :config # This class is responsible for setting up basic triggers that were # defined inside a Vagrantfile. # # @param [Object] env Vagrant environment # @param [Object] config Trigger configuration # @param [Object] machine Active Machine def initialize(env, config, machine) @env = env @config = config @machine = machine @logger = Log4r::Logger.new("vagrant::trigger::#{self.class.to_s.downcase}") end # Fires all triggers, if any are defined for the action and guest # # @param [Symbol] action Vagrant command to fire trigger on # @param [Symbol] stage :before or :after # @param [String] guest_name The guest that invoked firing the triggers def fire_triggers(action, stage, guest_name) # get all triggers matching action triggers = [] if stage == :before triggers = config.before_triggers.select { |t| t.command == action } elsif stage == :after triggers = config.after_triggers.select { |t| t.command == action } else # raise error, stage was not given # This is an internal error # TODO: Make sure this error exist raise Errors::Triggers::NoStageGiven, action: action, stage: stage, guest_name: guest_name end triggers = filter_triggers(triggers, guest_name) unless triggers.empty? @logger.info("Firing trigger for action #{action} on guest #{guest_name}") # TODO I18N me @machine.ui.info("Running triggers #{stage} #{action}...") fire(triggers, guest_name) end end protected #------------------------------------------------------------------- # Internal methods, don't call these. #------------------------------------------------------------------- # Filters triggers to be fired based on configured restraints # # @param [Array] triggers An array of triggers to be filtered # @param [String] guest_name The name of the current guest # @return [Array] The filtered array of triggers def filter_triggers(triggers, guest_name) # look for only_on trigger constraint and if it doesn't match guest # name, throw it away also be sure to preserve order filter = triggers.dup filter.each do |trigger| index = nil if !trigger.only_on.nil? trigger.only_on.each do |o| if o.match?(guest_name) index = triggers.index(trigger) end end end if !index.nil? @logger.debug("Trigger #{trigger.id} will be ignored for #{guest_name}") triggers.delete_at(index) end end return triggers end # Fires off all triggers in the given array # # @param [Array] triggers An array of triggers to be fired def fire(triggers, guest_name) # ensure on_error is respected by exiting or continuing triggers.each do |trigger| @logger.debug("Running trigger #{trigger.id}...") # TODO: I18n me if !trigger.name.nil? @machine.ui.info("Running trigger: #{trigger.name}...") else @machine.ui.info("Running trigger...") end if !trigger.info.nil? @logger.debug("Executing trigger info message...") self.info(trigger.info) end if !trigger.warn.nil? @logger.debug("Executing trigger warn message...") self.warn(trigger.warn) end if !trigger.run.nil? @logger.debug("Executing trigger run script...") self.run(trigger.run, trigger.on_error) end if !trigger.run_remote.nil? @logger.debug("Executing trigger run_remote script on #{guest_name}...") self.run_remote(trigger.run_remote, trigger.on_error) end end end # Prints the given message at info level for a trigger # # @param [String] message The string to be printed def info(message) @machine.ui.info(message) end # Prints the given message at warn level for a trigger # # @param [String] message The string to be printed def warn(message) @machine.ui.warn(message) end # Runs a script on a guest # # @param [ShellProvisioner/Config] config A Shell provisioner config def run(config, on_error) # TODO: I18n me if !config.inline.nil? cmd = Shellwords.split(config.inline) @machine.ui.info("Executing local: Inline script") else cmd = File.expand_path(config.path, @env.root_path) FileUtils.chmod("+x", cmd) # TODO: what about windows @machine.ui.info("Executing local: File script #{config.path}") end begin # TODO: should we check config or command for sudo? And if so, WARN the user? result = Vagrant::Util::Subprocess.execute(*cmd, :notify => [:stdout, :stderr]) do |type,data| case type when :stdout @machine.ui.detail(data) when :stderr @machine.ui.error(data) end end rescue Exception => e # TODO: I18n me and write better message @machine.ui.error("Trigger run failed:") @machine.ui.error(e.message) if on_error == :halt @logger.debug("Trigger run encountered an error. Halting on error...") # Raise proper Vagrant error to avoid ugly stacktrace raise e else @logger.debug("Trigger run encountered an error. Continuing on anyway...") end end end # Runs a script on the host # # @param [ShellProvisioner/Config] config A Shell provisioner config def run_remote(config, on_error) unless @machine.state.id == :running # TODO: I18n me, improve message, etc @machine.ui.error("Could not run remote script on #{@machine.name} because its state is #{@machine.state.id}") if on_error == :halt raise Errors::Triggers::RunRemoteGuestNotExist else @machine.ui.warn("Trigger configured to continue on error....") return end end prov = VagrantPlugins::Shell::Provisioner.new(@machine, config) begin prov.provision rescue Exception => e if on_error == :halt @logger.debug("Trigger run encountered an error. Halting on error...") raise e else @logger.debug("Trigger run encountered an error. Continuing on anyway...") # TODO: I18n me and write better message @machine.ui.error("Trigger run failed:") @machine.ui.error(e.message) end end end end end end end Match properly on guests with trigger filtering require 'log4r' require 'shellwords' require 'fileutils' require "vagrant/util/subprocess" require Vagrant.source_root.join("plugins/provisioners/shell/provisioner") require 'pry' module Vagrant module Plugin module V2 class Trigger # @return [Kernel_V2/Config/Trigger] attr_reader :config # This class is responsible for setting up basic triggers that were # defined inside a Vagrantfile. # # @param [Object] env Vagrant environment # @param [Object] config Trigger configuration # @param [Object] machine Active Machine def initialize(env, config, machine) @env = env @config = config @machine = machine @logger = Log4r::Logger.new("vagrant::trigger::#{self.class.to_s.downcase}") end # Fires all triggers, if any are defined for the action and guest # # @param [Symbol] action Vagrant command to fire trigger on # @param [Symbol] stage :before or :after # @param [String] guest_name The guest that invoked firing the triggers def fire_triggers(action, stage, guest_name) # get all triggers matching action triggers = [] if stage == :before triggers = config.before_triggers.select { |t| t.command == action } elsif stage == :after triggers = config.after_triggers.select { |t| t.command == action } else # raise error, stage was not given # This is an internal error # TODO: Make sure this error exist raise Errors::Triggers::NoStageGiven, action: action, stage: stage, guest_name: guest_name end triggers = filter_triggers(triggers, guest_name) unless triggers.empty? @logger.info("Firing trigger for action #{action} on guest #{guest_name}") # TODO I18N me @machine.ui.info("Running triggers #{stage} #{action}...") fire(triggers, guest_name) end end protected #------------------------------------------------------------------- # Internal methods, don't call these. #------------------------------------------------------------------- # Filters triggers to be fired based on configured restraints # # @param [Array] triggers An array of triggers to be filtered # @param [String] guest_name The name of the current guest # @return [Array] The filtered array of triggers def filter_triggers(triggers, guest_name) # look for only_on trigger constraint and if it doesn't match guest # name, throw it away also be sure to preserve order filter = triggers.dup filter.each do |trigger| index = nil match = false if !trigger.only_on.nil? trigger.only_on.each do |o| if o.match?(guest_name) # trigger matches on current guest, so we're fine to use it match = true break end end # no matches found, so don't use trigger for guest index = triggers.index(trigger) unless match == true end if !index.nil? @logger.debug("Trigger #{trigger.id} will be ignored for #{guest_name}") triggers.delete_at(index) end end return triggers end # Fires off all triggers in the given array # # @param [Array] triggers An array of triggers to be fired def fire(triggers, guest_name) # ensure on_error is respected by exiting or continuing triggers.each do |trigger| @logger.debug("Running trigger #{trigger.id}...") # TODO: I18n me if !trigger.name.nil? @machine.ui.info("Running trigger: #{trigger.name}...") else @machine.ui.info("Running trigger...") end if !trigger.info.nil? @logger.debug("Executing trigger info message...") self.info(trigger.info) end if !trigger.warn.nil? @logger.debug("Executing trigger warn message...") self.warn(trigger.warn) end if !trigger.run.nil? @logger.debug("Executing trigger run script...") self.run(trigger.run, trigger.on_error) end if !trigger.run_remote.nil? @logger.debug("Executing trigger run_remote script on #{guest_name}...") self.run_remote(trigger.run_remote, trigger.on_error) end end end # Prints the given message at info level for a trigger # # @param [String] message The string to be printed def info(message) @machine.ui.info(message) end # Prints the given message at warn level for a trigger # # @param [String] message The string to be printed def warn(message) @machine.ui.warn(message) end # Runs a script on a guest # # @param [ShellProvisioner/Config] config A Shell provisioner config def run(config, on_error) # TODO: I18n me if !config.inline.nil? cmd = Shellwords.split(config.inline) @machine.ui.info("Executing local: Inline script") else cmd = File.expand_path(config.path, @env.root_path) FileUtils.chmod("+x", cmd) # TODO: what about windows @machine.ui.info("Executing local: File script #{config.path}") end begin # TODO: should we check config or command for sudo? And if so, WARN the user? result = Vagrant::Util::Subprocess.execute(*cmd, :notify => [:stdout, :stderr]) do |type,data| case type when :stdout @machine.ui.detail(data) when :stderr @machine.ui.error(data) end end rescue Exception => e # TODO: I18n me and write better message @machine.ui.error("Trigger run failed:") @machine.ui.error(e.message) if on_error == :halt @logger.debug("Trigger run encountered an error. Halting on error...") # Raise proper Vagrant error to avoid ugly stacktrace raise e else @logger.debug("Trigger run encountered an error. Continuing on anyway...") @machine.ui.warn("Trigger configured to continue on error....") end end end # Runs a script on the host # # @param [ShellProvisioner/Config] config A Shell provisioner config def run_remote(config, on_error) unless @machine.state.id == :running # TODO: I18n me, improve message, etc @machine.ui.error("Could not run remote script on #{@machine.name} because its state is #{@machine.state.id}") if on_error == :halt # TODO: Make sure I exist raise Errors::Triggers::RunRemoteGuestNotExist else @machine.ui.warn("Trigger configured to continue on error....") return end end prov = VagrantPlugins::Shell::Provisioner.new(@machine, config) begin prov.provision rescue Exception => e if on_error == :halt @logger.debug("Trigger run encountered an error. Halting on error...") raise e else @logger.debug("Trigger run encountered an error. Continuing on anyway...") # TODO: I18n me and write better message @machine.ui.error("Trigger run failed:") @machine.ui.error(e.message) end end end end end end end
# encoding: utf-8 module Veritas module Algebra # Extend a relation to include calculated attributes class Extension < Relation include Relation::Operation::Unary include Equalizer.new(self, :operand, :extensions) # The extensions for the relation # # @return [Hash] # # @api private attr_reader :extensions # Initialize an Extension # # @param [Relation] operand # the relation to extend # @param [#to_hash] extensions # the extensions to add # # @return [undefined] # # @api private def initialize(operand, extensions) super(operand) @extensions = extensions.to_hash @header |= @extensions.keys end # Iterate over each tuple in the set # # @example # extension = Extension.new(operand, extensions) # extension.each { |tuple| ... } # # @yield [tuple] # # @yieldparam [Tuple] tuple # each tuple in the set # # @return [self] # # @api public def each return to_enum unless block_given? header = self.header extensions = self.extensions.values operand.each { |operand_tuple| yield operand_tuple.extend(header, extensions) } self end module Methods # Return an extended relation # # @example # extension = relation.extend do |context| # context.add(:total, context[:unit_price] * context[:quantity]) # end # # @yield [function] # Evaluate an extension function # # @yieldparam [Evaluator::Context] context # the context to evaluate the function within # # @return [Extension] # # @api public def extend context = Evaluator::Context.new(header) { |context| yield context } Extension.new(self, context.functions) end end # module Methods Relation.class_eval { include Methods } end # class Extension end # module Algebra end # module Veritas Refactor Algebra::Extension#initialize to use Header#extend # encoding: utf-8 module Veritas module Algebra # Extend a relation to include calculated attributes class Extension < Relation include Relation::Operation::Unary include Equalizer.new(self, :operand, :extensions) # The extensions for the relation # # @return [Hash] # # @api private attr_reader :extensions # Initialize an Extension # # @param [Relation] operand # the relation to extend # @param [#to_hash] extensions # the extensions to add # # @return [undefined] # # @api private def initialize(operand, extensions) super(operand) @extensions = extensions.to_hash @header = @header.extend(@extensions.keys) end # Iterate over each tuple in the set # # @example # extension = Extension.new(operand, extensions) # extension.each { |tuple| ... } # # @yield [tuple] # # @yieldparam [Tuple] tuple # each tuple in the set # # @return [self] # # @api public def each return to_enum unless block_given? header = self.header extensions = self.extensions.values operand.each { |operand_tuple| yield operand_tuple.extend(header, extensions) } self end module Methods # Return an extended relation # # @example # extension = relation.extend do |context| # context.add(:total, context[:unit_price] * context[:quantity]) # end # # @yield [function] # Evaluate an extension function # # @yieldparam [Evaluator::Context] context # the context to evaluate the function within # # @return [Extension] # # @api public def extend context = Evaluator::Context.new(header) { |context| yield context } Extension.new(self, context.functions) end end # module Methods Relation.class_eval { include Methods } end # class Extension end # module Algebra end # module Veritas