CombinedText
stringlengths
4
3.42M
module ManageIQ::Providers::Amazon::ManagerMixin extend ActiveSupport::Concern included do validates :provider_region, :inclusion => {:in => ->(_region) { ManageIQ::Providers::Amazon::Regions.names }} end def description ManageIQ::Providers::Amazon::Regions.find_by_name(provider_region)[:description] end # # Connections # def browser_url "https://console.aws.amazon.com/ec2/v2/home?region=#{provider_region}" end def connect(options = {}) auth_type = options[:auth_type] raise "no credentials defined" if missing_credentials?(auth_type) username = options[:user] || authentication_userid(auth_type) password = options[:pass] || authentication_password(auth_type) service = options[:service] || :EC2 proxy = options[:proxy_uri] || http_proxy_uri region = options[:region] || provider_region assume_role = options[:assume_role] || authentication_service_account(auth_type) self.class.raw_connect(username, password, service, region, proxy, :assume_role => assume_role) end def verify_credentials(auth_type = nil, options = {}) raise MiqException::MiqHostError, "No credentials defined" if missing_credentials?(auth_type) return true if auth_type == "smartstate_docker" self.class.connection_rescue_block do # EC2 does Lazy Connections, so call a cheap function with_provider_connection(options.merge(:auth_type => auth_type)) do |ec2| self.class.validate_connection(ec2) end end true end module ClassMethods # # Connections # # Validate Credentials # args: # { # "region" => "", # "endpoints" => { # "ec2" => { # "access_key" => "", # "secret_access_key" => "", # } # } # } def validate_credentials(args) region = args["region"] ec2_endpoint = args.dig("endpoints", "ec2") raw_connect(ec2_endpoint["access_key"], ec2_endpoint["secret_access_key"], "ec2", region) end def raw_connect(access_key_id, secret_access_key, service, region, proxy_uri = nil, validate = false, uri = nil, assume_role: nil) require 'aws-sdk' require 'patches/aws-sdk-core/seahorse_client_net_http_pool_patch' log_formatter_pattern = Aws::Log::Formatter.default.pattern.chomp secret_access_key = ManageIQ::Password.try_decrypt(secret_access_key) options = { :credentials => Aws::Credentials.new(access_key_id, secret_access_key), :region => region, :http_proxy => proxy_uri, :logger => $aws_log, :log_level => :debug, :log_formatter => Aws::Log::Formatter.new(log_formatter_pattern), } options[:endpoint] = uri.to_s if uri.to_s.present? if assume_role options[:credentials] = Aws::AssumeRoleCredentials.new( :client => Aws::STS::Client.new(options), :role_arn => assume_role, :role_session_name => "ManageIQ-#{service}", ) end connection = Aws.const_get(service)::Resource.new(options) validate_connection(connection) if validate connection end def validate_connection(connection) connection_rescue_block do connection.client.describe_regions.regions.map(&:region_name) end end def connection_rescue_block yield rescue => err miq_exception = translate_exception(err) raise unless miq_exception _log.error("Error Class=#{err.class.name}, Message=#{err.message}") raise miq_exception end def translate_exception(err) require 'aws-sdk' require 'patches/aws-sdk-core/seahorse_client_net_http_pool_patch' case err when Aws::EC2::Errors::SignatureDoesNotMatch MiqException::MiqHostError.new "SignatureMismatch - check your AWS Secret Access Key and signing method" when Aws::EC2::Errors::AuthFailure MiqException::MiqHostError.new "Login failed due to a bad username or password." when Aws::Errors::MissingCredentialsError MiqException::MiqHostError.new "Missing credentials" else MiqException::MiqHostError.new "Unexpected response returned from system: #{err.message}" end end end end Check for invalid ec2 endpoint config module ManageIQ::Providers::Amazon::ManagerMixin extend ActiveSupport::Concern included do validates :provider_region, :inclusion => {:in => ->(_region) { ManageIQ::Providers::Amazon::Regions.names }} end def description ManageIQ::Providers::Amazon::Regions.find_by_name(provider_region)[:description] end # # Connections # def browser_url "https://console.aws.amazon.com/ec2/v2/home?region=#{provider_region}" end def connect(options = {}) auth_type = options[:auth_type] raise "no credentials defined" if missing_credentials?(auth_type) username = options[:user] || authentication_userid(auth_type) password = options[:pass] || authentication_password(auth_type) service = options[:service] || :EC2 proxy = options[:proxy_uri] || http_proxy_uri region = options[:region] || provider_region assume_role = options[:assume_role] || authentication_service_account(auth_type) self.class.raw_connect(username, password, service, region, proxy, :assume_role => assume_role) end def verify_credentials(auth_type = nil, options = {}) raise MiqException::MiqHostError, "No credentials defined" if missing_credentials?(auth_type) return true if auth_type == "smartstate_docker" self.class.connection_rescue_block do # EC2 does Lazy Connections, so call a cheap function with_provider_connection(options.merge(:auth_type => auth_type)) do |ec2| self.class.validate_connection(ec2) end end true end module ClassMethods # # Connections # # Validate Credentials # args: # { # "region" => "", # "endpoints" => { # "ec2" => { # "access_key" => "", # "secret_access_key" => "", # } # } # } def validate_credentials(args) region = args["region"] ec2_endpoint = args.dig("endpoints", "ec2") raise MiqException::MiqInvalidCredentialsError, _("Provided credentials are invalid") if ec2_endpoint.nil? raw_connect(ec2_endpoint["access_key"], ec2_endpoint["secret_access_key"], "ec2", region) end def raw_connect(access_key_id, secret_access_key, service, region, proxy_uri = nil, validate = false, uri = nil, assume_role: nil) require 'aws-sdk' require 'patches/aws-sdk-core/seahorse_client_net_http_pool_patch' log_formatter_pattern = Aws::Log::Formatter.default.pattern.chomp secret_access_key = ManageIQ::Password.try_decrypt(secret_access_key) options = { :credentials => Aws::Credentials.new(access_key_id, secret_access_key), :region => region, :http_proxy => proxy_uri, :logger => $aws_log, :log_level => :debug, :log_formatter => Aws::Log::Formatter.new(log_formatter_pattern), } options[:endpoint] = uri.to_s if uri.to_s.present? if assume_role options[:credentials] = Aws::AssumeRoleCredentials.new( :client => Aws::STS::Client.new(options), :role_arn => assume_role, :role_session_name => "ManageIQ-#{service}", ) end connection = Aws.const_get(service)::Resource.new(options) validate_connection(connection) if validate connection end def validate_connection(connection) connection_rescue_block do connection.client.describe_regions.regions.map(&:region_name) end end def connection_rescue_block yield rescue => err miq_exception = translate_exception(err) raise unless miq_exception _log.error("Error Class=#{err.class.name}, Message=#{err.message}") raise miq_exception end def translate_exception(err) require 'aws-sdk' require 'patches/aws-sdk-core/seahorse_client_net_http_pool_patch' case err when Aws::EC2::Errors::SignatureDoesNotMatch MiqException::MiqHostError.new "SignatureMismatch - check your AWS Secret Access Key and signing method" when Aws::EC2::Errors::AuthFailure MiqException::MiqHostError.new "Login failed due to a bad username or password." when Aws::Errors::MissingCredentialsError MiqException::MiqHostError.new "Missing credentials" else MiqException::MiqHostError.new "Unexpected response returned from system: #{err.message}" end end end end
class ManageIQ::Providers::Redhat::InfraManager < ManageIQ::Providers::InfraManager require_nested :EventCatcher require_nested :EventParser require_nested :RefreshWorker require_nested :RefreshParser require_nested :MetricsCapture require_nested :MetricsCollectorWorker require_nested :Host require_nested :Provision require_nested :ProvisionViaIso require_nested :ProvisionViaPxe require_nested :ProvisionWorkflow require_nested :Refresher require_nested :Template require_nested :Vm supports :provisioning def self.ems_type @ems_type ||= "rhevm".freeze end def self.description @description ||= "Red Hat Enterprise Virtualization Manager".freeze end def self.default_blacklisted_event_names %w( UNASSIGNED USER_REMOVE_VG USER_REMOVE_VG_FAILED USER_VDC_LOGIN USER_VDC_LOGOUT USER_VDC_LOGIN_FAILED ) end def supports_port? true end def supported_auth_types %w(default metrics) end def supports_authentication?(authtype) supported_auth_types.include?(authtype.to_s) end # Connect to the engine using version 4 of the API and the `ovirt-engine-sdk` gem. def self.raw_connect_v4(server, port, path, username, password, service) require 'ovirtsdk4' # Get the timeout from the configuration: timeout, = ems_timeouts(:ems_redhat, service) # Create the connection: OvirtSDK4::Connection.new( :url => "https://#{server}:#{port}#{path}", :username => username, :password => password, :timeout => timeout, :insecure => true, :log => $rhevm_log, ) end # Connect to the engine using version 3 of the API and the `ovirt` gem. def self.raw_connect_v3(server, port, path, username, password, service) require 'ovirt' Ovirt.logger = $rhevm_log params = { :server => server, :port => port.presence && port.to_i, :path => path, :username => username, :password => password, :verify_ssl => false } read_timeout, open_timeout = ems_timeouts(:ems_redhat, service) params[:timeout] = read_timeout if read_timeout params[:open_timeout] = open_timeout if open_timeout Ovirt.const_get(service).new(params) end def connect(options = {}) raise "no credentials defined" if self.missing_credentials?(options[:auth_type]) # If there is API path stored in the endpoints table and use it: path = default_endpoint.path _log.info("Using stored API path '#{path}'.") unless path.blank? server = options[:ip] || address port = options[:port] || self.port username = options[:user] || authentication_userid(options[:auth_type]) password = options[:pass] || authentication_password(options[:auth_type]) service = options[:service] || "Service" version = options[:version] || 3 # Create the underlying connection according to the version of the oVirt API requested by # the caller: connect_method = version == 4 ? :raw_connect_v4 : :raw_connect_v3 connection = self.class.public_send(connect_method, server, port, path, username, password, service) # Copy the API path to the endpoints table: default_endpoint.path = version == 4 ? '/ovirt-engine/api' : connection.api_path connection end def rhevm_service @rhevm_service ||= connect(:service => "Service") end def rhevm_inventory @rhevm_inventory ||= connect(:service => "Inventory") end def with_provider_connection(options = {}) raise "no block given" unless block_given? _log.info("Connecting through #{self.class.name}: [#{name}]") begin connection = connect(options) yield connection ensure # The `connect` method will return different types of objects depending on the value of the `version` # parameter. If `version` is 3 the connection object is created by the `ovirt` gem and it is closed # using the `disconnect` method. If `version` is 4 the object is created by the oVirt Ruby SDK, and # it is closed using the `close` method. begin if connection.respond_to?(:disconnect) connection.disconnect elsif connection.respond_to?(:close) connection.close end rescue => error _log.error("Error while disconnecting #{error}") nil end end end def verify_credentials_for_rhevm(options = {}) connect(options).api rescue URI::InvalidURIError raise "Invalid URI specified for RHEV server." rescue SocketError => err raise "Error occurred attempted to connect to RHEV server.", err rescue => err _log.error("Error while verifying credentials #{err}") raise MiqException::MiqEVMLoginError, err end def rhevm_metrics_connect_options(options = {}) metrics_hostname = connection_configuration_by_role('metrics') .try(:endpoint) .try(:hostname) server = options[:hostname] || metrics_hostname || hostname username = options[:user] || authentication_userid(:metrics) password = options[:pass] || authentication_password(:metrics) database = options[:database] { :host => server, :database => database, :username => username, :password => password } end def verify_credentials_for_rhevm_metrics(options = {}) require 'ovirt_metrics' OvirtMetrics.connect(rhevm_metrics_connect_options(options)) OvirtMetrics.connected? rescue PGError => e message = (e.message.starts_with?("FATAL:") ? e.message[6..-1] : e.message).strip case message when /database \".*\" does not exist/ if database.nil? && (conn_info[:database] != OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME_3_0) conn_info[:database] = OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME_3_0 retry end end _log.warn("PGError: #{message}") raise MiqException::MiqEVMLoginError, message rescue Exception => e raise MiqException::MiqEVMLoginError, e.to_s ensure OvirtMetrics.disconnect rescue nil end def authentications_to_validate at = [:default] at << :metrics if self.has_authentication_type?(:metrics) at end def verify_credentials(auth_type = nil, options = {}) auth_type ||= 'default' case auth_type.to_s when 'default' then verify_credentials_for_rhevm(options) when 'metrics' then verify_credentials_for_rhevm_metrics(options) else; raise "Invalid Authentication Type: #{auth_type.inspect}" end end def self.event_monitor_class self::EventCatcher end def self.provision_class(via) case via when "iso" then self::ProvisionViaIso when "pxe" then self::ProvisionViaPxe else self::Provision end end def history_database_name @history_database_name ||= begin version = version_3_0? ? '3_0' : '>3_0' self.class.history_database_name_for(version) end end def self.history_database_name_for(api_version) require 'ovirt_metrics' case api_version when '3_0' OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME_3_0 else OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME end end def version_3_0? if @version_3_0.nil? @version_3_0 = if api_version.nil? with_provider_connection(&:version_3_0?) else api_version.starts_with?("3.0") end end @version_3_0 end def vm_reconfigure(vm, options = {}) log_header = "EMS: [#{name}] #{vm.class.name}: id [#{vm.id}], name [#{vm.name}], ems_ref [#{vm.ems_ref}]" spec = options[:spec] vm.with_provider_object do |rhevm_vm| _log.info("#{log_header} Started...") update_vm_memory(rhevm_vm, spec["memoryMB"] * 1.megabyte) if spec["memoryMB"] cpu_options = {} cpu_options[:cores] = spec["numCoresPerSocket"] if spec["numCoresPerSocket"] cpu_options[:sockets] = spec["numCPUs"] / (cpu_options[:cores] || vm.cpu_cores_per_socket) if spec["numCPUs"] rhevm_vm.cpu_topology = cpu_options if cpu_options.present? end _log.info("#{log_header} Completed.") end # RHEVM requires that the memory of the VM will be bigger or equal to the reserved memory at any given time. # Therefore, increasing the memory of the vm should precede to updating the reserved memory, and the opposite: # Decreasing the memory to a lower value than the reserved memory requires first to update the reserved memory def update_vm_memory(rhevm_vm, memory) if memory > rhevm_vm.attributes.fetch_path(:memory) rhevm_vm.memory = memory rhevm_vm.memory_reserve = memory else rhevm_vm.memory_reserve = memory rhevm_vm.memory = memory end end # Calculates an "ems_ref" from the "href" attribute provided by the oVirt REST API, removing the # "/ovirt-engine/" prefix, as for historic reasons the "ems_ref" stored in the database does not # contain it, it only contains the "/api" prefix which was used by older versions of the engine. def self.make_ems_ref(href) href && href.sub(%r{^/ovirt-engine/}, '/') end end Allow more than one iso datastore per *type* of EMS. https://bugzilla.redhat.com/show_bug.cgi?id=1358068 (transferred from ManageIQ/manageiq@80993d4b191df2ee73813724ee1205018fb405a5) class ManageIQ::Providers::Redhat::InfraManager < ManageIQ::Providers::InfraManager require_nested :EventCatcher require_nested :EventParser require_nested :RefreshWorker require_nested :RefreshParser require_nested :MetricsCapture require_nested :MetricsCollectorWorker require_nested :Host require_nested :Provision require_nested :ProvisionViaIso require_nested :ProvisionViaPxe require_nested :ProvisionWorkflow require_nested :Refresher require_nested :Template require_nested :Vm supports :provisioning def self.ems_type @ems_type ||= "rhevm".freeze end def self.description @description ||= "Red Hat Enterprise Virtualization Manager".freeze end def self.default_blacklisted_event_names %w( UNASSIGNED USER_REMOVE_VG USER_REMOVE_VG_FAILED USER_VDC_LOGIN USER_VDC_LOGOUT USER_VDC_LOGIN_FAILED ) end def self.without_datastores includes(:iso_datastore).where(:iso_datastores => {:id => nil}) end def self.any_without_datastores? without_datastores.count > 0 end def supports_port? true end def supported_auth_types %w(default metrics) end def supports_authentication?(authtype) supported_auth_types.include?(authtype.to_s) end # Connect to the engine using version 4 of the API and the `ovirt-engine-sdk` gem. def self.raw_connect_v4(server, port, path, username, password, service) require 'ovirtsdk4' # Get the timeout from the configuration: timeout, = ems_timeouts(:ems_redhat, service) # Create the connection: OvirtSDK4::Connection.new( :url => "https://#{server}:#{port}#{path}", :username => username, :password => password, :timeout => timeout, :insecure => true, :log => $rhevm_log, ) end # Connect to the engine using version 3 of the API and the `ovirt` gem. def self.raw_connect_v3(server, port, path, username, password, service) require 'ovirt' Ovirt.logger = $rhevm_log params = { :server => server, :port => port.presence && port.to_i, :path => path, :username => username, :password => password, :verify_ssl => false } read_timeout, open_timeout = ems_timeouts(:ems_redhat, service) params[:timeout] = read_timeout if read_timeout params[:open_timeout] = open_timeout if open_timeout Ovirt.const_get(service).new(params) end def connect(options = {}) raise "no credentials defined" if self.missing_credentials?(options[:auth_type]) # If there is API path stored in the endpoints table and use it: path = default_endpoint.path _log.info("Using stored API path '#{path}'.") unless path.blank? server = options[:ip] || address port = options[:port] || self.port username = options[:user] || authentication_userid(options[:auth_type]) password = options[:pass] || authentication_password(options[:auth_type]) service = options[:service] || "Service" version = options[:version] || 3 # Create the underlying connection according to the version of the oVirt API requested by # the caller: connect_method = version == 4 ? :raw_connect_v4 : :raw_connect_v3 connection = self.class.public_send(connect_method, server, port, path, username, password, service) # Copy the API path to the endpoints table: default_endpoint.path = version == 4 ? '/ovirt-engine/api' : connection.api_path connection end def rhevm_service @rhevm_service ||= connect(:service => "Service") end def rhevm_inventory @rhevm_inventory ||= connect(:service => "Inventory") end def with_provider_connection(options = {}) raise "no block given" unless block_given? _log.info("Connecting through #{self.class.name}: [#{name}]") begin connection = connect(options) yield connection ensure # The `connect` method will return different types of objects depending on the value of the `version` # parameter. If `version` is 3 the connection object is created by the `ovirt` gem and it is closed # using the `disconnect` method. If `version` is 4 the object is created by the oVirt Ruby SDK, and # it is closed using the `close` method. begin if connection.respond_to?(:disconnect) connection.disconnect elsif connection.respond_to?(:close) connection.close end rescue => error _log.error("Error while disconnecting #{error}") nil end end end def verify_credentials_for_rhevm(options = {}) connect(options).api rescue URI::InvalidURIError raise "Invalid URI specified for RHEV server." rescue SocketError => err raise "Error occurred attempted to connect to RHEV server.", err rescue => err _log.error("Error while verifying credentials #{err}") raise MiqException::MiqEVMLoginError, err end def rhevm_metrics_connect_options(options = {}) metrics_hostname = connection_configuration_by_role('metrics') .try(:endpoint) .try(:hostname) server = options[:hostname] || metrics_hostname || hostname username = options[:user] || authentication_userid(:metrics) password = options[:pass] || authentication_password(:metrics) database = options[:database] { :host => server, :database => database, :username => username, :password => password } end def verify_credentials_for_rhevm_metrics(options = {}) require 'ovirt_metrics' OvirtMetrics.connect(rhevm_metrics_connect_options(options)) OvirtMetrics.connected? rescue PGError => e message = (e.message.starts_with?("FATAL:") ? e.message[6..-1] : e.message).strip case message when /database \".*\" does not exist/ if database.nil? && (conn_info[:database] != OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME_3_0) conn_info[:database] = OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME_3_0 retry end end _log.warn("PGError: #{message}") raise MiqException::MiqEVMLoginError, message rescue Exception => e raise MiqException::MiqEVMLoginError, e.to_s ensure OvirtMetrics.disconnect rescue nil end def authentications_to_validate at = [:default] at << :metrics if self.has_authentication_type?(:metrics) at end def verify_credentials(auth_type = nil, options = {}) auth_type ||= 'default' case auth_type.to_s when 'default' then verify_credentials_for_rhevm(options) when 'metrics' then verify_credentials_for_rhevm_metrics(options) else; raise "Invalid Authentication Type: #{auth_type.inspect}" end end def self.event_monitor_class self::EventCatcher end def self.provision_class(via) case via when "iso" then self::ProvisionViaIso when "pxe" then self::ProvisionViaPxe else self::Provision end end def history_database_name @history_database_name ||= begin version = version_3_0? ? '3_0' : '>3_0' self.class.history_database_name_for(version) end end def self.history_database_name_for(api_version) require 'ovirt_metrics' case api_version when '3_0' OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME_3_0 else OvirtMetrics::DEFAULT_HISTORY_DATABASE_NAME end end def version_3_0? if @version_3_0.nil? @version_3_0 = if api_version.nil? with_provider_connection(&:version_3_0?) else api_version.starts_with?("3.0") end end @version_3_0 end def vm_reconfigure(vm, options = {}) log_header = "EMS: [#{name}] #{vm.class.name}: id [#{vm.id}], name [#{vm.name}], ems_ref [#{vm.ems_ref}]" spec = options[:spec] vm.with_provider_object do |rhevm_vm| _log.info("#{log_header} Started...") update_vm_memory(rhevm_vm, spec["memoryMB"] * 1.megabyte) if spec["memoryMB"] cpu_options = {} cpu_options[:cores] = spec["numCoresPerSocket"] if spec["numCoresPerSocket"] cpu_options[:sockets] = spec["numCPUs"] / (cpu_options[:cores] || vm.cpu_cores_per_socket) if spec["numCPUs"] rhevm_vm.cpu_topology = cpu_options if cpu_options.present? end _log.info("#{log_header} Completed.") end # RHEVM requires that the memory of the VM will be bigger or equal to the reserved memory at any given time. # Therefore, increasing the memory of the vm should precede to updating the reserved memory, and the opposite: # Decreasing the memory to a lower value than the reserved memory requires first to update the reserved memory def update_vm_memory(rhevm_vm, memory) if memory > rhevm_vm.attributes.fetch_path(:memory) rhevm_vm.memory = memory rhevm_vm.memory_reserve = memory else rhevm_vm.memory_reserve = memory rhevm_vm.memory = memory end end # Calculates an "ems_ref" from the "href" attribute provided by the oVirt REST API, removing the # "/ovirt-engine/" prefix, as for historic reasons the "ems_ref" stored in the database does not # contain it, it only contains the "/api" prefix which was used by older versions of the engine. def self.make_ems_ref(href) href && href.sub(%r{^/ovirt-engine/}, '/') end end
module Spree class Promotion < Spree::Activator module Rules Product.class_eval do belongs_to :product_group attr_accessible :products_source, :product_group_id def eligible_products product_group ? product_group.products : products end def products_source=(source) if source.to_s == 'manual' self.product_group_id = nil end end end end end end Prevent "superclass mismatch for class Promotion" error. * was happening intermittently in development * there were no other gems with `Promotion' class * was unable to replicate error in tests unless defined?(Spree::Promotion) module Spree class Promotion < Spree::Activator module Rules Product.class_eval do belongs_to :product_group attr_accessible :products_source, :product_group_id def eligible_products product_group ? product_group.products : products end def products_source=(source) if source.to_s == 'manual' self.product_group_id = nil end end end end end end end
require 'json' require 'carto/export/layer_exporter' # Version History # TODO: documentation at http://cartodb.readthedocs.org/en/latest/operations/exporting_importing_visualizations.html # 2: export full visualization. Limitations: # - No Odyssey support: export fails if any of parent_id / prev_id / next_id / slide_transition_options are set. # - Privacy is exported, but permissions are not. # 2.0.1: export Widget.source_id # 2.0.2: export username # 2.0.3: export state (Carto::State) # 2.0.4: export legends (Carto::Legend) # 2.0.5: export explicit widget order # 2.0.6: export version # 2.0.7: export map options # 2.0.8: export widget style # 2.0.9: export visualization id # 2.1.0: export datasets: permissions, user_tables and syncs module Carto module VisualizationsExportService2Configuration CURRENT_VERSION = '2.1.0'.freeze MAX_LOG_SIZE = 8192 def compatible_version?(version) version.to_i == CURRENT_VERSION.split('.')[0].to_i end end module VisualizationsExportService2Validator def check_valid_visualization(visualization) raise 'Only derived or canonical visualizations can be exported' unless visualization.derived? || visualization.canonical? || visualization.remote? end end module VisualizationsExportService2Importer include VisualizationsExportService2Configuration include LayerImporter def build_visualization_from_json_export(exported_json_string) build_visualization_from_hash_export(JSON.parse(exported_json_string, symbolize_names: true)) end def build_visualization_from_hash_export(exported_hash) raise 'Wrong export version' unless compatible_version?(exported_hash[:version]) build_visualization_from_hash(exported_hash[:visualization]) end private def build_visualization_from_hash(exported_visualization) exported_layers = exported_visualization[:layers] exported_overlays = exported_visualization[:overlays] visualization = Carto::Visualization.new( name: exported_visualization[:name], description: exported_visualization[:description], version: exported_visualization[:version] || 2, type: exported_visualization[:type], tags: exported_visualization[:tags], privacy: exported_visualization[:privacy], source: exported_visualization[:source], license: exported_visualization[:license], title: exported_visualization[:title], kind: exported_visualization[:kind], attributions: exported_visualization[:attributions], bbox: exported_visualization[:bbox], display_name: exported_visualization[:display_name], map: build_map_from_hash( exported_visualization[:map], layers: build_layers_from_hash(exported_layers)), overlays: build_overlays_from_hash(exported_overlays), analyses: exported_visualization[:analyses].map { |a| build_analysis_from_hash(a) }, permission: build_permission_from_hash(exported_visualization[:permission]), external_source: build_external_source_from_hash(exported_visualization[:external_source]) ) # This is optional as it was added in version 2.0.2 exported_user = exported_visualization[:user] if exported_user visualization.user = Carto::User.new(username: exported_user[:username]) end # Added in version 2.0.3 visualization.state = build_state_from_hash(exported_visualization[:state]) active_layer_order = exported_layers.index { |l| l['active_layer'] } if active_layer_order visualization.active_layer = visualization.layers.find { |l| l.order == active_layer_order } end # Dataset-specific user_table = build_user_table_from_hash(exported_visualization[:user_table]) visualization.map.user_table = user_table if user_table visualization.synchronization = build_synchronization_from_hash(exported_visualization[:synchronization]) visualization.id = exported_visualization[:id] if exported_visualization[:id] visualization end def build_map_from_hash(exported_map, layers:) return nil unless exported_map Carto::Map.new( provider: exported_map[:provider], bounding_box_sw: exported_map[:bounding_box_sw], bounding_box_ne: exported_map[:bounding_box_ne], center: exported_map[:center], zoom: exported_map[:zoom], view_bounds_sw: exported_map[:view_bounds_sw], view_bounds_ne: exported_map[:view_bounds_ne], scrollwheel: exported_map[:scrollwheel], legends: exported_map[:legends], layers: layers, options: exported_map[:options] ) end def build_overlays_from_hash(exported_overlays) return [] unless exported_overlays exported_overlays.map.with_index.map do |overlay, i| build_overlay_from_hash(overlay, order: (i + 1)) end end def build_overlay_from_hash(exported_overlay, order:) Carto::Overlay.new( order: order, options: exported_overlay[:options], type: exported_overlay[:type], template: exported_overlay[:template] ) end def build_analysis_from_hash(exported_analysis) return nil unless exported_analysis Carto::Analysis.new(analysis_definition: exported_analysis[:analysis_definition]) end def build_state_from_hash(exported_state) Carto::State.new(json: exported_state ? exported_state[:json] : nil) end def build_permission_from_hash(exported_permission) return nil unless exported_permission Carto::Permission.new(access_control_list: JSON.dump(exported_permission[:access_control_list])) end def build_synchronization_from_hash(exported_synchronization) return nil unless exported_synchronization Carto::Synchronization.new( name: exported_synchronization[:name], interval: exported_synchronization[:interval], url: exported_synchronization[:url], state: exported_synchronization[:state], created_at: exported_synchronization[:created_at], updated_at: exported_synchronization[:updated_at], run_at: exported_synchronization[:run_at], retried_times: exported_synchronization[:retried_times], log: build_log_from_hash(exported_synchronization[:log]), error_code: exported_synchronization[:error_code], error_message: exported_synchronization[:error_message], ran_at: exported_synchronization[:ran_at], modified_at: exported_synchronization[:modified_at], etag: exported_synchronization[:etag], checksum: exported_synchronization[:checksum], service_name: exported_synchronization[:service_name], service_item_id: exported_synchronization[:service_item_id], type_guessing: exported_synchronization[:type_guessing], quoted_fields_guessing: exported_synchronization[:quoted_fields_guessing], content_guessing: exported_synchronization[:content_guessing] ) end def build_log_from_hash(exported_log) return nil unless exported_log Carto::Log.new(type: exported_log[:type], entries: exported_log[:entries]) end def build_user_table_from_hash(exported_user_table) return nil unless exported_user_table user_table = Carto::UserTable.new user_table.name = exported_user_table[:name] user_table.privacy = exported_user_table[:privacy] user_table.tags = exported_user_table[:tags] user_table.geometry_columns = exported_user_table[:geometry_columns] user_table.rows_counted = exported_user_table[:rows_counted] user_table.rows_estimated = exported_user_table[:rows_estimated] user_table.indexes = exported_user_table[:indexes] user_table.database_name = exported_user_table[:database_name] user_table.description = exported_user_table[:description] user_table.table_id = exported_user_table[:table_id] user_table.data_import = build_data_import_from_hash(exported_user_table[:data_import]) user_table end def build_data_import_from_hash(exported_data_import) Carto::DataImport.new( data_source: exported_data_import[:data_source], data_type: exported_data_import[:data_type], table_name: exported_data_import[:table_name], state: exported_data_import[:state], success: exported_data_import[:success], log: build_log_from_hash(exported_data_import[:log]), updated_at: exported_data_import[:updated_at], created_at: exported_data_import[:created_at], error_code: exported_data_import[:error_code], queue_id: exported_data_import[:queue_id], tables_created_count: exported_data_import[:tables_created_count], table_names: exported_data_import[:table_names], append: exported_data_import[:append], migrate_table: exported_data_import[:migrate_table], table_copy: exported_data_import[:table_copy], from_query: exported_data_import[:from_query], id: exported_data_import[:id], service_name: exported_data_import[:service_name], service_item_id: exported_data_import[:service_item_id], stats: exported_data_import[:stats], type_guessing: exported_data_import[:type_guessing], quoted_fields_guessing: exported_data_import[:quoted_fields_guessing], content_guessing: exported_data_import[:content_guessing], server: exported_data_import[:server], host: exported_data_import[:host], upload_host: exported_data_import[:upload_host], resque_ppid: exported_data_import[:resque_ppid], create_visualization: exported_data_import[:create_visualization], visualization_id: exported_data_import[:visualization_id], user_defined_limits: exported_data_import[:user_defined_limits], import_extra_options: exported_data_import[:import_extra_options], original_url: exported_data_import[:original_url], privacy: exported_data_import[:privacy], cartodbfy_time: exported_data_import[:cartodbfy_time], http_response_code: exported_data_import[:http_response_code], rejected_layers: exported_data_import[:rejected_layers], runner_warnings: exported_data_import[:runner_warnings], collision_strategy: exported_data_import[:collision_strategy], external_data_imports: exported_data_import[:external_data_imports].map { |edi| build_external_data_import_from_hash(edi) } ) end def build_external_data_import_from_hash(exported_external_data_import) Carto::ExternalDataImport.new(external_source_id: exported_external_data_import[:external_source_id]) end def build_external_source_from_hash(exported_external_source) return nil unless exported_external_source es = Carto::ExternalSource.new( import_url: exported_external_source[:import_url], rows_counted: exported_external_source[:rows_counted], size: exported_external_source[:size], username: exported_external_source[:username], geometry_types: exported_external_source[:geometry_types] ) es.id = exported_external_source[:id] es end end module VisualizationsExportService2Exporter include VisualizationsExportService2Configuration include VisualizationsExportService2Validator include LayerExporter def export_visualization_json_string(visualization_id, user) export_visualization_json_hash(visualization_id, user).to_json end def export_visualization_json_hash(visualization_id, user) { version: CURRENT_VERSION, visualization: export(Carto::Visualization.find(visualization_id), user) } end private def export(visualization, user) check_valid_visualization(visualization) export_visualization(visualization, user) end def export_visualization(visualization, user) layers = visualization.layers_with_data_readable_by(user) active_layer_id = visualization.active_layer_id layer_exports = layers.map do |layer| export_layer(layer, active_layer: active_layer_id == layer.id) end { id: visualization.id, name: visualization.name, description: visualization.description, version: visualization.version, type: visualization.type, tags: visualization.tags, privacy: visualization.privacy, source: visualization.source, license: visualization.license, title: visualization.title, kind: visualization.kind, attributions: visualization.attributions, bbox: visualization.bbox, display_name: visualization.display_name, map: export_map(visualization.map), layers: layer_exports, overlays: visualization.overlays.map { |o| export_overlay(o) }, analyses: visualization.analyses.map { |a| exported_analysis(a) }, user: export_user(visualization.user), state: export_state(visualization.state), permission: export_permission(visualization.permission), synchronization: export_syncronization(visualization.synchronization), user_table: export_user_table(visualization.map.try(:user_table)), external_source: export_external_source(visualization.external_source) } end def export_user(user) { username: user.username } end def export_map(map) return nil unless map { provider: map.provider, bounding_box_sw: map.bounding_box_sw, bounding_box_ne: map.bounding_box_ne, center: map.center, zoom: map.zoom, view_bounds_sw: map.view_bounds_sw, view_bounds_ne: map.view_bounds_ne, scrollwheel: map.scrollwheel, legends: map.legends, options: map.options } end def export_overlay(overlay) { options: overlay.options, type: overlay.type, template: overlay.template } end def exported_analysis(analysis) { analysis_definition: analysis.analysis_definition } end def export_state(state) { json: state.json } end def export_permission(permission) { access_control_list: JSON.parse(permission.access_control_list, symbolize_names: true) } end def export_syncronization(synchronization) return nil unless synchronization { name: synchronization.name, interval: synchronization.interval, url: synchronization.url, state: synchronization.state, created_at: synchronization.created_at, updated_at: synchronization.updated_at, run_at: synchronization.run_at, retried_times: synchronization.retried_times, log: export_log(synchronization.log), error_code: synchronization.error_code, error_message: synchronization.error_message, ran_at: synchronization.ran_at, modified_at: synchronization.modified_at, etag: synchronization.etag, checksum: synchronization.checksum, service_name: synchronization.service_name, service_item_id: synchronization.service_item_id, type_guessing: synchronization.type_guessing, quoted_fields_guessing: synchronization.quoted_fields_guessing, content_guessing: synchronization.content_guessing } end def export_log(log) return nil unless log { type: log.type, entries: log.entries && log.entries.length > MAX_LOG_SIZE ? log.entries.slice(-MAX_LOG_SIZE..-1) : log.entries } end def export_user_table(user_table) return nil unless user_table { name: user_table.name, privacy: user_table.privacy, tags: user_table.tags, geometry_columns: user_table.geometry_columns, rows_counted: user_table.rows_counted, rows_estimated: user_table.rows_estimated, indexes: user_table.indexes, database_name: user_table.database_name, description: user_table.description, table_id: user_table.table_id, data_import: export_data_import(user_table.data_import) } end def export_data_import(data_import) return nil unless data_import { data_source: data_import.data_source, data_type: data_import.data_type, table_name: data_import.table_name, state: data_import.state, success: data_import.success, log: export_log(data_import.log), updated_at: data_import.updated_at, created_at: data_import.created_at, error_code: data_import.error_code, queue_id: data_import.queue_id, tables_created_count: data_import.tables_created_count, table_names: data_import.table_names, append: data_import.append, migrate_table: data_import.migrate_table, table_copy: data_import.table_copy, from_query: data_import.from_query, id: data_import.id, service_name: data_import.service_name, service_item_id: data_import.service_item_id, stats: data_import.stats, type_guessing: data_import.type_guessing, quoted_fields_guessing: data_import.quoted_fields_guessing, content_guessing: data_import.content_guessing, server: data_import.server, host: data_import.host, upload_host: data_import.upload_host, resque_ppid: data_import.resque_ppid, create_visualization: data_import.create_visualization, visualization_id: data_import.visualization_id, user_defined_limits: data_import.user_defined_limits, import_extra_options: data_import.import_extra_options, original_url: data_import.original_url, privacy: data_import.privacy, cartodbfy_time: data_import.cartodbfy_time, http_response_code: data_import.http_response_code, rejected_layers: data_import.rejected_layers, runner_warnings: data_import.runner_warnings, collision_strategy: data_import.collision_strategy, external_data_imports: data_import.external_data_imports.map { |edi| export_external_data_import(edi) } } end def export_external_data_import(external_data_import) { external_source_id: external_data_import.external_source_id } end def export_external_source(external_source) return nil unless external_source { id: external_source.id, import_url: external_source.import_url, rows_counted: external_source.rows_counted, size: external_source.size, username: external_source.username, geometry_types: external_source.geometry_types } end end # Both String and Hash versions are provided because `deep_symbolize_keys` won't symbolize through arrays # and having separated methods make handling and testing much easier. class VisualizationsExportService2 include VisualizationsExportService2Importer include VisualizationsExportService2Exporter end end Support empty data imports require 'json' require 'carto/export/layer_exporter' # Version History # TODO: documentation at http://cartodb.readthedocs.org/en/latest/operations/exporting_importing_visualizations.html # 2: export full visualization. Limitations: # - No Odyssey support: export fails if any of parent_id / prev_id / next_id / slide_transition_options are set. # - Privacy is exported, but permissions are not. # 2.0.1: export Widget.source_id # 2.0.2: export username # 2.0.3: export state (Carto::State) # 2.0.4: export legends (Carto::Legend) # 2.0.5: export explicit widget order # 2.0.6: export version # 2.0.7: export map options # 2.0.8: export widget style # 2.0.9: export visualization id # 2.1.0: export datasets: permissions, user_tables and syncs module Carto module VisualizationsExportService2Configuration CURRENT_VERSION = '2.1.0'.freeze MAX_LOG_SIZE = 8192 def compatible_version?(version) version.to_i == CURRENT_VERSION.split('.')[0].to_i end end module VisualizationsExportService2Validator def check_valid_visualization(visualization) raise 'Only derived or canonical visualizations can be exported' unless visualization.derived? || visualization.canonical? || visualization.remote? end end module VisualizationsExportService2Importer include VisualizationsExportService2Configuration include LayerImporter def build_visualization_from_json_export(exported_json_string) build_visualization_from_hash_export(JSON.parse(exported_json_string, symbolize_names: true)) end def build_visualization_from_hash_export(exported_hash) raise 'Wrong export version' unless compatible_version?(exported_hash[:version]) build_visualization_from_hash(exported_hash[:visualization]) end private def build_visualization_from_hash(exported_visualization) exported_layers = exported_visualization[:layers] exported_overlays = exported_visualization[:overlays] visualization = Carto::Visualization.new( name: exported_visualization[:name], description: exported_visualization[:description], version: exported_visualization[:version] || 2, type: exported_visualization[:type], tags: exported_visualization[:tags], privacy: exported_visualization[:privacy], source: exported_visualization[:source], license: exported_visualization[:license], title: exported_visualization[:title], kind: exported_visualization[:kind], attributions: exported_visualization[:attributions], bbox: exported_visualization[:bbox], display_name: exported_visualization[:display_name], map: build_map_from_hash( exported_visualization[:map], layers: build_layers_from_hash(exported_layers)), overlays: build_overlays_from_hash(exported_overlays), analyses: exported_visualization[:analyses].map { |a| build_analysis_from_hash(a) }, permission: build_permission_from_hash(exported_visualization[:permission]), external_source: build_external_source_from_hash(exported_visualization[:external_source]) ) # This is optional as it was added in version 2.0.2 exported_user = exported_visualization[:user] if exported_user visualization.user = Carto::User.new(username: exported_user[:username]) end # Added in version 2.0.3 visualization.state = build_state_from_hash(exported_visualization[:state]) active_layer_order = exported_layers.index { |l| l['active_layer'] } if active_layer_order visualization.active_layer = visualization.layers.find { |l| l.order == active_layer_order } end # Dataset-specific user_table = build_user_table_from_hash(exported_visualization[:user_table]) visualization.map.user_table = user_table if user_table visualization.synchronization = build_synchronization_from_hash(exported_visualization[:synchronization]) visualization.id = exported_visualization[:id] if exported_visualization[:id] visualization end def build_map_from_hash(exported_map, layers:) return nil unless exported_map Carto::Map.new( provider: exported_map[:provider], bounding_box_sw: exported_map[:bounding_box_sw], bounding_box_ne: exported_map[:bounding_box_ne], center: exported_map[:center], zoom: exported_map[:zoom], view_bounds_sw: exported_map[:view_bounds_sw], view_bounds_ne: exported_map[:view_bounds_ne], scrollwheel: exported_map[:scrollwheel], legends: exported_map[:legends], layers: layers, options: exported_map[:options] ) end def build_overlays_from_hash(exported_overlays) return [] unless exported_overlays exported_overlays.map.with_index.map do |overlay, i| build_overlay_from_hash(overlay, order: (i + 1)) end end def build_overlay_from_hash(exported_overlay, order:) Carto::Overlay.new( order: order, options: exported_overlay[:options], type: exported_overlay[:type], template: exported_overlay[:template] ) end def build_analysis_from_hash(exported_analysis) return nil unless exported_analysis Carto::Analysis.new(analysis_definition: exported_analysis[:analysis_definition]) end def build_state_from_hash(exported_state) Carto::State.new(json: exported_state ? exported_state[:json] : nil) end def build_permission_from_hash(exported_permission) return nil unless exported_permission Carto::Permission.new(access_control_list: JSON.dump(exported_permission[:access_control_list])) end def build_synchronization_from_hash(exported_synchronization) return nil unless exported_synchronization Carto::Synchronization.new( name: exported_synchronization[:name], interval: exported_synchronization[:interval], url: exported_synchronization[:url], state: exported_synchronization[:state], created_at: exported_synchronization[:created_at], updated_at: exported_synchronization[:updated_at], run_at: exported_synchronization[:run_at], retried_times: exported_synchronization[:retried_times], log: build_log_from_hash(exported_synchronization[:log]), error_code: exported_synchronization[:error_code], error_message: exported_synchronization[:error_message], ran_at: exported_synchronization[:ran_at], modified_at: exported_synchronization[:modified_at], etag: exported_synchronization[:etag], checksum: exported_synchronization[:checksum], service_name: exported_synchronization[:service_name], service_item_id: exported_synchronization[:service_item_id], type_guessing: exported_synchronization[:type_guessing], quoted_fields_guessing: exported_synchronization[:quoted_fields_guessing], content_guessing: exported_synchronization[:content_guessing] ) end def build_log_from_hash(exported_log) return nil unless exported_log Carto::Log.new(type: exported_log[:type], entries: exported_log[:entries]) end def build_user_table_from_hash(exported_user_table) return nil unless exported_user_table user_table = Carto::UserTable.new user_table.name = exported_user_table[:name] user_table.privacy = exported_user_table[:privacy] user_table.tags = exported_user_table[:tags] user_table.geometry_columns = exported_user_table[:geometry_columns] user_table.rows_counted = exported_user_table[:rows_counted] user_table.rows_estimated = exported_user_table[:rows_estimated] user_table.indexes = exported_user_table[:indexes] user_table.database_name = exported_user_table[:database_name] user_table.description = exported_user_table[:description] user_table.table_id = exported_user_table[:table_id] user_table.data_import = build_data_import_from_hash(exported_user_table[:data_import]) user_table end def build_data_import_from_hash(exported_data_import) return nil unless exported_data_import Carto::DataImport.new( data_source: exported_data_import[:data_source], data_type: exported_data_import[:data_type], table_name: exported_data_import[:table_name], state: exported_data_import[:state], success: exported_data_import[:success], log: build_log_from_hash(exported_data_import[:log]), updated_at: exported_data_import[:updated_at], created_at: exported_data_import[:created_at], error_code: exported_data_import[:error_code], queue_id: exported_data_import[:queue_id], tables_created_count: exported_data_import[:tables_created_count], table_names: exported_data_import[:table_names], append: exported_data_import[:append], migrate_table: exported_data_import[:migrate_table], table_copy: exported_data_import[:table_copy], from_query: exported_data_import[:from_query], id: exported_data_import[:id], service_name: exported_data_import[:service_name], service_item_id: exported_data_import[:service_item_id], stats: exported_data_import[:stats], type_guessing: exported_data_import[:type_guessing], quoted_fields_guessing: exported_data_import[:quoted_fields_guessing], content_guessing: exported_data_import[:content_guessing], server: exported_data_import[:server], host: exported_data_import[:host], upload_host: exported_data_import[:upload_host], resque_ppid: exported_data_import[:resque_ppid], create_visualization: exported_data_import[:create_visualization], visualization_id: exported_data_import[:visualization_id], user_defined_limits: exported_data_import[:user_defined_limits], import_extra_options: exported_data_import[:import_extra_options], original_url: exported_data_import[:original_url], privacy: exported_data_import[:privacy], cartodbfy_time: exported_data_import[:cartodbfy_time], http_response_code: exported_data_import[:http_response_code], rejected_layers: exported_data_import[:rejected_layers], runner_warnings: exported_data_import[:runner_warnings], collision_strategy: exported_data_import[:collision_strategy], external_data_imports: exported_data_import[:external_data_imports].map { |edi| build_external_data_import_from_hash(edi) } ) end def build_external_data_import_from_hash(exported_external_data_import) Carto::ExternalDataImport.new(external_source_id: exported_external_data_import[:external_source_id]) end def build_external_source_from_hash(exported_external_source) return nil unless exported_external_source es = Carto::ExternalSource.new( import_url: exported_external_source[:import_url], rows_counted: exported_external_source[:rows_counted], size: exported_external_source[:size], username: exported_external_source[:username], geometry_types: exported_external_source[:geometry_types] ) es.id = exported_external_source[:id] es end end module VisualizationsExportService2Exporter include VisualizationsExportService2Configuration include VisualizationsExportService2Validator include LayerExporter def export_visualization_json_string(visualization_id, user) export_visualization_json_hash(visualization_id, user).to_json end def export_visualization_json_hash(visualization_id, user) { version: CURRENT_VERSION, visualization: export(Carto::Visualization.find(visualization_id), user) } end private def export(visualization, user) check_valid_visualization(visualization) export_visualization(visualization, user) end def export_visualization(visualization, user) layers = visualization.layers_with_data_readable_by(user) active_layer_id = visualization.active_layer_id layer_exports = layers.map do |layer| export_layer(layer, active_layer: active_layer_id == layer.id) end { id: visualization.id, name: visualization.name, description: visualization.description, version: visualization.version, type: visualization.type, tags: visualization.tags, privacy: visualization.privacy, source: visualization.source, license: visualization.license, title: visualization.title, kind: visualization.kind, attributions: visualization.attributions, bbox: visualization.bbox, display_name: visualization.display_name, map: export_map(visualization.map), layers: layer_exports, overlays: visualization.overlays.map { |o| export_overlay(o) }, analyses: visualization.analyses.map { |a| exported_analysis(a) }, user: export_user(visualization.user), state: export_state(visualization.state), permission: export_permission(visualization.permission), synchronization: export_syncronization(visualization.synchronization), user_table: export_user_table(visualization.map.try(:user_table)), external_source: export_external_source(visualization.external_source) } end def export_user(user) { username: user.username } end def export_map(map) return nil unless map { provider: map.provider, bounding_box_sw: map.bounding_box_sw, bounding_box_ne: map.bounding_box_ne, center: map.center, zoom: map.zoom, view_bounds_sw: map.view_bounds_sw, view_bounds_ne: map.view_bounds_ne, scrollwheel: map.scrollwheel, legends: map.legends, options: map.options } end def export_overlay(overlay) { options: overlay.options, type: overlay.type, template: overlay.template } end def exported_analysis(analysis) { analysis_definition: analysis.analysis_definition } end def export_state(state) { json: state.json } end def export_permission(permission) { access_control_list: JSON.parse(permission.access_control_list, symbolize_names: true) } end def export_syncronization(synchronization) return nil unless synchronization { name: synchronization.name, interval: synchronization.interval, url: synchronization.url, state: synchronization.state, created_at: synchronization.created_at, updated_at: synchronization.updated_at, run_at: synchronization.run_at, retried_times: synchronization.retried_times, log: export_log(synchronization.log), error_code: synchronization.error_code, error_message: synchronization.error_message, ran_at: synchronization.ran_at, modified_at: synchronization.modified_at, etag: synchronization.etag, checksum: synchronization.checksum, service_name: synchronization.service_name, service_item_id: synchronization.service_item_id, type_guessing: synchronization.type_guessing, quoted_fields_guessing: synchronization.quoted_fields_guessing, content_guessing: synchronization.content_guessing } end def export_log(log) return nil unless log { type: log.type, entries: log.entries && log.entries.length > MAX_LOG_SIZE ? log.entries.slice(-MAX_LOG_SIZE..-1) : log.entries } end def export_user_table(user_table) return nil unless user_table { name: user_table.name, privacy: user_table.privacy, tags: user_table.tags, geometry_columns: user_table.geometry_columns, rows_counted: user_table.rows_counted, rows_estimated: user_table.rows_estimated, indexes: user_table.indexes, database_name: user_table.database_name, description: user_table.description, table_id: user_table.table_id, data_import: export_data_import(user_table.data_import) } end def export_data_import(data_import) return nil unless data_import { data_source: data_import.data_source, data_type: data_import.data_type, table_name: data_import.table_name, state: data_import.state, success: data_import.success, log: export_log(data_import.log), updated_at: data_import.updated_at, created_at: data_import.created_at, error_code: data_import.error_code, queue_id: data_import.queue_id, tables_created_count: data_import.tables_created_count, table_names: data_import.table_names, append: data_import.append, migrate_table: data_import.migrate_table, table_copy: data_import.table_copy, from_query: data_import.from_query, id: data_import.id, service_name: data_import.service_name, service_item_id: data_import.service_item_id, stats: data_import.stats, type_guessing: data_import.type_guessing, quoted_fields_guessing: data_import.quoted_fields_guessing, content_guessing: data_import.content_guessing, server: data_import.server, host: data_import.host, upload_host: data_import.upload_host, resque_ppid: data_import.resque_ppid, create_visualization: data_import.create_visualization, visualization_id: data_import.visualization_id, user_defined_limits: data_import.user_defined_limits, import_extra_options: data_import.import_extra_options, original_url: data_import.original_url, privacy: data_import.privacy, cartodbfy_time: data_import.cartodbfy_time, http_response_code: data_import.http_response_code, rejected_layers: data_import.rejected_layers, runner_warnings: data_import.runner_warnings, collision_strategy: data_import.collision_strategy, external_data_imports: data_import.external_data_imports.map { |edi| export_external_data_import(edi) } } end def export_external_data_import(external_data_import) { external_source_id: external_data_import.external_source_id } end def export_external_source(external_source) return nil unless external_source { id: external_source.id, import_url: external_source.import_url, rows_counted: external_source.rows_counted, size: external_source.size, username: external_source.username, geometry_types: external_source.geometry_types } end end # Both String and Hash versions are provided because `deep_symbolize_keys` won't symbolize through arrays # and having separated methods make handling and testing much easier. class VisualizationsExportService2 include VisualizationsExportService2Importer include VisualizationsExportService2Exporter end end
require "formula" class Osgearth < Formula homepage "http://osgearth.org" url "https://github.com/gwaldron/osgearth/archive/osgearth-2.5.tar.gz" sha1 "97ed0075422c3efcb7b958f89ae02b32d670c48e" head "https://github.com/gwaldron/osgearth.git", :branch => "master" option "without-minizip", "Build without Google KMZ file access support" option "with-v8", "Build with Google's V8 JavaScript engine support" option "with-tinyxml", "Use external libtinyxml, instead of internal" option "with-docs-examples", "Build and install html documentation and examples" depends_on "cmake" => :build depends_on "open-scene-graph" depends_on "gdal" depends_on "sqlite" depends_on "qt" => :recommended depends_on "minizip" => :recommended depends_on "v8" => :optional depends_on "tinyxml" => :optional resource "sphinx" do url "https://pypi.python.org/packages/source/S/Sphinx/Sphinx-1.2.1.tar.gz" sha1 "448cdb89d96c85993e01fe793ce7786494cbcda7" end # all merged upstream, remove on next version # find a v8 lib: https://github.com/gwaldron/osgearth/pull/434 # find JavaScriptCore lib: https://github.com/gwaldron/osgearth/pull/435 # find libnoise lib: https://github.com/gwaldron/osgearth/pull/436 patch :DATA def install if build.with? "docs-examples" and not which("sphinx-build") # temporarily vendor a local sphinx install sphinx_dir = prefix/"sphinx" sphinx_site = sphinx_dir/"lib/python2.7/site-packages" sphinx_site.mkpath ENV.prepend_create_path "PYTHONPATH", sphinx_site resource("sphinx").stage {quiet_system "python2.7", "setup.py", "install", "--prefix=#{sphinx_dir}"} ENV.prepend_path "PATH", sphinx_dir/"bin" end args = std_cmake_args if MacOS.prefer_64_bit? args << "-DCMAKE_OSX_ARCHITECTURES=#{Hardware::CPU.arch_64_bit}" else args << "-DCMAKE_OSX_ARCHITECTURES=i386" end args << "-DOSGEARTH_USE_QT=OFF" if build.without? "qt" args << "-DWITH_EXTERNAL_TINYXML=ON" if build.with? "tinyxml" # v8 and minizip options should have empty values if not defined '--with' if build.without? "v8" args << "-DV8_INCLUDE_DIR=''" << "-DV8_BASE_LIBRARY=''" << "-DV8_SNAPSHOT_LIBRARY=''" args << "-DV8_ICUI18N_LIBRARY=''" << "-DV8_ICUUC_LIBRARY=''" end # define libminizip paths (skips the only pkconfig dependency in cmake modules) mzo = Formula["minizip"].opt_prefix args << "-DMINIZIP_INCLUDE_DIR=#{(build.with? "minizip") ? mzo/"include/minizip" : "''"}" args << "-DMINIZIP_LIBRARY=#{(build.with? "minizip") ? mzo/"lib/libminizip.dylib" : "''"}" mkdir "build" do system "cmake", "..", *args system "make", "install" end if build.with? "docs-examples" cd "docs" do system "make", "html" doc.install "build/html" => "html" end doc.install "data" doc.install "tests" => "examples" rm_r prefix/"sphinx" if File.exist?(prefix/"sphinx") end end def caveats osg = Formula["open-scene-graph"] osgver = (osg.linked_keg.exist?) ? osg.version : "#.#.# (version)" <<-EOS.undent This formula installs Open Scene Graph plugins. To ensure access when using the osgEarth toolset, set the OSG_LIBRARY_PATH enviroment variable to: #{HOMEBREW_PREFIX}/lib/osgPlugins-#{osgver} EOS end test do system "#{bin}/osgearth_version" end end __END__ diff --git a/CMakeModules/FindV8.cmake b/CMakeModules/FindV8.cmake index 9f5684d..94cf4c4 100644 --- a/CMakeModules/FindV8.cmake +++ b/CMakeModules/FindV8.cmake @@ -21,7 +21,7 @@ FIND_PATH(V8_INCLUDE_DIR v8.h ) FIND_LIBRARY(V8_BASE_LIBRARY - NAMES v8_base v8_base.ia32 libv8_base + NAMES v8_base v8_base.ia32 v8_base.x64 libv8_base PATHS ${V8_DIR} ${V8_DIR}/lib @@ -40,7 +40,7 @@ FIND_LIBRARY(V8_BASE_LIBRARY ) FIND_LIBRARY(V8_BASE_LIBRARY_DEBUG - NAMES v8_base v8_base.ia32 libv8_base + NAMES v8_base v8_base.ia32 v8_base.x64 libv8_base PATHS ${V8_DIR} ${V8_DIR}/lib diff --git a/CMakeModules/FindJavaScriptCore.cmake b/CMakeModules/FindJavaScriptCore.cmake index 1bca250..3877cd5 100644 --- a/CMakeModules/FindJavaScriptCore.cmake +++ b/CMakeModules/FindJavaScriptCore.cmake @@ -21,7 +21,7 @@ FIND_PATH(JAVASCRIPTCORE_INCLUDE_DIR JavaScriptCore.h ) FIND_LIBRARY(JAVASCRIPTCORE_LIBRARY - NAMES libJavaScriptCore + NAMES libJavaScriptCore JavaScriptCore PATHS ${JAVASCRIPTCORE_DIR} ${JAVASCRIPTCORE_DIR}/lib diff --git a/CMakeModules/FindLibNoise.cmake b/CMakeModules/FindLibNoise.cmake index 99d006b..0051b51 100644 --- a/CMakeModules/FindLibNoise.cmake +++ b/CMakeModules/FindLibNoise.cmake @@ -43,7 +43,7 @@ FIND_LIBRARY(LIBNOISE_LIBRARY ) FIND_LIBRARY(LIBNOISE_LIBRARY - NAMES libnoise + NAMES libnoise noise PATHS ~/Library/Frameworks /Library/Frameworks osgearth: build open-scene-graph with Qt Fixes #1238. require "formula" class Osgearth < Formula homepage "http://osgearth.org" url "https://github.com/gwaldron/osgearth/archive/osgearth-2.5.tar.gz" sha1 "97ed0075422c3efcb7b958f89ae02b32d670c48e" head "https://github.com/gwaldron/osgearth.git", :branch => "master" option "without-minizip", "Build without Google KMZ file access support" option "with-v8", "Build with Google's V8 JavaScript engine support" option "with-tinyxml", "Use external libtinyxml, instead of internal" option "with-docs-examples", "Build and install html documentation and examples" depends_on "cmake" => :build depends_on "open-scene-graph" => (build.with? "qt") ? ["with-qt"] : [] depends_on "gdal" depends_on "sqlite" depends_on "qt" => :recommended depends_on "minizip" => :recommended depends_on "v8" => :optional depends_on "tinyxml" => :optional resource "sphinx" do url "https://pypi.python.org/packages/source/S/Sphinx/Sphinx-1.2.1.tar.gz" sha1 "448cdb89d96c85993e01fe793ce7786494cbcda7" end # all merged upstream, remove on next version # find a v8 lib: https://github.com/gwaldron/osgearth/pull/434 # find JavaScriptCore lib: https://github.com/gwaldron/osgearth/pull/435 # find libnoise lib: https://github.com/gwaldron/osgearth/pull/436 patch :DATA def install if build.with? "docs-examples" and not which("sphinx-build") # temporarily vendor a local sphinx install sphinx_dir = prefix/"sphinx" sphinx_site = sphinx_dir/"lib/python2.7/site-packages" sphinx_site.mkpath ENV.prepend_create_path "PYTHONPATH", sphinx_site resource("sphinx").stage {quiet_system "python2.7", "setup.py", "install", "--prefix=#{sphinx_dir}"} ENV.prepend_path "PATH", sphinx_dir/"bin" end args = std_cmake_args if MacOS.prefer_64_bit? args << "-DCMAKE_OSX_ARCHITECTURES=#{Hardware::CPU.arch_64_bit}" else args << "-DCMAKE_OSX_ARCHITECTURES=i386" end args << "-DOSGEARTH_USE_QT=OFF" if build.without? "qt" args << "-DWITH_EXTERNAL_TINYXML=ON" if build.with? "tinyxml" # v8 and minizip options should have empty values if not defined '--with' if build.without? "v8" args << "-DV8_INCLUDE_DIR=''" << "-DV8_BASE_LIBRARY=''" << "-DV8_SNAPSHOT_LIBRARY=''" args << "-DV8_ICUI18N_LIBRARY=''" << "-DV8_ICUUC_LIBRARY=''" end # define libminizip paths (skips the only pkconfig dependency in cmake modules) mzo = Formula["minizip"].opt_prefix args << "-DMINIZIP_INCLUDE_DIR=#{(build.with? "minizip") ? mzo/"include/minizip" : "''"}" args << "-DMINIZIP_LIBRARY=#{(build.with? "minizip") ? mzo/"lib/libminizip.dylib" : "''"}" mkdir "build" do system "cmake", "..", *args system "make", "install" end if build.with? "docs-examples" cd "docs" do system "make", "html" doc.install "build/html" => "html" end doc.install "data" doc.install "tests" => "examples" rm_r prefix/"sphinx" if File.exist?(prefix/"sphinx") end end def caveats osg = Formula["open-scene-graph"] osgver = (osg.linked_keg.exist?) ? osg.version : "#.#.# (version)" <<-EOS.undent This formula installs Open Scene Graph plugins. To ensure access when using the osgEarth toolset, set the OSG_LIBRARY_PATH enviroment variable to: #{HOMEBREW_PREFIX}/lib/osgPlugins-#{osgver} EOS end test do system "#{bin}/osgearth_version" end end __END__ diff --git a/CMakeModules/FindV8.cmake b/CMakeModules/FindV8.cmake index 9f5684d..94cf4c4 100644 --- a/CMakeModules/FindV8.cmake +++ b/CMakeModules/FindV8.cmake @@ -21,7 +21,7 @@ FIND_PATH(V8_INCLUDE_DIR v8.h ) FIND_LIBRARY(V8_BASE_LIBRARY - NAMES v8_base v8_base.ia32 libv8_base + NAMES v8_base v8_base.ia32 v8_base.x64 libv8_base PATHS ${V8_DIR} ${V8_DIR}/lib @@ -40,7 +40,7 @@ FIND_LIBRARY(V8_BASE_LIBRARY ) FIND_LIBRARY(V8_BASE_LIBRARY_DEBUG - NAMES v8_base v8_base.ia32 libv8_base + NAMES v8_base v8_base.ia32 v8_base.x64 libv8_base PATHS ${V8_DIR} ${V8_DIR}/lib diff --git a/CMakeModules/FindJavaScriptCore.cmake b/CMakeModules/FindJavaScriptCore.cmake index 1bca250..3877cd5 100644 --- a/CMakeModules/FindJavaScriptCore.cmake +++ b/CMakeModules/FindJavaScriptCore.cmake @@ -21,7 +21,7 @@ FIND_PATH(JAVASCRIPTCORE_INCLUDE_DIR JavaScriptCore.h ) FIND_LIBRARY(JAVASCRIPTCORE_LIBRARY - NAMES libJavaScriptCore + NAMES libJavaScriptCore JavaScriptCore PATHS ${JAVASCRIPTCORE_DIR} ${JAVASCRIPTCORE_DIR}/lib diff --git a/CMakeModules/FindLibNoise.cmake b/CMakeModules/FindLibNoise.cmake index 99d006b..0051b51 100644 --- a/CMakeModules/FindLibNoise.cmake +++ b/CMakeModules/FindLibNoise.cmake @@ -43,7 +43,7 @@ FIND_LIBRARY(LIBNOISE_LIBRARY ) FIND_LIBRARY(LIBNOISE_LIBRARY - NAMES libnoise + NAMES libnoise noise PATHS ~/Library/Frameworks /Library/Frameworks
object @container_taxonomy if set = params[:set] extends "spree/api/v1/container_taxonomies/#{set}" else attributes *container_taxonomy_attributes child :root => :root do attributes *container_taxon_attributes child :children => :container_taxons do attributes *container_taxon_attributes end end end Added variants to container taxonomy api view object @container_taxonomy if set = params[:set] extends "spree/api/v1/container_taxonomies/#{set}" else attributes *container_taxonomy_attributes child :root => :root do attributes *container_taxon_attributes child :variants => :variants do attributes *variant_attributes end child :children => :container_taxons do attributes *container_taxon_attributes child :variants => :variants do attributes *variant_attributes end end end end
module Cldr module Export module Data class Calendars class Gregorian < Base def initialize(locale) super update( :months => contexts('month'), :days => contexts('day'), :eras => eras, :quarters => contexts('quarter'), :periods => contexts('dayPeriod', :group => "alt"), :fields => fields, :formats => { :date => formats('date'), :time => formats('time'), :datetime => formats('dateTime') }, :additional_formats => additional_formats ) end def calendar @calendar ||= select('dates/calendars/calendar[@type="gregorian"]').first end def contexts(kind, options = {}) select(calendar, "#{kind}s/#{kind}Context").inject({}) do |result, node| context = node.attribute('type').value.to_sym result[context] = widths(node, kind, context, options) result end end def widths(node, kind, context, options = {}) select(node, "#{kind}Width").inject({}) do |result, node| width = node.attribute('type').value.to_sym result[width] = elements(node, kind, context, width, options) result end end def elements(node, kind, context, width, options = {}) aliased = select(node, 'alias').first if aliased xpath_to_key(aliased.attribute('path').value, kind, context, width) else select(node, kind).inject({}) do |result, node| key = node.attribute('type').value key = key =~ /^\d*$/ ? key.to_i : key.to_sym if options[:group] && found_group = node.attribute(options[:group]) result[found_group.value] ||= {} result[found_group.value][key] = node.content else result[key] = node.content end result end end end def xpath_to_key(xpath, kind, context, width) kind = (xpath =~ %r(/([^\/]*)Width) && $1) || kind context = (xpath =~ %r(Context\[@type='([^\/]*)'\]) && $1) || context width = (xpath =~ %r(Width\[@type='([^\/]*)'\]) && $1) || width :"calendars.gregorian.#{kind}s.#{context}.#{width}" end def xpath_width end def periods am = select(calendar, "am").first pm = select(calendar, "pm").first result = {} result[:am] = am.content if am result[:pm] = pm.content if pm result end def eras if calendar base_path = calendar.path.gsub('/ldml/', '') + '/eras' keys = select("#{base_path}/*").map { |node| node.name } keys.inject({}) do |result, name| path = "#{base_path}/#{name}/*" key = name.gsub('era', '').gsub(/s$/, '').downcase.to_sym result[key] = select(path).inject({}) do |ret, node| type = node.attribute('type').value.to_i rescue 0 ret[type] = node.content ret end result end else {} end end def extract(path, lambdas) nodes = select(path) nodes.inject({}) do |ret, node| key = lambdas[:key].call(node) ret[key] = lambdas[:value].call(node) ret end end def formats(type) formats = select(calendar, "#{type}Formats/#{type}FormatLength").inject({}) do |result, node| key = node.attribute('type').value.to_sym rescue :format result[key] = pattern(node, type) result end if default = default_format(type) formats = default.merge(formats) end formats end def additional_formats select(calendar, "dateTimeFormats/availableFormats/dateFormatItem").inject({}) do |result, node| key = node.attribute('id').value result[key] = node.content result end end def default_format(type) if node = select(calendar, "#{type}Formats/default").first key = node.attribute('choice').value.to_sym { :default => :"calendars.gregorian.formats.#{type.downcase}.#{key}" } end end def pattern(node, type) select(node, "#{type}Format/pattern").inject({}) do |result, node| pattern = node.content pattern = pattern.gsub('{0}', '{{time}}').gsub('{1}', '{{date}}') if type == 'dateTime' result[:pattern] = pattern result end end # NOTE: As of CLDR 23, this data moved from inside each "calendar" tag to under its parent, the "dates" tag. # That probably means this `fields` method should be moved up to the parent as well. def fields select("dates/fields/field").inject({}) do |result, node| key = node.attribute('type').value.to_sym name = node.xpath('displayName').first result[key] = name.content if name result end end end end end end end Remove `:format` default for `Gregorian#formats` `:format` is not a valid `type` anyway, so it would never match anyway. In the `ldml.dtd`: * For `dateFormatLength`, `timeFormatLength` the `type` attribute is `#REQUIRED`. * For `dateTimeFormatLength`, `type` attribute is `#IMPLIED` There are no instances in the code where any of these are missing the `type` attribute. So while in the future it could technically happen for `dateTimeFormatLength`, I'd rather the code fail in that case, then silently pass with a nonsense value. module Cldr module Export module Data class Calendars class Gregorian < Base def initialize(locale) super update( :months => contexts('month'), :days => contexts('day'), :eras => eras, :quarters => contexts('quarter'), :periods => contexts('dayPeriod', :group => "alt"), :fields => fields, :formats => { :date => formats('date'), :time => formats('time'), :datetime => formats('dateTime') }, :additional_formats => additional_formats ) end def calendar @calendar ||= select('dates/calendars/calendar[@type="gregorian"]').first end def contexts(kind, options = {}) select(calendar, "#{kind}s/#{kind}Context").inject({}) do |result, node| context = node.attribute('type').value.to_sym result[context] = widths(node, kind, context, options) result end end def widths(node, kind, context, options = {}) select(node, "#{kind}Width").inject({}) do |result, node| width = node.attribute('type').value.to_sym result[width] = elements(node, kind, context, width, options) result end end def elements(node, kind, context, width, options = {}) aliased = select(node, 'alias').first if aliased xpath_to_key(aliased.attribute('path').value, kind, context, width) else select(node, kind).inject({}) do |result, node| key = node.attribute('type').value key = key =~ /^\d*$/ ? key.to_i : key.to_sym if options[:group] && found_group = node.attribute(options[:group]) result[found_group.value] ||= {} result[found_group.value][key] = node.content else result[key] = node.content end result end end end def xpath_to_key(xpath, kind, context, width) kind = (xpath =~ %r(/([^\/]*)Width) && $1) || kind context = (xpath =~ %r(Context\[@type='([^\/]*)'\]) && $1) || context width = (xpath =~ %r(Width\[@type='([^\/]*)'\]) && $1) || width :"calendars.gregorian.#{kind}s.#{context}.#{width}" end def xpath_width end def periods am = select(calendar, "am").first pm = select(calendar, "pm").first result = {} result[:am] = am.content if am result[:pm] = pm.content if pm result end def eras if calendar base_path = calendar.path.gsub('/ldml/', '') + '/eras' keys = select("#{base_path}/*").map { |node| node.name } keys.inject({}) do |result, name| path = "#{base_path}/#{name}/*" key = name.gsub('era', '').gsub(/s$/, '').downcase.to_sym result[key] = select(path).inject({}) do |ret, node| type = node.attribute('type').value.to_i rescue 0 ret[type] = node.content ret end result end else {} end end def extract(path, lambdas) nodes = select(path) nodes.inject({}) do |ret, node| key = lambdas[:key].call(node) ret[key] = lambdas[:value].call(node) ret end end def formats(type) formats = select(calendar, "#{type}Formats/#{type}FormatLength").inject({}) do |result, node| key = node.attribute('type').value.to_sym result[key] = pattern(node, type) result end if default = default_format(type) formats = default.merge(formats) end formats end def additional_formats select(calendar, "dateTimeFormats/availableFormats/dateFormatItem").inject({}) do |result, node| key = node.attribute('id').value result[key] = node.content result end end def default_format(type) if node = select(calendar, "#{type}Formats/default").first key = node.attribute('choice').value.to_sym { :default => :"calendars.gregorian.formats.#{type.downcase}.#{key}" } end end def pattern(node, type) select(node, "#{type}Format/pattern").inject({}) do |result, node| pattern = node.content pattern = pattern.gsub('{0}', '{{time}}').gsub('{1}', '{{date}}') if type == 'dateTime' result[:pattern] = pattern result end end # NOTE: As of CLDR 23, this data moved from inside each "calendar" tag to under its parent, the "dates" tag. # That probably means this `fields` method should be moved up to the parent as well. def fields select("dates/fields/field").inject({}) do |result, node| key = node.attribute('type').value.to_sym name = node.xpath('displayName').first result[key] = name.content if name result end end end end end end end
require 'concurrent/edge/lock_free_linked_set/node' require 'concurrent/edge/lock_free_linked_set/window' module Concurrent module Edge # This class implements a lock-free linked set. The general idea of this # implementation is this: each node has a successor which is an Atomic # Markable Reference. This is used to ensure that all modifications to the # list are atomic, preserving the structure of the linked list under _any_ # circumstance in a multithreaded application. # # One interesting aspect of this algorithm occurs with removing a node. # Instead of physically removing a node when remove is called, a node is # logically removed, by 'marking it.' By doing this, we prevent calls to # `remove` from traversing the list twice to perform a physical removal. # Instead, we have have calls to `add` and `remove` clean up all marked # nodes they encounter while traversing the list. # # This algorithm is a variation of the Nonblocking Linked Set found in # 'The Art of Multiprocessor Programming' by Herlihy and Shavit. class LockFreeLinkedSet include Enumerable # @!macro [attach] lock_free_linked_list_method_initialize # # @param [Fixnum] initial_size the size of the linked_list to initialize def initialize(initial_size = 0, val = nil) @head = Head.new initial_size.times do val = block_given? ? yield : val add val end end # @!macro [attach] lock_free_linked_list_method_add # # Atomically adds the item to the set if it does not yet exist. Note: # internally the set uses `Object#hash` to compare equality of items, # meaning that Strings and other objects will be considered equal # despite being different objects. # # @param [Object] item the item you wish to insert # # @return [Boolean] `true` if successful. A `false` return indicates # that the item was already in the set. def add(item) loop do window = Window.find @head, item pred, curr = window.pred, window.curr # Item already in set return false if curr == item node = Node.new item, curr if pred.Successor_reference.compare_and_set curr, node, false, false return true end end end # @!macro [attach] lock_free_linked_list_method_<< # # Atomically adds the item to the set if it does not yet exist. # # @param [Object] item the item you wish to insert # # @return [Oject] the set on which the :<< method was invoked def <<(item) add item self end # @!macro [attach] lock_free_linked_list_method_contains # # Atomically checks to see if the set contains an item. This method # compares equality based on the `Object#hash` method, meaning that the # hashed contents of an object is what determines equality instead of # `Object#object_id` # # @param [Object] item the item you to check for presence in the set # # @return [Boolean] whether or not the item is in the set def contains?(item) curr = @head while curr < item curr = curr.next_node marked = curr.Successor_reference.marked? end curr == item && !marked end # @!macro [attach] lock_free_linked_list_method_remove # # Atomically attempts to remove an item, comparing using `Object#hash`. # # @param [Object] item the item you to remove from the set # # @return [Boolean] whether or not the item was removed from the set def remove(item) loop do window = Window.find @head, item pred, curr = window.pred, window.curr return false if curr != item succ = curr.next_node removed = curr.Successor_reference.compare_and_set succ, succ, false, true next_node unless removed pred.Successor_reference.compare_and_set curr, succ, false, false return true end end # @!macro [attach] lock_free_linked_list_method_each # # An iterator to loop through the set. # # @param [Object] item the item you to remove from the set # @yeild [Object] each item in the set # # @return [Object] self: the linked set on which each was called def each return to_enum unless block_given? curr = @head until curr.last? curr = curr.next_node marked = curr.Successor_reference.marked? yield curr.Data unless marked end self end end end end Fixed yardoc error. require 'concurrent/edge/lock_free_linked_set/node' require 'concurrent/edge/lock_free_linked_set/window' module Concurrent module Edge # This class implements a lock-free linked set. The general idea of this # implementation is this: each node has a successor which is an Atomic # Markable Reference. This is used to ensure that all modifications to the # list are atomic, preserving the structure of the linked list under _any_ # circumstance in a multithreaded application. # # One interesting aspect of this algorithm occurs with removing a node. # Instead of physically removing a node when remove is called, a node is # logically removed, by 'marking it.' By doing this, we prevent calls to # `remove` from traversing the list twice to perform a physical removal. # Instead, we have have calls to `add` and `remove` clean up all marked # nodes they encounter while traversing the list. # # This algorithm is a variation of the Nonblocking Linked Set found in # 'The Art of Multiprocessor Programming' by Herlihy and Shavit. class LockFreeLinkedSet include Enumerable # @!macro [attach] lock_free_linked_list_method_initialize # # @param [Fixnum] initial_size the size of the linked_list to initialize def initialize(initial_size = 0, val = nil) @head = Head.new initial_size.times do val = block_given? ? yield : val add val end end # @!macro [attach] lock_free_linked_list_method_add # # Atomically adds the item to the set if it does not yet exist. Note: # internally the set uses `Object#hash` to compare equality of items, # meaning that Strings and other objects will be considered equal # despite being different objects. # # @param [Object] item the item you wish to insert # # @return [Boolean] `true` if successful. A `false` return indicates # that the item was already in the set. def add(item) loop do window = Window.find @head, item pred, curr = window.pred, window.curr # Item already in set return false if curr == item node = Node.new item, curr if pred.Successor_reference.compare_and_set curr, node, false, false return true end end end # @!macro [attach] lock_free_linked_list_method_<< # # Atomically adds the item to the set if it does not yet exist. # # @param [Object] item the item you wish to insert # # @return [Oject] the set on which the :<< method was invoked def <<(item) add item self end # @!macro [attach] lock_free_linked_list_method_contains # # Atomically checks to see if the set contains an item. This method # compares equality based on the `Object#hash` method, meaning that the # hashed contents of an object is what determines equality instead of # `Object#object_id` # # @param [Object] item the item you to check for presence in the set # # @return [Boolean] whether or not the item is in the set def contains?(item) curr = @head while curr < item curr = curr.next_node marked = curr.Successor_reference.marked? end curr == item && !marked end # @!macro [attach] lock_free_linked_list_method_remove # # Atomically attempts to remove an item, comparing using `Object#hash`. # # @param [Object] item the item you to remove from the set # # @return [Boolean] whether or not the item was removed from the set def remove(item) loop do window = Window.find @head, item pred, curr = window.pred, window.curr return false if curr != item succ = curr.next_node removed = curr.Successor_reference.compare_and_set succ, succ, false, true next_node unless removed pred.Successor_reference.compare_and_set curr, succ, false, false return true end end # @!macro [attach] lock_free_linked_list_method_each # # An iterator to loop through the set. # # @yield [Object] each item in the set # @yieldparam [Object] item the item you to remove from the set # # @return [Object] self: the linked set on which each was called def each return to_enum unless block_given? curr = @head until curr.last? curr = curr.next_node marked = curr.Successor_reference.marked? yield curr.Data unless marked end self end end end end
require 'rspec/core/rake_task' require 'kitchen/rake_tasks' require 'foodcritic' require 'berkshelf' module CookbookDevelopment class TestTasks < Rake::TaskLib attr_reader :project_dir def initialize @project_dir = Dir.pwd yield(self) if block_given? define end def define kitchen_config = Kitchen::Config.new Kitchen.logger = Kitchen.default_file_logger namespace "kitchen" do kitchen_config.instances.each do |instance| desc "Run #{instance.name} test instance" task instance.name do destroy = (ENV['KITCHEN_DESTROY'] || 'passing').to_sym instance.test(destroy) end end desc "Run all test instances" task :all do destroy = ENV['KITCHEN_DESTROY'] || 'passing' concurrency = ENV['KITCHEN_CONCURRENCY'] || '1' require 'kitchen/cli' Kitchen::CLI.new([], {concurrency: concurrency.to_i, destroy: destroy}).test() end end desc 'Runs Foodcritic linting' FoodCritic::Rake::LintTask.new do |task| task.options = { :search_gems => true, :fail_tags => ['any'], :tags => ['~FC003', '~FC015'], :exclude_paths => ['vendor/**/*'] } end desc 'Runs unit tests' RSpec::Core::RakeTask.new(:unit) do |task| task.pattern = FileList[File.join(project_dir, 'test', 'unit', '**/*_spec.rb')] end desc 'Runs integration tests' task :integration do Rake::Task['kitchen:all'].invoke end desc 'Run all tests and linting' task :test do Rake::Task['foodcritic'].invoke Rake::Task['unit'].invoke Rake::Task['integration'].invoke end task :unit_test_header do puts "-----> Running unit tests with chefspec".cyan end task :unit => :unit_test_header task :foodcritic_header do puts "-----> Linting with foodcritic".cyan end task :foodcritic => :foodcritic_header task :integration_header do puts "-----> Running integration tests with test-kitchen".cyan end task :integration => :integration_header end end end Ignore some tags. (#24) require 'rspec/core/rake_task' require 'kitchen/rake_tasks' require 'foodcritic' require 'berkshelf' module CookbookDevelopment class TestTasks < Rake::TaskLib attr_reader :project_dir def initialize @project_dir = Dir.pwd yield(self) if block_given? define end def define kitchen_config = Kitchen::Config.new Kitchen.logger = Kitchen.default_file_logger namespace "kitchen" do kitchen_config.instances.each do |instance| desc "Run #{instance.name} test instance" task instance.name do destroy = (ENV['KITCHEN_DESTROY'] || 'passing').to_sym instance.test(destroy) end end desc "Run all test instances" task :all do destroy = ENV['KITCHEN_DESTROY'] || 'passing' concurrency = ENV['KITCHEN_CONCURRENCY'] || '1' require 'kitchen/cli' Kitchen::CLI.new([], {concurrency: concurrency.to_i, destroy: destroy}).test() end end desc 'Runs Foodcritic linting' FoodCritic::Rake::LintTask.new do |task| task.options = { :search_gems => true, :fail_tags => ['any'], :tags => ['~FC003', '~FC015', '~FC064', '~FC065', '~FC066', '~FC067'], :exclude_paths => ['vendor/**/*'] } end desc 'Runs unit tests' RSpec::Core::RakeTask.new(:unit) do |task| task.pattern = FileList[File.join(project_dir, 'test', 'unit', '**/*_spec.rb')] end desc 'Runs integration tests' task :integration do Rake::Task['kitchen:all'].invoke end desc 'Run all tests and linting' task :test do Rake::Task['foodcritic'].invoke Rake::Task['unit'].invoke Rake::Task['integration'].invoke end task :unit_test_header do puts "-----> Running unit tests with chefspec".cyan end task :unit => :unit_test_header task :foodcritic_header do puts "-----> Linting with foodcritic".cyan end task :foodcritic => :foodcritic_header task :integration_header do puts "-----> Running integration tests with test-kitchen".cyan end task :integration => :integration_header end end end
module DataMapper module Validate ## # # @author Guy van den Berg # @since 0.9 class ContextualValidators def dump contexts.each_pair do |key,context| puts "Key=#{key} Context: #{context}" end end # Get a hash of named context validators for the resource # # @return <Hash> a hash of validators <GenericValidator> def contexts @contexts ||= @contexts = {} end # Return an array of validators for a named context # # @return <Array> An array of validators def context(name) contexts[name] = [] unless contexts.has_key?(name) contexts[name] end # Clear all named context validators off of the resource # def clear! contexts.clear end # Execute all validators in the named context against the target # # @param <Symbol> named_context the context we are validating against # @param <Object> target the resource that we are validating # @return <Boolean> true if all are valid, otherwise false def execute(named_context, target) raise(ArgumentError, 'invalid context specified') if !named_context || (contexts.length > 0 && !contexts[named_context]) target.errors.clear! result = true context(named_context).each do |validator| next unless validator.execute?(target) result = false unless validator.call(target) end result end end # module ContextualValidators end # module Validate end # module DataMapper [dm-validations] Minor code cleanup module DataMapper module Validate ## # # @author Guy van den Berg # @since 0.9 class ContextualValidators def dump contexts.each_pair do |key,context| puts "Key=#{key} Context: #{context}" end end # Get a hash of named context validators for the resource # # @return <Hash> a hash of validators <GenericValidator> def contexts @contexts ||= {} end # Return an array of validators for a named context # # @return <Array> An array of validators def context(name) contexts[name] ||= [] end # Clear all named context validators off of the resource # def clear! contexts.clear end # Execute all validators in the named context against the target # # @param <Symbol> named_context the context we are validating against # @param <Object> target the resource that we are validating # @return <Boolean> true if all are valid, otherwise false def execute(named_context, target) raise(ArgumentError, 'invalid context specified') if !named_context || (contexts.length > 0 && !contexts[named_context]) target.errors.clear! result = true context(named_context).each do |validator| next unless validator.execute?(target) result = false unless validator.call(target) end result end end # module ContextualValidators end # module Validate end # module DataMapper
require "securerandom" require "dry/web/roda/generators/abstract_generator" module Dry module Web module Roda module Generators class FlatProject < AbstractGenerator def populate_templates add_bin add_config add_db add_log add_specs add_lib add_system add_web add_config_files end private def destination target_dir end def template_scope { underscored_project_name: underscored_project_name, camel_cased_app_name: Inflections.camel_cased_name(target_dir) } end def add_bin add_template('console.tt', 'bin/console') add_template('setup', 'bin/setup') end def add_config add_template('settings.yml.tt', 'config/settings.yml') end def add_db add_template('sample_data.rb', 'db/sample_data.rb') add_template('seed.rb', 'db/seed.rb') end def add_lib add_template('operation.rb.tt', "lib/#{underscored_project_name}/operation.rb") add_template('view_context.rb.tt', "lib/#{underscored_project_name}/view/context.rb") add_template('view_controller.rb.tt', "lib/#{underscored_project_name}/view/controller.rb") add_template('welcome.rb.tt', "lib/#{underscored_project_name}/views/welcome.rb") add_template('.keep', "lib/#{underscored_project_name}/.keep") add_template('.keep', 'lib/persistance/commands/.keep') add_template('.keep', 'lib/persistance/relations/.keep') add_template('types.rb', 'lib/types.rb') end def add_log add_template('.keep', 'log/.keep') end def add_specs add_template('test_factories.rb', 'spec/support/db/test_factories.rb') add_template('test_helpers.rb.tt', 'spec/support/test_helpers.rb') add_template('app_helper.rb', 'spec/app_helper.rb') add_template('db_helper.rb.tt', 'spec/db_helper.rb') add_template('spec_helper.rb.tt', 'spec/spec_helper.rb') end def add_system add_system_app_folder add_system_boot end def add_system_app_folder %w(application container import repository settings).each do |file| add_template("#{file}.rb.tt", "system/#{underscored_project_name}/#{file}.rb") end end def add_system_boot %w(monitor rom).each do |file| add_template("#{file}.rb.tt", "system/boot/#{file}.rb") end add_template('boot.rb.tt', 'system/boot.rb') end def add_web add_template('example_routes.rb.tt', 'web/routes/example.rb') add_template('application.html.slim', 'web/templates/layouts/application.html.slim') add_template('welcome.html.slim', 'web/templates/welcome.html.slim') end def add_config_files add_template('.gitignore', '.gitignore') add_template('Gemfile', 'Gemfile') add_template('Rakefile.tt', 'Rakefile') add_template('config.ru.tt', 'config.ru') add_template('README.md.tt', 'README.md') end end end end end end Tidy template setup a little require "securerandom" require "dry/web/roda/generators/abstract_generator" module Dry module Web module Roda module Generators class FlatProject < AbstractGenerator def populate_templates add_bin add_config add_db add_log add_specs add_lib add_system add_web add_config_files end private def destination target_dir end def template_scope { underscored_project_name: underscored_project_name, camel_cased_app_name: Inflections.camel_cased_name(target_dir) } end def add_bin add_template('console.tt', 'bin/console') add_template('setup', 'bin/setup') end def add_config add_template('settings.yml.tt', 'config/settings.yml') end def add_db add_template('sample_data.rb', 'db/sample_data.rb') add_template('seed.rb', 'db/seed.rb') end def add_lib add_template('types.rb', 'lib/types.rb') add_template('operation.rb.tt', "lib/#{underscored_project_name}/operation.rb") add_template('repository.rb.tt', "lib/#{underscored_project_name}/repository.rb") add_template('.keep', 'lib/persistance/relations/.keep') add_template('.keep', 'lib/persistance/commands/.keep') add_template('view_context.rb.tt', "lib/#{underscored_project_name}/view/context.rb") add_template('view_controller.rb.tt', "lib/#{underscored_project_name}/view/controller.rb") add_template('welcome.rb.tt', "lib/#{underscored_project_name}/views/welcome.rb") end def add_log add_template('.keep', 'log/.keep') end def add_specs add_template('test_factories.rb', 'spec/support/db/test_factories.rb') add_template('test_helpers.rb.tt', 'spec/support/test_helpers.rb') add_template('app_helper.rb', 'spec/app_helper.rb') add_template('db_helper.rb.tt', 'spec/db_helper.rb') add_template('spec_helper.rb.tt', 'spec/spec_helper.rb') end def add_system add_system_lib add_system_boot end def add_system_lib %w(application container import settings).each do |file| add_template("#{file}.rb.tt", "system/#{underscored_project_name}/#{file}.rb") end end def add_system_boot %w(monitor rom).each do |file| add_template("#{file}.rb.tt", "system/boot/#{file}.rb") end add_template('boot.rb.tt', 'system/boot.rb') end def add_web add_template('example_routes.rb.tt', 'web/routes/example.rb') add_template('application.html.slim', 'web/templates/layouts/application.html.slim') add_template('welcome.html.slim', 'web/templates/welcome.html.slim') end def add_config_files add_template('.gitignore', '.gitignore') add_template('Gemfile', 'Gemfile') add_template('Rakefile.tt', 'Rakefile') add_template('config.ru.tt', 'config.ru') add_template('README.md.tt', 'README.md') end end end end end end
[Update] RedPacket (2.3.0) Pod::Spec.new do |s| s.name = "RedPacket" s.version = "2.3.0" s.summary = "A short description of RedPacket-iOS." s.license = {"type"=>"MIT", "file"=>"LICENSE"} s.authors = {"jdy"=>"wzy2010416033@163.com"} s.homepage = "https://www.zplay.com" s.description = "A long description of RedPacket-iOS. No more description." s.source = { :http => 'https://adsdk.yumimobi.com/iOS/RedPacketSDK/RedPacketSDK_2.3.0.tar.bz2'} s.resource = "Resources/RedPacketResources.bundle" s.vendored_frameworks = "RedPacket.framework" s.frameworks = "AdSupport" s.weak_frameworks = 'WebKit' s.ios.deployment_target = '9.0' s.dependency 'AFNetworking', '~> 3.0' s.dependency 'YYModel', '~> 1.0' s.dependency 'Masonry', '~> 1.1.0' s.dependency 'WechatOpenSDK', '1.8.7' s.dependency 'SDWebImage', '~> 5.8.0' s.dependency 'FLAnimatedImage', '~> 1.0' s.static_framework = true end
# encoding: utf-8 require File.expand_path('../lib/rails_admin/version', __FILE__) Gem::Specification.new do |spec| # If you add a dependency, please maintain alphabetical order spec.add_dependency 'nested_form', '~> 0.3' spec.add_dependency 'sass-rails', '~> 3.1' spec.add_dependency 'bootstrap-sass', '~> 2.2' spec.add_dependency 'font-awesome-sass-rails', ['~> 3.0', '>= 3.0.0.1'] spec.add_dependency 'jquery-ui-rails', '~> 3.0' spec.add_dependency 'builder', '~> 3.0' spec.add_dependency 'coffee-rails', '~> 3.1' spec.add_dependency 'haml', '~> 3.1' spec.add_dependency 'jquery-rails', '~> 2.1' spec.add_dependency 'kaminari', '~> 0.14' spec.add_dependency 'rack-pjax', '~> 0.6' spec.add_dependency 'rails', '~> 3.1' spec.add_dependency 'remotipart', '~> 1.0' spec.add_development_dependency 'bundler', '~> 1.0' spec.authors = ["Erik Michaels-Ober", "Bogdan Gaza", "Petteri Kaapa", "Benoit Benezech"] spec.description = %q{RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data.} spec.email = ['sferik@gmail.com', 'bogdan@cadmio.org', 'petteri.kaapa@gmail.com'] spec.files = Dir['Gemfile', 'LICENSE.md', 'README.md', 'Rakefile', 'app/**/*', 'config/**/*', 'lib/**/*', 'public/**/*'] spec.licenses = ['MIT'] spec.homepage = 'https://github.com/sferik/rails_admin' spec.name = 'rails_admin' spec.require_paths = ['lib'] spec.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') spec.summary = %q{Admin for Rails} spec.test_files = Dir['spec/**/*'] spec.version = RailsAdmin::Version end require 'rails_admin/version' Because require hashes based on the string, not the expanded path of the file, it's important that we require the version file the same way that it will be required elsewhere to avoid constant warnings. # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rails_admin/version' Gem::Specification.new do |spec| # If you add a dependency, please maintain alphabetical order spec.add_dependency 'nested_form', '~> 0.3' spec.add_dependency 'sass-rails', '~> 3.1' spec.add_dependency 'bootstrap-sass', '~> 2.2' spec.add_dependency 'font-awesome-sass-rails', ['~> 3.0', '>= 3.0.0.1'] spec.add_dependency 'jquery-ui-rails', '~> 3.0' spec.add_dependency 'builder', '~> 3.0' spec.add_dependency 'coffee-rails', '~> 3.1' spec.add_dependency 'haml', '~> 3.1' spec.add_dependency 'jquery-rails', '~> 2.1' spec.add_dependency 'kaminari', '~> 0.14' spec.add_dependency 'rack-pjax', '~> 0.6' spec.add_dependency 'rails', '~> 3.1' spec.add_dependency 'remotipart', '~> 1.0' spec.add_development_dependency 'bundler', '~> 1.0' spec.authors = ["Erik Michaels-Ober", "Bogdan Gaza", "Petteri Kaapa", "Benoit Benezech"] spec.description = %q{RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data.} spec.email = ['sferik@gmail.com', 'bogdan@cadmio.org', 'petteri.kaapa@gmail.com'] spec.files = Dir['Gemfile', 'LICENSE.md', 'README.md', 'Rakefile', 'app/**/*', 'config/**/*', 'lib/**/*', 'public/**/*'] spec.licenses = ['MIT'] spec.homepage = 'https://github.com/sferik/rails_admin' spec.name = 'rails_admin' spec.require_paths = ['lib'] spec.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') spec.summary = %q{Admin for Rails} spec.test_files = Dir['spec/**/*'] spec.version = RailsAdmin::Version end
# coding: utf-8 require_relative 'introspection/symbol_map' require_relative 'introspection/class' require_relative 'introspection/object' require_relative 'introspection/word_specs' require_relative 'introspection/context' #* library/introspection_library.rb - The fOOrth introspection library. module XfOOrth #Dump the context. VirtualMachine.create_shared_method(')context', VmSpec, [], &lambda {|vm| vm.context.get_info.foorth_bullets(vm) }) #Dump the context right NOW!. VirtualMachine.create_shared_method(')context!', VmSpec, [:immediate], &lambda {|vm| vm.context.get_info.foorth_bullets(vm) }) #Dump the virtual machine. VirtualMachine.create_shared_method(')vm', VmSpec, [], &lambda {|vm| vm.debug_dump }) #Dump the virtual machine right NOW! VirtualMachine.create_shared_method(')vm!', VmSpec, [:immediate], &lambda {|vm| vm.debug_dump }) #Map a symbol entry VirtualMachine.create_shared_method(')map"', VmSpec, [], &lambda {|vm| str = vm.pop.to_s puts "#{str} => #{(SymbolMap.map(str).to_s)}" }) #Unmap a symbol entry VirtualMachine.create_shared_method(')unmap"', VmSpec, [], &lambda {|vm| str = vm.pop.to_s puts "#{str} <= #{(SymbolMap.unmap(str.to_sym).to_s)}" }) #Get information on a method. Class.create_shared_method('.method_info', TosSpec, [], &lambda{|vm| symbol, info = SymbolMap.map_info(name = vm.pop) results = [["Name", name], info] found = false if symbol spec, info = map_foorth_shared_info(symbol) if spec && !spec.has_tag?(:stub) results << ["", ""] results.concat(info) results.concat(spec.get_info) found = true end spec, info = map_foorth_exclusive_info(symbol) if spec && !spec.has_tag?(:stub) results << ["", ""] results.concat(info) results.concat(spec.get_info) found = true end results << ["Scope", "not found."] unless found end vm.push(results) }) #The user level command for the above. Class.create_shared_method(')method_info"', NosSpec, [], &lambda{|vm| foorth_method_info(vm) vm.pop.foorth_bullets(vm) }) #Get information on a method. Object.create_shared_method('.method_info', TosSpec, [], &lambda{|vm| symbol, info = SymbolMap.map_info(name = vm.pop) results = [["Name", name], info] found = false if symbol spec, info = map_foorth_exclusive_info(symbol) if spec && !spec.has_tag?(:stub) results << ["", ""] results.concat(info) results.concat(spec.get_info) found = true end results << ["Scope", "not found."] unless found end vm.push(results) }) #The user level command for the above. Object.create_shared_method(')method_info"', NosSpec, [], &lambda{|vm| foorth_method_info(vm) vm.pop.foorth_bullets(vm) }) #Scan all classes for information about a method. String.create_shared_method('.method_scan', TosSpec, [], &lambda{|vm| symbol, info = SymbolMap.map_info(self) results = [["Name", self], info] found = false if symbol $FOORTH_GLOBALS.values .select {|entry| entry.has_tag?(:class)} .collect {|spec| spec.new_class} .sort {|a,b| a.foorth_name <=> b.foorth_name} .each do |klass| spec, info = klass.map_foorth_shared_info(symbol, :shallow) if spec results << ["", ""] results.concat(info) results.concat(spec.get_info) found = true end spec, info = klass.map_foorth_exclusive_info(symbol, :shallow) if spec results << ["", ""] results.concat(info) results.concat(spec.get_info) found = true end end results << ["Scope", "not found in any class."] unless found end vm.push(results) }) #The user level command for the above. String.create_shared_method(')method_scan"', TosSpec, [], &lambda{|vm| foorth_method_scan(vm) vm.pop.foorth_bullets(vm) }) #Get this class's lineage in a string. Class.create_shared_method('.lineage', TosSpec, [], &lambda{|vm| vm.push(lineage.freeze) }) #The user level command for the above. Class.create_shared_method(')lineage', TosSpec, [], &lambda{|vm| puts lineage }) #Scan a class for stuff. Class.create_shared_method('.class_scan', TosSpec, [], &lambda{|vm| results = [["Lineage", lineage]] if foorth_has_exclusive? results.concat([["", ""], ["Class", ""]]) foorth_exclusive.extract_method_names.sort.each do |name| symbol, info = SymbolMap.map_info(name) results.concat([["", ""], ["Name", name]], info) spec, info = map_foorth_exclusive_info(symbol, :shallow) results.concat(info) results.concat(spec.get_info) end end unless foorth_shared.empty? results.concat([["", ""], ["Shared", ""]]) foorth_shared.extract_method_names.sort.each do |name| symbol, info = SymbolMap.map_info(name) results.concat([["", ""], ["Name", name]], info) spec, info = map_foorth_shared_info(symbol, :shallow) results.concat(info) results.concat(spec.get_info) end end vm.push(results) }) #The user level command for the above. Class.create_shared_method(')class_scan', TosSpec, [], &lambda{|vm| foorth_class_scan(vm) vm.pop.foorth_bullets(vm) }) end Some further refactoring. # coding: utf-8 require_relative 'introspection/symbol_map' require_relative 'introspection/class' require_relative 'introspection/object' require_relative 'introspection/word_specs' require_relative 'introspection/context' #* library/introspection_library.rb - The fOOrth introspection library. module XfOOrth #Dump the context. VirtualMachine.create_shared_method(')context', VmSpec, [], &lambda {|vm| vm.context.get_info.foorth_bullets(vm) }) #Dump the context right NOW!. VirtualMachine.create_shared_method(')context!', VmSpec, [:immediate], &lambda {|vm| vm.context.get_info.foorth_bullets(vm) }) #Dump the virtual machine. VirtualMachine.create_shared_method(')vm', VmSpec, [], &lambda {|vm| vm.debug_dump }) #Dump the virtual machine right NOW! VirtualMachine.create_shared_method(')vm!', VmSpec, [:immediate], &lambda {|vm| vm.debug_dump }) #Map a symbol entry VirtualMachine.create_shared_method(')map"', VmSpec, [], &lambda {|vm| str = vm.pop.to_s puts "#{str} => #{(SymbolMap.map(str).to_s)}" }) #Unmap a symbol entry VirtualMachine.create_shared_method(')unmap"', VmSpec, [], &lambda {|vm| str = vm.pop.to_s puts "#{str} <= #{(SymbolMap.unmap(str.to_sym).to_s)}" }) #Get information on a method. Class.create_shared_method('.method_info', TosSpec, [], &lambda{|vm| symbol, info = SymbolMap.map_info(name = vm.pop) results = [["Name", name], info] found = false if symbol spec, info = map_foorth_shared_info(symbol) if spec && !spec.has_tag?(:stub) (results << ["", ""]).concat(info).concat(spec.get_info) found = true end spec, info = map_foorth_exclusive_info(symbol) if spec && !spec.has_tag?(:stub) (results << ["", ""]).concat(info).concat(spec.get_info) found = true end results << ["Scope", "not found."] unless found end vm.push(results) }) #The user level command for the above. Class.create_shared_method(')method_info"', NosSpec, [], &lambda{|vm| foorth_method_info(vm) vm.pop.foorth_bullets(vm) }) #Get information on a method. Object.create_shared_method('.method_info', TosSpec, [], &lambda{|vm| symbol, info = SymbolMap.map_info(name = vm.pop) results = [["Name", name], info] found = false if symbol spec, info = map_foorth_exclusive_info(symbol) if spec && !spec.has_tag?(:stub) (results << ["", ""]).concat(info).concat(spec.get_info) found = true end results << ["Scope", "not found."] unless found end vm.push(results) }) #The user level command for the above. Object.create_shared_method(')method_info"', NosSpec, [], &lambda{|vm| foorth_method_info(vm) vm.pop.foorth_bullets(vm) }) #Scan all classes for information about a method. String.create_shared_method('.method_scan', TosSpec, [], &lambda{|vm| symbol, info = SymbolMap.map_info(self) results = [["Name", self], info] found = false if symbol $FOORTH_GLOBALS.values .select {|entry| entry.has_tag?(:class)} .collect {|spec| spec.new_class} .sort {|a,b| a.foorth_name <=> b.foorth_name} .each do |klass| spec, info = klass.map_foorth_shared_info(symbol, :shallow) if spec (results << ["", ""]).concat(info).concat(spec.get_info) found = true end spec, info = klass.map_foorth_exclusive_info(symbol, :shallow) if spec (results << ["", ""]).concat(info).concat(spec.get_info) found = true end end results << ["Scope", "not found in any class."] unless found end vm.push(results) }) #The user level command for the above. String.create_shared_method(')method_scan"', TosSpec, [], &lambda{|vm| foorth_method_scan(vm) vm.pop.foorth_bullets(vm) }) #Get this class's lineage in a string. Class.create_shared_method('.lineage', TosSpec, [], &lambda{|vm| vm.push(lineage.freeze) }) #The user level command for the above. Class.create_shared_method(')lineage', TosSpec, [], &lambda{|vm| puts lineage }) #Scan a class for stuff. Class.create_shared_method('.class_scan', TosSpec, [], &lambda{|vm| results = [["Lineage", lineage]] if foorth_has_exclusive? results.concat([["", ""], ["Class", ""]]) foorth_exclusive.extract_method_names.sort.each do |name| symbol, info = SymbolMap.map_info(name) results.concat([["", ""], ["Name", name], info]) spec, info = map_foorth_exclusive_info(symbol, :shallow) results.concat(info).concat(spec.get_info) end end unless foorth_shared.empty? results.concat([["", ""], ["Shared", ""]]) foorth_shared.extract_method_names.sort.each do |name| symbol, info = SymbolMap.map_info(name) results.concat([["", ""], ["Name", name], info]) spec, info = map_foorth_shared_info(symbol, :shallow) results.concat(info).concat(spec.get_info) end end vm.push(results) }) #The user level command for the above. Class.create_shared_method(')class_scan', TosSpec, [], &lambda{|vm| foorth_class_scan(vm) vm.pop.foorth_bullets(vm) }) end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rake/delphi/version' Gem::Specification.new do |spec| spec.name = "rake-delphi" spec.version = Rake::Delphi::VERSION spec.authors = ['Alexey Shumkin'] spec.email = ['Alex.Crezoff@gmail.com'] spec.description = 'Tasks for building Delphi projects' spec.summary = 'Tasks for building Delphi projects' spec.homepage = 'http://github.com/ashumkin/rake-delphi.gem' spec.license = 'MIT' spec.files = Dir['*', 'lib/**/*.*rb', 'test/*.rb', 'test/helpers/*.rb', 'test/resources/**/*', 'test/resources/**/.gitkeep'] # avoid adding redundant files spec.files.delete_if do |f| match = false [/\/test\/tmp\//, /\/dcu\//].each do |re| match = re.match(f) break if match end match end spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end gemspec: set `rake` version # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rake/delphi/version' Gem::Specification.new do |spec| spec.name = "rake-delphi" spec.version = Rake::Delphi::VERSION spec.authors = ['Alexey Shumkin'] spec.email = ['Alex.Crezoff@gmail.com'] spec.description = 'Tasks for building Delphi projects' spec.summary = 'Tasks for building Delphi projects' spec.homepage = 'http://github.com/ashumkin/rake-delphi.gem' spec.license = 'MIT' spec.files = Dir['*', 'lib/**/*.*rb', 'test/*.rb', 'test/helpers/*.rb', 'test/resources/**/*', 'test/resources/**/.gitkeep'] # avoid adding redundant files spec.files.delete_if do |f| match = false [/\/test\/tmp\//, /\/dcu\//].each do |re| match = re.match(f) break if match end match end spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake", "~> 10.0.4" end
module Facebooker2 module Rails module Helpers module Javascript def fb_html_safe(str) if str.respond_to?(:html_safe) str.html_safe else str end end def fb_connect_async_js(app_id=Facebooker2.app_id,options={},&proc) opts = Hash.new.merge!(options) cookie = opts[:cookie].nil? ? true : opts[:cookie] status = opts[:status].nil? ? true : opts[:status] xfbml = opts[:xfbml].nil? ? true : opts[:xfbml] channel_url = opts[:channel_url] lang = opts[:locale] || 'en_US' extra_js = capture(&proc) if block_given? js = <<-JAVASCRIPT <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : '#{app_id}', status : #{status}, // check login status cookie : #{cookie}, // enable cookies to allow the server to access the session #{"channelUrl : '#{channel_url}', // add channelURL to avoid IE redirect problems" unless channel_url.blank?} oauth : true, xfbml : #{xfbml} // parse XFBML }); #{extra_js} }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/#{lang}/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script> JAVASCRIPT escaped_js = fb_html_safe(js) if block_given? concat(escaped_js) #return the empty string, since concat returns the buffer and we don't want double output # from klochner "" else escaped_js end end end end end end music options added to operands module Facebooker2 module Rails module Helpers module Javascript def fb_html_safe(str) if str.respond_to?(:html_safe) str.html_safe else str end end def fb_connect_async_js(app_id=Facebooker2.app_id,options={},&proc) opts = Hash.new.merge!(options) cookie = opts[:cookie].nil? ? true : opts[:cookie] status = opts[:status].nil? ? true : opts[:status] xfbml = opts[:xfbml].nil? ? true : opts[:xfbml] music = opts[:music].nil? ? false : opts[:music] channel_url = opts[:channel_url] lang = opts[:locale] || 'en_US' extra_js = capture(&proc) if block_given? js = <<-JAVASCRIPT <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : '#{app_id}', status : #{status}, // check login status cookie : #{cookie}, // enable cookies to allow the server to access the session #{"channelUrl : '#{channel_url}', // add channelURL to avoid IE redirect problems" unless channel_url.blank?} oauth : true, music : #{music} xfbml : #{xfbml} // parse XFBML }); #{extra_js} }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/#{lang}/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script> JAVASCRIPT escaped_js = fb_html_safe(js) if block_given? concat(escaped_js) #return the empty string, since concat returns the buffer and we don't want double output # from klochner "" else escaped_js end end end end end end
module Facebooker2 module Rails module Helpers module Javascript def fb_html_safe(str) if str.respond_to?(:html_safe) str.html_safe else str end end def fb_connect_async_js(app_id=Facebooker2.app_id,options={},&proc) opts = Hash.new(true).merge!(options) cookie = opts[:cookie] status = opts[:status] xfbml = opts[:xfbml] extra_js = capture(&proc) if block_given? js = <<-JAVASCRIPT <script> window.fbAsyncInit = function() { FB.init({ appId : '#{app_id}', status : #{status}, // check login status cookie : #{cookie}, // enable cookies to allow the server to access the session xfbml : #{xfbml} // parse XFBML }); #{extra_js} }; (function() { var s = document.createElement('div'); s.setAttribute('id','fb-root'); document.documentElement.getElementsByTagName("body")[0].appendChild(s); var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; s.appendChild(e); }()); </script> JAVASCRIPT block_given? ? concat(js) : js end end end end end Updated js module Facebooker2 module Rails module Helpers module Javascript def fb_html_safe(str) if str.respond_to?(:html_safe) str.html_safe else str end end def fb_connect_async_js(app_id=Facebooker2.app_id,options={},&proc) opts = Hash.new(true).merge!(options) cookie = opts[:cookie] status = opts[:status] xfbml = opts[:xfbml] extra_js = capture(&proc) if block_given? js = <<-JAVASCRIPT <script> window.fbAsyncInit = function() { FB.init({ appId : '#{app_id}', status : #{status}, // check login status cookie : #{cookie}, // enable cookies to allow the server to access the session xfbml : #{xfbml} // parse XFBML }); #{extra_js} }; (function() { var s = document.createElement('div'); s.setAttribute('id','fb-root'); document.documentElement.getElementsByTagName("body")[0].appendChild(s); var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; s.appendChild(e); }()); </script> JAVASCRIPT escaped_js = fb_html_safe(js) block_given? ? concat(escaped_js) : escaped_js end end end end end
Implement loader for Rails 3 1 session string by a Rails 3 0 app module FlashPatch class Rails31SessionLoader def initialize(decrypted_session_string) @decrypted_session_string = decrypted_session_string end def load_session session = Marshal.load @decrypted_session_string.gsub('FlashHash','FlashGash') flash_messages_from_original_klass = session.delete('flash') session['flash'] = ActionDispatch::Flash::FlashHash.new.update(flash_messages_from_original_klass) session end end end
Update simplecov to version 0.20.0
# # Cookbook Name:: cronner # Resource:: cronner # # Copyright 2017 Tim Heckman <t@heckman.io> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. resource_name :cronner default_action :create property :job_name, String, name_property: true ### # cron_d Resource properties # property :command, String, required: true property :cookbook, String, default: 'cron' property :predefined_value, String property :minute, [String, Integer], default: '*' property :hour, [String, Integer], default: '*' property :day, [String, Integer], default: '*' property :month, [String, Integer], default: '*' property :weekday, [String, Integer], default: '*' property :user, String, default: 'root' property :mailto, [String, NilClass] property :path, [String, NilClass] property :home, [String, NilClass] property :shell, [String, NilClass] property :comment, [String, NilClass] property :environment, [Hash, NilClass], default: {} property :mode, [String, Integer], default: '0644' ### # cronner properties # # flag: -e/--event property :event, [TrueClass, FalseClass], default: false # flag: -E/--event-fail property :event_fail, [TrueClass, FalseClass], default: false # flag: -F/--log-fail property :log_fail, [TrueClass, FalseClass], default: false # flag: -G/--event-group property :event_group, [String, NilClass], default: nil # flag: -g/--group # use name metric_group to avoid colliding with group resource property :metric_group, [String, NilClass], default: nil # flag: -k/--lock property :lock, [TrueClass, FalseClass], default: false # flag: -l/--label property :label, [String, NilClass], default: nil # flag: -N/--namespace property :namespace, [String, NilClass], default: nil # flag: -p/--passthru property :passthru, [TrueClass, FalseClass], default: false # flag: -P/--use-parent property :use_parent, [TrueClass, FalseClass], default: false # flag: -s/--sensitive # use name sensitive_output to avoid colliding with built-in sensitive property property :sensitive_output, [TrueClass, FalseClass], default: false # flag: -w/--warn-after property :warn_after, Integer, default: 0 # flag: -W/--wait-secs property :wait_secs_for_lock, Integer, default: 0 # grab format_string and command_string helper methods include Cronner::Helpers action :create do include_recipe 'cronner' include_recipe 'cron' cron_d format_string(job_name) do command command_string cookbook new_resource.cookbook minute new_resource.minute hour new_resource.hour day new_resource.day month new_resource.month weekday new_resource.weekday user new_resource.user mailto new_resource.mailto path new_resource.path home new_resource.home shell new_resource.shell comment new_resource.comment environment new_resource.environment mode new_resource.mode predefined_value new_resource.predefined_value action :create end end action :delete do cron_d format_string(job_name) do command command_string cookbook new_resource.cookbook minute new_resource.minute hour new_resource.hour day new_resource.day month new_resource.month weekday new_resource.weekday user new_resource.user mailto new_resource.mailto path new_resource.path home new_resource.home shell new_resource.shell comment new_resource.comment environment new_resource.environment mode new_resource.mode predefined_value new_resource.predefined_value action :delete end end Add missing new_resource for Chef 14 compatibility # # Cookbook Name:: cronner # Resource:: cronner # # Copyright 2017 Tim Heckman <t@heckman.io> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. resource_name :cronner default_action :create property :job_name, String, name_property: true ### # cron_d Resource properties # property :command, String, required: true property :cookbook, String, default: 'cron' property :predefined_value, String property :minute, [String, Integer], default: '*' property :hour, [String, Integer], default: '*' property :day, [String, Integer], default: '*' property :month, [String, Integer], default: '*' property :weekday, [String, Integer], default: '*' property :user, String, default: 'root' property :mailto, [String, NilClass] property :path, [String, NilClass] property :home, [String, NilClass] property :shell, [String, NilClass] property :comment, [String, NilClass] property :environment, [Hash, NilClass], default: {} property :mode, [String, Integer], default: '0644' ### # cronner properties # # flag: -e/--event property :event, [TrueClass, FalseClass], default: false # flag: -E/--event-fail property :event_fail, [TrueClass, FalseClass], default: false # flag: -F/--log-fail property :log_fail, [TrueClass, FalseClass], default: false # flag: -G/--event-group property :event_group, [String, NilClass], default: nil # flag: -g/--group # use name metric_group to avoid colliding with group resource property :metric_group, [String, NilClass], default: nil # flag: -k/--lock property :lock, [TrueClass, FalseClass], default: false # flag: -l/--label property :label, [String, NilClass], default: nil # flag: -N/--namespace property :namespace, [String, NilClass], default: nil # flag: -p/--passthru property :passthru, [TrueClass, FalseClass], default: false # flag: -P/--use-parent property :use_parent, [TrueClass, FalseClass], default: false # flag: -s/--sensitive # use name sensitive_output to avoid colliding with built-in sensitive property property :sensitive_output, [TrueClass, FalseClass], default: false # flag: -w/--warn-after property :warn_after, Integer, default: 0 # flag: -W/--wait-secs property :wait_secs_for_lock, Integer, default: 0 # grab format_string and command_string helper methods include Cronner::Helpers action :create do include_recipe 'cronner' include_recipe 'cron' cron_d format_string(new_resource.job_name) do command command_string cookbook new_resource.cookbook minute new_resource.minute hour new_resource.hour day new_resource.day month new_resource.month weekday new_resource.weekday user new_resource.user mailto new_resource.mailto path new_resource.path home new_resource.home shell new_resource.shell comment new_resource.comment environment new_resource.environment mode new_resource.mode predefined_value new_resource.predefined_value action :create end end action :delete do cron_d format_string(new_resource.job_name) do command command_string cookbook new_resource.cookbook minute new_resource.minute hour new_resource.hour day new_resource.day month new_resource.month weekday new_resource.weekday user new_resource.user mailto new_resource.mailto path new_resource.path home new_resource.home shell new_resource.shell comment new_resource.comment environment new_resource.environment mode new_resource.mode predefined_value new_resource.predefined_value action :delete end end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "rattlecache" s.version = "0.1" s.platform = Gem::Platform::RUBY s.authors = ["Marv Cool"] s.email = "marv@hostin.is" s.homepage = "https://github.com/MrMarvin/rattlcache/wiki" s.summary = %q{A smart caching system for battlenet API Requests.} if s.respond_to?(:add_development_dependency) s.add_development_dependency "rspec" end s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end gem version up to 0.2 # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "rattlecache" s.version = "0.2" s.platform = Gem::Platform::RUBY s.authors = ["Marv Cool"] s.email = "marv@hostin.is" s.homepage = "https://github.com/MrMarvin/rattlcache/wiki" s.summary = %q{A smart caching system for battlenet API Requests.} if s.respond_to?(:add_development_dependency) s.add_development_dependency "rspec" end s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rautomation} s.version = "0.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jarmo Pertman"] s.date = %q{2010-12-17} s.description = %q{RAutomation is a small and easy to use library for helping out to automate windows and their controls for automated testing. RAutomation provides: * Easy to use and user-friendly API (inspired by Watir http://www.watir.com) * Cross-platform compatibility * Easy extensibility - with small scripting effort it's possible to add support for not yet supported platforms or technologies} s.email = %q{jarmo.p@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", ".rspec", ".yardopts", "History.rdoc", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "ext/AutoItX/AutoItX.chm", "ext/AutoItX/AutoItX3.dll", "lib/rautomation.rb", "lib/rautomation/adapter/autoit.rb", "lib/rautomation/adapter/autoit/button.rb", "lib/rautomation/adapter/autoit/locators.rb", "lib/rautomation/adapter/autoit/text_field.rb", "lib/rautomation/adapter/autoit/window.rb", "lib/rautomation/adapter/ffi.rb", "lib/rautomation/adapter/ffi/button.rb", "lib/rautomation/adapter/ffi/constants.rb", "lib/rautomation/adapter/ffi/functions.rb", "lib/rautomation/adapter/ffi/locators.rb", "lib/rautomation/adapter/ffi/text_field.rb", "lib/rautomation/adapter/ffi/window.rb", "lib/rautomation/adapter/helper.rb", "lib/rautomation/button.rb", "lib/rautomation/text_field.rb", "lib/rautomation/wait_helper.rb", "lib/rautomation/window.rb", "rautomation.gemspec", "spec/button_spec.rb", "spec/spec_helper.rb", "spec/test.html", "spec/text_field_spec.rb", "spec/window_spec.rb" ] s.homepage = %q{http://github.com/jarmo/RAutomation} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Automate windows and their controls through user-friendly API with Ruby} s.test_files = [ "spec/button_spec.rb", "spec/spec_helper.rb", "spec/text_field_spec.rb", "spec/window_spec.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, ["~> 2.3"]) else s.add_dependency(%q<rspec>, ["~> 2.3"]) end else s.add_dependency(%q<rspec>, ["~> 2.3"]) end end Regenerated gemspec for version 0.3.0 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rautomation} s.version = "0.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jarmo Pertman"] s.date = %q{2010-12-18} s.description = %q{RAutomation is a small and easy to use library for helping out to automate windows and their controls for automated testing. RAutomation provides: * Easy to use and user-friendly API (inspired by Watir http://www.watir.com) * Cross-platform compatibility * Easy extensibility - with small scripting effort it's possible to add support for not yet supported platforms or technologies} s.email = %q{jarmo.p@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", ".rspec", ".yardopts", "History.rdoc", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "ext/AutoItX/AutoItX.chm", "ext/AutoItX/AutoItX3.dll", "lib/rautomation.rb", "lib/rautomation/adapter/autoit.rb", "lib/rautomation/adapter/autoit/button.rb", "lib/rautomation/adapter/autoit/locators.rb", "lib/rautomation/adapter/autoit/text_field.rb", "lib/rautomation/adapter/autoit/window.rb", "lib/rautomation/adapter/ffi.rb", "lib/rautomation/adapter/ffi/button.rb", "lib/rautomation/adapter/ffi/constants.rb", "lib/rautomation/adapter/ffi/functions.rb", "lib/rautomation/adapter/ffi/locators.rb", "lib/rautomation/adapter/ffi/text_field.rb", "lib/rautomation/adapter/ffi/window.rb", "lib/rautomation/adapter/helper.rb", "lib/rautomation/button.rb", "lib/rautomation/text_field.rb", "lib/rautomation/wait_helper.rb", "lib/rautomation/window.rb", "rautomation.gemspec", "spec/button_spec.rb", "spec/spec_helper.rb", "spec/test.html", "spec/text_field_spec.rb", "spec/window_spec.rb" ] s.homepage = %q{http://github.com/jarmo/RAutomation} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Automate windows and their controls through user-friendly API with Ruby} s.test_files = [ "spec/button_spec.rb", "spec/spec_helper.rb", "spec/text_field_spec.rb", "spec/window_spec.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, ["~> 2.3"]) else s.add_dependency(%q<rspec>, ["~> 2.3"]) end else s.add_dependency(%q<rspec>, ["~> 2.3"]) end end
include Apache2::Cookbook::Helpers property :root_group, String, default: lazy { default_apache_root_group }, description: 'Group that the root user on the box runs as' property :apache_user, String, default: lazy { default_apache_user }, description: 'Set to override the default apache2 user' property :apache_group, String, default: lazy { default_apache_group }, description: 'Set to override the default apache2 user' property :log_dir, String, default: lazy { default_log_dir }, description: 'Log directory' property :error_log, String, default: lazy { default_error_log }, description: 'Log directory' property :log_level, String, default: 'warn', description: 'log level for apache2' property :apache_locale, String, default: 'system', description: 'Locale for apache2, defaults to the system locale' property :status_url, String, default: 'http://localhost:80/server-status', description: 'URL for status checks' property :httpd_t_timeout, Integer, default: 10, description: 'Service timeout setting. Defaults to 10 seconds' property :mpm, String, default: lazy { default_mpm }, description: 'Multi-processing Module, defaults to each platforms default' property :listen, [String, Array], default: %w(80 443), description: 'Port to listen on. Defaults to both 80 & 443' action :install do package [apache_pkg, perl_pkg] package 'perl-Getopt-Long-Descriptive' if platform?('fedora') directory apache_dir do mode '0751' owner 'root' group new_resource.root_group end %w(sites-available sites-enabled mods-available mods-enabled conf-available conf-enabled).each do |dir| directory "#{apache_dir}/#{dir}" do mode '0750' owner 'root' group new_resource.root_group end end directory new_resource.log_dir do mode '0750' recursive true end %w(a2ensite a2dissite a2enmod a2dismod a2enconf a2disconf).each do |modscript| link "/usr/sbin/#{modscript}" do action :delete only_if { ::File.symlink?("/usr/sbin/#{modscript}") } end template "/usr/sbin/#{modscript}" do source "#{modscript}.erb" cookbook 'apache2' mode '0700' owner 'root' variables( apachectl: apachectl, apache_dir: apache_dir ) group new_resource.root_group action :create end end unless platform_family?('debian') cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do source 'apache2_module_conf_generate.pl' cookbook 'apache2' mode '0750' owner 'root' group new_resource.root_group end execute 'generate-module-list' do command "/usr/local/bin/apache2_module_conf_generate.pl #{lib_dir} #{apache_dir}/mods-available" action :nothing end end if platform_family?('freebsd') directory "#{apache_dir}/Includes" do action :delete recursive true end directory "#{apache_dir}/extra" do action :delete recursive true end end if platform_family?('suse') directory "#{apache_dir}/vhosts.d" do action :delete recursive true end %w(charset.conv default-vhost.conf default-server.conf default-vhost-ssl.conf errors.conf listen.conf mime.types mod_autoindex-defaults.conf mod_info.conf mod_log_config.conf mod_status.conf mod_userdir.conf mod_usertrack.conf uid.conf).each do |file| file "#{apache_dir}/#{file}" do action :delete backup false end end end directory "#{apache_dir}/ssl" do mode '0750' owner 'root' group new_resource.root_group end directory cache_dir do mode '0750' owner 'root' group new_resource.root_group end directory lock_dir do mode '0750' if node['platform_family'] == 'debian' owner new_resource.apache_user else owner 'root' end group new_resource.root_group end template "/etc/sysconfig/#{apache_platform_service_name}" do source 'etc-sysconfig-httpd.erb' cookbook 'apache2' owner 'root' group new_resource.root_group mode '0644' variables( apache_binary: apache_binary, apache_dir: apache_dir ) only_if { platform_family?('rhel', 'amazon', 'fedora', 'suse') } end template "#{apache_dir}/envvars" do source 'envvars.erb' cookbook 'apache2' owner 'root' group new_resource.root_group mode '0644' variables( lock_dir: lock_dir, log_dir: new_resource.log_dir, apache_user: new_resource.apache_user, apache_group: new_resource.apache_group, pid_file: apache_pid_file, apache_locale: new_resource.apache_locale, status_url: new_resource.status_url ) only_if { platform_family?('debian') } end template 'apache2.conf' do if platform_family?('debian') path "#{apache_conf_dir}/apache2.conf" else path "#{apache_conf_dir}/httpd.conf" end action :create source 'apache2.conf.erb' cookbook 'apache2' owner 'root' group new_resource.root_group mode '0640' variables( apache_binary: apache_binary, apache_dir: apache_dir, lock_dir: lock_dir, log_dir: new_resource.log_dir, error_log: new_resource.error_log, log_level: new_resource.log_level, pid_file: apache_pid_file, apache_user: new_resource.apache_user, apache_group: new_resource.apache_group ) end apache2_conf 'security' apache2_conf 'charset' template 'ports.conf' do path "#{apache_dir}/ports.conf" source 'ports.conf.erb' cookbook 'apache2' mode '0644' variables(listen: new_resource.listen) end # MPM Support Setup case new_resource.mpm when 'event' if platform_family?('suse') package %w(apache2-prefork apache2-worker) do action :remove end package 'apache2-event' else %w(mpm_prefork mpm_worker).each do |mpm| apache2_module mpm do action :disable end end apache2_module 'mpm_event' do conf true apache_service_notification :restart end end when 'prefork' if platform_family?('suse') package %w(apache2-event apache2-worker) do action :remove end package 'apache2-prefork' else %w(mpm_event mpm_worker).each do |mpm| apache2_module mpm do action :disable end end apache2_module 'mpm_prefork' do conf true apache_service_notification :restart end end when 'worker' if platform_family?('suse') package %w(apache2-event apache2-prefork) do action :remove end package 'apache2-worker' else %w(prefork event).each do |mpm| apache2_module mpm do action :disable end end apache2_module 'mpm_worker' do conf true apache_service_notification :restart end end end default_modules.each do |mod| recipe = mod =~ /^mod_/ ? mod : "mod_#{mod}" include_recipe "apache2::#{recipe}" end service 'apache2' do service_name apache_platform_service_name supports [:start, :restart, :reload, :status] action [:enable, :start] only_if "#{apache_binary} -t", environment: { 'APACHE_LOG_DIR' => new_resource.log_dir }, timeout: new_resource.httpd_t_timeout end end action_class do include Apache2::Cookbook::Helpers end Fix mpm uninstall for debian platforms include Apache2::Cookbook::Helpers property :root_group, String, default: lazy { default_apache_root_group }, description: 'Group that the root user on the box runs as' property :apache_user, String, default: lazy { default_apache_user }, description: 'Set to override the default apache2 user' property :apache_group, String, default: lazy { default_apache_group }, description: 'Set to override the default apache2 user' property :log_dir, String, default: lazy { default_log_dir }, description: 'Log directory' property :error_log, String, default: lazy { default_error_log }, description: 'Log directory' property :log_level, String, default: 'warn', description: 'log level for apache2' property :apache_locale, String, default: 'system', description: 'Locale for apache2, defaults to the system locale' property :status_url, String, default: 'http://localhost:80/server-status', description: 'URL for status checks' property :httpd_t_timeout, Integer, default: 10, description: 'Service timeout setting. Defaults to 10 seconds' property :mpm, String, default: lazy { default_mpm }, description: 'Multi-processing Module, defaults to each platforms default' property :listen, [String, Array], default: %w(80 443), description: 'Port to listen on. Defaults to both 80 & 443' action :install do package [apache_pkg, perl_pkg] package 'perl-Getopt-Long-Descriptive' if platform?('fedora') directory apache_dir do mode '0751' owner 'root' group new_resource.root_group end %w(sites-available sites-enabled mods-available mods-enabled conf-available conf-enabled).each do |dir| directory "#{apache_dir}/#{dir}" do mode '0750' owner 'root' group new_resource.root_group end end directory new_resource.log_dir do mode '0750' recursive true end %w(a2ensite a2dissite a2enmod a2dismod a2enconf a2disconf).each do |modscript| link "/usr/sbin/#{modscript}" do action :delete only_if { ::File.symlink?("/usr/sbin/#{modscript}") } end template "/usr/sbin/#{modscript}" do source "#{modscript}.erb" cookbook 'apache2' mode '0700' owner 'root' variables( apachectl: apachectl, apache_dir: apache_dir ) group new_resource.root_group action :create end end unless platform_family?('debian') cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do source 'apache2_module_conf_generate.pl' cookbook 'apache2' mode '0750' owner 'root' group new_resource.root_group end execute 'generate-module-list' do command "/usr/local/bin/apache2_module_conf_generate.pl #{lib_dir} #{apache_dir}/mods-available" action :nothing end end if platform_family?('freebsd') directory "#{apache_dir}/Includes" do action :delete recursive true end directory "#{apache_dir}/extra" do action :delete recursive true end end if platform_family?('suse') directory "#{apache_dir}/vhosts.d" do action :delete recursive true end %w(charset.conv default-vhost.conf default-server.conf default-vhost-ssl.conf errors.conf listen.conf mime.types mod_autoindex-defaults.conf mod_info.conf mod_log_config.conf mod_status.conf mod_userdir.conf mod_usertrack.conf uid.conf).each do |file| file "#{apache_dir}/#{file}" do action :delete backup false end end end directory "#{apache_dir}/ssl" do mode '0750' owner 'root' group new_resource.root_group end directory cache_dir do mode '0750' owner 'root' group new_resource.root_group end directory lock_dir do mode '0750' if node['platform_family'] == 'debian' owner new_resource.apache_user else owner 'root' end group new_resource.root_group end template "/etc/sysconfig/#{apache_platform_service_name}" do source 'etc-sysconfig-httpd.erb' cookbook 'apache2' owner 'root' group new_resource.root_group mode '0644' variables( apache_binary: apache_binary, apache_dir: apache_dir ) only_if { platform_family?('rhel', 'amazon', 'fedora', 'suse') } end template "#{apache_dir}/envvars" do source 'envvars.erb' cookbook 'apache2' owner 'root' group new_resource.root_group mode '0644' variables( lock_dir: lock_dir, log_dir: new_resource.log_dir, apache_user: new_resource.apache_user, apache_group: new_resource.apache_group, pid_file: apache_pid_file, apache_locale: new_resource.apache_locale, status_url: new_resource.status_url ) only_if { platform_family?('debian') } end template 'apache2.conf' do if platform_family?('debian') path "#{apache_conf_dir}/apache2.conf" else path "#{apache_conf_dir}/httpd.conf" end action :create source 'apache2.conf.erb' cookbook 'apache2' owner 'root' group new_resource.root_group mode '0640' variables( apache_binary: apache_binary, apache_dir: apache_dir, lock_dir: lock_dir, log_dir: new_resource.log_dir, error_log: new_resource.error_log, log_level: new_resource.log_level, pid_file: apache_pid_file, apache_user: new_resource.apache_user, apache_group: new_resource.apache_group ) end apache2_conf 'security' apache2_conf 'charset' template 'ports.conf' do path "#{apache_dir}/ports.conf" source 'ports.conf.erb' cookbook 'apache2' mode '0644' variables(listen: new_resource.listen) end # MPM Support Setup case new_resource.mpm when 'event' if platform_family?('suse') package %w(apache2-prefork apache2-worker) do action :remove end package 'apache2-event' else %w(mpm_prefork mpm_worker).each do |mpm| apache2_module mpm do action :disable end end apache2_module 'mpm_event' do conf true apache_service_notification :restart end end when 'prefork' if platform_family?('suse') package %w(apache2-event apache2-worker) do action :remove end package 'apache2-prefork' else %w(mpm_event mpm_worker).each do |mpm| apache2_module mpm do action :disable end end apache2_module 'mpm_prefork' do conf true apache_service_notification :restart end end when 'worker' if platform_family?('suse') package %w(apache2-event apache2-prefork) do action :remove end package 'apache2-worker' else %w(mpm_prefork mpm_event).each do |mpm| apache2_module mpm do action :disable end end apache2_module 'mpm_worker' do conf true apache_service_notification :restart end end end default_modules.each do |mod| recipe = mod =~ /^mod_/ ? mod : "mod_#{mod}" include_recipe "apache2::#{recipe}" end service 'apache2' do service_name apache_platform_service_name supports [:start, :restart, :reload, :status] action [:enable, :start] only_if "#{apache_binary} -t", environment: { 'APACHE_LOG_DIR' => new_resource.log_dir }, timeout: new_resource.httpd_t_timeout end end action_class do include Apache2::Cookbook::Helpers end
# Copyright:: 2017-2018 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # resource_name :hab_service property :service_name, String, name_property: true property :loaded, [true, false], default: false, desired_state: true property :running, [true, false], default: false, desired_state: true # hab svc options which get included based on the action of the resource property :strategy, [Symbol, String], equal_to: [:none, 'none', :'at-once', 'at-once', :rolling, 'rolling'], default: :none, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :topology, [Symbol, String], equal_to: [:standalone, 'standalone', :leader, 'leader'], default: :standalone, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :bldr_url, String, default: 'https://bldr.habitat.sh' property :channel, [Symbol, String], default: :stable, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :bind, [String, Array], coerce: proc { |b| b.is_a?(String) ? [b] : b }, default: [] property :binding_mode, [Symbol, String], equal_to: [:strict, 'strict', :relaxed, 'relaxed'], default: :strict, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :service_group, String, default: 'default' property :shutdown_timeout, Integer, default: 8 property :health_check_interval, Integer, default: 30 property :remote_sup, String, default: '127.0.0.1:9632', desired_state: false # Http port needed for querying/comparing current config value property :remote_sup_http, String, default: '127.0.0.1:9631', desired_state: false load_current_value do service_details = get_service_details(service_name) running service_up?(service_details) loaded service_loaded?(service_details) if loaded service_name get_spec_identifier(service_details) strategy get_update_strategy(service_details) topology get_topology(service_details) bldr_url get_builder_url(service_details) channel get_channel(service_details) bind get_binds(service_details) binding_mode get_binding_mode(service_details) service_group get_service_group(service_details) shutdown_timeout get_shutdown_timeout(service_details) health_check_interval get_health_check_interval(service_details) end Chef::Log.debug("service #{service_name} service name: #{service_name}") Chef::Log.debug("service #{service_name} running state: #{running}") Chef::Log.debug("service #{service_name} loaded state: #{loaded}") Chef::Log.debug("service #{service_name} strategy: #{strategy}") Chef::Log.debug("service #{service_name} topology: #{topology}") Chef::Log.debug("service #{service_name} builder url: #{bldr_url}") Chef::Log.debug("service #{service_name} channel: #{channel}") Chef::Log.debug("service #{service_name} binds: #{bind}") Chef::Log.debug("service #{service_name} binding mode: #{binding_mode}") Chef::Log.debug("service #{service_name} service group: #{service_group}") Chef::Log.debug("service #{service_name} shutdown timeout: #{shutdown_timeout}") Chef::Log.debug("service #{service_name} health check interval: #{health_check_interval}") end # This method is defined here otherwise it isn't usable in the # `load_current_value` method. # # It performs a check with TCPSocket to ensure that the HTTP API is # available first. If it cannot connect, it assumes that the service # is not running. It then attempts to reach the `/services` path of # the API to get a list of services. If this fails for some reason, # then it assumes the service is not running. # # Finally, it walks the services returned by the API to look for the # service we're configuring. If it is "Up", then we know the service # is running and fully operational according to Habitat. This is # wrapped in a begin/rescue block because if the service isn't # present and `sup_for_service_name` will be nil and we will get a # NoMethodError. # def get_service_details(svc_name) http_uri = "http://#{remote_sup_http}" begin TCPSocket.new(URI(http_uri).host, URI(http_uri).port).close rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH Chef::Log.debug("Could not connect to #{http_uri} to retrieve status for #{service_name}") return false end begin svcs = Chef::HTTP::SimpleJSON.new(http_uri).get('/services') rescue Chef::Log.debug("Could not connect to #{http_uri}/services to retrieve status for #{service_name}") return false end origin, name, _version, _release = svc_name.split('/') svcs.find do |s| s['pkg']['origin'] == origin && s['pkg']['name'] == name end end def service_up?(service_details) begin service_details['process']['state'] == 'up' rescue Chef::Log.debug("#{service_name} not found on the Habitat supervisor") false end end def service_loaded?(service_details) if service_details true else false end end def get_spec_identifier(service_details) begin service_details['spec_ident']['spec_identifier'] rescue Chef::Log.debug("#{service_name} not found on the Habitat supervisor") nil end end def get_update_strategy(service_details) begin service_details['update_strategy'].to_sym rescue Chef::Log.debug("Update Strategy for #{service_name} not found on Supervisor API") 'none' end end def get_topology(service_details) begin service_details['topology'].to_sym rescue Chef::Log.debug("Topology for #{service_name} not found on Supervisor API") 'standalone' end end def get_builder_url(service_details) begin service_details['bldr_url'] rescue Chef::Log.debug("Builder URL for #{service_name} not found on Supervisor API") 'https://bldr.habitat.sh' end end def get_channel(service_details) begin service_details['channel'].to_sym rescue Chef::Log.debug("Channel for #{service_name} not found on Supervisor API") 'stable' end end def get_binds(service_details) begin service_details['binds'] rescue Chef::Log.debug("Update Strategy for #{service_name} not found on Supervisor API") [] end end def get_binding_mode(service_details) begin service_details['binding_mode'].to_sym rescue Chef::Log.debug("Binding mode for #{service_name} not found on Supervisor API") 'strict' end end def get_service_group(service_details) begin service_details['service_group'].split('.').last rescue Chef::Log.debug("Service Group for #{service_name} not found on Supervisor API") 'default' end end def get_shutdown_timeout(service_details) begin service_details['pkg']['shutdown_timeout'] rescue Chef::Log.debug("Shutdown Timeout for #{service_name} not found on Supervisor API") 8 end end def get_health_check_interval(service_details) begin service_details['health_check_interval']['secs'] rescue Chef::Log.debug("Health Check Interval for #{service_name} not found on Supervisor API") 30 end end action :load do modified = false converge_if_changed :service_name do modified = true end converge_if_changed :strategy do modified = true end converge_if_changed :topology do modified = true end converge_if_changed :bldr_url do modified = true end converge_if_changed :channel do modified = true end converge_if_changed :bind do modified = true end converge_if_changed :binding_mode do modified = true end converge_if_changed :service_group do modified = true end converge_if_changed :shutdown_timeout do modified = true end converge_if_changed :health_check_interval do modified = true end options = svc_options if current_resource.loaded && modified Chef::Log.debug("Reloading #{current_resource.service_name} using --force due to parameter change") options << "--force" end execute "hab svc load #{new_resource.service_name} #{options.join(' ')}" unless current_resource.loaded && !modified end action :unload do if current_resource.loaded execute "hab svc unload #{new_resource.service_name} #{svc_options.join(' ')}" wait_for_service_unloaded end end action :start do unless current_resource.loaded Chef::Log.fatal("No service named #{new_resource.service_name} is loaded on the Habitat supervisor") raise "No service named #{new_resource.service_name} is loaded on the Habitat supervisor" end execute "hab svc start #{new_resource.service_name} #{svc_options.join(' ')}" unless current_resource.running end action :stop do unless current_resource.loaded Chef::Log.fatal("No service named #{new_resource.service_name} is loaded on the Habitat supervisor") raise "No service named #{new_resource.service_name} is loaded on the Habitat supervisor" end if current_resource.running execute "hab svc stop #{new_resource.service_name} #{svc_options.join(' ')}" wait_for_service_stopped end end action :restart do action_stop action_start end action :reload do action_unload action_load end action_class do def svc_options opts = [] # certain options are only valid for specific `hab svc` subcommands. case action when :load opts.push(*new_resource.bind.map { |b| "--bind #{b}" }) if new_resource.bind opts << "--binding-mode #{new_resource.binding_mode}" opts << "--url #{new_resource.bldr_url}" if new_resource.bldr_url opts << "--channel #{new_resource.channel}" if new_resource.channel opts << "--group #{new_resource.service_group}" if new_resource.service_group opts << "--strategy #{new_resource.strategy}" if new_resource.strategy opts << "--topology #{new_resource.topology}" if new_resource.topology opts << "--health-check-interval #{new_resource.health_check_interval}" if new_resource.health_check_interval opts << "--shutdown-timeout #{new_resource.shutdown_timeout}" if new_resource.shutdown_timeout when :unload, :stop opts << "--shutdown-timeout #{new_resource.shutdown_timeout}" if new_resource.shutdown_timeout end opts << "--remote-sup #{new_resource.remote_sup}" if new_resource.remote_sup opts.map(&:split).flatten.compact end def wait_for_service_unloaded ruby_block 'wait-for-service-unloaded' do block do raise "#{new_resource.service_name} still loaded" if service_loaded?(get_service_details(new_resource.service_name)) end retries get_shutdown_timeout(new_resource.service_name) + 1 retry_delay 1 end ruby_block 'update current_resource' do block do current_resource.loaded = service_loaded?(get_service_details(new_resource.service_name)) end action :nothing subscribes :run, 'ruby_block[wait-for-service-unloaded]', :immediately end end def wait_for_service_stopped ruby_block 'wait-for-service-stopped' do block do raise "#{new_resource.service_name} still running" if service_up?(get_service_details(new_resource.service_name)) end retries get_shutdown_timeout(new_resource.service_name) + 1 retry_delay 1 ruby_block 'update current_resource' do block do current_resource.running = service_up?(get_service_details(new_resource.service_name)) end action :nothing subscribes :run, 'ruby_block[wait-for-service-stopped]', :immediately end end end end Cookstyle fixes Signed-off-by: Siraj Rauff <54a206d076a096cd67de0c9db2325a49b5e69888@gmail.com> # Copyright:: 2017-2018 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # resource_name :hab_service property :service_name, String, name_property: true property :loaded, [true, false], default: false, desired_state: true property :running, [true, false], default: false, desired_state: true # hab svc options which get included based on the action of the resource property :strategy, [Symbol, String], equal_to: [:none, 'none', :'at-once', 'at-once', :rolling, 'rolling'], default: :none, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :topology, [Symbol, String], equal_to: [:standalone, 'standalone', :leader, 'leader'], default: :standalone, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :bldr_url, String, default: 'https://bldr.habitat.sh' property :channel, [Symbol, String], default: :stable, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :bind, [String, Array], coerce: proc { |b| b.is_a?(String) ? [b] : b }, default: [] property :binding_mode, [Symbol, String], equal_to: [:strict, 'strict', :relaxed, 'relaxed'], default: :strict, coerce: proc { |s| s.is_a?(String) ? s.to_sym : s } property :service_group, String, default: 'default' property :shutdown_timeout, Integer, default: 8 property :health_check_interval, Integer, default: 30 property :remote_sup, String, default: '127.0.0.1:9632', desired_state: false # Http port needed for querying/comparing current config value property :remote_sup_http, String, default: '127.0.0.1:9631', desired_state: false load_current_value do service_details = get_service_details(service_name) running service_up?(service_details) loaded service_loaded?(service_details) if loaded service_name get_spec_identifier(service_details) strategy get_update_strategy(service_details) topology get_topology(service_details) bldr_url get_builder_url(service_details) channel get_channel(service_details) bind get_binds(service_details) binding_mode get_binding_mode(service_details) service_group get_service_group(service_details) shutdown_timeout get_shutdown_timeout(service_details) health_check_interval get_health_check_interval(service_details) end Chef::Log.debug("service #{service_name} service name: #{service_name}") Chef::Log.debug("service #{service_name} running state: #{running}") Chef::Log.debug("service #{service_name} loaded state: #{loaded}") Chef::Log.debug("service #{service_name} strategy: #{strategy}") Chef::Log.debug("service #{service_name} topology: #{topology}") Chef::Log.debug("service #{service_name} builder url: #{bldr_url}") Chef::Log.debug("service #{service_name} channel: #{channel}") Chef::Log.debug("service #{service_name} binds: #{bind}") Chef::Log.debug("service #{service_name} binding mode: #{binding_mode}") Chef::Log.debug("service #{service_name} service group: #{service_group}") Chef::Log.debug("service #{service_name} shutdown timeout: #{shutdown_timeout}") Chef::Log.debug("service #{service_name} health check interval: #{health_check_interval}") end # This method is defined here otherwise it isn't usable in the # `load_current_value` method. # # It performs a check with TCPSocket to ensure that the HTTP API is # available first. If it cannot connect, it assumes that the service # is not running. It then attempts to reach the `/services` path of # the API to get a list of services. If this fails for some reason, # then it assumes the service is not running. # # Finally, it walks the services returned by the API to look for the # service we're configuring. If it is "Up", then we know the service # is running and fully operational according to Habitat. This is # wrapped in a begin/rescue block because if the service isn't # present and `sup_for_service_name` will be nil and we will get a # NoMethodError. # def get_service_details(svc_name) http_uri = "http://#{remote_sup_http}" begin TCPSocket.new(URI(http_uri).host, URI(http_uri).port).close rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH Chef::Log.debug("Could not connect to #{http_uri} to retrieve status for #{service_name}") return false end begin svcs = Chef::HTTP::SimpleJSON.new(http_uri).get('/services') rescue Chef::Log.debug("Could not connect to #{http_uri}/services to retrieve status for #{service_name}") return false end origin, name, _version, _release = svc_name.split('/') svcs.find do |s| s['pkg']['origin'] == origin && s['pkg']['name'] == name end end def service_up?(service_details) service_details['process']['state'] == 'up' rescue Chef::Log.debug("#{service_name} not found on the Habitat supervisor") false end def service_loaded?(service_details) if service_details true else false end end def get_spec_identifier(service_details) service_details['spec_ident']['spec_identifier'] rescue Chef::Log.debug("#{service_name} not found on the Habitat supervisor") nil end def get_update_strategy(service_details) service_details['update_strategy'].to_sym rescue Chef::Log.debug("Update Strategy for #{service_name} not found on Supervisor API") 'none' end def get_topology(service_details) service_details['topology'].to_sym rescue Chef::Log.debug("Topology for #{service_name} not found on Supervisor API") 'standalone' end def get_builder_url(service_details) service_details['bldr_url'] rescue Chef::Log.debug("Builder URL for #{service_name} not found on Supervisor API") 'https://bldr.habitat.sh' end def get_channel(service_details) service_details['channel'].to_sym rescue Chef::Log.debug("Channel for #{service_name} not found on Supervisor API") 'stable' end def get_binds(service_details) service_details['binds'] rescue Chef::Log.debug("Update Strategy for #{service_name} not found on Supervisor API") [] end def get_binding_mode(service_details) service_details['binding_mode'].to_sym rescue Chef::Log.debug("Binding mode for #{service_name} not found on Supervisor API") 'strict' end def get_service_group(service_details) service_details['service_group'].split('.').last rescue Chef::Log.debug("Service Group for #{service_name} not found on Supervisor API") 'default' end def get_shutdown_timeout(service_details) service_details['pkg']['shutdown_timeout'] rescue Chef::Log.debug("Shutdown Timeout for #{service_name} not found on Supervisor API") 8 end def get_health_check_interval(service_details) service_details['health_check_interval']['secs'] rescue Chef::Log.debug("Health Check Interval for #{service_name} not found on Supervisor API") 30 end action :load do modified = false converge_if_changed :service_name do modified = true end converge_if_changed :strategy do modified = true end converge_if_changed :topology do modified = true end converge_if_changed :bldr_url do modified = true end converge_if_changed :channel do modified = true end converge_if_changed :bind do modified = true end converge_if_changed :binding_mode do modified = true end converge_if_changed :service_group do modified = true end converge_if_changed :shutdown_timeout do modified = true end converge_if_changed :health_check_interval do modified = true end options = svc_options if current_resource.loaded && modified Chef::Log.debug("Reloading #{current_resource.service_name} using --force due to parameter change") options << '--force' end execute "hab svc load #{new_resource.service_name} #{options.join(' ')}" unless current_resource.loaded && !modified end action :unload do if current_resource.loaded execute "hab svc unload #{new_resource.service_name} #{svc_options.join(' ')}" wait_for_service_unloaded end end action :start do unless current_resource.loaded Chef::Log.fatal("No service named #{new_resource.service_name} is loaded on the Habitat supervisor") raise "No service named #{new_resource.service_name} is loaded on the Habitat supervisor" end execute "hab svc start #{new_resource.service_name} #{svc_options.join(' ')}" unless current_resource.running end action :stop do unless current_resource.loaded Chef::Log.fatal("No service named #{new_resource.service_name} is loaded on the Habitat supervisor") raise "No service named #{new_resource.service_name} is loaded on the Habitat supervisor" end if current_resource.running execute "hab svc stop #{new_resource.service_name} #{svc_options.join(' ')}" wait_for_service_stopped end end action :restart do action_stop action_start end action :reload do action_unload action_load end action_class do def svc_options opts = [] # certain options are only valid for specific `hab svc` subcommands. case action when :load opts.push(*new_resource.bind.map { |b| "--bind #{b}" }) if new_resource.bind opts << "--binding-mode #{new_resource.binding_mode}" opts << "--url #{new_resource.bldr_url}" if new_resource.bldr_url opts << "--channel #{new_resource.channel}" if new_resource.channel opts << "--group #{new_resource.service_group}" if new_resource.service_group opts << "--strategy #{new_resource.strategy}" if new_resource.strategy opts << "--topology #{new_resource.topology}" if new_resource.topology opts << "--health-check-interval #{new_resource.health_check_interval}" if new_resource.health_check_interval opts << "--shutdown-timeout #{new_resource.shutdown_timeout}" if new_resource.shutdown_timeout when :unload, :stop opts << "--shutdown-timeout #{new_resource.shutdown_timeout}" if new_resource.shutdown_timeout end opts << "--remote-sup #{new_resource.remote_sup}" if new_resource.remote_sup opts.map(&:split).flatten.compact end def wait_for_service_unloaded ruby_block 'wait-for-service-unloaded' do block do raise "#{new_resource.service_name} still loaded" if service_loaded?(get_service_details(new_resource.service_name)) end retries get_shutdown_timeout(new_resource.service_name) + 1 retry_delay 1 end ruby_block 'update current_resource' do block do current_resource.loaded = service_loaded?(get_service_details(new_resource.service_name)) end action :nothing subscribes :run, 'ruby_block[wait-for-service-unloaded]', :immediately end end def wait_for_service_stopped ruby_block 'wait-for-service-stopped' do block do raise "#{new_resource.service_name} still running" if service_up?(get_service_details(new_resource.service_name)) end retries get_shutdown_timeout(new_resource.service_name) + 1 retry_delay 1 ruby_block 'update current_resource' do block do current_resource.running = service_up?(get_service_details(new_resource.service_name)) end action :nothing subscribes :run, 'ruby_block[wait-for-service-stopped]', :immediately end end end end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "readline-ng" Gem::Specification.new do |s| s.name = "readline-ng" s.version = ReadlineNG::VERSION s.authors = ["Rich Healey"] s.email = ["richo@psych0tik.net"] s.homepage = "http://github.com/richoH/readline-ng" s.summary = "Essentially, readline++" s.description = s.summary s.add_development_dependency 'rspec' s.add_development_dependency 'mocha' s.add_development_dependency 'rake' s.files = `git ls-files`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end update github username # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "readline-ng" Gem::Specification.new do |s| s.name = "readline-ng" s.version = ReadlineNG::VERSION s.authors = ["Rich Healey"] s.email = ["richo@psych0tik.net"] s.homepage = "http://github.com/richo/readline-ng" s.summary = "Essentially, readline++" s.description = s.summary s.add_development_dependency 'rspec' s.add_development_dependency 'mocha' s.add_development_dependency 'rake' s.files = `git ls-files`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end
# # Copyright 2014 John Bellone <jbellone@bloomberg.net> # Copyright 2014 Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'json' # Configure directories consul_directories = [] consul_directories << node['consul']['data_dir'] consul_directories << node['consul']['config_dir'] consul_directories << '/var/lib/consul' # Select service user & group case node['consul']['init_style'] when 'runit' include_recipe 'runit::default' consul_user = node['consul']['service_user'] consul_group = node['consul']['service_group'] consul_directories << '/var/log/consul' else consul_user = 'root' consul_group = 'root' end # Create service user user "consul service user: #{consul_user}" do not_if { consul_user == 'root' } username consul_user home '/dev/null' shell '/bin/false' comment 'consul service user' end # Create service group group "consul service group: #{consul_group}" do not_if { consul_group == 'root' } group_name consul_group members consul_user append true end # Create service directories consul_directories.each do |dirname| directory dirname do owner consul_user group consul_group mode 0755 end end # Determine service params service_config = JSON.parse(node['consul']['extra_params'].to_json) service_config['data_dir'] = node['consul']['data_dir'] num_cluster = node['consul']['bootstrap_expect'].to_i case node['consul']['service_mode'] when 'bootstrap' service_config['server'] = true service_config['bootstrap'] = true when 'cluster' service_config['server'] = true if num_cluster > 1 service_config['bootstrap_expect'] = num_cluster service_config['start_join'] = node['consul']['servers'] else service_config['bootstrap'] = true end when 'server' service_config['server'] = true service_config['start_join'] = node['consul']['servers'] when 'client' service_config['start_join'] = node['consul']['servers'] else Chef::Application.fatal! %Q(node['consul']['service_mode'] must be "bootstrap", "cluster", "server", or "client") end iface_addr_map = { :bind_interface => :bind_addr, :advertise_interface => :advertise_addr, :client_interface => :client_addr } iface_addr_map.each_pair do |interface,addr| next unless node['consul'][interface] if node["network"]["interfaces"][node['consul'][interface]] ip = node["network"]["interfaces"][node['consul'][interface]]["addresses"].detect{|k,v| v[:family] == "inet"}.first node.default['consul'][addr] = ip else Chef::Application.fatal!("Interface specified in node['consul'][#{interface}] does not exist!") end end if node['consul']['serve_ui'] service_config['ui_dir'] = node['consul']['ui_dir'] service_config['client_addr'] = node['consul']['client_addr'] end copy_params = [ :bind_addr, :datacenter, :domain, :log_level, :node_name, :advertise_addr, :ports, :enable_syslog ] copy_params.each do |key| if node['consul'][key] if key == :ports Chef::Application.fatal! 'node[:consul][:ports] must be a Hash' unless node[:consul][key].kind_of?(Hash) end service_config[key] = node['consul'][key] end end dbi = nil # Gossip encryption if node.consul.encrypt_enabled # Fetch the databag only once, and use empty hash if it doesn't exists dbi = consul_encrypted_dbi || {} secret = consul_dbi_key_with_node_default(dbi, 'encrypt') raise "Consul encrypt key is empty or nil" if secret.nil? or secret.empty? service_config['encrypt'] = secret else # for backward compatibilty service_config['encrypt'] = node.consul.encrypt unless node.consul.encrypt.nil? end # TLS encryption if node.consul.verify_incoming || node.consul.verify_outgoing dbi = consul_encrypted_dbi || {} if dbi.nil? service_config['verify_outgoing'] = node.consul.verify_outgoing service_config['verify_incoming'] = node.consul.verify_incoming ca_path = node.consul.ca_path % { config_dir: node.consul.config_dir } service_config['ca_file'] = ca_path cert_path = node.consul.cert_path % { config_dir: node.consul.config_dir } service_config['cert_file'] = cert_path key_path = node.consul.key_file_path % { config_dir: node.consul.config_dir } service_config['key_file'] = key_path # Search for key_file_hostname since key and cert file can be unique/host key_content = dbi['key_file_' + node.fqdn] || consul_dbi_key_with_node_default(dbi, 'key_file') cert_content = dbi['cert_file_' + node.fqdn] || consul_dbi_key_with_node_default(dbi, 'cert_file') ca_content = consul_dbi_key_with_node_default(dbi, 'ca_cert') # Save the certs if exists {ca_path => ca_content, key_path => key_content, cert_path => cert_content}.each do |path, content| unless content.nil? or content.empty? file path do user consul_user group consul_group mode 0600 action :create content content end end end end consul_config_filename = File.join(node['consul']['config_dir'], 'default.json') file consul_config_filename do user consul_user group consul_group mode 0600 action :create content JSON.pretty_generate(service_config, quirks_mode: true) # https://github.com/johnbellone/consul-cookbook/issues/72 notifies :restart, "service[consul]" end case node['consul']['init_style'] when 'init' if platform?("ubuntu") init_file = '/etc/init/consul.conf' init_tmpl = 'consul.conf.erb' else init_file = '/etc/init.d/consul' init_tmpl = 'consul-init.erb' end template node['consul']['etc_config_dir'] do source 'consul-sysconfig.erb' mode 0755 notifies :create, "template[#{init_file}]", :immediately end template init_file do source init_tmpl mode 0755 variables( consul_binary: "#{node['consul']['install_dir']}/consul", config_dir: node['consul']['config_dir'], ) notifies :restart, 'service[consul]', :immediately end service 'consul' do provider Chef::Provider::Service::Upstart if platform?("ubuntu") supports status: true, restart: true, reload: true action [:enable, :start] subscribes :restart, "file[#{consul_config_filename}", :delayed end when 'runit' runit_service 'consul' do supports status: true, restart: true, reload: true action [:enable, :start] subscribes :restart, "file[#{consul_config_filename}]", :delayed log true options( consul_binary: "#{node['consul']['install_dir']}/consul", config_dir: node['consul']['config_dir'], ) end end removed newly redundent logic in recipe # # Copyright 2014 John Bellone <jbellone@bloomberg.net> # Copyright 2014 Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'json' # Configure directories consul_directories = [] consul_directories << node['consul']['data_dir'] consul_directories << node['consul']['config_dir'] consul_directories << '/var/lib/consul' # Select service user & group if node['consul']['init_style'] == 'runit' include_recipe 'runit::default' consul_directories << '/var/log/consul' end # Create service user user "consul service user: #{consul_user}" do not_if { consul_user == 'root' } username consul_user home '/dev/null' shell '/bin/false' comment 'consul service user' end # Create service group group "consul service group: #{consul_group}" do not_if { consul_group == 'root' } group_name consul_group members consul_user append true end # Create service directories consul_directories.each do |dirname| directory dirname do owner consul_user group consul_group mode 0755 end end # Determine service params service_config = JSON.parse(node['consul']['extra_params'].to_json) service_config['data_dir'] = node['consul']['data_dir'] num_cluster = node['consul']['bootstrap_expect'].to_i case node['consul']['service_mode'] when 'bootstrap' service_config['server'] = true service_config['bootstrap'] = true when 'cluster' service_config['server'] = true if num_cluster > 1 service_config['bootstrap_expect'] = num_cluster service_config['start_join'] = node['consul']['servers'] else service_config['bootstrap'] = true end when 'server' service_config['server'] = true service_config['start_join'] = node['consul']['servers'] when 'client' service_config['start_join'] = node['consul']['servers'] else Chef::Application.fatal! %Q(node['consul']['service_mode'] must be "bootstrap", "cluster", "server", or "client") end iface_addr_map = { :bind_interface => :bind_addr, :advertise_interface => :advertise_addr, :client_interface => :client_addr } iface_addr_map.each_pair do |interface,addr| next unless node['consul'][interface] if node["network"]["interfaces"][node['consul'][interface]] ip = node["network"]["interfaces"][node['consul'][interface]]["addresses"].detect{|k,v| v[:family] == "inet"}.first node.default['consul'][addr] = ip else Chef::Application.fatal!("Interface specified in node['consul'][#{interface}] does not exist!") end end if node['consul']['serve_ui'] service_config['ui_dir'] = node['consul']['ui_dir'] service_config['client_addr'] = node['consul']['client_addr'] end copy_params = [ :bind_addr, :datacenter, :domain, :log_level, :node_name, :advertise_addr, :ports, :enable_syslog ] copy_params.each do |key| if node['consul'][key] if key == :ports Chef::Application.fatal! 'node[:consul][:ports] must be a Hash' unless node[:consul][key].kind_of?(Hash) end service_config[key] = node['consul'][key] end end dbi = nil # Gossip encryption if node.consul.encrypt_enabled # Fetch the databag only once, and use empty hash if it doesn't exists dbi = consul_encrypted_dbi || {} secret = consul_dbi_key_with_node_default(dbi, 'encrypt') raise "Consul encrypt key is empty or nil" if secret.nil? or secret.empty? service_config['encrypt'] = secret else # for backward compatibilty service_config['encrypt'] = node.consul.encrypt unless node.consul.encrypt.nil? end # TLS encryption if node.consul.verify_incoming || node.consul.verify_outgoing dbi = consul_encrypted_dbi || {} if dbi.nil? service_config['verify_outgoing'] = node.consul.verify_outgoing service_config['verify_incoming'] = node.consul.verify_incoming ca_path = node.consul.ca_path % { config_dir: node.consul.config_dir } service_config['ca_file'] = ca_path cert_path = node.consul.cert_path % { config_dir: node.consul.config_dir } service_config['cert_file'] = cert_path key_path = node.consul.key_file_path % { config_dir: node.consul.config_dir } service_config['key_file'] = key_path # Search for key_file_hostname since key and cert file can be unique/host key_content = dbi['key_file_' + node.fqdn] || consul_dbi_key_with_node_default(dbi, 'key_file') cert_content = dbi['cert_file_' + node.fqdn] || consul_dbi_key_with_node_default(dbi, 'cert_file') ca_content = consul_dbi_key_with_node_default(dbi, 'ca_cert') # Save the certs if exists {ca_path => ca_content, key_path => key_content, cert_path => cert_content}.each do |path, content| unless content.nil? or content.empty? file path do user consul_user group consul_group mode 0600 action :create content content end end end end consul_config_filename = File.join(node['consul']['config_dir'], 'default.json') file consul_config_filename do user consul_user group consul_group mode 0600 action :create content JSON.pretty_generate(service_config, quirks_mode: true) # https://github.com/johnbellone/consul-cookbook/issues/72 notifies :restart, "service[consul]" end case node['consul']['init_style'] when 'init' if platform?("ubuntu") init_file = '/etc/init/consul.conf' init_tmpl = 'consul.conf.erb' else init_file = '/etc/init.d/consul' init_tmpl = 'consul-init.erb' end template node['consul']['etc_config_dir'] do source 'consul-sysconfig.erb' mode 0755 notifies :create, "template[#{init_file}]", :immediately end template init_file do source init_tmpl mode 0755 variables( consul_binary: "#{node['consul']['install_dir']}/consul", config_dir: node['consul']['config_dir'], ) notifies :restart, 'service[consul]', :immediately end service 'consul' do provider Chef::Provider::Service::Upstart if platform?("ubuntu") supports status: true, restart: true, reload: true action [:enable, :start] subscribes :restart, "file[#{consul_config_filename}", :delayed end when 'runit' runit_service 'consul' do supports status: true, restart: true, reload: true action [:enable, :start] subscribes :restart, "file[#{consul_config_filename}]", :delayed log true options( consul_binary: "#{node['consul']['install_dir']}/consul", config_dir: node['consul']['config_dir'], ) end end
remove json from dependency
# The VM Object # # @author Eric Fehr (eric.fehr@publicis-modem.fr, github: ricofehr) class Vm < ActiveRecord::Base # An Heleer module contains IO functions include VmsHelper belongs_to :project belongs_to :vmsize belongs_to :user belongs_to :systemimage # Some scope for find vms objects by commit, by project or by name scope :find_by_user_commit, ->(user_id, commit){ where("user_id=#{user_id} AND commit_id like '%#{commit}'") } scope :find_by_user_project, ->(user_id, project_id){ where(user_id: user_id, project_id: project_id) } scope :find_by_name, ->(name){ where(name: name).first } attr_accessor :floating_ip, :commit # Some hooks before vm changes before_create :boot_os after_create :generate_host_all before_destroy :delete_vm # Init external api objects and extra attributes after_initialize :init_osapi, :init_extra_attr # openstack api connector, static object @@osapi = nil # Update status field with time build # # No param # No return def setupcomplete self.status = (Time.now - self.created_at).to_i save end # Get build time (=status if vm is running) # builtime is > 0 if vm is running, else is negative # # No param # No return def buildtime return self.status if self.status != 0 ret = (Time.now - self.created_at).to_i # more 2hours into setup status is equal to error status (ret > 7200) ? (1) : (-ret) end protected # Return unique vm title # # No param # @return [String] unique vm title def vm_name user = self.user project = self.project if !self.name || self.name.empty? "#{user.id}-#{project.name.gsub('.','-')}-#{Time.now.to_i.to_s.gsub(/^../,'')}".downcase else self.name end end # Return main URL vm # # No param # @return [String] url targetting the vm def vm_url "#{vm_name}#{Rails.application.config.os_suffix}" end private # Create a new vm to openstack with current object attributes # # No param # No return def boot_os # Raise an exception if the limit of vms is reachable raise Exceptions::MvmcException.new("Vms limit is reachable") if Vm.all.length > Rails.application.config.limit_vm begin self.name = vm_name generate_hiera generate_vcl user_data = generate_userdata sshname = user.sshkeys.first ? user.sshkeys.first.name : '' self.nova_id = @@osapi.boot_vm(self.name, systemimage.glance_id, sshname, self.vmsize.title, user_data) self.status = 0 rescue Exceptions::MvmcException => me me.log_e end end # Init openstack api object # # No param # No return def init_osapi @@osapi = Apiexternal::Osapi.new if @@osapi == nil end # Init extra attributes # # No param # No return def init_extra_attr @floating_ip = nil if self.nova_id ret = @@osapi.get_floatingip(self.nova_id) @floating_ip = ret[:ip] if ret end @commit = Commit.find(self.commit_id) #check_status end # Stop and delete a vm from openstack # # No param # No return def delete_vm begin @@osapi.delete_vm(self.nova_id) rescue Exceptions::MvmcException => me me.log end # delete hiera and vcl files clear_vmfiles end end cache floatingip value into rails memcache # The VM Object # # @author Eric Fehr (eric.fehr@publicis-modem.fr, github: ricofehr) class Vm < ActiveRecord::Base # An Heleer module contains IO functions include VmsHelper belongs_to :project belongs_to :vmsize belongs_to :user belongs_to :systemimage # Some scope for find vms objects by commit, by project or by name scope :find_by_user_commit, ->(user_id, commit){ where("user_id=#{user_id} AND commit_id like '%#{commit}'") } scope :find_by_user_project, ->(user_id, project_id){ where(user_id: user_id, project_id: project_id) } scope :find_by_name, ->(name){ where(name: name).first } attr_accessor :floating_ip, :commit # Some hooks before vm changes before_create :boot_os after_create :generate_host_all before_destroy :delete_vm # Init external api objects and extra attributes after_initialize :init_osapi, :init_extra_attr # openstack api connector, static object @@osapi = nil # Update status field with time build # # No param # No return def setupcomplete self.status = (Time.now - self.created_at).to_i save end # Get build time (=status if vm is running) # builtime is > 0 if vm is running, else is negative # # No param # No return def buildtime return self.status if self.status != 0 ret = (Time.now - self.created_at).to_i # more 2hours into setup status is equal to error status (ret > 7200) ? (1) : (-ret) end protected # Return unique vm title # # No param # @return [String] unique vm title def vm_name user = self.user project = self.project if !self.name || self.name.empty? "#{user.id}-#{project.name.gsub('.','-')}-#{Time.now.to_i.to_s.gsub(/^../,'')}".downcase else self.name end end # Return main URL vm # # No param # @return [String] url targetting the vm def vm_url "#{vm_name}#{Rails.application.config.os_suffix}" end private # Create a new vm to openstack with current object attributes # # No param # No return def boot_os # Raise an exception if the limit of vms is reachable raise Exceptions::MvmcException.new("Vms limit is reachable") if Vm.all.length > Rails.application.config.limit_vm begin self.name = vm_name generate_hiera generate_vcl user_data = generate_userdata sshname = user.sshkeys.first ? user.sshkeys.first.name : '' self.nova_id = @@osapi.boot_vm(self.name, systemimage.glance_id, sshname, self.vmsize.title, user_data) self.status = 0 rescue Exceptions::MvmcException => me me.log_e end end # Init openstack api object # # No param # No return def init_osapi @@osapi = Apiexternal::Osapi.new if @@osapi == nil end # Init extra attributes # # No param # No return def init_extra_attr @floating_ip = nil if self.nova_id # store floating_ip in rails cache @floating_ip = Rails.cache.fetch("vms/#{cache_key}/floating_ip", expires_in: 72.hours) do ret = @@osapi.get_floatingip(self.nova_id) if ret ret[:ip] else nil end end end @commit = Commit.find(self.commit_id) #check_status end # Stop and delete a vm from openstack # # No param # No return def delete_vm begin @@osapi.delete_vm(self.nova_id) rescue Exceptions::MvmcException => me me.log end # delete hiera and vcl files clear_vmfiles end end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'cucumber-core' s.version = '3.0.0.alpha.1' s.authors = ["Gáspár Nagy", "Aslak Hellesøy"] s.description = 'Gherkin parser' s.summary = "gherkin-#{s.version}" s.email = 'cukes@googlegroups.com' s.homepage = "https://github.com/cucumber/gherkin3" s.platform = Gem::Platform::RUBY s.license = "MIT" s.required_ruby_version = ">= 1.9.3" s.add_development_dependency 'bundler', '>= 1.5.3' s.add_development_dependency 'rake', '>= 0.10.1' s.add_development_dependency 'rspec', '>= 2.14.1' # For coverage reports s.add_development_dependency 'coveralls', '>= 0.7.0' s.rubygems_version = ">= 1.6.1" s.files = `git ls-files`.split("\n").reject {|path| path =~ /\.gitignore$/ } s.test_files = `git ls-files -- spec/*`.split("\n") s.rdoc_options = ["--charset=UTF-8"] s.require_path = "lib" end Travis has an old bundler # encoding: utf-8 Gem::Specification.new do |s| s.name = 'cucumber-core' s.version = '3.0.0.alpha.1' s.authors = ["Gáspár Nagy", "Aslak Hellesøy"] s.description = 'Gherkin parser' s.summary = "gherkin-#{s.version}" s.email = 'cukes@googlegroups.com' s.homepage = "https://github.com/cucumber/gherkin3" s.platform = Gem::Platform::RUBY s.license = "MIT" s.required_ruby_version = ">= 1.9.3" s.add_development_dependency 'bundler', '>= 1.3.5' s.add_development_dependency 'rake', '>= 0.10.1' s.add_development_dependency 'rspec', '>= 2.14.1' # For coverage reports s.add_development_dependency 'coveralls', '>= 0.7.0' s.rubygems_version = ">= 1.6.1" s.files = `git ls-files`.split("\n").reject {|path| path =~ /\.gitignore$/ } s.test_files = `git ls-files -- spec/*`.split("\n") s.rdoc_options = ["--charset=UTF-8"] s.require_path = "lib" end
$LOAD_PATH.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = 'ruby-boolean' s.version = '1.2.0' s.date = '2015-04-28' s.summary = 'Boolean for Ruby' s.description = 'A way to handle booleans in a terse way for a specific use case.' s.authors = ['Jake Yesbeck'] s.email = 'yesbeckjs@gmail.com' s.require_paths = ['lib'] s.files = ['lib/ruby_boolean.rb', 'lib/boolean/boolean.rb'] s.homepage = 'http://rubygems.org/gems/ruby-boolean' s.license = 'MIT' end Version update $LOAD_PATH.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = 'ruby-boolean' s.version = '1.2.1' s.date = '2015-04-28' s.summary = 'Boolean for Ruby' s.description = 'A way to handle booleans in a terse way for a specific use case.' s.authors = ['Jake Yesbeck'] s.email = 'yesbeckjs@gmail.com' s.require_paths = ['lib'] s.files = ['lib/ruby_boolean.rb', 'lib/boolean/boolean.rb'] s.homepage = 'http://rubygems.org/gems/ruby-boolean' s.license = 'MIT' end
default['meygam']['artifactory_server'] = '192.168.33.10' default['meygam']['artifactory_repos'] = [ "http://#{default['meygam']['artifactory_server']}:8081/artifactory/libs-snapshot-local", "http://#{default['meygam']['artifactory_server']}:8081/artifactory/libs-release-local" ] default['meygam_petclinic']['java_max_memory'] = '1024m' fixed the chef attribute issue default['meygam']['artifactory_server'] = '192.168.33.10' default['meygam']['artifactory_repos'] = [ "http://#{node['meygam']['artifactory_server']}:8081/artifactory/libs-snapshot-local", "http://#{node['meygam']['artifactory_server']}:8081/artifactory/libs-release-local" ] default['meygam_petclinic']['java_max_memory'] = '1024m'
Add system::shutdown recipe. # encoding: UTF-8 # # Cookbook Name:: system # Recipe:: shutdown # # Copyright 2015, Chris Fordham # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. execute 'shutdown_system' do command '(sleep 5 && shutdown -h now) > /dev/null 2>&1' end
require_relative "test_helper" class BasicTest < Minitest::Test def setup City.delete_all end def test_explain assert_match "Result", PgHero.explain("SELECT 1") end def test_explain_analyze City.create! assert_equal 1, City.count PgHero.explain("ANALYZE DELETE FROM cities") assert_equal 1, City.count end def test_explain_multiple_statements City.create! assert_raises(ActiveRecord::StatementInvalid) { PgHero.explain("ANALYZE DELETE FROM cities; DELETE FROM cities; COMMIT") } end def test_analyze_tables assert PgHero.analyze_tables end def test_relation_sizes assert PgHero.relation_sizes end def test_transaction_id_danger assert PgHero.transaction_id_danger(threshold: 10000000000) end def test_autovacuum_danger assert PgHero.autovacuum_danger end def test_duplicate_indexes assert_equal 1, PgHero.duplicate_indexes.size end def test_databases assert PgHero.databases[:primary].running_queries end def test_connections assert PgHero.connections end def test_connection_pool 1000.times do [:@config, :@databases].each do |var| PgHero.remove_instance_variable(var) if PgHero.instance_variable_defined?(var) end threads = 2.times.map do Thread.new do PgHero.databases[:primary].instance_variable_get(:@connection_model) end end values = threads.map(&:value) assert_same values.first, values.last refute_nil values.first end end end Added test for explain timeout require_relative "test_helper" class BasicTest < Minitest::Test def setup City.delete_all end def test_explain assert_match "Result", PgHero.explain("SELECT 1") end def test_explain_analyze City.create! assert_equal 1, City.count PgHero.explain("ANALYZE DELETE FROM cities") assert_equal 1, City.count end def test_explain_statement_timeout with_explain_timeout(1) do assert_raises(ActiveRecord::QueryCanceled) do PgHero.explain("ANALYZE SELECT pg_sleep(2)") end end end def test_explain_multiple_statements City.create! assert_raises(ActiveRecord::StatementInvalid) { PgHero.explain("ANALYZE DELETE FROM cities; DELETE FROM cities; COMMIT") } end def test_analyze_tables assert PgHero.analyze_tables end def test_relation_sizes assert PgHero.relation_sizes end def test_transaction_id_danger assert PgHero.transaction_id_danger(threshold: 10000000000) end def test_autovacuum_danger assert PgHero.autovacuum_danger end def test_duplicate_indexes assert_equal 1, PgHero.duplicate_indexes.size end def test_databases assert PgHero.databases[:primary].running_queries end def test_connections assert PgHero.connections end def test_connection_pool 1000.times do [:@config, :@databases].each do |var| PgHero.remove_instance_variable(var) if PgHero.instance_variable_defined?(var) end threads = 2.times.map do Thread.new do PgHero.databases[:primary].instance_variable_get(:@connection_model) end end values = threads.map(&:value) assert_same values.first, values.last refute_nil values.first end end def with_explain_timeout(value) previous_value = PgHero.explain_timeout_sec begin PgHero.explain_timeout_sec = value yield ensure PgHero.explain_timeout_sec = previous_value end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{iCuke} s.version = "0.5.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Rob Holland"] s.date = %q{2010-05-11} s.description = %q{Cucumber support for iPhone applications} s.email = %q{rob@the-it-refinery.co.uk} s.extensions = ["ext/iCuke/Rakefile"] s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".gitignore", "History.txt", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "app/.gitignore", "app/AlertsViewController.h", "app/AlertsViewController.m", "app/AppDelegate.h", "app/AppDelegate.m", "app/ButtonsViewController.h", "app/ButtonsViewController.m", "app/Constants.h", "app/ControlsViewController.h", "app/ControlsViewController.m", "app/ImagesViewController.h", "app/ImagesViewController.m", "app/Info.plist", "app/MainViewController.h", "app/MainViewController.m", "app/Picker/CustomPickerDataSource.h", "app/Picker/CustomPickerDataSource.m", "app/Picker/CustomView.h", "app/Picker/CustomView.m", "app/PickerViewController.h", "app/PickerViewController.m", "app/Prefix.pch", "app/ReadMe.txt", "app/SearchBarController.h", "app/SearchBarController.m", "app/SegmentViewController.h", "app/SegmentViewController.m", "app/TextFieldController.h", "app/TextFieldController.m", "app/TextViewController.h", "app/TextViewController.m", "app/ToolbarViewController.h", "app/ToolbarViewController.m", "app/TransitionViewController.h", "app/TransitionViewController.m", "app/UICatalog.xcodeproj/project.pbxproj", "app/WebViewController.h", "app/WebViewController.m", "app/en.lproj/AlertsViewController.xib", "app/en.lproj/ButtonsViewController.xib", "app/en.lproj/ControlsViewController.xib", "app/en.lproj/ImagesViewController.xib", "app/en.lproj/Localizable.strings", "app/en.lproj/MainWindow.xib", "app/en.lproj/PickerViewController.xib", "app/en.lproj/SearchBarController.xib", "app/en.lproj/SegmentViewController.xib", "app/en.lproj/TextFieldController.xib", "app/en.lproj/TextViewController.xib", "app/en.lproj/ToolbarViewController.xib", "app/en.lproj/TransitionViewController.xib", "app/en.lproj/WebViewController.xib", "app/images/12-6AM.png", "app/images/12-6PM.png", "app/images/6-12AM.png", "app/images/6-12PM.png", "app/images/Default.png", "app/images/Icon.png", "app/images/UIButton_custom.png", "app/images/blueButton.png", "app/images/orangeslide.png", "app/images/scene1.jpg", "app/images/scene2.jpg", "app/images/scene3.jpg", "app/images/scene4.jpg", "app/images/scene5.jpg", "app/images/segment_check.png", "app/images/segment_search.png", "app/images/segment_tools.png", "app/images/slider_ball.png", "app/images/whiteButton.png", "app/images/yellowslide.png", "app/main.m", "ext/iCuke/.gitignore", "ext/iCuke/DefaultsResponse.h", "ext/iCuke/DefaultsResponse.m", "ext/iCuke/EventResponse.h", "ext/iCuke/EventResponse.m", "ext/iCuke/Rakefile", "ext/iCuke/Recorder.h", "ext/iCuke/Recorder.m", "ext/iCuke/RecorderResponse.h", "ext/iCuke/RecorderResponse.m", "ext/iCuke/SynthesizeSingleton.h", "ext/iCuke/ViewResponse.h", "ext/iCuke/ViewResponse.m", "ext/iCuke/Viewer.h", "ext/iCuke/Viewer.m", "ext/iCuke/iCukeHTTPResponseHandler.h", "ext/iCuke/iCukeHTTPResponseHandler.m", "ext/iCuke/iCukeHTTPServer.h", "ext/iCuke/iCukeHTTPServer.m", "ext/iCuke/iCukeServer.h", "ext/iCuke/iCukeServer.m", "ext/iCuke/json/JSON.h", "ext/iCuke/json/NSObject+SBJSON.h", "ext/iCuke/json/NSObject+SBJSON.m", "ext/iCuke/json/NSString+SBJSON.h", "ext/iCuke/json/NSString+SBJSON.m", "ext/iCuke/json/SBJSON.h", "ext/iCuke/json/SBJSON.m", "ext/iCuke/json/SBJsonBase.h", "ext/iCuke/json/SBJsonBase.m", "ext/iCuke/json/SBJsonParser.h", "ext/iCuke/json/SBJsonParser.m", "ext/iCuke/json/SBJsonWriter.h", "ext/iCuke/json/SBJsonWriter.m", "ext/iCuke/libicuke.dylib", "features/support/env.rb", "features/uicatalog.feature", "iCuke.gemspec", "lib/icuke.rb", "lib/icuke/com.apple.Accessibility.plist", "lib/icuke/core_ext.rb", "lib/icuke/cucumber.rb", "lib/icuke/headless.rb", "lib/icuke/simulate.rb", "lib/icuke/simulator.rb", "lib/icuke/xcode.rb" ] s.homepage = %q{http://github.com/unboxed/iCuke} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{Cucumber support for iPhone applications} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<cucumber>, [">= 0"]) s.add_runtime_dependency(%q<rb-appscript>, [">= 0"]) s.add_runtime_dependency(%q<httparty>, [">= 0"]) s.add_runtime_dependency(%q<nokogiri>, [">= 0"]) else s.add_dependency(%q<cucumber>, [">= 0"]) s.add_dependency(%q<rb-appscript>, [">= 0"]) s.add_dependency(%q<httparty>, [">= 0"]) s.add_dependency(%q<nokogiri>, [">= 0"]) end else s.add_dependency(%q<cucumber>, [">= 0"]) s.add_dependency(%q<rb-appscript>, [">= 0"]) s.add_dependency(%q<httparty>, [">= 0"]) s.add_dependency(%q<nokogiri>, [">= 0"]) end end Regenerated gemspec for version 0.5.2 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{iCuke} s.version = "0.5.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Rob Holland"] s.date = %q{2010-05-11} s.description = %q{Cucumber support for iPhone applications} s.email = %q{rob@the-it-refinery.co.uk} s.extensions = ["ext/iCuke/Rakefile"] s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".gitignore", "History.txt", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "app/.gitignore", "app/AlertsViewController.h", "app/AlertsViewController.m", "app/AppDelegate.h", "app/AppDelegate.m", "app/ButtonsViewController.h", "app/ButtonsViewController.m", "app/Constants.h", "app/ControlsViewController.h", "app/ControlsViewController.m", "app/ImagesViewController.h", "app/ImagesViewController.m", "app/Info.plist", "app/MainViewController.h", "app/MainViewController.m", "app/Picker/CustomPickerDataSource.h", "app/Picker/CustomPickerDataSource.m", "app/Picker/CustomView.h", "app/Picker/CustomView.m", "app/PickerViewController.h", "app/PickerViewController.m", "app/Prefix.pch", "app/ReadMe.txt", "app/SearchBarController.h", "app/SearchBarController.m", "app/SegmentViewController.h", "app/SegmentViewController.m", "app/TextFieldController.h", "app/TextFieldController.m", "app/TextViewController.h", "app/TextViewController.m", "app/ToolbarViewController.h", "app/ToolbarViewController.m", "app/TransitionViewController.h", "app/TransitionViewController.m", "app/UICatalog.xcodeproj/project.pbxproj", "app/WebViewController.h", "app/WebViewController.m", "app/en.lproj/AlertsViewController.xib", "app/en.lproj/ButtonsViewController.xib", "app/en.lproj/ControlsViewController.xib", "app/en.lproj/ImagesViewController.xib", "app/en.lproj/Localizable.strings", "app/en.lproj/MainWindow.xib", "app/en.lproj/PickerViewController.xib", "app/en.lproj/SearchBarController.xib", "app/en.lproj/SegmentViewController.xib", "app/en.lproj/TextFieldController.xib", "app/en.lproj/TextViewController.xib", "app/en.lproj/ToolbarViewController.xib", "app/en.lproj/TransitionViewController.xib", "app/en.lproj/WebViewController.xib", "app/images/12-6AM.png", "app/images/12-6PM.png", "app/images/6-12AM.png", "app/images/6-12PM.png", "app/images/Default.png", "app/images/Icon.png", "app/images/UIButton_custom.png", "app/images/blueButton.png", "app/images/orangeslide.png", "app/images/scene1.jpg", "app/images/scene2.jpg", "app/images/scene3.jpg", "app/images/scene4.jpg", "app/images/scene5.jpg", "app/images/segment_check.png", "app/images/segment_search.png", "app/images/segment_tools.png", "app/images/slider_ball.png", "app/images/whiteButton.png", "app/images/yellowslide.png", "app/main.m", "ext/iCuke/.gitignore", "ext/iCuke/DefaultsResponse.h", "ext/iCuke/DefaultsResponse.m", "ext/iCuke/EventResponse.h", "ext/iCuke/EventResponse.m", "ext/iCuke/Rakefile", "ext/iCuke/Recorder.h", "ext/iCuke/Recorder.m", "ext/iCuke/RecorderResponse.h", "ext/iCuke/RecorderResponse.m", "ext/iCuke/SynthesizeSingleton.h", "ext/iCuke/ViewResponse.h", "ext/iCuke/ViewResponse.m", "ext/iCuke/Viewer.h", "ext/iCuke/Viewer.m", "ext/iCuke/iCukeHTTPResponseHandler.h", "ext/iCuke/iCukeHTTPResponseHandler.m", "ext/iCuke/iCukeHTTPServer.h", "ext/iCuke/iCukeHTTPServer.m", "ext/iCuke/iCukeServer.h", "ext/iCuke/iCukeServer.m", "ext/iCuke/json/JSON.h", "ext/iCuke/json/NSObject+SBJSON.h", "ext/iCuke/json/NSObject+SBJSON.m", "ext/iCuke/json/NSString+SBJSON.h", "ext/iCuke/json/NSString+SBJSON.m", "ext/iCuke/json/SBJSON.h", "ext/iCuke/json/SBJSON.m", "ext/iCuke/json/SBJsonBase.h", "ext/iCuke/json/SBJsonBase.m", "ext/iCuke/json/SBJsonParser.h", "ext/iCuke/json/SBJsonParser.m", "ext/iCuke/json/SBJsonWriter.h", "ext/iCuke/json/SBJsonWriter.m", "ext/iCuke/libicuke.dylib", "features/support/env.rb", "features/uicatalog.feature", "iCuke.gemspec", "lib/icuke.rb", "lib/icuke/com.apple.Accessibility.plist", "lib/icuke/core_ext.rb", "lib/icuke/cucumber.rb", "lib/icuke/headless.rb", "lib/icuke/simulate.rb", "lib/icuke/simulator.rb", "lib/icuke/xcode.rb" ] s.homepage = %q{http://github.com/unboxed/iCuke} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{Cucumber support for iPhone applications} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<cucumber>, [">= 0"]) s.add_runtime_dependency(%q<rb-appscript>, [">= 0"]) s.add_runtime_dependency(%q<httparty>, [">= 0"]) s.add_runtime_dependency(%q<nokogiri>, [">= 0"]) else s.add_dependency(%q<cucumber>, [">= 0"]) s.add_dependency(%q<rb-appscript>, [">= 0"]) s.add_dependency(%q<httparty>, [">= 0"]) s.add_dependency(%q<nokogiri>, [">= 0"]) end else s.add_dependency(%q<cucumber>, [">= 0"]) s.add_dependency(%q<rb-appscript>, [">= 0"]) s.add_dependency(%q<httparty>, [">= 0"]) s.add_dependency(%q<nokogiri>, [">= 0"]) end end
require 'active_support/core_ext/hash/deep_merge' module Formtastic module Inputs class AutocompleteInput < StringInput def to_html input_wrapping do label_html << builder.text_field(method, input_html_options) << builder.hidden_field(method, hidden_html_options) end end private def input_html_options { class: 'autocomplete' }.merge(super).deep_merge( name: '', id: options.key?(:input_html) && options[:input_html].key?(:id) ? options[:input_html][:id] : input_tag_id, value: options.key?(:value) ? options[:value] : input_tag_value, data: { source: options[:source] } ) end def hidden_html_options { value: options.key?(:value) ? options[:value] : input_tag_value } end def input_tag_id "#{sanitized_object_name}_#{sanitized_method}_autocomplete" end def input_tag_value return unless association if association.respond_to?(:label) association.label elsif association.respond_to?(:title) association.title elsif association.respond_to?(:name) association.name else warn "#{association.class} must respond to label, title, or name" nil end end def hidden_tag_value association.id if association end def sanitized_object_name @sanitized_object_name ||= object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, '_').sub(/_$/, '') end def sanitized_method @sanitized_method ||= method.to_s.sub(/\?$/, '') end def association @association ||= begin association_name = method.to_s association_name.gsub!(/_id\z/, '') @builder.object.send(association_name.to_sym) end end end end end Fix value require 'active_support/core_ext/hash/deep_merge' module Formtastic module Inputs class AutocompleteInput < StringInput def to_html input_wrapping do label_html << builder.text_field(method, input_html_options) << builder.hidden_field(method, hidden_html_options) end end private def input_html_options { class: 'autocomplete' }.merge(super).deep_merge( name: '', id: options.key?(:input_html) && options[:input_html].key?(:id) ? options[:input_html][:id] : input_tag_id, value: options.key?(:value) ? options[:value] : input_tag_value, data: { source: options[:source] } ) end def hidden_html_options { value: options.key?(:value) ? options[:value] : hidden_tag_value } end def input_tag_id "#{sanitized_object_name}_#{sanitized_method}_autocomplete" end def input_tag_value return unless association if association.respond_to?(:label) association.label elsif association.respond_to?(:title) association.title elsif association.respond_to?(:name) association.name else warn "#{association.class} must respond to label, title, or name" nil end end def hidden_tag_value association.id if association end def sanitized_object_name @sanitized_object_name ||= object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, '_').sub(/_$/, '') end def sanitized_method @sanitized_method ||= method.to_s.sub(/\?$/, '') end def association @association ||= begin association_name = method.to_s association_name.gsub!(/_id\z/, '') @builder.object.send(association_name.to_sym) end end end end end
# This code is free software; you can redistribute it and/or modify it under # the terms of the new BSD License. # # Copyright (c) 2015, Sebastian Staudt # Monkey-patch for Sinatra 1.4 and Rack 1.6 # # See https://github.com/sinatra/sinatra/issues/951 class Gallerist::ShowExceptions < Sinatra::ShowExceptions def call(env) @app.call(env) rescue Exception => e errors, env["rack.errors"] = env["rack.errors"], @@eats_errors if prefers_plain_text?(env) content_type = "text/plain" exception_string = dump_exception(e) else content_type = "text/html" exception_string = pretty(env, e) end env["rack.errors"] = errors # Post 893a2c50 in rack/rack, the #pretty method above, implemented in # Rack::ShowExceptions, returns a String instead of an array. body = Array(exception_string) [ 500, {"Content-Type" => content_type, "Content-Length" => Rack::Utils.bytesize(body.join).to_s}, body ] end end Ensure exceptions during warmup are fatal # This code is free software; you can redistribute it and/or modify it under # the terms of the new BSD License. # # Copyright (c) 2015, Sebastian Staudt # Monkey-patch for Sinatra 1.4 and Rack 1.6 # # See https://github.com/sinatra/sinatra/issues/951 class Gallerist::ShowExceptions < Sinatra::ShowExceptions def call(env) @app.call(env) rescue Exception => e raise e if env['rack.errors'].is_a? StringIO errors, env["rack.errors"] = env["rack.errors"], @@eats_errors if prefers_plain_text?(env) content_type = "text/plain" exception_string = dump_exception(e) else content_type = "text/html" exception_string = pretty(env, e) end env["rack.errors"] = errors # Post 893a2c50 in rack/rack, the #pretty method above, implemented in # Rack::ShowExceptions, returns a String instead of an array. body = Array(exception_string) [ 500, {"Content-Type" => content_type, "Content-Length" => Rack::Utils.bytesize(body.join).to_s}, body ] end end
# encoding: UTF-8 require File.expand_path("./helper", File.dirname(__FILE__)) prepare.clear test "no rewriting of settings hash when using Ohm.connect" do settings = { :url => "redis://127.0.0.1:6379/15" }.freeze ex = nil begin Ohm.connect(settings) rescue RuntimeError => e ex = e end assert_equal ex, nil end test "connects lazily" do Ohm.connect(:port => 9876) begin Ohm.redis.get "foo" rescue => e assert_equal Redis::CannotConnectError, e.class end end test "provides a separate connection for each thread" do assert Ohm.redis == Ohm.redis conn1, conn2 = nil threads = [] threads << Thread.new do conn1 = Ohm.redis end threads << Thread.new do conn2 = Ohm.redis end threads.each { |t| t.join } assert conn1 != conn2 end test "supports connecting by URL" do Ohm.connect(:url => "redis://localhost:9876") begin Ohm.redis.get "foo" rescue => e assert_equal Redis::CannotConnectError, e.class end end setup do Ohm.connect(:url => "redis://localhost:6379/0") end test "connection class" do conn = Ohm::Connection.new(:foo, :url => "redis://localhost:6379/0") assert conn.redis.kind_of?(Redis) end test "issue #46" do class B < Ohm::Model connect(:url => "redis://localhost:6379/15") end # We do this since we did prepare.clear above. B.db.flushall b1, b2 = nil, nil Thread.new { b1 = B.create }.join Thread.new { b2 = B.create }.join assert_equal [b1, b2], B.all.sort.to_a end test "model can define its own connection" do class B < Ohm::Model connect(:url => "redis://localhost:6379/1") end assert_equal B.conn.options, {:url=>"redis://localhost:6379/1"} assert_equal Ohm.conn.options, {:url=>"redis://localhost:6379/0"} end test "model inherits Ohm.redis connection by default" do Ohm.connect(:url => "redis://localhost:9876") class C < Ohm::Model end assert_equal C.conn.options, Ohm.conn.options end Define `Redis::CannotConnectError` conditionally. In order to make all the tests pass in redis 2.x, we simply have to assign Redis::CannotConnectError to Errno::ECONNREFUSED. # encoding: UTF-8 require File.expand_path("./helper", File.dirname(__FILE__)) unless defined?(Redis::CannotConnectError) Redis::CannotConnectError = Errno::ECONNREFUSED end prepare.clear test "no rewriting of settings hash when using Ohm.connect" do settings = { :url => "redis://127.0.0.1:6379/15" }.freeze ex = nil begin Ohm.connect(settings) rescue RuntimeError => e ex = e end assert_equal ex, nil end test "connects lazily" do Ohm.connect(:port => 9876) begin Ohm.redis.get "foo" rescue => e assert_equal Redis::CannotConnectError, e.class end end test "provides a separate connection for each thread" do assert Ohm.redis == Ohm.redis conn1, conn2 = nil threads = [] threads << Thread.new do conn1 = Ohm.redis end threads << Thread.new do conn2 = Ohm.redis end threads.each { |t| t.join } assert conn1 != conn2 end test "supports connecting by URL" do Ohm.connect(:url => "redis://localhost:9876") begin Ohm.redis.get "foo" rescue => e assert_equal Redis::CannotConnectError, e.class end end setup do Ohm.connect(:url => "redis://localhost:6379/0") end test "connection class" do conn = Ohm::Connection.new(:foo, :url => "redis://localhost:6379/0") assert conn.redis.kind_of?(Redis) end test "issue #46" do class B < Ohm::Model connect(:url => "redis://localhost:6379/15") end # We do this since we did prepare.clear above. B.db.flushall b1, b2 = nil, nil Thread.new { b1 = B.create }.join Thread.new { b2 = B.create }.join assert_equal [b1, b2], B.all.sort.to_a end test "model can define its own connection" do class B < Ohm::Model connect(:url => "redis://localhost:6379/1") end assert_equal B.conn.options, {:url=>"redis://localhost:6379/1"} assert_equal Ohm.conn.options, {:url=>"redis://localhost:6379/0"} end test "model inherits Ohm.redis connection by default" do Ohm.connect(:url => "redis://localhost:9876") class C < Ohm::Model end assert_equal C.conn.options, Ohm.conn.options end
require 'genevalidator/validation_output' ## # Class that stores the validation output information class DuplciationValidationOutput < ValidationReport attr_reader :pvalue attr_reader :threshold def initialize (pvalue, threshold = 0.05, expected = :no) @pvalue = pvalue @threshold = threshold @result = validation @expected = expected end def print "pval=#{@pvalue.round(2)}" end def validation if @pvalue < @threshold :yes else :no end end def color if validation == :no "success" else "danger" end end end ## # This class contains the methods necessary for # finding duplicated subsequences in the predicted gene class DuplicationValidation < ValidationTest def initialize(type, prediction, hits = nil) super @short_header = "Duplication" @header = "Duplication" @description = "Check whether there is a duplicated subsequence in the predicted gene by counting the hsp residue coverag of the prediction, for each hit. Meaning of the output displayed: P-value of the Wilcoxon test which test the distribution of hit average coverage against 1. P-values higher than 5% pass the validation test." @cli_name = "dup" end ## # Check duplication in the first n hits # Output: # +DuplciationValidationOutput+ object def run(n=10) begin raise Exception unless prediction.is_a? Sequence and hits[0].is_a? Sequence and hits.length >= 5 # get the first n hits less_hits = @hits[0..[n-1,@hits.length].min] averages = [] less_hits.each do |hit| # indexing in blast starts from 1 #unused !!!!!!!!!! start_match_interval = hit.hsp_list.each.map{|x| x.hit_from}.min - 1 end_match_interval = hit.hsp_list.map{|x| x.hit_to}.max - 1 coverage = Array.new(hit.xml_length,0) hit.hsp_list.each do |hsp| aux = [] # for each hsp # iterate through the alignment and count the matching residues [*(0 .. hsp.align_len-1)].each do |i| residue_hit = hsp.hit_alignment[i] residue_query = hsp.query_alignment[i] if residue_hit != ' ' and residue_hit != '+' and residue_hit != '-' if residue_hit == residue_query idx = i + (hsp.hit_from-1) - hsp.hit_alignment[0..i].scan(/-/).length aux.push(idx) # indexing in blast starts from 1 coverage[idx] += 1 end end end end overlap = coverage.reject{|x| x==0} averages.push(overlap.inject(:+)/(overlap.length + 0.0)).map{|x| x.round(2)} end # if all hsps match only one time if averages.reject{|x| x==1} == [] @validation_report = DuplciationValidationOutput.new(1) return @validation_report end R.eval("library(preprocessCore)") #make the wilcox-test and get the p-value R.eval("coverageDistrib = c#{averages.to_s.gsub('[','(').gsub(']',')')}") R. eval("pval = wilcox.test(coverageDistrib - 1)$p.value") pval = R.pull "pval" @validation_report = DuplciationValidationOutput.new(pval) # Exception is raised when blast founds no hits rescue Exception => error # puts error.backtrace ValidationReport.new("Not enough evidence") end end end Update validation_duplication.rb tabular input format require 'genevalidator/validation_output' ## # Class that stores the validation output information class DuplciationValidationOutput < ValidationReport attr_reader :pvalue attr_reader :threshold def initialize (pvalue, threshold = 0.05, expected = :no) @pvalue = pvalue @threshold = threshold @result = validation @expected = expected end def print "pval=#{@pvalue.round(2)}" end def validation if @pvalue < @threshold :yes else :no end end def color if validation == :no "success" else "danger" end end end ## # This class contains the methods necessary for # finding duplicated subsequences in the predicted gene class DuplicationValidation < ValidationTest def initialize(type, prediction, hits = nil) super @short_header = "Duplication" @header = "Duplication" @description = "Check whether there is a duplicated subsequence in the"<< " predicted gene by counting the hsp residue coverag of the prediction,"<< " for each hit. Meaning of the output displayed: P-value of the Wilcoxon"<< " test which test the distribution of hit average coverage against 1."<< " P-values higher than 5% pass the validation test." @cli_name = "dup" end ## # Check duplication in the first n hits # Output: # +DuplciationValidationOutput+ object def run(n=10) begin raise Exception unless prediction.is_a? Sequence and hits[0].is_a? Sequence and hits.length >= 5 # get the first n hits less_hits = @hits[0..[n-1,@hits.length].min] # get raw sequences for less_hits less_hits.map do |hit| #get gene by accession number if hit.raw_sequence == nil if hit.seq_type == :protein hit.get_sequence_by_accession_no(hit.accession_no, "protein") else hit.get_sequence_by_accession_no(hit.accession_no, "nucleotide") end end end averages = [] less_hits.each do |hit| coverage = Array.new(hit.xml_length,0) hit.hsp_list.each do |hsp| # indexing in blast starts from 1 hit_local = hit.raw_sequence[hsp.hit_from-1..hsp.hit_to-1] query_local = prediction.raw_sequence[hsp.match_query_from-1..hsp.match_query_to-1] # local alignment for hit and query seqs = [hit_local, query_local] options = ['--maxiterate', '1000', '--localpair', '--quiet'] mafft = Bio::MAFFT.new("/usr/bin/mafft", options) report = mafft.query_align(seqs) raw_align = report.alignment align = [] raw_align.each { |s| align.push(s.to_s) } hit_alignment = align[0] query_alignment = align[1] =begin puts hit_alignment puts "" puts query_alignment =end aux = [] # for each hsp # iterate through the alignment and count the matching residues [*(0 .. hsp.align_len-1)].each do |i| residue_hit = hit_alignment[i] residue_query = query_alignment[i] if residue_hit != ' ' and residue_hit != '+' and residue_hit != '-' if residue_hit == residue_query # indexing in blast starts from 1 idx = i + (hsp.hit_from-1) - hit_alignment[0..i].scan(/-/).length if coverage.length > idx coverage[idx] += 1 end end end end end overlap = coverage.reject{|x| x==0} averages.push(overlap.inject(:+)/(overlap.length + 0.0)).map{|x| x.round(2)} end # if all hsps match only one time if averages.reject{|x| x==1} == [] @validation_report = DuplciationValidationOutput.new(1) return @validation_report end R.eval("library(preprocessCore)") #make the wilcox-test and get the p-value R.eval("coverageDistrib = c#{averages.to_s.gsub('[','(').gsub(']',')')}") R. eval("pval = wilcox.test(coverageDistrib - 1)$p.value") pval = R.pull "pval" @validation_report = DuplciationValidationOutput.new(pval) # Exception is raised when blast founds no hits rescue Exception => error puts error.backtrace ValidationReport.new("Not enough evidence") end end end
require 'rubygems' require 'ghtorrent/ghtorrent' require 'ghtorrent/settings' require 'ghtorrent/logging' require 'ghtorrent/command' require 'ghtorrent/retriever' class GHTRetrieveRepo < GHTorrent::Command include GHTorrent::Settings include GHTorrent::Retriever include GHTorrent::Persister def prepare_options(options) options.banner <<-BANNER An efficient way to get all data for a single repo #{command_name} [options] owner repo BANNER end def validate super Trollop::die "Two arguments are required" unless args[0] && !args[0].empty? end def logger ght.logger end def persister @persister ||= connect(:mongo, settings) @persister end def ext_uniq @ext_uniq ||= config(:uniq_id) @ext_uniq end def ght @ght ||= TransactedGHTorrent.new(settings) @ght end def go self.settings = override_config(settings, :mirror_history_pages_back, -1) user_entry = ght.transaction{ght.ensure_user(ARGV[0], false, false)} if user_entry.nil? Trollop::die "Cannot find user #{ARGV[0]}" end user = user_entry[:login] repo_entry = ght.transaction{ght.ensure_repo(ARGV[0], ARGV[1], false, false, false, false)} if repo_entry.nil? Trollop::die "Cannot find repository #{ARGV[0]}/#{ARGV[1]}" end repo = repo_entry[:name] def send_message(function, user, repo) begin ght.send(function, user, repo) rescue Exception => e puts STDERR, e.message puts STDERR, e.backtrace end end functions = %w(ensure_commits ensure_forks ensure_pull_requests ensure_issues ensure_project_members ensure_watchers) if ARGV[2].nil? functions.each do |x| send_message(x, user, repo) end else Trollop::die("Not a valid function: #{ARGV[2]}") unless functions.include? ARGV[2] send_message(ARGV[2], user, repo) end end end # A version of the GHTorrent class that creates a transaction per processed # item class TransactedGHTorrent < GHTorrent::Mirror def ensure_commit(repo, sha, user, comments = true) check_transaction do super(repo, sha, user, comments) end end def ensure_fork(owner, repo, fork_id) check_transaction do super(owner, repo, fork_id) end end def ensure_pull_request(owner, repo, pullreq_id, comments = true, commits = true, state = nil, created_at = nil) check_transaction do super(owner, repo, pullreq_id, comments, commits, state, created_at) end end def ensure_issue(owner, repo, issue_id, events = true, comments = true) check_transaction do super(owner, repo, issue_id, events, comments) end end def ensure_project_member(owner, repo, new_member, date_added) check_transaction do super(owner, repo, new_member, date_added) end end def ensure_watcher(owner, repo, watcher, date_added = nil) check_transaction do super(owner, repo, watcher, date_added) end end def check_transaction(&block) begin if @db.in_transaction? debug "Transaction already started" yield block else transaction do yield block end end rescue Exception => e puts STDERR, e.message puts STDERR, e.backtrace end end end Refresh items by default require 'rubygems' require 'ghtorrent/ghtorrent' require 'ghtorrent/settings' require 'ghtorrent/logging' require 'ghtorrent/command' require 'ghtorrent/retriever' class GHTRetrieveRepo < GHTorrent::Command include GHTorrent::Settings include GHTorrent::Retriever include GHTorrent::Persister def prepare_options(options) options.banner <<-BANNER An efficient way to get all data for a single repo #{command_name} [options] owner repo BANNER end def validate super Trollop::die "Two arguments are required" unless args[0] && !args[0].empty? end def logger ght.logger end def persister @persister ||= connect(:mongo, settings) @persister end def ext_uniq @ext_uniq ||= config(:uniq_id) @ext_uniq end def ght @ght ||= TransactedGHTorrent.new(settings) @ght end def go self.settings = override_config(settings, :mirror_history_pages_back, -1) user_entry = ght.transaction{ght.ensure_user(ARGV[0], false, false)} if user_entry.nil? Trollop::die "Cannot find user #{ARGV[0]}" end user = user_entry[:login] repo_entry = ght.transaction{ght.ensure_repo(ARGV[0], ARGV[1], false, false, false, false)} if repo_entry.nil? Trollop::die "Cannot find repository #{ARGV[0]}/#{ARGV[1]}" end repo = repo_entry[:name] def send_message(function, user, repo) begin ght.send(function, user, repo, refresh = true) rescue Exception => e puts STDERR, e.message puts STDERR, e.backtrace end end functions = %w(ensure_commits ensure_forks ensure_pull_requests ensure_issues ensure_project_members ensure_watchers) if ARGV[2].nil? functions.each do |x| send_message(x, user, repo) end else Trollop::die("Not a valid function: #{ARGV[2]}") unless functions.include? ARGV[2] send_message(ARGV[2], user, repo) end end end # A version of the GHTorrent class that creates a transaction per processed # item class TransactedGHTorrent < GHTorrent::Mirror def ensure_commit(repo, sha, user, comments = true) check_transaction do super(repo, sha, user, comments) end end def ensure_fork(owner, repo, fork_id) check_transaction do super(owner, repo, fork_id) end end def ensure_pull_request(owner, repo, pullreq_id, comments = true, commits = true, state = nil, created_at = nil) check_transaction do super(owner, repo, pullreq_id, comments, commits, state, created_at) end end def ensure_issue(owner, repo, issue_id, events = true, comments = true) check_transaction do super(owner, repo, issue_id, events, comments) end end def ensure_project_member(owner, repo, new_member, date_added) check_transaction do super(owner, repo, new_member, date_added) end end def ensure_watcher(owner, repo, watcher, date_added = nil) check_transaction do super(owner, repo, watcher, date_added) end end def check_transaction(&block) begin if @db.in_transaction? debug "Transaction already started" yield block else transaction do yield block end end rescue Exception => e puts STDERR, e.message puts STDERR, e.backtrace end end end
module GoogleSpreadsheets module Enhanced module Syncing extend ActiveSupport::Concern REL_NAME_SPREADSHEET = 'http://schemas.google.com/spreadsheets/2006#spreadsheet' REL_NAME_ROW = 'http://schemas.google.com/spreadsheets/2006#listfeed' included do class_attribute :synchronizers self.synchronizers = {} end module ClassMethods # === Example # class User < ActiveRecord::Base # include GoogleSpreadsheets::Enhanced::Syncing # sync_with :user_rows, spreadsheet_id: 'xxxx', # worksheet_title: 'users' # after_commit :sync_user_row def sync_with(rows_name, options) options.assert_valid_keys(:spreadsheet_id, :worksheet_title, :class_name, :assigner, :include_blank) opts = options.dup spreadsheet_id = opts.delete(:spreadsheet_id) worksheet_title = opts.delete(:worksheet_title) || rows_name.to_s class_name = opts.delete(:class_name) || rows_name.to_s.classify synchronizer = Synchronizer.new(self, class_name.safe_constantize, spreadsheet_id, worksheet_title, opts) self.synchronizers = self.synchronizers.merge(rows_name => synchronizer) # not share parent class attrs # rows accessor define_singleton_method(rows_name) do synchronizer = self.synchronizers[rows_name] synchronizer.all_rows end # inbound sync all (import) define_singleton_method("sync_with_#{rows_name}") do synchronizer = self.synchronizers[rows_name] synchronizer.sync_with_rows end # outbound sync one (export) define_method("sync_#{rows_name.to_s.singularize}") do synchronizer = self.class.synchronizers[rows_name] synchronizer.sync_row(self) end end end class Synchronizer attr_reader :record_class, :row_class, :spreadsheet_id, :worksheet_title def initialize(record_class, row_class, spreadsheet_id, worksheet_title, options = {}) @record_class = record_class @row_class = row_class || default_class_for(REL_NAME_ROW) @spreadsheet_id = spreadsheet_id @worksheet_title = worksheet_title @options = options end def all_rows reflections = worksheet.class.reflections.values.find_all{|ref| ref.is_a?(LinkRelations::LinkRelationReflection) } if reflection = reflections.find{|ref| ref.klass == row_class } worksheet.send(reflection.name) elsif reflection = reflections.find{|ref| ref.options[:rel] == REL_NAME_ROW } worksheet.send(reflection.name, as: row_class.to_s) else raise "Reflection for #{row_class.to_s} not found." end end def sync_with_rows reset records_to_save = {} all_rows.each do |row| record_id = row.id.to_i record = records_to_save[record_id] || record_class.find_or_initialize_by(id: record_id) if row.all_values_empty? # Due to destroy if exists record.instance_variable_set(:@due_to_destroy, true) next end row_attributes = Hash[row.aliased_attributes.map{|attr| [attr, row.send(attr)] }] row_attributes.reject!{|_, v| v.blank? } unless @options[:include_blank] if @options[:assigner] record.send(@options[:assigner], row_attributes) else assign_row_attributes(record, row_attributes) end records_to_save[row.id.to_i] = record end skipping_outbound_sync_of(records_to_save.values) do |records_with_skipped_outbound| transaction_if_possible(record_class) do records_with_skipped_outbound.each do |record| if record.instance_variable_get(:@due_to_destroy) record.destroy else record.save end end end end end def sync_row(record) return if record.instance_variable_defined?(:@_skip_outbound_sync) && record.instance_variable_get(:@_skip_outbound_sync) row = all_rows.find(record.id) if record.destroyed? row.destroy else # TODO: separate by AttributeAssignment row.aliased_attributes.each do |attr| value = (record.respond_to?(:attributes_before_type_cast) && record.attributes_before_type_cast[attr]) || record.send(attr) row.send("#{attr}=", value) end row.save end end def worksheet @worksheet ||= default_class_for(REL_NAME_SPREADSHEET) .find(spreadsheet_id) .worksheets .find_by!(title: worksheet_title) end def reset @worksheet = nil self end private def default_class_for(rel_name) LinkRelations.class_name_mappings[rel_name].classify.constantize end def assign_row_attributes(record, row_attributes) row_attributes.each do |attr, value| record.public_send("#{attr}=", value) end end def transaction_if_possible(origin = self, &block) if origin.respond_to?(:transaction) origin.transaction(&block) elsif defined?(ActiveRecord) ActiveRecord::Base.transaction(&block) else yield # no transaction end end def skipping_outbound_sync_of(records) records = Array(records) unless records.is_a?(Enumerable) records.each do |record| record.instance_variable_set(:@_skip_outbound_sync, true) end yield records ensure records.each do |record| record.remove_instance_variable(:@_skip_outbound_sync) if record.instance_variable_defined?(:@_skip_outbound_sync) end end end end end end :bug: Fix that a record only with id has not been deleted module GoogleSpreadsheets module Enhanced module Syncing extend ActiveSupport::Concern REL_NAME_SPREADSHEET = 'http://schemas.google.com/spreadsheets/2006#spreadsheet' REL_NAME_ROW = 'http://schemas.google.com/spreadsheets/2006#listfeed' included do class_attribute :synchronizers self.synchronizers = {} end module ClassMethods # === Example # class User < ActiveRecord::Base # include GoogleSpreadsheets::Enhanced::Syncing # sync_with :user_rows, spreadsheet_id: 'xxxx', # worksheet_title: 'users' # after_commit :sync_user_row def sync_with(rows_name, options) options.assert_valid_keys(:spreadsheet_id, :worksheet_title, :class_name, :assigner, :include_blank) opts = options.dup spreadsheet_id = opts.delete(:spreadsheet_id) worksheet_title = opts.delete(:worksheet_title) || rows_name.to_s class_name = opts.delete(:class_name) || rows_name.to_s.classify synchronizer = Synchronizer.new(self, class_name.safe_constantize, spreadsheet_id, worksheet_title, opts) self.synchronizers = self.synchronizers.merge(rows_name => synchronizer) # not share parent class attrs # rows accessor define_singleton_method(rows_name) do synchronizer = self.synchronizers[rows_name] synchronizer.all_rows end # inbound sync all (import) define_singleton_method("sync_with_#{rows_name}") do synchronizer = self.synchronizers[rows_name] synchronizer.sync_with_rows end # outbound sync one (export) define_method("sync_#{rows_name.to_s.singularize}") do synchronizer = self.class.synchronizers[rows_name] synchronizer.sync_row(self) end end end class Synchronizer attr_reader :record_class, :row_class, :spreadsheet_id, :worksheet_title def initialize(record_class, row_class, spreadsheet_id, worksheet_title, options = {}) @record_class = record_class @row_class = row_class || default_class_for(REL_NAME_ROW) @spreadsheet_id = spreadsheet_id @worksheet_title = worksheet_title @options = options end def all_rows reflections = worksheet.class.reflections.values.find_all{|ref| ref.is_a?(LinkRelations::LinkRelationReflection) } if reflection = reflections.find{|ref| ref.klass == row_class } worksheet.send(reflection.name) elsif reflection = reflections.find{|ref| ref.options[:rel] == REL_NAME_ROW } worksheet.send(reflection.name, as: row_class.to_s) else raise "Reflection for #{row_class.to_s} not found." end end def sync_with_rows reset records_to_save = {} all_rows.each do |row| record_id = row.id.to_i record = records_to_save[record_id] || record_class.find_or_initialize_by(id: record_id) if row.all_values_empty? # Due to destroy if exists record.instance_variable_set(:@due_to_destroy, true) records_to_save[row.id.to_i] = record next end row_attributes = Hash[row.aliased_attributes.map{|attr| [attr, row.send(attr)] }] row_attributes.reject!{|_, v| v.blank? } unless @options[:include_blank] if @options[:assigner] record.send(@options[:assigner], row_attributes) else assign_row_attributes(record, row_attributes) end records_to_save[row.id.to_i] = record end skipping_outbound_sync_of(records_to_save.values) do |records_with_skipped_outbound| transaction_if_possible(record_class) do records_with_skipped_outbound.each do |record| if record.instance_variable_get(:@due_to_destroy) record.destroy else record.save end end end end end def sync_row(record) return if record.instance_variable_defined?(:@_skip_outbound_sync) && record.instance_variable_get(:@_skip_outbound_sync) row = all_rows.find(record.id) if record.destroyed? row.destroy else # TODO: separate by AttributeAssignment row.aliased_attributes.each do |attr| value = (record.respond_to?(:attributes_before_type_cast) && record.attributes_before_type_cast[attr]) || record.send(attr) row.send("#{attr}=", value) end row.save end end def worksheet @worksheet ||= default_class_for(REL_NAME_SPREADSHEET) .find(spreadsheet_id) .worksheets .find_by!(title: worksheet_title) end def reset @worksheet = nil self end private def default_class_for(rel_name) LinkRelations.class_name_mappings[rel_name].classify.constantize end def assign_row_attributes(record, row_attributes) row_attributes.each do |attr, value| record.public_send("#{attr}=", value) end end def transaction_if_possible(origin = self, &block) if origin.respond_to?(:transaction) origin.transaction(&block) elsif defined?(ActiveRecord) ActiveRecord::Base.transaction(&block) else yield # no transaction end end def skipping_outbound_sync_of(records) records = Array(records) unless records.is_a?(Enumerable) records.each do |record| record.instance_variable_set(:@_skip_outbound_sync, true) end yield records ensure records.each do |record| record.remove_instance_variable(:@_skip_outbound_sync) if record.instance_variable_defined?(:@_skip_outbound_sync) end end end end end end
# -*- encoding: utf-8 -*- module JasperRails class JasperReportsRenderer < AbstractRenderer attr_accessor :file_extension attr_accessor :options attr_accessor :block def initialize file_extension, options, &block self.file_extension = file_extension self.options = options self.block = block end def compile jasper_file _JasperCompileManager = Rjb::import 'net.sf.jasperreports.engine.JasperCompileManager' jrxml_file = jasper_file.sub(/\.jasper$/, ".jrxml") # Recursively compile subreports Nokogiri::XML(open(jrxml_file)).css('subreport/subreportExpression').each do |subreport_expression_node| subreport_file = subreport_expression_node.text[1..-2] if Pathname.new(subreport_file).relative? subreport_file = File.expand_path(File.join(File.dirname(jrxml_file), subreport_file)) end compile(subreport_file) end # Compile it, if needed if !File.exist?(jasper_file) || (File.exist?(jrxml_file) && File.mtime(jrxml_file) > File.mtime(jasper_file)) _JasperCompileManager.compileReportToFile(jrxml_file, jasper_file) end end def fill(jasper_file, datasource, parameters, controller_options={}) _JRException = Rjb::import 'net.sf.jasperreports.engine.JRException' _JasperFillManager = Rjb::import 'net.sf.jasperreports.engine.JasperFillManager' _JasperPrint = Rjb::import 'net.sf.jasperreports.engine.JasperPrint' _JRXmlUtils = Rjb::import 'net.sf.jasperreports.engine.util.JRXmlUtils' _JREmptyDataSource = Rjb::import 'net.sf.jasperreports.engine.JREmptyDataSource' # This is here to avoid the "already initialized constant QUERY_EXECUTER_FACTORY_PREFIX" warnings. _JRXPathQueryExecuterFactory = silence_warnings{Rjb::import 'net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory'} _InputSource = Rjb::import 'org.xml.sax.InputSource' _StringReader = Rjb::import 'java.io.StringReader' _HashMap = Rjb::import 'java.util.HashMap' _ByteArrayInputStream = Rjb::import 'java.io.ByteArrayInputStream' _String = Rjb::import 'java.lang.String' parameters ||= {} # Converting default report params to java HashMap jasper_params = _HashMap.new JasperRails.config[:report_params].each do |k,v| jasper_params.put(k, v) end # Convert the ruby parameters' hash to a java HashMap, but keeps it as # default when they already represent a JRB entity. # Pay attention that, for now, all other parameters are converted to string! parameters.each do |key, value| jasper_params.put(_String.new(key.to_s, "UTF-8"), parameter_value_of(value)) end # Fill the report if datasource input_source = _InputSource.new input_source.setCharacterStream(_StringReader.new(datasource.to_xml(JasperRails.config[:xml_options].update(controller_options)).to_s)) data_document = silence_warnings do # This is here to avoid the "already initialized constant DOCUMENT_POSITION_*" warnings. _JRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source) end jasper_params.put(_JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document) jasper_print = _JasperFillManager.fillReport(jasper_file, jasper_params) else jasper_print = _JasperFillManager.fillReport(jasper_file, jasper_params, _JREmptyDataSource.new) end end def export jasper_print, jr_exporter _ByteArrayOutputStream = Rjb::import 'java.io.ByteArrayOutputStream' _JRExporter = Rjb::import jr_exporter _JRExporterParameter = Rjb::import 'net.sf.jasperreports.engine.JRExporterParameter' exporter = _JRExporter.new baos = _ByteArrayOutputStream.new exporter.setParameter(_JRExporterParameter.JASPER_PRINT, jasper_print); exporter.setParameter(_JRExporterParameter.OUTPUT_STREAM, baos) exporter.exportReport baos.toByteArray end def render jasper_file, datasource, parameters, controller_options begin compile(jasper_file) jasper_print = fill(jasper_file, datasource, parameters, controller_options) run_after_fill_blocks jasper_print, controller_options instance_exec(jasper_print, controller_options, &block) rescue Exception=>e if e.respond_to? 'printStackTrace' ::Rails.logger.error e.message e.printStackTrace else ::Rails.logger.error e.message + "\n " + e.backtrace.join("\n ") end raise e end end private def run_after_fill_blocks jasper_print, controller_options after_fill_blocks.each do |block| instance_exec(jasper_print, controller_options, &block) end end # Returns the value without conversion when it's converted to Java Types. # When isn't a Rjb class, returns a Java String of it. def parameter_value_of(param) _String = Rjb::import 'java.lang.String' # Using Rjb::import('java.util.HashMap').new, it returns an instance of # Rjb::Rjb_JavaProxy, so the Rjb_JavaProxy parent is the Rjb module itself. if param.class.parent == Rjb param else _String.new(param.to_s, "UTF-8") end end end end Moving JasperPrint gereration to its own method # -*- encoding: utf-8 -*- module JasperRails class JasperReportsRenderer < AbstractRenderer attr_accessor :file_extension attr_accessor :options attr_accessor :block def initialize file_extension, options, &block self.file_extension = file_extension self.options = options self.block = block end def compile jasper_file _JasperCompileManager = Rjb::import 'net.sf.jasperreports.engine.JasperCompileManager' jrxml_file = jasper_file.sub(/\.jasper$/, ".jrxml") # Recursively compile subreports Nokogiri::XML(open(jrxml_file)).css('subreport/subreportExpression').each do |subreport_expression_node| subreport_file = subreport_expression_node.text[1..-2] if Pathname.new(subreport_file).relative? subreport_file = File.expand_path(File.join(File.dirname(jrxml_file), subreport_file)) end compile(subreport_file) end # Compile it, if needed if !File.exist?(jasper_file) || (File.exist?(jrxml_file) && File.mtime(jrxml_file) > File.mtime(jasper_file)) _JasperCompileManager.compileReportToFile(jrxml_file, jasper_file) end end def fill(jasper_file, datasource, parameters, controller_options={}) _JRException = Rjb::import 'net.sf.jasperreports.engine.JRException' _JasperFillManager = Rjb::import 'net.sf.jasperreports.engine.JasperFillManager' _JasperPrint = Rjb::import 'net.sf.jasperreports.engine.JasperPrint' _JRXmlUtils = Rjb::import 'net.sf.jasperreports.engine.util.JRXmlUtils' _JREmptyDataSource = Rjb::import 'net.sf.jasperreports.engine.JREmptyDataSource' # This is here to avoid the "already initialized constant QUERY_EXECUTER_FACTORY_PREFIX" warnings. _JRXPathQueryExecuterFactory = silence_warnings{Rjb::import 'net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory'} _InputSource = Rjb::import 'org.xml.sax.InputSource' _StringReader = Rjb::import 'java.io.StringReader' _HashMap = Rjb::import 'java.util.HashMap' _ByteArrayInputStream = Rjb::import 'java.io.ByteArrayInputStream' _String = Rjb::import 'java.lang.String' parameters ||= {} # Converting default report params to java HashMap jasper_params = _HashMap.new JasperRails.config[:report_params].each do |k,v| jasper_params.put(k, v) end # Convert the ruby parameters' hash to a java HashMap, but keeps it as # default when they already represent a JRB entity. # Pay attention that, for now, all other parameters are converted to string! parameters.each do |key, value| jasper_params.put(_String.new(key.to_s, "UTF-8"), parameter_value_of(value)) end # Fill the report if datasource input_source = _InputSource.new input_source.setCharacterStream(_StringReader.new(datasource.to_xml(JasperRails.config[:xml_options].update(controller_options)).to_s)) data_document = silence_warnings do # This is here to avoid the "already initialized constant DOCUMENT_POSITION_*" warnings. _JRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source) end jasper_params.put(_JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document) generate_jasper_print jasper_params, jasper_file else jasper_print = _JasperFillManager.fillReport(jasper_file, jasper_params, _JREmptyDataSource.new) end end def generate_jasper_print jasper_params, jasper_file _JasperFillManager = Rjb::import 'net.sf.jasperreports.engine.JasperFillManager' jasper_print = _JasperFillManager.fillReport(jasper_file, jasper_params) end def export jasper_print, jr_exporter _ByteArrayOutputStream = Rjb::import 'java.io.ByteArrayOutputStream' _JRExporter = Rjb::import jr_exporter _JRExporterParameter = Rjb::import 'net.sf.jasperreports.engine.JRExporterParameter' exporter = _JRExporter.new baos = _ByteArrayOutputStream.new exporter.setParameter(_JRExporterParameter.JASPER_PRINT, jasper_print) exporter.setParameter(_JRExporterParameter.OUTPUT_STREAM, baos) exporter.exportReport baos.toByteArray end def render jasper_file, datasource, parameters, controller_options begin compile(jasper_file) jasper_print = fill(jasper_file, datasource, parameters, controller_options) run_after_fill_blocks jasper_print, controller_options instance_exec(jasper_print, controller_options, &block) rescue Exception=>e if e.respond_to? 'printStackTrace' ::Rails.logger.error e.message e.printStackTrace else ::Rails.logger.error e.message + "\n " + e.backtrace.join("\n ") end raise e end end private def run_after_fill_blocks jasper_print, controller_options after_fill_blocks.each do |block| instance_exec(jasper_print, controller_options, &block) end end # Returns the value without conversion when it's converted to Java Types. # When isn't a Rjb class, returns a Java String of it. def parameter_value_of(param) _String = Rjb::import 'java.lang.String' # Using Rjb::import('java.util.HashMap').new, it returns an instance of # Rjb::Rjb_JavaProxy, so the Rjb_JavaProxy parent is the Rjb module itself. if param.class.parent == Rjb param else _String.new(param.to_s, "UTF-8") end end end end
module Middleman module GoogleAnalytics class Options < Struct.new(:tracking_id, :anonymize_ip, :debug); end class << self def options @@options ||= Options.new(options) end def registered(app, options={}) @@options ||= Options.new(options) yield @@options if block_given? app.send :include, InstanceMethods end alias :included :registered end module InstanceMethods def google_analytics_tag options = ::Middleman::GoogleAnalytics.options options.debug ||= not build? ga = options.debug ? 'ga' : '/u/ga_debug' if tracking_id = options.tracking_id gaq = [] gaq << ['_setAccount', "#{tracking_id}"] gaq << ['_gat._anonymizeIp'] if options.anonymize_ip gaq << ['_trackPageview'] %Q{<script type="text/javascript"> //<![CDATA[ var _gaq = _gaq || []; #{gaq.map! { |x| "_gaq.push(#{x});" }.join("\n ")} (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? '//ssl' : '//www') + '.google-analytics.com/#{ga}.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); //]]> </script>} end end end end end Fix syntax error module Middleman module GoogleAnalytics class Options < Struct.new(:tracking_id, :anonymize_ip, :debug); end class << self def options @@options ||= Options.new(options) end def registered(app, options={}) @@options ||= Options.new(options) yield @@options if block_given? app.send :include, InstanceMethods end alias :included :registered end module InstanceMethods def google_analytics_tag options = ::Middleman::GoogleAnalytics.options options.debug ||= (not build?) ga = options.debug ? 'ga' : '/u/ga_debug' if tracking_id = options.tracking_id gaq = [] gaq << ['_setAccount', "#{tracking_id}"] gaq << ['_gat._anonymizeIp'] if options.anonymize_ip gaq << ['_trackPageview'] %Q{<script type="text/javascript"> //<![CDATA[ var _gaq = _gaq || []; #{gaq.map! { |x| "_gaq.push(#{x});" }.join("\n ")} (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? '//ssl' : '//www') + '.google-analytics.com/#{ga}.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); //]]> </script>} end end end end end
# frozen-string-literal: true require "mobility/plugins/active_model/dirty" module Mobility module Plugins module ActiveRecord =begin Dirty tracking for AR models. See {Mobility::Plugins::ActiveModel::Dirty} for details on usage. In addition to methods added by {Mobility::Plugins::ActiveModel::Dirty}, the AR::Dirty plugin adds support for the following persistence-specific methods (for a model with a translated attribute +title+): - +saved_changes+ - +saved_change_to_title?+ - +saved_change_to_title+ - +title_before_last_save+ - +will_save_change_to_title?+ - +title_change_to_be_saved+ - +title_in_database+ =end module Dirty include ActiveModel::Dirty # Builds module which patches a few AR methods to handle changes to # translated attributes just like normal attributes. class MethodsBuilder < ActiveModel::Dirty::MethodsBuilder def initialize(*attribute_names) super @attribute_names = attribute_names define_method_overrides if ::ActiveRecord::VERSION::STRING < '5.2' define_attribute_methods if ::ActiveRecord::VERSION::STRING >= '5.1' end # Overrides +ActiveRecord::AttributeMethods::ClassMethods#has_attribute+ (in AR 5.1) and # +ActiveModel::AttributeMethods#_read_attribute+ (in AR >= 5.2) to # ensure that fallthrough attribute methods are treated like "real" # attribute methods. # # @note Patching +has_attribute?+ is necessary in AR 5.1 due to this commit[https://github.com/rails/rails/commit/4fed08fa787a316fa51f14baca9eae11913f5050]. # @param [Attributes] attributes def included(model_class) super if ::ActiveRecord::VERSION::MAJOR == 5 && ::ActiveRecord::VERSION::MINOR == 1 names = @attribute_names method_name_regex = /\A(#{names.join('|')})_([a-z]{2}(_[a-z]{2})?)(=?|\??)\z/.freeze has_attribute = Module.new do define_method :has_attribute? do |attr_name| super(attr_name) || !!method_name_regex.match(attr_name) end end model_class.extend has_attribute elsif ::ActiveRecord::VERSION::STRING >= '5.2' model_class.include ReadAttribute end end private # @note These method overrides are needed for AR versions < 5.2, # since AR::Dirty overrides AM::Dirty, disabling previous_changes # from being set. Here we "undo" that. def define_method_overrides changes_applied_method = ::ActiveRecord::VERSION::STRING < '5.1' ? :changes_applied : :changes_internally_applied define_method changes_applied_method do @previously_changed = changes super() end define_method :clear_changes_information do @previously_changed = ActiveSupport::HashWithIndifferentAccess.new super() end define_method :previous_changes do (@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super()) end end # For AR >= 5.1 only def define_attribute_methods define_method :saved_changes do (@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super()) end @attribute_names.each do |name| define_method :"saved_change_to_#{name}?" do previous_changes.include?(Mobility.normalize_locale_accessor(name)) end define_method :"saved_change_to_#{name}" do previous_changes[Mobility.normalize_locale_accessor(name)] end define_method :"#{name}_before_last_save" do previous_changes[Mobility.normalize_locale_accessor(name)].first end alias_method :"will_save_change_to_#{name}?", :"#{name}_changed?" alias_method :"#{name}_change_to_be_saved", :"#{name}_change" alias_method :"#{name}_in_database", :"#{name}_was" end end # Overrides _read_attribute to correctly dispatch reads on translated # attributes to their respective setters, rather than to # +@attributes+, which would otherwise return +nil+. # # For background on why this is necessary, see: # https://github.com/shioyama/mobility/issues/115 module ReadAttribute # @note We first check if attributes has the key +attr+ to avoid # doing any extra work in case this is a "normal" # (non-translated) attribute. def _read_attribute(attr, *args) if @attributes.key?(attr) super else mobility_changed_attributes.include?(attr) ? __send__(attr) : super end end end end end end end end Always assign @previously_changed if translated attributes change # frozen-string-literal: true require "mobility/plugins/active_model/dirty" module Mobility module Plugins module ActiveRecord =begin Dirty tracking for AR models. See {Mobility::Plugins::ActiveModel::Dirty} for details on usage. In addition to methods added by {Mobility::Plugins::ActiveModel::Dirty}, the AR::Dirty plugin adds support for the following persistence-specific methods (for a model with a translated attribute +title+): - +saved_changes+ - +saved_change_to_title?+ - +saved_change_to_title+ - +title_before_last_save+ - +will_save_change_to_title?+ - +title_change_to_be_saved+ - +title_in_database+ =end module Dirty include ActiveModel::Dirty # Builds module which patches a few AR methods to handle changes to # translated attributes just like normal attributes. class MethodsBuilder < ActiveModel::Dirty::MethodsBuilder def initialize(*attribute_names) super @attribute_names = attribute_names define_method_overrides if ::ActiveRecord::VERSION::STRING < '5.2' define_attribute_methods if ::ActiveRecord::VERSION::STRING >= '5.1' end # Overrides +ActiveRecord::AttributeMethods::ClassMethods#has_attribute+ (in AR 5.1) and # +ActiveModel::AttributeMethods#_read_attribute+ (in AR >= 5.2) to # ensure that fallthrough attribute methods are treated like "real" # attribute methods. # # @note Patching +has_attribute?+ is necessary in AR 5.1 due to this commit[https://github.com/rails/rails/commit/4fed08fa787a316fa51f14baca9eae11913f5050]. # @param [Attributes] attributes def included(model_class) super if ::ActiveRecord::VERSION::MAJOR == 5 && ::ActiveRecord::VERSION::MINOR == 1 names = @attribute_names method_name_regex = /\A(#{names.join('|')})_([a-z]{2}(_[a-z]{2})?)(=?|\??)\z/.freeze has_attribute = Module.new do define_method :has_attribute? do |attr_name| super(attr_name) || !!method_name_regex.match(attr_name) end end model_class.extend has_attribute elsif ::ActiveRecord::VERSION::STRING >= '5.2' model_class.include ReadAttribute end end private # @note These method overrides are needed for AR versions < 5.2, # since AR::Dirty overrides AM::Dirty, disabling previous_changes # from being set. Here we "undo" that. def define_method_overrides changes_applied_method = ::ActiveRecord::VERSION::STRING < '5.1' ? :changes_applied : :changes_internally_applied define_method changes_applied_method do @previously_changed = changes super() end define_method :clear_changes_information do @previously_changed = ActiveSupport::HashWithIndifferentAccess.new super() end define_method :previous_changes do (@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super()) end end # For AR >= 5.1 only def define_attribute_methods define_method :saved_changes do (@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super()) end @attribute_names.each do |name| define_method :"saved_change_to_#{name}?" do previous_changes.include?(Mobility.normalize_locale_accessor(name)) end define_method :"saved_change_to_#{name}" do previous_changes[Mobility.normalize_locale_accessor(name)] end define_method :"#{name}_before_last_save" do previous_changes[Mobility.normalize_locale_accessor(name)].first end alias_method :"will_save_change_to_#{name}?", :"#{name}_changed?" alias_method :"#{name}_change_to_be_saved", :"#{name}_change" alias_method :"#{name}_in_database", :"#{name}_was" end end # Overrides _read_attribute to correctly dispatch reads on translated # attributes to their respective setters, rather than to # +@attributes+, which would otherwise return +nil+. # # For background on why this is necessary, see: # https://github.com/shioyama/mobility/issues/115 module ReadAttribute # @note We first check if attributes has the key +attr+ to avoid # doing any extra work in case this is a "normal" # (non-translated) attribute. def _read_attribute(attr, *args) if @attributes.key?(attr) super else mobility_changed_attributes.include?(attr) ? __send__(attr) : super end end # @note This is necessary due to a performance fix in e12607 # which skips setting @previously_changed if @attributes is # defined. For Mobility models using the Dirty plugin, there will # be cases where @attributes has been set, but there are *other* # changes on virtual translated attributes which need to also be # assigned. In this case, we use the presence of such changed # virtual attributes as an alternative trigger to set this variable. # # See: # - https://github.com/rails/rails/commit/e126078a0e013acfe0a397a8dad33b2c9de78732 # - https://github.com/shioyama/mobility/pull/166 def changes_applied if defined?(@attributes) && mobility_changed_attributes.any? @previously_changed = changes end super end end end end end end end
require 'date' module NipperParser # SecurityAudit parses the 'Security Audit' part including all it's sections. # Security Audit part contains the following sections: # - introduction # - findings # - Conclusions # - Recommendations # - Mitigation Classification # # @example Basic Usage # require 'nokogiri' # require 'pp' # config = Nokogiri::XML open(ARGV[0]) # security_audit = NipperParser::SecurityAudit.new(config) # pp security_audit.introduction.index # pp security_audit.introduction.title # pp security_audit.introduction.devices # @example Dealing with findings # finding = security_audit.findings[1] # pp finding.index # pp finding.title # pp finding.ref # pp finding.affected_devices # pp finding.finding # pp finding.impact # pp finding.recommendation # @example Dealing with report summaries # pp security_audit.conclusions # pp security_audit.conclusions.per_device # pp security_audit.conclusions.list_critical # pp security_audit.recommendations.list # # pp security_audit.mitigation_classification # pp security_audit.mitigation_classification.list_by.fixing[:involved] # pp security_audit.mitigation_classification.list_by.fixing[:involved][0].rating[:rating] # pp security_audit.mitigation_classification.list_by.rating[:high] # pp security_audit.mitigation_classification.list_by.rating[:high][0].rating[:fix] # pp security_audit.mitigation_classification.statistics # pp security_audit.mitigation_classification.statistics.critical # pp security_audit.mitigation_classification.statistics.quick # pp security_audit.mitigation_classification.statistics.report # # @param config [Nokogiri::XML] parsed XML # @attr_reader title the report title # @attr_reader config a parsed XML [Nokogiri::XML] object class SecurityAudit include ParserUtils # Skeleton for SecurityAudit parts Introduction = Struct.new( :index, :title, :ref, :date, :devices, :security_issue_overview, :rating ) Finding = Struct.new( :index, :title, :ref, :affected_devices, :rating, :finding, :impact, :ease, :recommendation ) Conclusion = Struct.new( :index, :title, :ref, :per_device, :per_rating, :list_critical, :list_high, :list_medium, :list_low, :list_info ) Recommendations = Struct.new( :index, :title, :ref, :list ) MitigationClassification = Struct.new( :index, :title, :ref, :list_by, :statistics ) ListBy = Struct.new( :fixing, :rating, :all ) Statistics = Struct.new( :findings, :critical, :high, :medium, :low, :informational, :quick, :planned, :involved, :report ) attr_reader :config, :title def initialize(config) @config = config.xpath("//report/part[@ref='SECURITYAUDIT']")[0].elements @title = @config[0].elements[1].attributes['title'].text introduction findings end def introduction intro = @config[0] index = attributes(intro).index title = attributes(intro).title reference = attributes(intro).ref.to_i date = Date.parse(intro.elements[0].text).to_s devices = generate_table(intro.elements[1].elements) security_issue_overview = {} intro.elements[2].elements[1..4].map do |issue| security_issue_overview[issue['title']] = issue.text end rating = generate_table(intro.elements[3].elements[2].elements[1].elements) Introduction.new( index, title, reference, date, devices, security_issue_overview, rating ) end # Parse findings from given configurations # @return [Array<Finding>] def findings findings = @config.to_a.clone findings.shift # pop first item, the introduction findings.pop(3) # pop last 3 item, conclusion, recommendations, Mitigation Classification @findings = findings.map do |finding| Finding.new( attributes(finding).index.to_f, attributes(finding).title, attributes(finding).ref, finding.elements[0].elements[0].elements.map(&:attributes), # affected_devices rating_table(finding.elements[0].elements[1].elements), finding.elements[2].elements.first(2).map(&:text).join("\n"), # finding finding.elements[3].elements.text, # impact finding.elements[4].elements.text, # ease finding.elements[5].elements.text # recommendation ) end end # Conclusions def conclusions conc = @config[-3] index = attributes(conc).index.to_f title = attributes(conc).title reference = attributes(conc).ref per_device = generate_table(conc.elements[1].elements) per_rating = { critical: conc.elements[3].elements.map(&:text), high: conc.elements[5].elements.map(&:text), medium: conc.elements[7].elements.map(&:text), low: conc.elements[9].elements.map(&:text), info: conc.elements[11].elements.map(&:text) } Conclusion.new( index, title, reference, per_device, per_rating, per_rating[:critical], per_rating[:high], per_rating[:medium], per_rating[:low], per_rating[:info], ) end # Recommendations def recommendations # recom = @config[-2] recom = @config.search("section[@ref='SECURITY.RECOMMENDATIONS']")[0] index = attributes(recom).index.to_f title = attributes(recom).title reference = attributes(recom).ref list = generate_table(recom.elements[1].elements) Recommendations.new( index, title, reference, list ) end def mitigation_classification @mitigation = @config.search("section[@ref='SECURITY.MITIGATIONS']")[0] # @config[-1] index = attributes(@mitigation).index title = attributes(@mitigation).title reference = attributes(@mitigation).ref MitigationClassification.new( index, title, reference, list_by, statistics ) end private # list_by list different type of mitigation, by fixing type, and by rating type. # # @example: # list_by.fixing #=> [Hash] # list_by.fixing[:quick] #=> [Array<Findings>] # list_by.rating #=> [Hash] # list_by.rating[:critical] #=> [Array<Findings>] # list_by.all #=> [Hash] # # @return [ListBy] def list_by @fixing_lists = @mitigation.search('list') _by_fixing = by_fixing _by_rating = by_rating fixing = {quick: _by_fixing[0], planned: _by_fixing[1], involved: _by_fixing[2]} rating = {critical: _by_rating[:critical], high: _by_rating[:high], medium: _by_rating[:medium], low: _by_rating[:low], informational: _by_rating[:informational]} _by_all = {fixing: fixing, rating: rating} ListBy.new( _by_all[:fixing], _by_all[:rating], _by_all ) end # finding_objects maps finding listitems text with the findings object def by_fixing findings = @findings.dup @fixing_lists.map do |_class| _class.search('listitem').map do |item| # if finding reference = item mentioned index (extracted from text), then return the finding object findings.select{|finding| finding.index == item.text.match(/\d+\.\d+/).to_s.to_f}[0] end end end # search in all finding by rating def by_rating findings = @findings.dup rating = {critical: nil, high: nil, medium: nil, low: nil, informational: nil} rating.keys.each do |rate| rating[rate] = findings.select {|finding| finding.rating[:rating].downcase == rate.to_s} end rating end # mitigation statistics def statistics findings = @findings.size ratings = {critical: nil, high: nil, medium: nil, low: nil, informational: nil} ratings.keys.each do |rating| ratings[rating] = {total: list_by.rating[rating].size, perce: ( (list_by.rating[rating].size/@findings.size.to_f) * 100.0 ).round(2)} end fixing = {quick: nil, involved: nil, planned: nil} fixing.keys.each do |fix| fixing[fix] = {total: list_by.fixing[fix].size, perce: ( (list_by.fixing[fix].size/@findings.size.to_f) * 100.0 ).round(2)} end report = {ratings: ratings, fixing: fixing} Statistics.new( findings, ratings[:critical], ratings[:high], ratings[:medium], ratings[:low], ratings[:informational], fixing[:quick], fixing[:involved], fixing[:planned], report ) end end end if __FILE__ == $0 require 'nokogiri' require 'pp' require_relative 'parser_utils' config = Nokogiri::XML open(ARGV[0]) security_audit = NipperParser::SecurityAudit.new(config) pp security_audit.introduction.index pp security_audit.introduction.title pp security_audit.introduction.rating pp security_audit.introduction.security_issue_overview pp security_audit.introduction.ref pp security_audit.introduction.devices finding = security_audit.findings[0] pp finding pp finding.index pp finding.title pp finding.rating pp finding.ref pp finding.affected_devices pp finding.finding pp finding.impact pp finding.recommendation pp security_audit.introduction pp security_audit.conclusions pp security_audit.conclusions.per_device pp security_audit.conclusions.list_critical pp security_audit.recommendations.list pp security_audit.mitigation_classification pp security_audit.mitigation_classification.list_by.fixing[:involved] pp security_audit.mitigation_classification.list_by.fixing[:involved][0].rating[:rating] pp security_audit.mitigation_classification.list_by.rating[:high] pp security_audit.mitigation_classification.list_by.rating[:high][0].rating[:fix] pp security_audit.mitigation_classification.statistics.findings pp security_audit.mitigation_classification.statistics pp security_audit.mitigation_classification.statistics.report end fix documentations require 'date' require_relative 'parser_utils' module NipperParser # SecurityAudit parses the 'Security Audit' part including all it's sections. # Security Audit part contains the following sections: # - introduction # - findings # - Conclusions # - Recommendations # - Mitigation Classification # # @example Basic Usage # require 'nokogiri' # require 'pp' # config = Nokogiri::XML open(ARGV[0]) # security_audit = NipperParser::SecurityAudit.new(config) # pp security_audit.introduction.class # pp security_audit.introduction.index # pp security_audit.introduction.title # pp security_audit.introduction.devices # @example Dealing with findings # finding = security_audit.findings[0] # pp finding.class # pp finding.index # pp finding.title # pp finding.ref # pp finding.affected_devices # pp finding.finding # pp finding.impact # pp finding.recommendation # @example Dealing with report summaries # pp security_audit.conclusions.class # pp security_audit.conclusions.per_device # pp security_audit.conclusions.list_critical # pp security_audit.recommendations.class # pp security_audit.recommendations.list # pp security_audit.mitigation_classification.class # pp security_audit.mitigation_classification.list_by.fixing[:involved] # pp security_audit.mitigation_classification.list_by.fixing[:involved][0].rating[:rating] # pp security_audit.mitigation_classification.list_by.rating[:high] # pp security_audit.mitigation_classification.list_by.rating[:high][0].rating[:fix] # pp security_audit.mitigation_classification.statistics.class # pp security_audit.mitigation_classification.statistics.critical # pp security_audit.mitigation_classification.statistics.quick # pp security_audit.mitigation_classification.statistics.report # # @param config [Nokogiri::XML] parsed XML # @attr_reader title the report title # @attr_reader config a parsed XML [Nokogiri::XML] object class SecurityAudit include ParserUtils # Skeleton for SecurityAudit parts Introduction = Struct.new( # introduction's index :index, :title, :ref, :date, :devices, :security_issue_overview, :rating ) Finding = Struct.new( :index, :title, :ref, :affected_devices, :rating, :finding, :impact, :ease, :recommendation ) Conclusion = Struct.new( :index, :title, :ref, :per_device, :per_rating, :list_critical, :list_high, :list_medium, :list_low, :list_info ) Recommendations = Struct.new( :index, :title, :ref, :list ) MitigationClassification = Struct.new( :index, :title, :ref, :list_by, :statistics ) ListBy = Struct.new( :fixing, :rating, :all ) Statistics = Struct.new( :findings, :critical, :high, :medium, :low, :informational, :quick, :planned, :involved, :report ) attr_reader :config, :title # @param config [Nokogiri::XML::Document] def initialize(config) @config = config.xpath("//report/part[@ref='SECURITYAUDIT']")[0].elements @title = @config[0].elements[1].attributes['title'].text introduction findings end # Introduction of the Security Audit report def introduction intro = @config[0] index = attributes(intro).index title = attributes(intro).title reference = attributes(intro).ref.to_i date = Date.parse(intro.elements[0].text).to_s devices = generate_table(intro.elements[1].elements) security_issue_overview = {} intro.elements[2].elements[1..4].map do |issue| security_issue_overview[issue['title']] = issue.text end rating = generate_table(intro.elements[3].elements[2].elements[1].elements) Introduction.new( index, title, reference, date, devices, security_issue_overview, rating ) end # Parse findings from given configurations # @return [Array<Finding>] def findings findings = @config.to_a.clone findings.shift # pop first item, the introduction findings.pop(3) # pop last 3 item, conclusion, recommendations, Mitigation Classification @findings = findings.map do |finding| Finding.new( attributes(finding).index.to_f, attributes(finding).title, attributes(finding).ref, finding.elements[0].elements[0].elements.map(&:attributes), # affected_devices rating_table(finding.elements[0].elements[1].elements), # Rating table finding.elements[2].elements.first(2).map(&:text).join("\n"), # finding finding.elements[3].elements.text, # impact finding.elements[4].elements.text, # ease finding.elements[5].elements.text # recommendation ) end end # Conclusions def conclusions conc = @config.search("section[@ref='SECURITY.CONCLUSIONS']")[0] index = attributes(conc).index.to_f title = attributes(conc).title reference = attributes(conc).ref per_device = generate_table(conc.elements[1].elements) per_rating = { critical: conc.elements[3].elements.map(&:text), high: conc.elements[5].elements.map(&:text), medium: conc.elements[7].elements.map(&:text), low: conc.elements[9].elements.map(&:text), info: conc.elements[11].elements.map(&:text) } Conclusion.new( index, title, reference, per_device, per_rating, per_rating[:critical], per_rating[:high], per_rating[:medium], per_rating[:low], per_rating[:info], ) end # Recommendations def recommendations recom = @config.search("section[@ref='SECURITY.RECOMMENDATIONS']")[0] index = attributes(recom).index.to_f title = attributes(recom).title reference = attributes(recom).ref list = generate_table(recom.elements[1].elements) Recommendations.new( index, title, reference, list ) end def mitigation_classification @mitigation = @config.search("section[@ref='SECURITY.MITIGATIONS']")[0] # @config[-1] index = attributes(@mitigation).index title = attributes(@mitigation).title reference = attributes(@mitigation).ref MitigationClassification.new( index, title, reference, list_by, statistics ) end private # list_by list different type of mitigation, by fixing type, and by rating type. # # @example: # list_by.fixing # @return [Hash] # list_by.fixing[:quick] # @return [Array<Findings>] # list_by.rating # @return [Hash] # list_by.rating[:critical] # @return [Array<Findings>] # list_by.all # @return [Hash] # # @return [ListBy] def list_by @fixing_lists = @mitigation.search('list') _by_fixing = by_fixing # @see by_fixing _by_rating = by_rating # @see by_rating fixing = {quick: _by_fixing[0], planned: _by_fixing[1], involved: _by_fixing[2]} rating = {critical: _by_rating[:critical], high: _by_rating[:high], medium: _by_rating[:medium], low: _by_rating[:low], informational: _by_rating[:informational]} _by_all = {fixing: fixing, rating: rating} ListBy.new( _by_all[:fixing], _by_all[:rating], _by_all ) end # finding_objects maps finding listitems text with the findings object def by_fixing findings = @findings.dup @fixing_lists.map do |_class| _class.search('listitem').map do |item| # if 'finding' reference = item mentioned index (extracted from text 'See section' ), # then return the finding object findings.select{|finding| finding.index == item.text.match(/\d+\.\d+/).to_s.to_f}[0] end end end # search in all finding by rating def by_rating findings = @findings.dup rating = {critical: nil, high: nil, medium: nil, low: nil, informational: nil} rating.keys.each do |rate| rating[rate] = findings.select {|finding| finding.rating[:rating].downcase == rate.to_s} end rating end # mitigation statistics regarding to number of: # - findings # - findings by rating # - findings by fixing # @return [Statistics] def statistics findings = @findings.size ratings = {critical: nil, high: nil, medium: nil, low: nil, informational: nil} ratings.keys.each do |rating| ratings[rating] = {total: list_by.rating[rating].size, perce: ( (list_by.rating[rating].size/@findings.size.to_f) * 100.0 ).round(2)} end fixing = {quick: nil, involved: nil, planned: nil} fixing.keys.each do |fix| fixing[fix] = {total: list_by.fixing[fix].size, perce: ( (list_by.fixing[fix].size/@findings.size.to_f) * 100.0 ).round(2)} end report = {ratings: ratings, fixing: fixing} Statistics.new( findings, ratings[:critical], ratings[:high], ratings[:medium], ratings[:low], ratings[:informational], fixing[:quick], fixing[:involved], fixing[:planned], report ) end end end if __FILE__ == $0 require 'nokogiri' require 'pp' require_relative 'parser_utils' config = Nokogiri::XML open(ARGV[0]) security_audit = NipperParser::SecurityAudit.new(config) pp security_audit.introduction.class pp security_audit.introduction.index pp security_audit.introduction.title pp security_audit.introduction.rating pp security_audit.introduction.security_issue_overview pp security_audit.introduction.ref pp security_audit.introduction.devices finding = security_audit.findings[0] pp finding.class pp finding.index pp finding.title pp finding.rating pp finding.ref pp finding.affected_devices pp finding.finding pp finding.impact pp finding.recommendation pp security_audit.introduction pp security_audit.conclusions.class pp security_audit.conclusions.per_device pp security_audit.conclusions.list_critical pp security_audit.recommendations.class pp security_audit.recommendations.list pp security_audit.mitigation_classification.class pp security_audit.mitigation_classification.list_by.fixing[:involved] pp security_audit.mitigation_classification.list_by.fixing[:involved][0].rating[:rating] pp security_audit.mitigation_classification.list_by.rating[:high] pp security_audit.mitigation_classification.list_by.rating[:high][0].rating[:fix] pp security_audit.mitigation_classification.statistics.class pp security_audit.mitigation_classification.statistics.findings pp security_audit.mitigation_classification.statistics.report end
%w{ timeout blather/client/dsl punchblock/core_ext/blather/stanza punchblock/core_ext/blather/stanza/presence }.each { |f| require f } module Punchblock module Protocol class Ozone class Connection < GenericConnection include Blather::DSL ## # Initialize the required connection attributes # # @param [Hash] options # @option options [String] :username client JID # @option options [String] :password XMPP password # @option options [String] :ozone_domain the domain on which Ozone is running # @option options [Logger] :wire_logger to which all XMPP transactions will be logged # @option options [Boolean, Optional] :auto_reconnect whether or not to auto reconnect # def initialize(options = {}) super raise ArgumentError unless @username = options.delete(:username) raise ArgumentError unless options.has_key? :password @ozone_domain = options[:ozone_domain] || Blather::JID.new(@username).domain setup @username, options.delete(:password) # This hash is used to synchronize between threads calling #write # and the connection-level responses they need to return from the # EventMachine loop. @command_callbacks = {} @callmap = {} # This hash maps call IDs to their XMPP domain. @command_id_to_iq_id = {} @iq_id_to_command = {} @auto_reconnect = !!options[:auto_reconnect] @reconnect_attempts = 0 Blather.logger = options.delete(:wire_logger) if options.has_key?(:wire_logger) # FIXME: Force autoload events so they get registered properly [Event::Answered, Event::Complete, Event::End, Event::Info, Event::Offer, Event::Ringing, Ref] end ## # Write a command to the Ozone server for a particular call # # @param [Call, String] call the call on which to act, or its ID # @param [CommandNode] cmd the command to execute on the call # @param [String, Optional] command_id the command_id on which to execute # # @raise Exception if there is a server-side error # # @return true # def write(call_id, cmd, command_id = nil) queue = async_write call_id, cmd, command_id begin Timeout::timeout(3) { queue.pop } ensure queue = nil # Shut down this queue end.tap { |result| raise result if result.is_a? Exception } end ## # @return [Queue] Pop this queue to determine result of command execution. Will be true or an exception def async_write(call_id, cmd, command_id = nil) iq = prep_command_for_execution call_id, cmd, command_id Queue.new.tap do |queue| @command_callbacks[iq.id] = lambda do |result| case result when Blather::Stanza::Iq ref = result.ozone_node if ref.is_a?(Ref) cmd.command_id = ref.id @command_id_to_iq_id[ref.id] = iq.id end cmd.execute! queue << true when Exception queue << result end end write_to_stream iq cmd.request! end end def prep_command_for_execution(call_id, cmd, command_id = nil) cmd.connection = self call_id = call_id.call_id if call_id.is_a? Call cmd.call_id = call_id jid = cmd.is_a?(Command::Dial) ? @ozone_domain : "#{call_id}@#{@callmap[call_id]}" jid << "/#{command_id}" if command_id create_iq(jid).tap do |iq| @logger.debug "Sending IQ ID #{iq.id} #{cmd.inspect} to #{jid}" if @logger iq << cmd @iq_id_to_command[iq.id] = cmd end end ## # Fire up the connection # def run register_handlers connect end def connect Thread.new do begin trap(:INT) do @reconnect_attempts = nil EM.stop end trap(:TERM) do @reconnect_attempts = nil EM.stop end EM.run { client.run } rescue Blather::SASLError, Blather::StreamError => e raise ProtocolError.new(e.class.to_s, e.message) rescue => e puts "Exception in XMPP thread! #{e}" puts e.backtrace.join("\t\n") end end end def connected? client.connected? end ## # # Get the original command issued by command ID # # @param [String] command_id # # @return [OzoneNode] # def original_command_from_id(command_id) @iq_id_to_command[@command_id_to_iq_id[command_id]] end private def handle_presence(p) @logger.info "Receiving event for call ID #{p.call_id}" if @logger @callmap[p.call_id] = p.from.domain @logger.debug p.inspect if @logger event = p.event event.connection = self event.source.add_event event if event.source @event_queue.push event.is_a?(Event::Offer) ? Punchblock::Call.new(p.call_id, p.to, event.headers_hash) : event end def handle_iq_result(iq) # FIXME: Do we need to raise a warning if the domain changes? @callmap[iq.from.node] = iq.from.domain @logger.debug "Command #{iq.id} completed successfully" if @logger callback = @command_callbacks[iq.id] callback.call iq if callback end def handle_error(iq) e = Blather::StanzaError.import iq protocol_error = ProtocolError.new e.name, e.text, iq.call_id, iq.command_id if callback = @command_callbacks[iq.id] callback.call protocol_error else # Un-associated transport error?? raise protocol_error end end def register_handlers # Push a message to the queue and the log that we connected when_ready do @event_queue.push connected @logger.info "Connected to XMPP as #{@username}" if @logger @reconnect_attempts = 0 @ozone_ping = EM::PeriodicTimer.new(60) { ping_ozone } end disconnected do @ozone_ping.cancel if @ozone_ping if @auto_reconnect && @reconnect_attempts timer = 30 * 2 ** @reconnect_attempts @logger.warn "XMPP disconnected. Tried to reconnect #{@reconnect_attempts} times. Reconnecting in #{timer}s." if @logger sleep timer @logger.info "Trying to reconnect..." if @logger @reconnect_attempts += 1 connect end end # Read/handle call control messages. These are mostly just acknowledgement of commands iq :result? do |msg| handle_iq_result msg end # Read/handle error IQs iq :error? do |e| handle_error e end # Read/handle presence requests. This is how we get events. presence { |msg| handle_presence msg } end def ping_ozone client.write_with_handler Blather::Stanza::Iq::Ping.new(:set, @ozone_domain) do |response| begin handle_error response if response.is_a? Blather::BlatherError rescue ProtocolError => e raise e unless e.name == :feature_not_implemented end end end def create_iq(jid = nil) Blather::Stanza::Iq.new :set, jid || @call_id end end end end end Swallow xmpp ping errors %w{ timeout blather/client/dsl punchblock/core_ext/blather/stanza punchblock/core_ext/blather/stanza/presence }.each { |f| require f } module Punchblock module Protocol class Ozone class Connection < GenericConnection include Blather::DSL ## # Initialize the required connection attributes # # @param [Hash] options # @option options [String] :username client JID # @option options [String] :password XMPP password # @option options [String] :ozone_domain the domain on which Ozone is running # @option options [Logger] :wire_logger to which all XMPP transactions will be logged # @option options [Boolean, Optional] :auto_reconnect whether or not to auto reconnect # def initialize(options = {}) super raise ArgumentError unless @username = options.delete(:username) raise ArgumentError unless options.has_key? :password @ozone_domain = options[:ozone_domain] || Blather::JID.new(@username).domain setup @username, options.delete(:password) # This hash is used to synchronize between threads calling #write # and the connection-level responses they need to return from the # EventMachine loop. @command_callbacks = {} @callmap = {} # This hash maps call IDs to their XMPP domain. @command_id_to_iq_id = {} @iq_id_to_command = {} @auto_reconnect = !!options[:auto_reconnect] @reconnect_attempts = 0 Blather.logger = options.delete(:wire_logger) if options.has_key?(:wire_logger) # FIXME: Force autoload events so they get registered properly [Event::Answered, Event::Complete, Event::End, Event::Info, Event::Offer, Event::Ringing, Ref] end ## # Write a command to the Ozone server for a particular call # # @param [Call, String] call the call on which to act, or its ID # @param [CommandNode] cmd the command to execute on the call # @param [String, Optional] command_id the command_id on which to execute # # @raise Exception if there is a server-side error # # @return true # def write(call_id, cmd, command_id = nil) queue = async_write call_id, cmd, command_id begin Timeout::timeout(3) { queue.pop } ensure queue = nil # Shut down this queue end.tap { |result| raise result if result.is_a? Exception } end ## # @return [Queue] Pop this queue to determine result of command execution. Will be true or an exception def async_write(call_id, cmd, command_id = nil) iq = prep_command_for_execution call_id, cmd, command_id Queue.new.tap do |queue| @command_callbacks[iq.id] = lambda do |result| case result when Blather::Stanza::Iq ref = result.ozone_node if ref.is_a?(Ref) cmd.command_id = ref.id @command_id_to_iq_id[ref.id] = iq.id end cmd.execute! queue << true when Exception queue << result end end write_to_stream iq cmd.request! end end def prep_command_for_execution(call_id, cmd, command_id = nil) cmd.connection = self call_id = call_id.call_id if call_id.is_a? Call cmd.call_id = call_id jid = cmd.is_a?(Command::Dial) ? @ozone_domain : "#{call_id}@#{@callmap[call_id]}" jid << "/#{command_id}" if command_id create_iq(jid).tap do |iq| @logger.debug "Sending IQ ID #{iq.id} #{cmd.inspect} to #{jid}" if @logger iq << cmd @iq_id_to_command[iq.id] = cmd end end ## # Fire up the connection # def run register_handlers connect end def connect Thread.new do begin trap(:INT) do @reconnect_attempts = nil EM.stop end trap(:TERM) do @reconnect_attempts = nil EM.stop end EM.run { client.run } rescue Blather::SASLError, Blather::StreamError => e raise ProtocolError.new(e.class.to_s, e.message) rescue => e puts "Exception in XMPP thread! #{e}" puts e.backtrace.join("\t\n") end end end def connected? client.connected? end ## # # Get the original command issued by command ID # # @param [String] command_id # # @return [OzoneNode] # def original_command_from_id(command_id) @iq_id_to_command[@command_id_to_iq_id[command_id]] end private def handle_presence(p) @logger.info "Receiving event for call ID #{p.call_id}" if @logger @callmap[p.call_id] = p.from.domain @logger.debug p.inspect if @logger event = p.event event.connection = self event.source.add_event event if event.source @event_queue.push event.is_a?(Event::Offer) ? Punchblock::Call.new(p.call_id, p.to, event.headers_hash) : event end def handle_iq_result(iq) # FIXME: Do we need to raise a warning if the domain changes? @callmap[iq.from.node] = iq.from.domain @logger.debug "Command #{iq.id} completed successfully" if @logger callback = @command_callbacks[iq.id] callback.call iq if callback end def handle_error(iq) e = Blather::StanzaError.import iq protocol_error = ProtocolError.new e.name, e.text, iq.call_id, iq.command_id if callback = @command_callbacks[iq.id] callback.call protocol_error else # Un-associated transport error?? raise protocol_error end end def register_handlers # Push a message to the queue and the log that we connected when_ready do @event_queue.push connected @logger.info "Connected to XMPP as #{@username}" if @logger @reconnect_attempts = 0 @ozone_ping = EM::PeriodicTimer.new(60) { ping_ozone } end disconnected do @ozone_ping.cancel if @ozone_ping if @auto_reconnect && @reconnect_attempts timer = 30 * 2 ** @reconnect_attempts @logger.warn "XMPP disconnected. Tried to reconnect #{@reconnect_attempts} times. Reconnecting in #{timer}s." if @logger sleep timer @logger.info "Trying to reconnect..." if @logger @reconnect_attempts += 1 connect end end # Read/handle call control messages. These are mostly just acknowledgement of commands iq :result? do |msg| handle_iq_result msg end # Read/handle error IQs iq :error? do |e| handle_error e end # Read/handle presence requests. This is how we get events. presence { |msg| handle_presence msg } end def ping_ozone client.write_with_handler Blather::Stanza::Iq::Ping.new(:set, @ozone_domain) { |response| nil } end def create_iq(jid = nil) Blather::Stanza::Iq.new :set, jid || @call_id end end end end end
Add first version of is_port_open function. Adding first version of is_port_open function to use within Puppet DSL. Signed-off-by: Krzysztof Wilczynski <9bf091559fc98493329f7d619638c79e91ccf029@linux.com> # # is_port_open.rb # # Copyright 2012 Puppet Labs Inc. # Copyright 2012 Krzysztof Wilczynski # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module Puppet::Parser::Functions newfunction(:is_port_open, :type => :rvalue, :doc => <<-EOS Returns true if given port is open on a remote peer (host) and false otherwise. Prototype: is_port_open(h, p) is_port_open(h, p, t) Where h is a string type which can be either a host name or IP address of the remote peer and p is a numeric type which is the port to check on the remote peer. Additionally, a numeric value can be set as t to specify number of seconds (a time out) to wait before assumming that given port is not accessible on the remote peer. This value should always be greater than zero. By default it will be set to 2 if not specified. For example: Given the following statements: $a = 'google.com' $b = 'yahoo.com' $c = 'localhost' notice is_port_open($a, 22) notice is_port_open($b, 80) notice is_port_open($c, 22) The result will be as follows: notice: Scope(Class[main]): false notice: Scope(Class[main]): true notice: Scope(Class[main]): true Known issues: Currently, there is no support for floating-point time out values. EOS ) do |*arguments| # # This is to ensure that whenever we call this function from within # the Puppet manifest or alternatively form a template it will always # do the right thing ... # arguments = arguments.shift if arguments.first.is_a?(Array) # Technically we support three arguments but only two are mandatory ... raise Puppet::ParseError, "is_port_open(): Wrong number of arguments " + "given (#{arguments.size} for 2)" if arguments.size < 2 host = arguments.shift raise Puppet::ParseError, 'is_port_open(): First argument requires ' + 'a string type to work with' unless host.is_a?(String) port = arguments.shift # This should cover all the generic numeric types present in Puppet ... unless port.class.ancestors.include?(Numeric) or port.is_a?(String) raise Puppet::ParseError, 'is_port_open(): Second argument requires ' + 'a numeric type to work with' end # We blindly cast port to integer assuming that it is correct ... port = port.to_i timeout = arguments.shift if timeout # This should cover all the generic numeric types present in Puppet ... unless timeout.class.ancestors.include?(Numeric) or timeout.is_a?(String) raise Puppet::ParseError, 'is_port_open(): Optional argument requires ' + 'a numeric type to work with' end # We blindly cast time out to integer assuming that it is correct ... timeout = timeout.to_i if timeout <= 0 raise Puppet::ParseError, 'is_port_open(): Value of optional ' + 'argument must be be greater than zero' end else # Pick some sane default? Should be more than enough for local networks ... timeout = 2 end require 'socket' require 'timeout' # We assume that port is closed unless proven otherwise later ... result = false socket = nil begin Timeout::timeout(timeout) do socket = TCPSocket.open(host, port) result = true end rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT # Common exceptions related to connection being refused, etc .. rescue Timeout::Error # We might time out for many reasons, for instance port is filtered ... ensure # We make an attempt to close socket gracefully ... if socket socket.shutdown rescue nil socket.close rescue nil end end result end end # vim: set ts=2 sw=2 et : # encoding: utf-8
# Copyright (C) 2017 IntechnologyWIFI / Michael Shaw # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. require 'json' require 'puppet_x/intechwifi/constants' require 'puppet_x/intechwifi/logical' require 'puppet_x/intechwifi/awscmds' require 'puppet_x/intechwifi/exceptions' Puppet::Type.type(:load_balancer).provide(:awscli) do commands :awscli => "aws" def create args = [ 'elbv2', 'create-load-balancer', '--region', @resource[:region], '--name', @resource[:name], '--subnets', 'subnet-a6f08a8b', 'subnet-66d4a43d' #'--subnet-ids', resource[:subnets].map{|subnet| PuppetX::IntechWIFI::AwsCmds.find_id_by_name(@resource[:region], 'subnet', subnet){|*arg| awscli(*arg)} } ] awscli(args.flatten) @property_hash[:name] = @resource[:name] @property_hash[:region] = @resource[:region] @property_hash[:subnets] = @resource[:subnets] end def destroy args = [ 'elbv2', 'delete-load-balancer', '--region', @resource[:region], '--load-balancer-arn', @arn ] awscli(args.flatten) end def exists? # # If the puppet manifest is delcaring the existance of a VPC then we know its region. # regions = [ resource[:region] ] if resource[:region] # # If we don't know the region, then we have to search each region in turn. # regions = PuppetX::IntechWIFI::Constants.Regions if !resource[:region] debug("searching regions=#{regions} for load_balancer=#{resource[:name]}\n") search_results = PuppetX::IntechWIFI::AwsCmds.find_load_balancer_by_name(regions, resource[:name]) do | *arg | awscli(*arg) end @property_hash[:region] = search_results[:region] @property_hash[:name] = resource[:name] data = search_results[:data][0] @arn = data["LoadBalancerArn"] true rescue PuppetX::IntechWIFI::Exceptions::NotFoundError => e debug(e) false rescue PuppetX::IntechWIFI::Exceptions::MultipleMatchesError => e fail(e) false end def flush if @property_flush and @property_flush.length > 0 end end def initialize(value={}) super(value) @property_flush = {} end mk_resource_methods end PAWS-46: Implement the subnets property. Can now set and change subnets for load_balancers # Copyright (C) 2017 IntechnologyWIFI / Michael Shaw # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. require 'json' require 'puppet_x/intechwifi/constants' require 'puppet_x/intechwifi/logical' require 'puppet_x/intechwifi/awscmds' require 'puppet_x/intechwifi/exceptions' Puppet::Type.type(:load_balancer).provide(:awscli) do commands :awscli => "aws" def create args = [ 'elbv2', 'create-load-balancer', '--region', @resource[:region], '--name', @resource[:name], '--subnets', resource[:subnets].map{|subnet| PuppetX::IntechWIFI::AwsCmds.find_id_by_name(@resource[:region], 'subnet', subnet){|*arg| awscli(*arg)} } ] awscli(args.flatten) @property_hash[:name] = @resource[:name] @property_hash[:region] = @resource[:region] @property_hash[:subnets] = @resource[:subnets] end def destroy args = [ 'elbv2', 'delete-load-balancer', '--region', @resource[:region], '--load-balancer-arn', @arn ] awscli(args.flatten) end def exists? # # If the puppet manifest is delcaring the existance of a VPC then we know its region. # regions = [ resource[:region] ] if resource[:region] # # If we don't know the region, then we have to search each region in turn. # regions = PuppetX::IntechWIFI::Constants.Regions if !resource[:region] debug("searching regions=#{regions} for load_balancer=#{resource[:name]}\n") search_results = PuppetX::IntechWIFI::AwsCmds.find_load_balancer_by_name(regions, resource[:name]) do | *arg | awscli(*arg) end @property_hash[:region] = search_results[:region] @property_hash[:name] = resource[:name] data = search_results[:data][0] @arn = data["LoadBalancerArn"] @property_hash[:subnets] = data["AvailabilityZones"].map{|subnet| PuppetX::IntechWIFI::AwsCmds.find_name_by_id(@property_hash[:region], 'subnet', subnet["SubnetId"]){|*arg| awscli(*arg)} } true rescue PuppetX::IntechWIFI::Exceptions::NotFoundError => e debug(e) false rescue PuppetX::IntechWIFI::Exceptions::MultipleMatchesError => e fail(e) false end def flush if @property_flush and @property_flush.length > 0 set_subnets(@property_flush[:subnets]) if !@property_flush[:subnets].nil? end end def initialize(value={}) super(value) @property_flush = {} end def set_subnets(subnets) args = [ 'elbv2', 'set-subnets', '--region', @property_hash[:region], '--load-balancer-arn', @arn, '--subnets', subnets.map{|subnet| PuppetX::IntechWIFI::AwsCmds.find_id_by_name(@property_hash[:region], 'subnet', subnet){|*arg| awscli(*arg)} } ] awscli(args.flatten) end mk_resource_methods def region=(value) @property_flush[:region] = value end def subnets=(value) @property_flush[:subnets] = value end end
require 'uri' require 'openssl' require 'cgi' require 'puppet/util/network_device/transport_ftos' require 'puppet/util/network_device/transport_ftos/base_ftos' class Puppet::Util::NetworkDevice::Base_ftos attr_accessor :url, :transport, :crypt def initialize(url) @url = URI.parse(url) @query = CGI.parse(@url.query) if @url.query require "puppet/util/network_device/transport_ftos/#{@url.scheme}" unless @transport @transport = Puppet::Util::NetworkDevice::Transport_ftos.const_get(@url.scheme.capitalize).new @transport.host = @url.host @transport.port = @url.port || case @url.scheme ; when "ssh" ; 22 ; when "telnet" ; 23 ; else ;23 ; end if @query && @query['crypt'] && @query['crypt'] == ['true'] self.crypt = true # FIXME: https://github.com/puppetlabs/puppet/blob/master/lib/puppet/application/device.rb#L181 master = File.read(File.join('/etc/puppet', 'networkdevice-secret')) master = master.strip @transport.user = decrypt(master, [@url.user].pack('h*')) @transport.password = decrypt(master, [@url.password].pack('h*')) else @transport.user = @url.user @transport.password = @url.password end end end def decrypt(master, str) cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.decrypt cipher.key = key = OpenSSL::Digest::SHA512.new(master).digest out = cipher.update(str) out << cipher.final return out end end add uri decoding of username/password to more modules require 'uri' require 'openssl' require 'cgi' require 'puppet/util/network_device/transport_ftos' require 'puppet/util/network_device/transport_ftos/base_ftos' class Puppet::Util::NetworkDevice::Base_ftos attr_accessor :url, :transport, :crypt def initialize(url) @url = URI.parse(url) @query = CGI.parse(@url.query) if @url.query require "puppet/util/network_device/transport_ftos/#{@url.scheme}" unless @transport @transport = Puppet::Util::NetworkDevice::Transport_ftos.const_get(@url.scheme.capitalize).new @transport.host = @url.host @transport.port = @url.port || case @url.scheme ; when "ssh" ; 22 ; when "telnet" ; 23 ; else ;23 ; end if @query && @query['crypt'] && @query['crypt'] == ['true'] self.crypt = true # FIXME: https://github.com/puppetlabs/puppet/blob/master/lib/puppet/application/device.rb#L181 master = File.read(File.join('/etc/puppet', 'networkdevice-secret')) master = master.strip @transport.user = decrypt(master, [@url.user].pack('h*')) @transport.password = decrypt(master, [@url.password].pack('h*')) else @transport.user = URI.decode(@url.user) @transport.password = URI.decode(@url.password) end end end def decrypt(master, str) cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.decrypt cipher.key = key = OpenSSL::Digest::SHA512.new(master).digest out = cipher.update(str) out << cipher.final return out end end
module RailsAdmin module Config module Actions class Authorize < RailsAdmin::Config::Actions::Base register_instance_option :http_methods do [:get] end register_instance_option :member do true end register_instance_option :controller do proc do client = OAuth2::Client.new(@object.client.identifier, @object.client.secret, authorize_url: @object.provider.authorization_endpoint) redirect_to client.auth_code.authorize_url(redirect_uri: "#{Cenit.oauth2_callback_site}/oauth2/callback", state: Account.current.id.to_s + ' ' + @object.id.to_s, scope: @object.scopes.collect { |scope| scope.name }.join(' ')) end end register_instance_option :link_icon do 'icon-check' end register_instance_option :pjax? do false end end end end end Authorize action only for authorizations module RailsAdmin module Config module Actions class Authorize < RailsAdmin::Config::Actions::Base register_instance_option :only do Setup::Oauth2Authorization end register_instance_option :http_methods do [:get] end register_instance_option :member do true end register_instance_option :controller do proc do client = OAuth2::Client.new(@object.client.identifier, @object.client.secret, authorize_url: @object.provider.authorization_endpoint) redirect_to client.auth_code.authorize_url(redirect_uri: "#{Cenit.oauth2_callback_site}/oauth2/callback", state: Account.current.id.to_s + ' ' + @object.id.to_s, scope: @object.scopes.collect { |scope| scope.name }.join(' ')) end end register_instance_option :link_icon do 'icon-check' end register_instance_option :pjax? do false end end end end end
module RailsAdmin class MongoffModelConfig < RailsAdmin::Config::Model include ThreadAware def initialize(mongoff_entity) super @model = @abstract_model.model @parent = self titles = Set.new titles.add(nil) groups = {} @model.properties.each do |property| property = @abstract_model.property_or_association(property) type = property.type if property.is_a?(RailsAdmin::MongoffAssociation) type = (type.to_s + '_association').to_sym elsif (enumeration = property.enum) type = :enum end configure property.name, type do visible { property.visible? } read_only do bindings[:object].new_record? ? false : property.read_only? end if titles.include?(title = property.title) title = property.name.to_s.to_title end titles.add(title) label { title } filterable { property.filterable? } required { property.required? } queryable { property.queryable? } valid_length { {} } if enumeration enum { enumeration } filter_enum { enumeration } end if (description = property.description) description = "#{property.required? ? 'Required' : 'Optional'}. #{description}".html_safe help { description } end unless (g = property.group.to_s.gsub(/ +/, '_').underscore.to_sym).blank? group g groups[g] = property.group.to_s end if property.is_a?(RailsAdmin::MongoffAssociation) # associated_collection_cache_all true pretty_value do v = bindings[:view] action = v.instance_variable_get(:@action) if action.is_a?(RailsAdmin::Config::Actions::Show) && !v.instance_variable_get(:@showing) amc = RailsAdmin.config(association.klass) else amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config # perf optimization for non-polymorphic associations end am = amc.abstract_model if action.is_a?(RailsAdmin::Config::Actions::Show) && !v.instance_variable_get(:@showing) values = [value].flatten.select(&:present?) fields = amc.list.with(controller: self, view: v, object: amc.abstract_model.model.new).visible_fields unless fields.length == 1 && values.length == 1 v.instance_variable_set(:@showing, true) end table = <<-HTML <table class="table table-condensed table-striped"> <thead> <tr> #{fields.collect { |field| "<th class=\"#{field.css_class} #{field.type_css_class}\">#{field.label}</th>" }.join} <th class="last shrink"></th> <tr> </thead> <tbody> #{values.collect do |associated| can_see = !am.embedded_in?(bindings[:controller].instance_variable_get(:@abstract_model)) && (show_action = v.action(:show, am, associated)) '<tr class="script_row">' + fields.collect do |field| field.bind(object: associated, view: v) "<td class=\"#{field.css_class} #{field.type_css_class}\" title=\"#{v.strip_tags(associated.to_s)}\">#{field.pretty_value}</td>" end.join + '<td class="last links"><ul class="inline list-inline">' + if can_see v.menu_for(:member, amc.abstract_model, associated, true) else '' end + '</ul></td>' + '</tr>' end.join} </tbody> </table> HTML v.instance_variable_set(:@showing, false) table.html_safe else max_associated_to_show = 3 count_associated = [value].flatten.count associated_links = [value].flatten.select(&:present?).collect do |associated| wording = associated.send(amc.object_label_method) can_see = !am.embedded_in?(bindings[:controller].instance_variable_get(:@abstract_model)) && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to(max_associated_to_show-1).to_sentence.html_safe if (count_associated > max_associated_to_show) associated_links = associated_links+ " and #{count_associated - max_associated_to_show} more".html_safe end associated_links end end end end end if @model.is_a?(Mongoff::GridFs::FileModel) configure :data, :mongoff_file_upload do required { bindings[:object].new_record? } end configure :length do label 'Size' pretty_value do #TODO Factorize these code in custom rails admin field type if (objects = bindings[:controller].instance_variable_get(:@objects)) unless (max = bindings[:controller].instance_variable_get(:@max_length)) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.reject(&:nil?).max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end edit do field :_id do visible do (o = bindings[:object]) && (o = o.class.data_type) && (o = o.schema) && (o = o['properties']['_id']) && o.key?('type') end help 'Required' end field :data field :metadata end list do field :_id field :filename field :contentType field :uploadDate field :aliases field :metadata field :length end show do field :_id field :filename field :contentType field :uploadDate field :aliases field :metadata field :length field :md5 end else edit do parent.target.properties.each do |property| next if (property == '_id' && !parent.target.property_schema('_id').key?('type')) || Mongoff::Model[:base_schema]['properties'].key?(property) field property.to_sym end end end navigation_label { target.data_type.namespace } object_label_method do @object_label_method ||= if target.labeled? :to_s else Config.label_methods.detect { |method| target.property?(method) } || :to_s end end groups.each do |key, name| group key do label name end end end def parent self end def target @model end def excluded? false end def label contextualized_label end def label_plural contextualized_label_plural end def contextualized_label(context = nil) target.label(context) end def contextualized_label_plural(context = nil) contextualized_label(context).to_plural end def root self end def visible? true end class << self def new(mongoff_entity) mongoff_entity = RailsAdmin::MongoffAbstractModel.abstract_model_for(mongoff_entity) current_thread_cache[mongoff_entity.to_s] ||= super(mongoff_entity) end end end end Fixing mongoff associations views for the show action module RailsAdmin class MongoffModelConfig < RailsAdmin::Config::Model include ThreadAware def initialize(mongoff_entity) super @model = @abstract_model.model @parent = self titles = Set.new titles.add(nil) groups = {} @model.properties.each do |property| property = @abstract_model.property_or_association(property) type = property.type if property.is_a?(RailsAdmin::MongoffAssociation) type = (type.to_s + '_association').to_sym elsif (enumeration = property.enum) type = :enum end configure property.name, type do visible { property.visible? } read_only do bindings[:object].new_record? ? false : property.read_only? end if titles.include?(title = property.title) title = property.name.to_s.to_title end titles.add(title) label { title } filterable { property.filterable? } required { property.required? } queryable { property.queryable? } valid_length { {} } if enumeration enum { enumeration } filter_enum { enumeration } end if (description = property.description) description = "#{property.required? ? 'Required' : 'Optional'}. #{description}".html_safe help { description } end unless (g = property.group.to_s.gsub(/ +/, '_').underscore.to_sym).blank? group g groups[g] = property.group.to_s end if property.is_a?(RailsAdmin::MongoffAssociation) # associated_collection_cache_all true pretty_value do v = bindings[:view] action = v.instance_variable_get(:@action) if (action.is_a?(RailsAdmin::Config::Actions::Show) || action.is_a?(RailsAdmin::Config::Actions::RemoteSharedCollection)) && !v.instance_variable_get(:@showing) amc = RailsAdmin.config(association.klass) else amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config # perf optimization for non-polymorphic associations end am = amc.abstract_model if action.is_a?(RailsAdmin::Config::Actions::Show) && !v.instance_variable_get(:@showing) values = [value].flatten.select(&:present?) fields = amc.list.with(controller: bindings[:controller], view: v, object: amc.abstract_model.model.new).visible_fields unless fields.length == 1 && values.length == 1 v.instance_variable_set(:@showing, true) end table = <<-HTML <table class="table table-condensed table-striped"> <thead> <tr> #{fields.collect { |field| "<th class=\"#{field.css_class} #{field.type_css_class}\">#{field.label}</th>" }.join} <th class="last shrink"></th> <tr> </thead> <tbody> #{values.collect do |associated| can_see = !am.embedded_in?(bindings[:controller].instance_variable_get(:@abstract_model)) && (show_action = v.action(:show, am, associated)) '<tr class="script_row">' + fields.collect do |field| field.bind(object: associated, view: v) "<td class=\"#{field.css_class} #{field.type_css_class}\" title=\"#{v.strip_tags(associated.to_s)}\">#{field.pretty_value}</td>" end.join + '<td class="last links"><ul class="inline list-inline">' + if can_see v.menu_for(:member, amc.abstract_model, associated, true) else '' end + '</ul></td>' + '</tr>' end.join} </tbody> </table> HTML v.instance_variable_set(:@showing, false) table.html_safe else max_associated_to_show = 3 count_associated = [value].flatten.count associated_links = [value].flatten.select(&:present?).collect do |associated| wording = associated.send(amc.object_label_method) can_see = !am.embedded_in?(bindings[:controller].instance_variable_get(:@abstract_model)) && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to(max_associated_to_show-1).to_sentence.html_safe if (count_associated > max_associated_to_show) associated_links = associated_links+ " and #{count_associated - max_associated_to_show} more".html_safe end associated_links end end end end end if @model.is_a?(Mongoff::GridFs::FileModel) configure :data, :mongoff_file_upload do required { bindings[:object].new_record? } end configure :length do label 'Size' pretty_value do #TODO Factorize these code in custom rails admin field type if (objects = bindings[:controller].instance_variable_get(:@objects)) unless (max = bindings[:controller].instance_variable_get(:@max_length)) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.reject(&:nil?).max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end edit do field :_id do visible do (o = bindings[:object]) && (o = o.class.data_type) && (o = o.schema) && (o = o['properties']['_id']) && o.key?('type') end help 'Required' end field :data field :metadata end list do field :_id field :filename field :contentType field :uploadDate field :aliases field :metadata field :length end show do field :_id field :filename field :contentType field :uploadDate field :aliases field :metadata field :length field :md5 end else edit do parent.target.properties.each do |property| next if (property == '_id' && !parent.target.property_schema('_id').key?('type')) || Mongoff::Model[:base_schema]['properties'].key?(property) field property.to_sym end end end navigation_label { target.data_type.namespace } object_label_method do @object_label_method ||= if target.labeled? :to_s else Config.label_methods.detect { |method| target.property?(method) } || :to_s end end groups.each do |key, name| group key do label name end end end def parent self end def target @model end def excluded? false end def label contextualized_label end def label_plural contextualized_label_plural end def contextualized_label(context = nil) target.label(context) end def contextualized_label_plural(context = nil) contextualized_label(context).to_plural end def root self end def visible? true end class << self def new(mongoff_entity) mongoff_entity = RailsAdmin::MongoffAbstractModel.abstract_model_for(mongoff_entity) current_thread_cache[mongoff_entity.to_s] ||= super(mongoff_entity) end end end end
module RedmineResources module Patches module UserPatch def self.included(base) base.send :include, InstanceMethods end module InstanceMethods def resource_names @resource_names ||= resources.map do |resource| "#{ resource.name }, #{ resource.code }, #{ resource.division.name }" end.join(', ') end def resources Resource.joins('INNER JOIN project_resources ON project_resources.resource_id = resources.id') .joins('INNER JOIN projects ON projects.id = project_resources.project_id') .joins('INNER JOIN project_resource_emails ON project_resource_emails.project_id = projects.id AND project_resource_emails.resource_id = resources.id') .joins('INNER JOIN members ON members.project_id = projects.id') .joins('INNER JOIN users ON users.id = members.user_id ') .where('users.id = ?', id) .where('project_resource_emails.email = ?', mail) .select('DISTINCT resources.name, resources.code') .includes(:division) end end end end end unless User.included_modules.include? RedmineResources::Patches::UserPatch User.send :include, RedmineResources::Patches::UserPatch end Added department name in allocations module RedmineResources module Patches module UserPatch def self.included(base) base.send :include, InstanceMethods end module InstanceMethods def resource_names @resource_names ||= begin result = resources.map do |resource| "#{ resource.name }, #{ resource.code }, #{ resource.division.name }" end.join(', ') if Redmine::Plugin.installed?(:redmine_people) person = Person.find(id) result << ", #{ person.department.name }" if person.department end end end def resources Resource.joins('INNER JOIN project_resources ON project_resources.resource_id = resources.id') .joins('INNER JOIN projects ON projects.id = project_resources.project_id') .joins('INNER JOIN project_resource_emails ON project_resource_emails.project_id = projects.id AND project_resource_emails.resource_id = resources.id') .joins('INNER JOIN members ON members.project_id = projects.id') .joins('INNER JOIN users ON users.id = members.user_id ') .where('users.id = ?', id) .where('project_resource_emails.email = ?', mail) .select('DISTINCT resources.name, resources.code') .includes(:division) end end end end end unless User.included_modules.include? RedmineResources::Patches::UserPatch User.send :include, RedmineResources::Patches::UserPatch end
module Restforce module DB module Associations # Restforce::DB::Associations::BelongsTo defines a relationship in which # a Salesforce ID on the named database association exists on this # Mapping's Salesforce record. class BelongsTo < Base # Public: Construct a database record from the Salesforce records # associated with the supplied parent Salesforce record. # # database_record - An instance of an ActiveRecord::Base subclass. # salesforce_record - A Hashie::Mash representing a Salesforce object. # cache - A Restforce::DB::AssociationCache (optional). # # Returns an Array of constructed association records. def build(database_record, salesforce_record, cache = AssociationCache.new(database_record)) return [] unless build? @cache = cache lookups = {} attributes = {} instances = [] for_mappings(database_record) do |mapping, lookup| lookup_id = deep_lookup(salesforce_record, lookup) lookups[mapping.lookup_column] = lookup_id # If the referenced database record already exists, we can short- # circuit the accumulation of attributes here. next if mapping.database_model.exists?(mapping.lookup_column => lookup_id) instance = mapping.salesforce_record_type.find(lookup_id) # If any of the mappings are invalid, short-circuit the creation of # the associated record. return [] unless instance instances << instance attrs = mapping.convert(mapping.database_model, instance.attributes) attributes = attributes.merge(attrs) end constructed_records(database_record, lookups, attributes) do |associated| instances.flat_map { |i| nested_records(database_record, associated, i) } end ensure @cache = nil end # Public: Get a Hash of Lookup IDs for a specified database record, # based on the current record for this association. # # database_record - An instance of an ActiveRecord::Base subclass. # # Returns a Hash. def lookups(database_record) ids = {} for_mappings(database_record) do |mapping, lookup| # It's possible to define a belongs_to association in a Mapping # for what is actually a one-to-many association on the # ActiveRecord object, so we always treat the result as an Array. associated = Array(database_record.association(name).reader) ids[lookup] = associated.first.send(mapping.lookup_column) unless associated.empty? end ids end private # Internal: Iterate through all relevant mappings for the target # ActiveRecord class. # # database_record - An instance of an ActiveRecord::Base subclass. # # Yields the Restforce::DB::Mapping and the corresponding String lookup. # Returns nothing. def for_mappings(database_record) Registry[target_class(database_record)].each do |mapping| lookup = lookup_field(mapping, target_reflection(database_record)) next unless lookup yield mapping, lookup end end # Internal: Get the Salesforce ID belonging to the associated record # for a supplied instance. Must be implemented per-association. # # instance - A Restforce::DB::Instances::Base. # # Returns a String. def associated_salesforce_id(instance) reflection = instance.mapping.database_model.reflect_on_association(name) inverse_association = association_for(reflection) salesforce_instance = instance.mapping.salesforce_record_type.find(instance.id) deep_lookup(salesforce_instance.record, inverse_association.lookup) if salesforce_instance end # Internal: Get the value for a potentially nested lookup field. # # salesforce_record - A Hashie::Mash representing a Salesforce object. # lookup - A String value lookup. # # Example: # # hash = { "Name" => "Chaplin", "Address_r" => { "City" => "Berlin" } } # # deep_lookup(hash, "Name") # # => "Chaplin" # # deep_lookup(hash, "Address_r.City") # # => "Berlin" # # Returns the value of the nested key. def deep_lookup(salesforce_record, lookup) lookup.split(".").inject(salesforce_record) do |hash, key| hash[key] end end end end end end Consult all cached records during BelongsTo#build When we have already cached an unpersisted database record during our association-building process, we can short-circuit the related HTTP requests. This should cut down on extraneous API calls made during the initial sync for a record. module Restforce module DB module Associations # Restforce::DB::Associations::BelongsTo defines a relationship in which # a Salesforce ID on the named database association exists on this # Mapping's Salesforce record. class BelongsTo < Base # Public: Construct a database record from the Salesforce records # associated with the supplied parent Salesforce record. # # database_record - An instance of an ActiveRecord::Base subclass. # salesforce_record - A Hashie::Mash representing a Salesforce object. # cache - A Restforce::DB::AssociationCache (optional). # # Returns an Array of constructed association records. def build(database_record, salesforce_record, cache = AssociationCache.new(database_record)) return [] unless build? @cache = cache lookups = {} attributes = {} instances = [] for_mappings(database_record) do |mapping, lookup| lookup_id = deep_lookup(salesforce_record, lookup) lookups[mapping.lookup_column] = lookup_id # If the referenced database record already exists, we can short- # circuit the accumulation of attributes here. next if cache.find(mapping.database_model, mapping.lookup_column => lookup_id) instance = mapping.salesforce_record_type.find(lookup_id) # If any of the mappings are invalid, short-circuit the creation of # the associated record. return [] unless instance instances << instance attrs = mapping.convert(mapping.database_model, instance.attributes) attributes = attributes.merge(attrs) end constructed_records(database_record, lookups, attributes) do |associated| instances.flat_map { |i| nested_records(database_record, associated, i) } end ensure @cache = nil end # Public: Get a Hash of Lookup IDs for a specified database record, # based on the current record for this association. # # database_record - An instance of an ActiveRecord::Base subclass. # # Returns a Hash. def lookups(database_record) ids = {} for_mappings(database_record) do |mapping, lookup| # It's possible to define a belongs_to association in a Mapping # for what is actually a one-to-many association on the # ActiveRecord object, so we always treat the result as an Array. associated = Array(database_record.association(name).reader) ids[lookup] = associated.first.send(mapping.lookup_column) unless associated.empty? end ids end private # Internal: Iterate through all relevant mappings for the target # ActiveRecord class. # # database_record - An instance of an ActiveRecord::Base subclass. # # Yields the Restforce::DB::Mapping and the corresponding String lookup. # Returns nothing. def for_mappings(database_record) Registry[target_class(database_record)].each do |mapping| lookup = lookup_field(mapping, target_reflection(database_record)) next unless lookup yield mapping, lookup end end # Internal: Get the Salesforce ID belonging to the associated record # for a supplied instance. Must be implemented per-association. # # instance - A Restforce::DB::Instances::Base. # # Returns a String. def associated_salesforce_id(instance) reflection = instance.mapping.database_model.reflect_on_association(name) inverse_association = association_for(reflection) salesforce_instance = instance.mapping.salesforce_record_type.find(instance.id) deep_lookup(salesforce_instance.record, inverse_association.lookup) if salesforce_instance end # Internal: Get the value for a potentially nested lookup field. # # salesforce_record - A Hashie::Mash representing a Salesforce object. # lookup - A String value lookup. # # Example: # # hash = { "Name" => "Chaplin", "Address_r" => { "City" => "Berlin" } } # # deep_lookup(hash, "Name") # # => "Chaplin" # # deep_lookup(hash, "Address_r.City") # # => "Berlin" # # Returns the value of the nested key. def deep_lookup(salesforce_record, lookup) lookup.split(".").inject(salesforce_record) do |hash, key| hash[key] end end end end end end
require 'rubytree' require_relative 'system_registry/system_registry_client.rb' require_relative '../templater/templater.rb' require_relative '../system/system_access.rb' require '/opt/engines/lib/ruby/system/system_utils.rb' class ServiceManager < ErrorsApi require_relative 'result_checks.rb' require_relative 'service_definitions.rb' require_relative 'sm_service_control.rb' require_relative 'sm_engine_services.rb' require_relative 'sm_service_forced_methods.rb' require_relative 'sm_registry_tree.rb' require_relative 'sm_orphan_services.rb' require_relative 'sm_subservices.rb' require_relative 'sm_service_info.rb' require_relative 'sm_attach_static_services.rb' require_relative 'sm_attached_services.rb' require_relative 'sm_service_info.rb' require_relative 'sm_service_configurations.rb' require_relative 'registry_client.rb' # attr_accessor :system_registry_client #@ call initialise Service Registry Tree which conects to the registry server def initialize(core_api) @core_api = core_api @system_registry = SystemRegistryClient.new(@core_api) end include SMSubservices include SmServiceInfo include SmServiceForcedMethods include SmRegistryTree include SmOrphanServices include SmEngineServices include SMAttachedServices include SmAttachStaticServices include RegistryClient include SmServiceControl include SmServiceConfigurations end service sharing require 'rubytree' require_relative 'system_registry/system_registry_client.rb' require_relative '../templater/templater.rb' require_relative '../system/system_access.rb' require '/opt/engines/lib/ruby/system/system_utils.rb' class ServiceManager < ErrorsApi require_relative 'result_checks.rb' require_relative 'service_definitions.rb' require_relative 'sm_service_control.rb' require_relative 'sm_engine_services.rb' require_relative 'sm_service_forced_methods.rb' require_relative 'sm_registry_tree.rb' require_relative 'sm_orphan_services.rb' require_relative 'sm_subservices.rb' require_relative 'sm_service_info.rb' require_relative 'sm_attach_static_services.rb' require_relative 'sm_attached_services.rb' require_relative 'sm_service_info.rb' require_relative 'sm_service_configurations.rb' require_relative 'registry_client.rb' require_relative 'shared_services.rb' # attr_accessor :system_registry_client #@ call initialise Service Registry Tree which conects to the registry server def initialize(core_api) @core_api = core_api @system_registry = SystemRegistryClient.new(@core_api) end include SMSubservices include SmServiceInfo include SmServiceForcedMethods include SmRegistryTree include SmOrphanServices include SmEngineServices include SMAttachedServices include SmAttachStaticServices include RegistryClient include SmServiceControl include SmServiceConfigurations end
Gem::Specification.new do |s| s.name = %q{refinerycms} s.version = "0.9.5.13" s.authors = ["Resolve Digital", "David Jones", "Philip Arndt"] s.date = %q{2009-11-19} s.description = %q{A beautiful open source Ruby on Rails content manager for small business. Easy to extend, easy to use, lightweight and all wrapped up in a super slick UI.} s.summary = %q{A beautiful open source Ruby on Rails content manager for small business.} s.email = %q{info@refinerycms.com} s.extra_rdoc_files = ["README", "CONTRIBUTORS", "LICENSE"] s.executables = ["refinery", "refinery-update-core"] s.default_executable = %q{refinery} s.files = ["Rakefile","lib","lib/refinery_initializer.rb","app","app/controllers","app/controllers/application.rb","app/controllers/application_controller.rb","app/controllers/admin","app/controllers/admin/base_controller.rb","config","config/amazon_s3.yml","config/boot.rb","config/database.yml.example","config/environment.rb","config/environments","config/environments/development.rb","config/environments/production.rb","config/environments/test.rb","config/initializers","config/initializers/inflections.rb","config/initializers/mime_types.rb","config/preinitializer.rb","config/rackspace_cloudfiles.yml","config/routes.rb","db","db/migrate","db/migrate/20091029034951_remove_blurb_from_news_items.rb","db/migrate/20091109012126_add_missing_indexes.rb","db/schema.rb","db/seeds.rb","public","public/.htaccess","public/404.html","public/422.html","public/500.html","public/favicon.ico","public/images","public/images/lightbox","public/images/lightbox/bullet.gif","public/images/lightbox/close.gif","public/images/lightbox/closelabel.gif","public/images/lightbox/donate-button.gif","public/images/lightbox/download-icon.gif","public/images/lightbox/loading.gif","public/images/lightbox/nextlabel.gif","public/images/lightbox/prevlabel.gif","public/images/refinery","public/images/refinery/add.gif","public/images/refinery/add.png","public/images/refinery/admin_bg.png","public/images/refinery/ajax-loader.gif","public/images/refinery/branch-end.gif","public/images/refinery/branch-start.gif","public/images/refinery/branch.gif","public/images/refinery/cross.gif","public/images/refinery/deactive-gradient.gif","public/images/refinery/delete.gif","public/images/refinery/drag.gif","public/images/refinery/edit.gif","public/images/refinery/header-background.gif","public/images/refinery/header_background.png","public/images/refinery/hover-gradient.jpg","public/images/refinery/icons","public/images/refinery/icons/accept.png","public/images/refinery/icons/add.png","public/images/refinery/icons/application_edit.png","public/images/refinery/icons/application_go.png","public/images/refinery/icons/arrow_left.png","public/images/refinery/icons/arrow_switch.png","public/images/refinery/icons/arrow_up.png","public/images/refinery/icons/bin_closed.png","public/images/refinery/icons/cancel.png","public/images/refinery/icons/cog_add.png","public/images/refinery/icons/cog_edit.png","public/images/refinery/icons/cross.png","public/images/refinery/icons/delete.png","public/images/refinery/icons/edit.png","public/images/refinery/icons/email_edit.png","public/images/refinery/icons/email_go.png","public/images/refinery/icons/email_open.png","public/images/refinery/icons/eye.png","public/images/refinery/icons/help.png","public/images/refinery/icons/image_add.png","public/images/refinery/icons/image_edit.png","public/images/refinery/icons/layout_add.png","public/images/refinery/icons/layout_edit.png","public/images/refinery/icons/page_add.png","public/images/refinery/icons/page_edit.png","public/images/refinery/icons/page_link.png","public/images/refinery/icons/page_white_edit.png","public/images/refinery/icons/page_white_put.png","public/images/refinery/icons/reorder.png","public/images/refinery/icons/tick.png","public/images/refinery/icons/user.png","public/images/refinery/icons/user_add.png","public/images/refinery/icons/user_comment.png","public/images/refinery/icons/user_edit.png","public/images/refinery/info.gif","public/images/refinery/logo.png","public/images/refinery/m-tools.gif","public/images/refinery/magnifier.png","public/images/refinery/nav-3-background.gif","public/images/refinery/page_bg.png","public/images/refinery/resolve-digital.gif","public/images/refinery/search.gif","public/images/refinery/shad_blcorner.png","public/images/refinery/shad_bottom.png","public/images/refinery/shad_brcorner.png","public/images/refinery/shad_tlcorner.png","public/images/refinery/shad_trcorner.png","public/images/refinery/tableft.gif","public/images/refinery/tabright.gif","public/images/refinery/tick.gif","public/images/thickbox","public/images/thickbox/cross.png","public/images/thickbox/loadingAnimation.gif","public/images/thickbox/macFFBgHack.png","public/images/wymeditor","public/images/wymeditor/skins","public/images/wymeditor/skins/refinery","public/images/wymeditor/skins/refinery/blockquote.png","public/images/wymeditor/skins/refinery/center.png","public/images/wymeditor/skins/refinery/css.png","public/images/wymeditor/skins/refinery/h1.png","public/images/wymeditor/skins/refinery/h2.png","public/images/wymeditor/skins/refinery/h3.png","public/images/wymeditor/skins/refinery/h4.png","public/images/wymeditor/skins/refinery/h5.png","public/images/wymeditor/skins/refinery/h6.png","public/images/wymeditor/skins/refinery/icons.png","public/images/wymeditor/skins/refinery/iframe","public/images/wymeditor/skins/refinery/iframe/lbl-blockquote.png","public/images/wymeditor/skins/refinery/iframe/lbl-h1.png","public/images/wymeditor/skins/refinery/iframe/lbl-h2.png","public/images/wymeditor/skins/refinery/iframe/lbl-h3.png","public/images/wymeditor/skins/refinery/iframe/lbl-h4.png","public/images/wymeditor/skins/refinery/iframe/lbl-h5.png","public/images/wymeditor/skins/refinery/iframe/lbl-h6.png","public/images/wymeditor/skins/refinery/iframe/lbl-p.png","public/images/wymeditor/skins/refinery/iframe/lbl-pre.png","public/images/wymeditor/skins/refinery/justify.png","public/images/wymeditor/skins/refinery/left.png","public/images/wymeditor/skins/refinery/paragraph.png","public/images/wymeditor/skins/refinery/right.png","public/images/wymeditor/skins/wymeditor_icon.png","public/javascripts","public/javascripts/refinery/admin.js","public/javascripts/application.js","public/javascripts/builder.js","public/javascripts/controls.js","public/javascripts/refinery/dialog.js","public/javascripts/dragdrop.js","public/javascripts/effects.js","public/javascripts/fastinit.js","public/javascripts/jquery","public/javascripts/jquery/GPL-LICENSE.txt","public/javascripts/jquery/jquery.js","public/javascripts/jquery/MIT-LICENSE.txt","public/javascripts/lightbox.js","public/javascripts/livepipe.js","public/javascripts/refinery/parse_url.js","public/javascripts/refinery/prototype.enhancements.js","public/javascripts/prototype.js","public/javascripts/scriptaculous.js","public/javascripts/slider.js","public/javascripts/tabs.js","public/javascripts/thickbox.js","public/javascripts/refinery/tooltips.js","public/javascripts/wymeditor","public/javascripts/refinery/boot_wym.js","public/javascripts/wymeditor/jquery.refinery.wymeditor.js","public/javascripts/wymeditor/lang","public/javascripts/wymeditor/lang/ca.js","public/javascripts/wymeditor/lang/cs.js","public/javascripts/wymeditor/lang/de.js","public/javascripts/wymeditor/lang/en.js","public/javascripts/wymeditor/lang/es.js","public/javascripts/wymeditor/lang/fa.js","public/javascripts/wymeditor/lang/fr.js","public/javascripts/wymeditor/lang/he.js","public/javascripts/wymeditor/lang/hu.js","public/javascripts/wymeditor/lang/it.js","public/javascripts/wymeditor/lang/nb.js","public/javascripts/wymeditor/lang/nl.js","public/javascripts/wymeditor/lang/nn.js","public/javascripts/wymeditor/lang/pl.js","public/javascripts/wymeditor/lang/pt-br.js","public/javascripts/wymeditor/lang/pt.js","public/javascripts/wymeditor/lang/ru.js","public/javascripts/wymeditor/lang/sv.js","public/javascripts/wymeditor/lang/tr.js","public/javascripts/wymeditor/lang/zh_cn.js","public/javascripts/wymeditor/skins","public/javascripts/wymeditor/skins/refinery","public/javascripts/wymeditor/skins/refinery/skin.js","public/robots.txt","public/stylesheets","public/stylesheets/application.css","public/stylesheets/formatting.css","public/stylesheets/home.css","public/stylesheets/ie6.css","public/stylesheets/ie7.css","public/stylesheets/lightbox.css","public/stylesheets/refinery/application.css","public/stylesheets/refinery/refinery.css","public/stylesheets/refinery/home.css","public/stylesheets/refinery/formatting.css","public/stylesheets/theme.css","public/stylesheets/refinery/theme.css","public/stylesheets/refinery/thickbox.css","public/stylesheets/refinery/tooltips.css","public/stylesheets/wymeditor","public/stylesheets/wymeditor/skins","public/stylesheets/wymeditor/skins/refinery","public/stylesheets/wymeditor/skins/refinery/skin.css","public/stylesheets/wymeditor/skins/refinery/wymiframe.css","public/wymeditor","public/wymeditor/GPL-license.txt","public/wymeditor/MIT-license.txt","public/wymeditor/README","script","script/about","script/console","script/dbconsole","script/destroy","script/generate","script/performance","script/performance/profiler","script/performance/request","script/plugin","script/process","script/runner","script/server","script/process/inspector","script/process/reaper","script/process/spawner","vendor","vendor/plugins","vendor/plugins/acts_as_indexed","vendor/plugins/acts_as_indexed/CHANGELOG","vendor/plugins/acts_as_indexed/init.rb","vendor/plugins/acts_as_indexed/lib","vendor/plugins/acts_as_indexed/lib/acts_as_indexed.rb","vendor/plugins/acts_as_indexed/lib/search_atom.rb","vendor/plugins/acts_as_indexed/lib/search_index.rb","vendor/plugins/acts_as_indexed/lib/will_paginate_search.rb","vendor/plugins/acts_as_indexed/MIT-LICENSE","vendor/plugins/acts_as_indexed/Rakefile","vendor/plugins/acts_as_indexed/README.rdoc","vendor/plugins/acts_as_indexed/test","vendor/plugins/acts_as_indexed/test/abstract_unit.rb","vendor/plugins/acts_as_indexed/test/acts_as_indexed_test.rb","vendor/plugins/acts_as_indexed/test/database.yml","vendor/plugins/acts_as_indexed/test/fixtures","vendor/plugins/acts_as_indexed/test/fixtures/post.rb","vendor/plugins/acts_as_indexed/test/fixtures/posts.yml","vendor/plugins/acts_as_indexed/test/schema.rb","vendor/plugins/acts_as_tree","vendor/plugins/acts_as_tree/init.rb","vendor/plugins/acts_as_tree/lib","vendor/plugins/acts_as_tree/lib/active_record","vendor/plugins/acts_as_tree/lib/active_record/acts","vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb","vendor/plugins/acts_as_tree/Rakefile","vendor/plugins/acts_as_tree/README","vendor/plugins/acts_as_tree/test","vendor/plugins/acts_as_tree/test/abstract_unit.rb","vendor/plugins/acts_as_tree/test/acts_as_tree_test.rb","vendor/plugins/acts_as_tree/test/database.yml","vendor/plugins/acts_as_tree/test/fixtures","vendor/plugins/acts_as_tree/test/fixtures/mixin.rb","vendor/plugins/acts_as_tree/test/fixtures/mixins.yml","vendor/plugins/acts_as_tree/test/schema.rb","vendor/plugins/attachment_fu","vendor/plugins/attachment_fu/amazon_s3.yml.tpl","vendor/plugins/attachment_fu/CHANGELOG","vendor/plugins/attachment_fu/init.rb","vendor/plugins/attachment_fu/install.rb","vendor/plugins/attachment_fu/lib","vendor/plugins/attachment_fu/lib/geometry.rb","vendor/plugins/attachment_fu/lib/technoweenie","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb","vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb","vendor/plugins/attachment_fu/LICENSE","vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl","vendor/plugins/attachment_fu/Rakefile","vendor/plugins/attachment_fu/README","vendor/plugins/attachment_fu/test","vendor/plugins/attachment_fu/test/backends","vendor/plugins/attachment_fu/test/backends/db_file_test.rb","vendor/plugins/attachment_fu/test/backends/file_system_test.rb","vendor/plugins/attachment_fu/test/backends/remote","vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb","vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb","vendor/plugins/attachment_fu/test/base_attachment_tests.rb","vendor/plugins/attachment_fu/test/basic_test.rb","vendor/plugins/attachment_fu/test/database.yml","vendor/plugins/attachment_fu/test/extra_attachment_test.rb","vendor/plugins/attachment_fu/test/fixtures","vendor/plugins/attachment_fu/test/fixtures/attachment.rb","vendor/plugins/attachment_fu/test/fixtures/files","vendor/plugins/attachment_fu/test/fixtures/files/fake","vendor/plugins/attachment_fu/test/fixtures/files/fake/rails.png","vendor/plugins/attachment_fu/test/fixtures/files/foo.txt","vendor/plugins/attachment_fu/test/fixtures/files/rails.png","vendor/plugins/attachment_fu/test/geometry_test.rb","vendor/plugins/attachment_fu/test/processors","vendor/plugins/attachment_fu/test/processors/core_image_test.rb","vendor/plugins/attachment_fu/test/processors/gd2_test.rb","vendor/plugins/attachment_fu/test/processors/image_science_test.rb","vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb","vendor/plugins/attachment_fu/test/processors/rmagick_test.rb","vendor/plugins/attachment_fu/test/schema.rb","vendor/plugins/attachment_fu/test/test_helper.rb","vendor/plugins/attachment_fu/test/validation_test.rb","vendor/plugins/attachment_fu/vendor","vendor/plugins/attachment_fu/vendor/red_artisan","vendor/plugins/attachment_fu/vendor/red_artisan/core_image","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb","vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb","vendor/plugins/authentication","vendor/plugins/authentication/app","vendor/plugins/authentication/app/controllers","vendor/plugins/authentication/app/controllers/admin","vendor/plugins/authentication/app/controllers/admin/users_controller.rb","vendor/plugins/authentication/app/controllers/sessions_controller.rb","vendor/plugins/authentication/app/controllers/users_controller.rb","vendor/plugins/authentication/app/helpers","vendor/plugins/authentication/app/helpers/sessions_helper.rb","vendor/plugins/authentication/app/helpers/users_helper.rb","vendor/plugins/authentication/app/models","vendor/plugins/authentication/app/models/user.rb","vendor/plugins/authentication/app/models/user_mailer.rb","vendor/plugins/authentication/app/models/user_observer.rb","vendor/plugins/authentication/app/models/user_plugin.rb","vendor/plugins/authentication/app/views","vendor/plugins/authentication/app/views/admin","vendor/plugins/authentication/app/views/admin/users","vendor/plugins/authentication/app/views/admin/users/_form.html.erb","vendor/plugins/authentication/app/views/admin/users/edit.html.erb","vendor/plugins/authentication/app/views/admin/users/index.html.erb","vendor/plugins/authentication/app/views/admin/users/new.html.erb","vendor/plugins/authentication/app/views/sessions","vendor/plugins/authentication/app/views/sessions/new.html.erb","vendor/plugins/authentication/app/views/user_mailer","vendor/plugins/authentication/app/views/user_mailer/activation.html.erb","vendor/plugins/authentication/app/views/user_mailer/signup_notification.html.erb","vendor/plugins/authentication/app/views/users","vendor/plugins/authentication/app/views/users/new.html.erb","vendor/plugins/authentication/config","vendor/plugins/authentication/config/routes.rb","vendor/plugins/authentication/init.rb","vendor/plugins/authentication/lib","vendor/plugins/authentication/lib/authenticated_system.rb","vendor/plugins/authentication/lib/authenticated_test_helper.rb","vendor/plugins/authentication/Rakefile","vendor/plugins/authentication/README","vendor/plugins/authentication/test","vendor/plugins/authentication/test/fixtures","vendor/plugins/authentication/test/fixtures/users.yml","vendor/plugins/authentication/test/functional","vendor/plugins/authentication/test/functional/admin","vendor/plugins/authentication/test/functional/admin/base_controller_test.rb","vendor/plugins/authentication/test/functional/admin/dashboard_controller_test.rb","vendor/plugins/authentication/test/functional/admin/pages_controller_test.rb","vendor/plugins/authentication/test/functional/sessions_controller_test.rb","vendor/plugins/authentication/test/functional/users_controller_test.rb","vendor/plugins/authentication/test/test_helper.rb","vendor/plugins/authentication/test/unit","vendor/plugins/authentication/test/unit/user_mailer_test.rb","vendor/plugins/authentication/test/unit/user_test.rb","vendor/plugins/dashboard","vendor/plugins/dashboard/app","vendor/plugins/dashboard/app/controllers","vendor/plugins/dashboard/app/controllers/admin","vendor/plugins/dashboard/app/controllers/admin/dashboard_controller.rb","vendor/plugins/dashboard/app/helpers","vendor/plugins/dashboard/app/helpers/admin","vendor/plugins/dashboard/app/helpers/admin/dashboard_helper.rb","vendor/plugins/dashboard/app/views","vendor/plugins/dashboard/app/views/admin","vendor/plugins/dashboard/app/views/admin/dashboard","vendor/plugins/dashboard/app/views/admin/dashboard/_recent_activity.html.erb","vendor/plugins/dashboard/app/views/admin/dashboard/index.html.erb","vendor/plugins/dashboard/config","vendor/plugins/dashboard/config/routes.rb","vendor/plugins/dashboard/init.rb","vendor/plugins/images","vendor/plugins/images/app","vendor/plugins/images/app/controllers","vendor/plugins/images/app/controllers/admin","vendor/plugins/images/app/controllers/admin/images_controller.rb","vendor/plugins/images/app/helpers","vendor/plugins/images/app/helpers/admin","vendor/plugins/images/app/helpers/admin/images_helper.rb","vendor/plugins/images/app/models","vendor/plugins/images/app/models/image.rb","vendor/plugins/images/app/views","vendor/plugins/images/app/views/admin","vendor/plugins/images/app/views/admin/images","vendor/plugins/images/app/views/admin/images/_form.html.erb","vendor/plugins/images/app/views/admin/images/_grid_view.html.erb","vendor/plugins/images/app/views/admin/images/_list_view.html.erb","vendor/plugins/images/app/views/admin/images/_list_view_image.html.erb","vendor/plugins/images/app/views/admin/images/edit.html.erb","vendor/plugins/images/app/views/admin/images/index.html.erb","vendor/plugins/images/app/views/admin/images/insert.html.erb","vendor/plugins/images/app/views/admin/images/new.html.erb","vendor/plugins/images/config","vendor/plugins/images/config/routes.rb","vendor/plugins/images/init.rb","vendor/plugins/images/lib","vendor/plugins/images/lib/tasks","vendor/plugins/images/lib/tasks/images.rake","vendor/plugins/inquiries","vendor/plugins/inquiries/app","vendor/plugins/inquiries/app/controllers","vendor/plugins/inquiries/app/controllers/admin","vendor/plugins/inquiries/app/controllers/admin/inquiries_controller.rb","vendor/plugins/inquiries/app/controllers/admin/inquiry_settings_controller.rb","vendor/plugins/inquiries/app/controllers/inquiries_controller.rb","vendor/plugins/inquiries/app/helpers","vendor/plugins/inquiries/app/helpers/inquiries_helper.rb","vendor/plugins/inquiries/app/models","vendor/plugins/inquiries/app/models/inquiry.rb","vendor/plugins/inquiries/app/models/inquiry_mailer.rb","vendor/plugins/inquiries/app/models/inquiry_setting.rb","vendor/plugins/inquiries/app/views","vendor/plugins/inquiries/app/views/admin","vendor/plugins/inquiries/app/views/admin/inquiries","vendor/plugins/inquiries/app/views/admin/inquiries/_inquiry.html.erb","vendor/plugins/inquiries/app/views/admin/inquiries/index.html.erb","vendor/plugins/inquiries/app/views/admin/inquiries/show.html.erb","vendor/plugins/inquiries/app/views/admin/inquiry_settings","vendor/plugins/inquiries/app/views/admin/inquiry_settings/_confirmation_email_form.html.erb","vendor/plugins/inquiries/app/views/admin/inquiry_settings/_notification_recipients_form.html.erb","vendor/plugins/inquiries/app/views/admin/inquiry_settings/edit.html.erb","vendor/plugins/inquiries/app/views/admin/inquiry_settings/index.html.erb","vendor/plugins/inquiries/app/views/inquiries","vendor/plugins/inquiries/app/views/inquiries/new.html.erb","vendor/plugins/inquiries/app/views/inquiries/thank_you.html.erb","vendor/plugins/inquiries/app/views/inquiry_mailer","vendor/plugins/inquiries/app/views/inquiry_mailer/confirmation.html.erb","vendor/plugins/inquiries/app/views/inquiry_mailer/notification.html.erb","vendor/plugins/inquiries/config","vendor/plugins/inquiries/config/routes.rb","vendor/plugins/inquiries/init.rb","vendor/plugins/news","vendor/plugins/news/app","vendor/plugins/news/app/controllers","vendor/plugins/news/app/controllers/admin","vendor/plugins/news/app/controllers/admin/news_items_controller.rb","vendor/plugins/news/app/controllers/news_items_controller.rb","vendor/plugins/news/app/models","vendor/plugins/news/app/models/news_item.rb","vendor/plugins/news/app/views","vendor/plugins/news/app/views/admin","vendor/plugins/news/app/views/admin/news_items","vendor/plugins/news/app/views/admin/news_items/_form.html.erb","vendor/plugins/news/app/views/admin/news_items/_news_item.html.erb","vendor/plugins/news/app/views/admin/news_items/edit.html.erb","vendor/plugins/news/app/views/admin/news_items/index.html.erb","vendor/plugins/news/app/views/admin/news_items/new.html.erb","vendor/plugins/news/app/views/news_items","vendor/plugins/news/app/views/news_items/_recent_posts.html.erb","vendor/plugins/news/app/views/news_items/index.html.erb","vendor/plugins/news/app/views/news_items/show.html.erb","vendor/plugins/news/config","vendor/plugins/news/config/routes.rb","vendor/plugins/news/init.rb","vendor/plugins/pages","vendor/plugins/pages/app","vendor/plugins/pages/app/controllers","vendor/plugins/pages/app/controllers/admin","vendor/plugins/pages/app/controllers/admin/page_dialogs_controller.rb","vendor/plugins/pages/app/controllers/admin/page_parts_controller.rb","vendor/plugins/pages/app/controllers/admin/pages_controller.rb","vendor/plugins/pages/app/controllers/pages_controller.rb","vendor/plugins/pages/app/helpers","vendor/plugins/pages/app/helpers/pages_helper.rb","vendor/plugins/pages/app/models","vendor/plugins/pages/app/models/page.rb","vendor/plugins/pages/app/models/page_part.rb","vendor/plugins/pages/app/views","vendor/plugins/pages/app/views/admin","vendor/plugins/pages/app/views/admin/page_dialogs","vendor/plugins/pages/app/views/admin/page_dialogs/_page_link.html.erb","vendor/plugins/pages/app/views/admin/page_dialogs/link_to.html.erb","vendor/plugins/pages/app/views/admin/pages","vendor/plugins/pages/app/views/admin/pages/_form.html.erb","vendor/plugins/pages/app/views/admin/pages/_list.html.erb","vendor/plugins/pages/app/views/admin/pages/_page_part_field.html.erb","vendor/plugins/pages/app/views/admin/pages/_sortable_list.html.erb","vendor/plugins/pages/app/views/admin/pages/edit.html.erb","vendor/plugins/pages/app/views/admin/pages/index.html.erb","vendor/plugins/pages/app/views/admin/pages/new.html.erb","vendor/plugins/pages/app/views/pages","vendor/plugins/pages/app/views/pages/home.html.erb","vendor/plugins/pages/app/views/pages/show.html.erb","vendor/plugins/pages/config","vendor/plugins/pages/config/routes.rb","vendor/plugins/pages/init.rb","vendor/plugins/refinery","vendor/plugins/refinery/app","vendor/plugins/refinery/app/controllers","vendor/plugins/refinery/app/controllers/admin","vendor/plugins/refinery/app/controllers/admin/refinery_core_controller.rb","app/helpers/application_helper.rb","vendor/plugins/refinery/lib/refinery/application_helper.rb","vendor/plugins/refinery/lib/refinery/admin_base_controller.rb","vendor/plugins/refinery/app/views","vendor/plugins/refinery/app/views/admin","vendor/plugins/refinery/app/views/admin/_head.html.erb","vendor/plugins/refinery/app/views/admin/_menu.html.erb","vendor/plugins/refinery/app/views/layouts","vendor/plugins/refinery/app/views/layouts/admin.html.erb","vendor/plugins/refinery/app/views/layouts/application.html.erb","vendor/plugins/refinery/app/views/shared","vendor/plugins/refinery/app/views/shared/_footer.html.erb","vendor/plugins/refinery/app/views/shared/_header.html.erb","vendor/plugins/refinery/app/views/shared/_google_analytics.html.erb","vendor/plugins/refinery/app/views/shared/_ie6check.html.erb","vendor/plugins/refinery/app/views/shared/_menu.html.erb","vendor/plugins/refinery/app/views/shared/_menu_branch.html.erb","vendor/plugins/refinery/app/views/shared/_message.html.erb","vendor/plugins/refinery/app/views/shared/_submenu.html.erb","vendor/plugins/refinery/app/views/shared/_submenu_branch.html.erb","vendor/plugins/refinery/app/views/shared/admin","vendor/plugins/refinery/app/views/shared/admin/_continue_editing.html.erb","vendor/plugins/refinery/app/views/shared/admin/_error_messages_for.html.erb","vendor/plugins/refinery/app/views/shared/admin/_form_actions.html.erb","vendor/plugins/refinery/app/views/shared/admin/_image_picker.html.erb","vendor/plugins/refinery/app/views/shared/admin/_resource_picker.html.erb","vendor/plugins/refinery/app/views/shared/admin/_make_sortable.html.erb","vendor/plugins/refinery/app/views/shared/admin/_search.html.erb","vendor/plugins/refinery/app/views/shared/admin/_sortable_list.html.erb","vendor/plugins/refinery/app/views/welcome.html.erb","vendor/plugins/refinery/app/views/wymiframe.html.erb","vendor/plugins/refinery/config","vendor/plugins/refinery/config/routes.rb","vendor/plugins/refinery/init.rb","vendor/plugins/refinery/lib","vendor/plugins/refinery/lib/crud.rb","vendor/plugins/refinery/lib/generators","vendor/plugins/refinery/lib/generators/refinery","vendor/plugins/refinery/lib/generators/refinery/install.rb","vendor/plugins/refinery/lib/generators/refinery/Rakefile","vendor/plugins/refinery/lib/generators/refinery/README","vendor/plugins/refinery/lib/generators/refinery/refinery_generator.rb","vendor/plugins/refinery/lib/generators/refinery/templates","vendor/plugins/refinery/lib/generators/refinery/templates/config","vendor/plugins/refinery/lib/generators/refinery/templates/config/routes.rb","vendor/plugins/refinery/lib/generators/refinery/templates/controller.rb","vendor/plugins/refinery/lib/generators/refinery/templates/init.rb","vendor/plugins/refinery/lib/generators/refinery/templates/migration.rb","vendor/plugins/refinery/lib/generators/refinery/templates/model.rb","vendor/plugins/refinery/lib/generators/refinery/templates/public_controller.rb","vendor/plugins/refinery/lib/generators/refinery/templates/views","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/_form.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/_singular_name.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/_sortable_list.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/edit.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/index.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/new.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/index.html.erb","vendor/plugins/refinery/lib/generators/refinery/templates/views/show.html.erb","vendor/plugins/refinery/lib/generators/refinery/USAGE","vendor/plugins/refinery/lib/refinery","vendor/plugins/refinery/lib/refinery/activity.rb","vendor/plugins/refinery/lib/refinery/application_controller.rb","vendor/plugins/refinery/lib/refinery/form_helpers.rb","vendor/plugins/refinery/lib/refinery/html_truncation_helper.rb","vendor/plugins/refinery/lib/refinery/initializer.rb","vendor/plugins/refinery/lib/refinery/link_renderer.rb","vendor/plugins/refinery/lib/refinery/plugin.rb","vendor/plugins/refinery/lib/refinery/plugins.rb","vendor/plugins/refinery/lib/indexer.rb","vendor/plugins/refinery/lib/refinery.rb","vendor/plugins/refinery/lib/tasks","vendor/plugins/refinery/lib/tasks/indexer.rake","vendor/plugins/refinery/lib/tasks/refinery.rake","vendor/plugins/refinery_dialogs","vendor/plugins/refinery_dialogs/app","vendor/plugins/refinery_dialogs/app/controllers","vendor/plugins/refinery_dialogs/app/controllers/admin","vendor/plugins/refinery_dialogs/app/controllers/admin/dialogs_controller.rb","vendor/plugins/refinery_dialogs/app/views","vendor/plugins/refinery_dialogs/app/views/admin","vendor/plugins/refinery_dialogs/app/views/admin/dialogs","vendor/plugins/refinery_dialogs/app/views/admin/dialogs/show.html.erb","vendor/plugins/refinery_dialogs/app/views/layouts","vendor/plugins/refinery_dialogs/app/views/layouts/admin_dialog.html.erb","vendor/plugins/refinery_dialogs/config","vendor/plugins/refinery_dialogs/config/routes.rb","vendor/plugins/refinery_dialogs/init.rb","vendor/plugins/refinery_settings","vendor/plugins/refinery_settings/app","vendor/plugins/refinery_settings/app/controllers","vendor/plugins/refinery_settings/app/controllers/admin","vendor/plugins/refinery_settings/app/controllers/admin/refinery_settings_controller.rb","vendor/plugins/refinery_settings/app/models","vendor/plugins/refinery_settings/app/models/refinery_setting.rb","vendor/plugins/refinery_settings/app/views","vendor/plugins/refinery_settings/app/views/admin","vendor/plugins/refinery_settings/app/views/admin/refinery_settings","vendor/plugins/refinery_settings/app/views/admin/refinery_settings/_form.html.erb","vendor/plugins/refinery_settings/app/views/admin/refinery_settings/_make_sortable.html.erb","vendor/plugins/refinery_settings/app/views/admin/refinery_settings/_refinery_setting.html.erb","vendor/plugins/refinery_settings/app/views/admin/refinery_settings/edit.html.erb","vendor/plugins/refinery_settings/app/views/admin/refinery_settings/index.html.erb","vendor/plugins/refinery_settings/app/views/admin/refinery_settings/new.html.erb","vendor/plugins/refinery_settings/config","vendor/plugins/refinery_settings/config/routes.rb","vendor/plugins/refinery_settings/init.rb","vendor/plugins/resources","vendor/plugins/resources/app","vendor/plugins/resources/app/controllers","vendor/plugins/resources/app/controllers/admin","vendor/plugins/resources/app/controllers/admin/resources_controller.rb","vendor/plugins/resources/app/models","vendor/plugins/resources/app/models/resource.rb","vendor/plugins/resources/app/views","vendor/plugins/resources/app/views/admin","vendor/plugins/resources/app/views/admin/resources","vendor/plugins/resources/app/views/admin/resources/_form.html.erb","vendor/plugins/resources/app/views/admin/resources/_resource.html.erb","vendor/plugins/resources/app/views/admin/resources/edit.html.erb","vendor/plugins/resources/app/views/admin/resources/index.html.erb","vendor/plugins/resources/app/views/admin/resources/insert.html.erb","vendor/plugins/resources/app/views/admin/resources/new.html.erb","vendor/plugins/resources/config","vendor/plugins/resources/config/routes.rb","vendor/plugins/resources/init.rb"] s.homepage = %q{http://refinerycms.com} s.rubygems_version = %q{1.3.4} end Cleaned up file list in gemspec Files on separate lines makes it easier to track diffs. Signed-off-by: Philip Arndt <05447a56ef8d61f6725eec433ebbace12c6c37bc@gmail.com> Gem::Specification.new do |s| s.name = %q{refinerycms} s.version = "0.9.5.13" s.authors = ["Resolve Digital", "David Jones", "Philip Arndt"] s.date = %q{2009-11-19} s.description = %q{A beautiful open source Ruby on Rails content manager for small business. Easy to extend, easy to use, lightweight and all wrapped up in a super slick UI.} s.summary = %q{A beautiful open source Ruby on Rails content manager for small business.} s.email = %q{info@refinerycms.com} s.extra_rdoc_files = ["README", "CONTRIBUTORS", "LICENSE"] s.executables = ["refinery", "refinery-update-core"] s.default_executable = %q{refinery} s.homepage = %q{http://refinerycms.com} s.rubygems_version = %q{1.3.4} s.files = [ "CONTRIBUTORS", "LICENSE", "README", "Rakefile", "app/controllers/admin/base_controller.rb", "app/controllers/application.rb", "app/controllers/application_controller.rb", "app/helpers/application_helper.rb", "bin/refinery", "bin/refinery-update-core", "config/amazon_s3.yml", "config/boot.rb", "config/database.yml.example", "config/environment.rb", "config/environments/development.rb", "config/environments/production.rb", "config/environments/test.rb", "config/initializers/inflections.rb", "config/initializers/mime_types.rb", "config/preinitializer.rb", "config/rackspace_cloudfiles.yml", "config/routes.rb", "db/migrate/20091029034951_remove_blurb_from_news_items.rb", "db/migrate/20091109012126_add_missing_indexes.rb", "db/schema.rb", "db/seeds.rb", "lib/refinery_initializer.rb", "public/.htaccess", "public/404.html", "public/422.html", "public/500.html", "public/favicon.ico", "public/images/lightbox/bullet.gif", "public/images/lightbox/close.gif", "public/images/lightbox/closelabel.gif", "public/images/lightbox/donate-button.gif", "public/images/lightbox/download-icon.gif", "public/images/lightbox/loading.gif", "public/images/lightbox/nextlabel.gif", "public/images/lightbox/prevlabel.gif", "public/images/refinery/add.gif", "public/images/refinery/add.png", "public/images/refinery/admin_bg.png", "public/images/refinery/ajax-loader.gif", "public/images/refinery/branch-end.gif", "public/images/refinery/branch-start.gif", "public/images/refinery/branch.gif", "public/images/refinery/cross.gif", "public/images/refinery/deactive-gradient.gif", "public/images/refinery/delete.gif", "public/images/refinery/drag.gif", "public/images/refinery/edit.gif", "public/images/refinery/header-background.gif", "public/images/refinery/header_background.png", "public/images/refinery/hover-gradient.jpg", "public/images/refinery/icons/accept.png", "public/images/refinery/icons/add.png", "public/images/refinery/icons/application_edit.png", "public/images/refinery/icons/application_go.png", "public/images/refinery/icons/arrow_left.png", "public/images/refinery/icons/arrow_switch.png", "public/images/refinery/icons/arrow_up.png", "public/images/refinery/icons/bin_closed.png", "public/images/refinery/icons/cancel.png", "public/images/refinery/icons/cog_add.png", "public/images/refinery/icons/cog_edit.png", "public/images/refinery/icons/cross.png", "public/images/refinery/icons/delete.png", "public/images/refinery/icons/edit.png", "public/images/refinery/icons/email_edit.png", "public/images/refinery/icons/email_go.png", "public/images/refinery/icons/email_open.png", "public/images/refinery/icons/eye.png", "public/images/refinery/icons/help.png", "public/images/refinery/icons/image_add.png", "public/images/refinery/icons/image_edit.png", "public/images/refinery/icons/layout_add.png", "public/images/refinery/icons/layout_edit.png", "public/images/refinery/icons/page_add.png", "public/images/refinery/icons/page_edit.png", "public/images/refinery/icons/page_link.png", "public/images/refinery/icons/page_white_edit.png", "public/images/refinery/icons/page_white_put.png", "public/images/refinery/icons/reorder.png", "public/images/refinery/icons/tick.png", "public/images/refinery/icons/user.png", "public/images/refinery/icons/user_add.png", "public/images/refinery/icons/user_comment.png", "public/images/refinery/icons/user_edit.png", "public/images/refinery/info.gif", "public/images/refinery/logo-large.png", "public/images/refinery/logo-medium.png", "public/images/refinery/logo-small-medium.png", "public/images/refinery/logo-small.png", "public/images/refinery/logo.png", "public/images/refinery/m-tools.gif", "public/images/refinery/magnifier.png", "public/images/refinery/nav-3-background.gif", "public/images/refinery/page_bg.png", "public/images/refinery/resolve-digital.gif", "public/images/refinery/resolve_digital_footer_logo.png", "public/images/refinery/search.gif", "public/images/refinery/shad_blcorner.png", "public/images/refinery/shad_bottom.png", "public/images/refinery/shad_brcorner.png", "public/images/refinery/shad_tlcorner.png", "public/images/refinery/shad_trcorner.png", "public/images/refinery/tableft.gif", "public/images/refinery/tabright.gif", "public/images/refinery/tick.gif", "public/images/thickbox/cross.png", "public/images/thickbox/loadingAnimation.gif", "public/images/thickbox/macFFBgHack.png", "public/images/wymeditor/skins/refinery/blockquote.png", "public/images/wymeditor/skins/refinery/center.png", "public/images/wymeditor/skins/refinery/css.png", "public/images/wymeditor/skins/refinery/h1.png", "public/images/wymeditor/skins/refinery/h2.png", "public/images/wymeditor/skins/refinery/h3.png", "public/images/wymeditor/skins/refinery/h4.png", "public/images/wymeditor/skins/refinery/h5.png", "public/images/wymeditor/skins/refinery/h6.png", "public/images/wymeditor/skins/refinery/icons.png", "public/images/wymeditor/skins/refinery/iframe/lbl-blockquote.png", "public/images/wymeditor/skins/refinery/iframe/lbl-h1.png", "public/images/wymeditor/skins/refinery/iframe/lbl-h2.png", "public/images/wymeditor/skins/refinery/iframe/lbl-h3.png", "public/images/wymeditor/skins/refinery/iframe/lbl-h4.png", "public/images/wymeditor/skins/refinery/iframe/lbl-h5.png", "public/images/wymeditor/skins/refinery/iframe/lbl-h6.png", "public/images/wymeditor/skins/refinery/iframe/lbl-p.png", "public/images/wymeditor/skins/refinery/iframe/lbl-pre.png", "public/images/wymeditor/skins/refinery/justify.png", "public/images/wymeditor/skins/refinery/left.png", "public/images/wymeditor/skins/refinery/paragraph.png", "public/images/wymeditor/skins/refinery/right.png", "public/images/wymeditor/skins/wymeditor_icon.png", "public/javascripts/application.js", "public/javascripts/builder.js", "public/javascripts/controls.js", "public/javascripts/dragdrop.js", "public/javascripts/effects.js", "public/javascripts/fastinit.js", "public/javascripts/jquery/GPL-LICENSE.txt", "public/javascripts/jquery/jquery.js", "public/javascripts/jquery/MIT-LICENSE.txt", "public/javascripts/lightbox.js", "public/javascripts/livepipe.js", "public/javascripts/prototype.js", "public/javascripts/refinery/admin.js", "public/javascripts/refinery/boot_wym.js", "public/javascripts/refinery/dialog.js", "public/javascripts/refinery/parse_url.js", "public/javascripts/refinery/prototype.enhancements.js", "public/javascripts/refinery/tooltips.js", "public/javascripts/scriptaculous.js", "public/javascripts/slider.js", "public/javascripts/tabs.js", "public/javascripts/thickbox.js", "public/javascripts/wymeditor/jquery.refinery.wymeditor.js", "public/javascripts/wymeditor/lang/ca.js", "public/javascripts/wymeditor/lang/cs.js", "public/javascripts/wymeditor/lang/de.js", "public/javascripts/wymeditor/lang/en.js", "public/javascripts/wymeditor/lang/es.js", "public/javascripts/wymeditor/lang/fa.js", "public/javascripts/wymeditor/lang/fr.js", "public/javascripts/wymeditor/lang/he.js", "public/javascripts/wymeditor/lang/hu.js", "public/javascripts/wymeditor/lang/it.js", "public/javascripts/wymeditor/lang/nb.js", "public/javascripts/wymeditor/lang/nl.js", "public/javascripts/wymeditor/lang/nn.js", "public/javascripts/wymeditor/lang/pl.js", "public/javascripts/wymeditor/lang/pt-br.js", "public/javascripts/wymeditor/lang/pt.js", "public/javascripts/wymeditor/lang/ru.js", "public/javascripts/wymeditor/lang/sv.js", "public/javascripts/wymeditor/lang/tr.js", "public/javascripts/wymeditor/lang/zh_cn.js", "public/javascripts/wymeditor/skins/refinery/skin.js", "public/robots.txt", "public/stylesheets/application.css", "public/stylesheets/formatting.css", "public/stylesheets/home.css", "public/stylesheets/ie6.css", "public/stylesheets/ie7.css", "public/stylesheets/lightbox.css", "public/stylesheets/refinery/application.css", "public/stylesheets/refinery/formatting.css", "public/stylesheets/refinery/home.css", "public/stylesheets/refinery/refinery.css", "public/stylesheets/refinery/theme.css", "public/stylesheets/refinery/thickbox.css", "public/stylesheets/refinery/tooltips.css", "public/stylesheets/theme.css", "public/stylesheets/wymeditor/skins/refinery/skin.css", "public/stylesheets/wymeditor/skins/refinery/wymiframe.css", "public/wymeditor/GPL-license.txt", "public/wymeditor/MIT-license.txt", "public/wymeditor/README", "script/about", "script/console", "script/dbconsole", "script/destroy", "script/generate", "script/performance/benchmarker", "script/performance/profiler", "script/performance/request", "script/plugin", "script/process/inspector", "script/process/reaper", "script/process/spawner", "script/runner", "script/server", "vendor/plugins/acts_as_indexed/CHANGELOG", "vendor/plugins/acts_as_indexed/init.rb", "vendor/plugins/acts_as_indexed/lib/acts_as_indexed.rb", "vendor/plugins/acts_as_indexed/lib/search_atom.rb", "vendor/plugins/acts_as_indexed/lib/search_index.rb", "vendor/plugins/acts_as_indexed/lib/will_paginate_search.rb", "vendor/plugins/acts_as_indexed/MIT-LICENSE", "vendor/plugins/acts_as_indexed/Rakefile", "vendor/plugins/acts_as_indexed/README.rdoc", "vendor/plugins/acts_as_indexed/test/abstract_unit.rb", "vendor/plugins/acts_as_indexed/test/acts_as_indexed_test.rb", "vendor/plugins/acts_as_indexed/test/database.yml", "vendor/plugins/acts_as_indexed/test/fixtures/post.rb", "vendor/plugins/acts_as_indexed/test/fixtures/posts.yml", "vendor/plugins/acts_as_indexed/test/schema.rb", "vendor/plugins/acts_as_tree/init.rb", "vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb", "vendor/plugins/acts_as_tree/Rakefile", "vendor/plugins/acts_as_tree/README", "vendor/plugins/acts_as_tree/test/abstract_unit.rb", "vendor/plugins/acts_as_tree/test/acts_as_tree_test.rb", "vendor/plugins/acts_as_tree/test/database.yml", "vendor/plugins/acts_as_tree/test/fixtures/mixin.rb", "vendor/plugins/acts_as_tree/test/fixtures/mixins.yml", "vendor/plugins/acts_as_tree/test/schema.rb", "vendor/plugins/attachment_fu/amazon_s3.yml.tpl", "vendor/plugins/attachment_fu/CHANGELOG", "vendor/plugins/attachment_fu/init.rb", "vendor/plugins/attachment_fu/install.rb", "vendor/plugins/attachment_fu/lib/geometry.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb", "vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb", "vendor/plugins/attachment_fu/LICENSE", "vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl", "vendor/plugins/attachment_fu/Rakefile", "vendor/plugins/attachment_fu/README", "vendor/plugins/attachment_fu/test/backends/db_file_test.rb", "vendor/plugins/attachment_fu/test/backends/file_system_test.rb", "vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb", "vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb", "vendor/plugins/attachment_fu/test/base_attachment_tests.rb", "vendor/plugins/attachment_fu/test/basic_test.rb", "vendor/plugins/attachment_fu/test/database.yml", "vendor/plugins/attachment_fu/test/extra_attachment_test.rb", "vendor/plugins/attachment_fu/test/fixtures/attachment.rb", "vendor/plugins/attachment_fu/test/fixtures/files/fake/rails.png", "vendor/plugins/attachment_fu/test/fixtures/files/foo.txt", "vendor/plugins/attachment_fu/test/fixtures/files/rails.png", "vendor/plugins/attachment_fu/test/geometry_test.rb", "vendor/plugins/attachment_fu/test/processors/core_image_test.rb", "vendor/plugins/attachment_fu/test/processors/gd2_test.rb", "vendor/plugins/attachment_fu/test/processors/image_science_test.rb", "vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb", "vendor/plugins/attachment_fu/test/processors/rmagick_test.rb", "vendor/plugins/attachment_fu/test/schema.rb", "vendor/plugins/attachment_fu/test/test_helper.rb", "vendor/plugins/attachment_fu/test/validation_test.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb", "vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb", "vendor/plugins/authentication/app/controllers/admin/users_controller.rb", "vendor/plugins/authentication/app/controllers/sessions_controller.rb", "vendor/plugins/authentication/app/controllers/users_controller.rb", "vendor/plugins/authentication/app/helpers/sessions_helper.rb", "vendor/plugins/authentication/app/helpers/users_helper.rb", "vendor/plugins/authentication/app/models/user.rb", "vendor/plugins/authentication/app/models/user_mailer.rb", "vendor/plugins/authentication/app/models/user_observer.rb", "vendor/plugins/authentication/app/models/user_plugin.rb", "vendor/plugins/authentication/app/views/admin/users/_form.html.erb", "vendor/plugins/authentication/app/views/admin/users/edit.html.erb", "vendor/plugins/authentication/app/views/admin/users/index.html.erb", "vendor/plugins/authentication/app/views/admin/users/new.html.erb", "vendor/plugins/authentication/app/views/sessions/new.html.erb", "vendor/plugins/authentication/app/views/user_mailer/activation.html.erb", "vendor/plugins/authentication/app/views/user_mailer/signup_notification.html.erb", "vendor/plugins/authentication/app/views/users/new.html.erb", "vendor/plugins/authentication/config/routes.rb", "vendor/plugins/authentication/init.rb", "vendor/plugins/authentication/lib/authenticated_system.rb", "vendor/plugins/authentication/lib/authenticated_test_helper.rb", "vendor/plugins/authentication/Rakefile", "vendor/plugins/authentication/README", "vendor/plugins/authentication/test/fixtures/users.yml", "vendor/plugins/authentication/test/functional/admin/base_controller_test.rb", "vendor/plugins/authentication/test/functional/admin/dashboard_controller_test.rb", "vendor/plugins/authentication/test/functional/admin/pages_controller_test.rb", "vendor/plugins/authentication/test/functional/sessions_controller_test.rb", "vendor/plugins/authentication/test/functional/users_controller_test.rb", "vendor/plugins/authentication/test/test_helper.rb", "vendor/plugins/authentication/test/unit/user_mailer_test.rb", "vendor/plugins/authentication/test/unit/user_test.rb", "vendor/plugins/dashboard/app/controllers/admin/dashboard_controller.rb", "vendor/plugins/dashboard/app/helpers/admin/dashboard_helper.rb", "vendor/plugins/dashboard/app/views/admin/dashboard/_recent_activity.html.erb", "vendor/plugins/dashboard/app/views/admin/dashboard/index.html.erb", "vendor/plugins/dashboard/config/routes.rb", "vendor/plugins/dashboard/init.rb", "vendor/plugins/images/app/controllers/admin/images_controller.rb", "vendor/plugins/images/app/helpers/admin/images_helper.rb", "vendor/plugins/images/app/models/image.rb", "vendor/plugins/images/app/views/admin/images/_form.html.erb", "vendor/plugins/images/app/views/admin/images/_grid_view.html.erb", "vendor/plugins/images/app/views/admin/images/_list_view.html.erb", "vendor/plugins/images/app/views/admin/images/_list_view_image.html.erb", "vendor/plugins/images/app/views/admin/images/edit.html.erb", "vendor/plugins/images/app/views/admin/images/index.html.erb", "vendor/plugins/images/app/views/admin/images/insert.html.erb", "vendor/plugins/images/app/views/admin/images/new.html.erb", "vendor/plugins/images/config/routes.rb", "vendor/plugins/images/init.rb", "vendor/plugins/images/lib/tasks/images.rake", "vendor/plugins/inquiries/app/controllers/admin/inquiries_controller.rb", "vendor/plugins/inquiries/app/controllers/admin/inquiry_settings_controller.rb", "vendor/plugins/inquiries/app/controllers/inquiries_controller.rb", "vendor/plugins/inquiries/app/helpers/inquiries_helper.rb", "vendor/plugins/inquiries/app/models/inquiry.rb", "vendor/plugins/inquiries/app/models/inquiry_mailer.rb", "vendor/plugins/inquiries/app/models/inquiry_setting.rb", "vendor/plugins/inquiries/app/views/admin/inquiries/_inquiry.html.erb", "vendor/plugins/inquiries/app/views/admin/inquiries/index.html.erb", "vendor/plugins/inquiries/app/views/admin/inquiries/show.html.erb", "vendor/plugins/inquiries/app/views/admin/inquiry_settings/_confirmation_email_form.html.erb", "vendor/plugins/inquiries/app/views/admin/inquiry_settings/_notification_recipients_form.html.erb", "vendor/plugins/inquiries/app/views/admin/inquiry_settings/edit.html.erb", "vendor/plugins/inquiries/app/views/admin/inquiry_settings/index.html.erb", "vendor/plugins/inquiries/app/views/inquiries/new.html.erb", "vendor/plugins/inquiries/app/views/inquiries/thank_you.html.erb", "vendor/plugins/inquiries/app/views/inquiry_mailer/confirmation.html.erb", "vendor/plugins/inquiries/app/views/inquiry_mailer/notification.html.erb", "vendor/plugins/inquiries/config/routes.rb", "vendor/plugins/inquiries/init.rb", "vendor/plugins/news/app/controllers/admin/news_items_controller.rb", "vendor/plugins/news/app/controllers/news_items_controller.rb", "vendor/plugins/news/app/models/news_item.rb", "vendor/plugins/news/app/views/admin/news_items/_form.html.erb", "vendor/plugins/news/app/views/admin/news_items/_news_item.html.erb", "vendor/plugins/news/app/views/admin/news_items/edit.html.erb", "vendor/plugins/news/app/views/admin/news_items/index.html.erb", "vendor/plugins/news/app/views/admin/news_items/new.html.erb", "vendor/plugins/news/app/views/news_items/_recent_posts.html.erb", "vendor/plugins/news/app/views/news_items/index.html.erb", "vendor/plugins/news/app/views/news_items/show.html.erb", "vendor/plugins/news/config/routes.rb", "vendor/plugins/news/init.rb", "vendor/plugins/pages/app/controllers/admin/page_dialogs_controller.rb", "vendor/plugins/pages/app/controllers/admin/page_parts_controller.rb", "vendor/plugins/pages/app/controllers/admin/pages_controller.rb", "vendor/plugins/pages/app/controllers/pages_controller.rb", "vendor/plugins/pages/app/helpers/pages_helper.rb", "vendor/plugins/pages/app/models/page.rb", "vendor/plugins/pages/app/models/page_part.rb", "vendor/plugins/pages/app/views/admin/page_dialogs/_page_link.html.erb", "vendor/plugins/pages/app/views/admin/page_dialogs/link_to.html.erb", "vendor/plugins/pages/app/views/admin/pages/_form.html.erb", "vendor/plugins/pages/app/views/admin/pages/_list.html.erb", "vendor/plugins/pages/app/views/admin/pages/_page_part_field.html.erb", "vendor/plugins/pages/app/views/admin/pages/_sortable_list.html.erb", "vendor/plugins/pages/app/views/admin/pages/edit.html.erb", "vendor/plugins/pages/app/views/admin/pages/index.html.erb", "vendor/plugins/pages/app/views/admin/pages/new.html.erb", "vendor/plugins/pages/app/views/pages/home.html.erb", "vendor/plugins/pages/app/views/pages/show.html.erb", "vendor/plugins/pages/config/routes.rb", "vendor/plugins/pages/init.rb", "vendor/plugins/refinery/app/controllers/admin/refinery_core_controller.rb", "vendor/plugins/refinery/app/views/admin/_head.html.erb", "vendor/plugins/refinery/app/views/admin/_menu.html.erb", "vendor/plugins/refinery/app/views/layouts/admin.html.erb", "vendor/plugins/refinery/app/views/layouts/application.html.erb", "vendor/plugins/refinery/app/views/shared/_footer.html.erb", "vendor/plugins/refinery/app/views/shared/_google_analytics.html.erb", "vendor/plugins/refinery/app/views/shared/_header.html.erb", "vendor/plugins/refinery/app/views/shared/_ie6check.html.erb", "vendor/plugins/refinery/app/views/shared/_menu.html.erb", "vendor/plugins/refinery/app/views/shared/_menu_branch.html.erb", "vendor/plugins/refinery/app/views/shared/_message.html.erb", "vendor/plugins/refinery/app/views/shared/_submenu.html.erb", "vendor/plugins/refinery/app/views/shared/_submenu_branch.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_continue_editing.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_error_messages_for.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_form_actions.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_image_picker.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_make_sortable.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_resource_picker.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_search.html.erb", "vendor/plugins/refinery/app/views/shared/admin/_sortable_list.html.erb", "vendor/plugins/refinery/app/views/welcome.html.erb", "vendor/plugins/refinery/app/views/wymiframe.html.erb", "vendor/plugins/refinery/config/routes.rb", "vendor/plugins/refinery/init.rb", "vendor/plugins/refinery/lib/crud.rb", "vendor/plugins/refinery/lib/generators/refinery/install.rb", "vendor/plugins/refinery/lib/generators/refinery/Rakefile", "vendor/plugins/refinery/lib/generators/refinery/README", "vendor/plugins/refinery/lib/generators/refinery/refinery_generator.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/config/routes.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/controller.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/init.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/migration.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/model.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/public_controller.rb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/_form.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/_singular_name.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/_sortable_list.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/edit.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/index.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/admin/new.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/index.html.erb", "vendor/plugins/refinery/lib/generators/refinery/templates/views/show.html.erb", "vendor/plugins/refinery/lib/generators/refinery/USAGE", "vendor/plugins/refinery/lib/indexer.rb", "vendor/plugins/refinery/lib/refinery/activity.rb", "vendor/plugins/refinery/lib/refinery/admin_base_controller.rb", "vendor/plugins/refinery/lib/refinery/application_controller.rb", "vendor/plugins/refinery/lib/refinery/application_helper.rb", "vendor/plugins/refinery/lib/refinery/form_helpers.rb", "vendor/plugins/refinery/lib/refinery/html_truncation_helper.rb", "vendor/plugins/refinery/lib/refinery/initializer.rb", "vendor/plugins/refinery/lib/refinery/link_renderer.rb", "vendor/plugins/refinery/lib/refinery/plugin.rb", "vendor/plugins/refinery/lib/refinery/plugins.rb", "vendor/plugins/refinery/lib/refinery.rb", "vendor/plugins/refinery/lib/tasks/indexer.rake", "vendor/plugins/refinery/lib/tasks/refinery.rake", "vendor/plugins/refinery_dialogs/app/controllers/admin/dialogs_controller.rb", "vendor/plugins/refinery_dialogs/app/views/admin/dialogs/show.html.erb", "vendor/plugins/refinery_dialogs/app/views/layouts/admin_dialog.html.erb", "vendor/plugins/refinery_dialogs/config/routes.rb", "vendor/plugins/refinery_dialogs/init.rb", "vendor/plugins/refinery_settings/app/controllers/admin/refinery_settings_controller.rb", "vendor/plugins/refinery_settings/app/models/refinery_setting.rb", "vendor/plugins/refinery_settings/app/views/admin/refinery_settings/_form.html.erb", "vendor/plugins/refinery_settings/app/views/admin/refinery_settings/_make_sortable.html.erb", "vendor/plugins/refinery_settings/app/views/admin/refinery_settings/_refinery_setting.html.erb", "vendor/plugins/refinery_settings/app/views/admin/refinery_settings/edit.html.erb", "vendor/plugins/refinery_settings/app/views/admin/refinery_settings/index.html.erb", "vendor/plugins/refinery_settings/app/views/admin/refinery_settings/new.html.erb", "vendor/plugins/refinery_settings/config/routes.rb", "vendor/plugins/refinery_settings/init.rb", "vendor/plugins/resources/app/controllers/admin/resources_controller.rb", "vendor/plugins/resources/app/models/resource.rb", "vendor/plugins/resources/app/views/admin/resources/_form.html.erb", "vendor/plugins/resources/app/views/admin/resources/_resource.html.erb", "vendor/plugins/resources/app/views/admin/resources/edit.html.erb", "vendor/plugins/resources/app/views/admin/resources/index.html.erb", "vendor/plugins/resources/app/views/admin/resources/insert.html.erb", "vendor/plugins/resources/app/views/admin/resources/new.html.erb", "vendor/plugins/resources/config/routes.rb", "vendor/plugins/resources/init.rb" ] end
module Sastrawi module Dictionary class ArrayDictionary attr_reader :words def initialize(words = []) @words = [] add_words(words) end ## # Check whether a word is contained in the dictionary def contains?(word) @words.include?(word) end ## # Count how many words in the dictionary def count @words.length end ## # Add multiple words to the dictionary def add_words(new_words) new_words.each do |word| add(word) end end ## # Add a word to the dictionary def add(word) return if word == '' @words.push(word) end ## # Add words from a text file to the dictionary def add_words_from_text_file(file_path) words = [] File.open(file_path, 'r') do |file| file.each do |line| words.push(line.chomp) end end add_words(words) end ## # Remove a word from the dictionary def remove(word) @words.delete(word) end end end end Remove all whitespace from the start and the end before adding a word to dictionary module Sastrawi module Dictionary class ArrayDictionary attr_reader :words def initialize(words = []) @words = [] add_words(words) end ## # Check whether a word is contained in the dictionary def contains?(word) @words.include?(word) end ## # Count how many words in the dictionary def count @words.length end ## # Add multiple words to the dictionary def add_words(new_words) new_words.each do |word| add(word) end end ## # Add a word to the dictionary def add(word) return if word.strip == '' @words.push(word) end ## # Add words from a text file to the dictionary def add_words_from_text_file(file_path) words = [] File.open(file_path, 'r') do |file| file.each do |line| words.push(line.chomp) end end add_words(words) end ## # Remove a word from the dictionary def remove(word) @words.delete(word) end end end end
class GenericLoader def initialize(options = {}) @path = options[:path] || "." @id_mapping = {} end def restore_all read_data('__dependencies').each { |entry| restore_table(*entry) } end def restore_table(model_name, *associations) puts "Restoring #{model_name}..." assoc = associations.map { |attr, options| keyed_dependency(attr, options) } assoc = Hash[*assoc.flatten] table_name = model_name.underscore.pluralize mapping = (@id_mapping[table_name] ||= {}) rows = read_data(table_name) if self.respond_to?("restore_#{table_name}") self.send("restore_#{table_name}", rows, mapping, assoc) else default_restore_table(model_name.classify, rows, mapping, assoc) end puts " done!" end private def default_restore_table(model_name, rows, mapping, associations, &block) model = model_name.constantize model.class_attribute :attr_protected model.class_attribute :attr_accessible attr_protected = model.attr_protected attr_accessible = model.attr_accessible count = 0 model.transaction do rows.each do |item| attr = mapped_attributes(item, associations) attr = block.call(attr) if block if attr instance = model.new(attr) instance.save!(:validate => false) mapping[item['id']] = instance.id end count += 1 puts " #{count}/#{rows.length}" if count % 1000 == 0 end end model.attr_protected = attr_protected model.attr_accessible = attr_accessible end def custom_restore_table(rows, mapping, associations, &block) raise "Needs a block" unless block count = 0 rows.each do |item| block.call(mapped_attributes(item, associations)) count += 1 puts " #{count}/#{rows.length}" if count % 1000 == 0 end end def read_data(name) filename = "#{@path}/#{name}.json.gz" JSON::load(Zlib::GzipReader.open(filename) { |gz| gz.read }) end def keyed_dependency(attr, options) key = options["foreign_key"] || "#{attr}_id" table = if options["polymorphic"] options["foreign_type"] || "#{attr}_type" else (options["class_name"] || attr).pluralize.underscore end [key, { :table => table, :polymorphic => options["polymorphic"] }] end def mapped_attributes(item, assoc) attr = {} item.each do |key, val| if assoc[key] table = assoc[key][:table] table = item[table].underscore.pluralize if assoc[key][:polymorphic] begin val = @id_mapping[table][val] rescue #TODO fix references to the same table val = nil end elsif val.is_a?(String) val = val.strip end attr[key] = val end attr end end class Loader < GenericLoader def initialize(options = {}) super dependencies = read_data('__dependencies') class << self; self end.class_eval do dependencies.each do |entry| method_name = "restore_#{entry[0].pluralize.underscore}" unless method_defined?(method_name) define_method(method_name) { |a, b, c| puts ' (ignored)' } end end end end def restore_all dependencies = read_data('__dependencies') # - Project depends on User, but has no explicit 'has_many' in old Plexus restore_table(*dependencies.assoc('User')) # - restore all remaining tables after User is done dependencies.each { |item| restore_table(*item) unless item[0] == 'User' } end def restore_users(*args) default_restore_table('User', *args) do |attr| (attr['login_name'] != 'bootstrap') && attr.merge('abilities' => []) end end def restore_permissions(*args) User.transaction do custom_restore_table(*args) do |attr| user = User.find_by_id(attr['user_id']) if user ability = attr['ability_name'].sub(/update/, 'upload') user.send(User.ability_setter(ability), '1') user.save! end end end end def restore_activity_logs(*args) User.transaction do custom_restore_table(*args) do |attr| user = User.find_by_id(attr['user_id']) if user and not attr['timestamp'].blank? user.log_activity(Time.parse(attr['timestamp'])) end end end end def restore_projects(rows, mapping, associations) managers = {} default_restore_table('Project', rows, mapping, associations) do |attr| managers[attr['id']] = attr['local_manager'] Hash[*attr.select { |key, val| %w{name organization}.include? key }.flatten] end @managers = managers.map { |k,v| [@id_mapping['projects'][k], v] } end def restore_project_memberships(*args) default_restore_table('Membership', *args) do |attr| attr.merge('role' => 'client') end @managers.each do |k,v| project = Project.find(k) user = User.find_by_id(v) project.set_role(user, 'manager') if project and user end end def restore_samples(*args) #TODO - restore extra information as annotations default_restore_table('Sample', *args) do |attr| { 'name' => attr['nickname'], 'external_id' => attr['name'], 'project_id' => attr['project_id'] } end end def restore_process_nodes(*args) default_restore_table('ProcessNode', *args) end def restore_domains(rows, mapping, associations) def grab(item, base_key) %w{x y z}.map { |axis| item["#{base_key}_#{axis}"] } end @domains = [] custom_restore_table(rows, mapping, associations) do |item| mapping[item['id']] = @domains.count @domains << { 'domain_origin' => grab(item, 'domain_origin'), 'domain_size' => grab(item, 'domain_size'), 'voxel_size' => grab(item, 'voxel_size'), 'voxel_unit' => item['voxel_unit'] } end end def restore_data_nodes(*args) #TODO - add fingerprints default_restore_table('DataNode', *args) do |attr| attr.reject { |k| %w{process_node_id domain_id}.include? k }. merge({ 'producer_id' => attr['process_node_id'] }). merge(attr['domain_id'].blank? ? {} : @domains[attr['domain_id']]) end ProcessNode.transaction do DataNode.all.each do |v| v.producer.update_attribute(:sample, v.sample) if v.producer end end end def restore_external_resources(*args) DataNode.transaction do custom_restore_table(*args) do |attr| node = DataNode.find_by_id(attr['data_node_id']) if node node.filename = attr['name'] node.synchronized_at = attr['synchronized_at'] node.save!(:validate => false) end end end end def restore_input_links(*args) ProcessNode.transaction do custom_restore_table(*args) do |attr| data = DataNode.find(attr['data_node_id']) process = ProcessNode.find(attr['process_node_id']) process.add_input(data) if data and process end end end def restore_process_attributes(*args) parameters = {} custom_restore_table(*args) do |attr| val = attr['numerical_value'] val = attr['text_value'] if val.nil? (parameters[attr['process_node_id']] ||= {})[attr['name']] = val end ProcessNode.transaction do ProcessNode.all.each do |p| p.update_attribute(:parameters, parameters[p.id] || {}) end end end def restore_data_pictures(*args) excluded = %w{storage_path data_node_id parent_id thumbnail process_node_id} default_restore_table('Image', *args) do |attr| unless attr['data_node_id'].blank? or attr['storage_path'].blank? extra = { :stored_path => attr['storage_path'], :illustratable_id => attr['data_node_id'], :illustratable_type => 'DataNode' } attr.reject { |k| excluded.include? k }.merge(extra) end end end def restore_comments(*args) default_restore_table('Comment', *args) do |attr| { :text => attr['value'], :commentable_id => attr['asset_id'], :commentable_type => attr['asset_type'] } end end def restore_imports(rows, mapping, associations) excluded = %w{replace content import_log} Import.transaction do custom_restore_table(rows, mapping, associations) do |item| attr = item.reject { |k| excluded.include? k } if attr instance = Import.new(attr) %w{content import_log}.each do |key| instance.instance_eval { write_attribute(key, item[key]) } end instance.save!(:validate => false) mapping[item['id']] = instance.id end end end end # def restore_imports(*args) # default_restore_table('Import', *args) do |attr| # attr.reject { |k| k == 'replace' } # end # end #TODO - restore_data_logs (needs a model to write to) #TODO - restore_access_restrictions (Projects only) #TODO - restore_data_attachments #TODO - restore_version_stamps end Loader.new(:path => ARGV[2]).restore_all More corrections on the restore script class GenericLoader def initialize(options = {}) @path = options[:path] || "." @id_mapping = {} end def restore_all read_data('__dependencies').each { |entry| restore_table(*entry) } end def restore_table(model_name, *associations) puts "Restoring #{model_name}..." assoc = associations.map { |attr, options| keyed_dependency(attr, options) } assoc = Hash[*assoc.flatten] table_name = model_name.underscore.pluralize mapping = (@id_mapping[table_name] ||= {}) rows = read_data(table_name) if self.respond_to?("restore_#{table_name}") self.send("restore_#{table_name}", rows, mapping, assoc) else default_restore_table(model_name.classify, rows, mapping, assoc) end puts " done!" end private def default_restore_table(model_name, rows, mapping, associations, &block) model = model_name.constantize model.class_attribute :attr_protected model.class_attribute :attr_accessible attr_protected = model.attr_protected attr_accessible = model.attr_accessible count = 0 model.transaction do rows.each do |item| attr = mapped_attributes(item, associations) attr = block.call(attr) if block if attr instance = model.new(attr) instance.save!(:validate => false) mapping[item['id']] = instance.id end count += 1 puts " #{count}/#{rows.length}" if count % 1000 == 0 end end model.attr_protected = attr_protected model.attr_accessible = attr_accessible end def custom_restore_table(rows, mapping, associations, &block) raise "Needs a block" unless block count = 0 rows.each do |item| block.call(mapped_attributes(item, associations)) count += 1 puts " #{count}/#{rows.length}" if count % 1000 == 0 end end def read_data(name) filename = "#{@path}/#{name}.json.gz" JSON::load(Zlib::GzipReader.open(filename) { |gz| gz.read }) end def keyed_dependency(attr, options) key = options["foreign_key"] || "#{attr}_id" table = if options["polymorphic"] options["foreign_type"] || "#{attr}_type" else (options["class_name"] || attr).pluralize.underscore end [key, { :table => table, :polymorphic => options["polymorphic"] }] end def mapped_attributes(item, assoc) attr = {} item.each do |key, val| if assoc[key] table = assoc[key][:table] table = item[table].underscore.pluralize if assoc[key][:polymorphic] begin val = @id_mapping[table][val] rescue #TODO fix references to the same table val = nil end elsif val.is_a?(String) val = val.strip end attr[key] = val end attr end end class Loader < GenericLoader def initialize(options = {}) super dependencies = read_data('__dependencies') class << self; self end.class_eval do dependencies.each do |entry| method_name = "restore_#{entry[0].pluralize.underscore}" unless method_defined?(method_name) define_method(method_name) { |a, b, c| puts ' (ignored)' } end end end end def restore_all dependencies = read_data('__dependencies') # - Project depends on User, but has no explicit 'has_many' in old Plexus restore_table(*dependencies.assoc('User')) # - restore all remaining tables after User is done dependencies.each { |item| restore_table(*item) unless item[0] == 'User' } end def restore_users(*args) default_restore_table('User', *args) do |attr| (attr['login_name'] != 'bootstrap') && attr.merge('abilities' => []) end end def restore_permissions(*args) User.transaction do custom_restore_table(*args) do |attr| user = User.find_by_id(attr['user_id']) if user ability = attr['ability_name'].sub(/update/, 'upload') user.send(User.ability_setter(ability), '1') user.save! end end end end def restore_activity_logs(*args) User.transaction do custom_restore_table(*args) do |attr| user = User.find_by_id(attr['user_id']) if user and not attr['timestamp'].blank? user.log_activity(Time.parse(attr['timestamp'])) end end end end def restore_projects(rows, mapping, associations) managers = {} default_restore_table('Project', rows, mapping, associations) do |attr| managers[attr['id']] = attr['local_manager'] Hash[*attr.select { |key, val| %w{name organization}.include? key }.flatten] end @managers = managers.map { |k,v| [@id_mapping['projects'][k], v] } end def restore_project_memberships(*args) default_restore_table('Membership', *args) do |attr| attr.merge('role' => 'client') end @managers.each do |k,v| project = Project.find(k) user = User.find_by_id(v) project.set_role(user, 'manager') if project and user end end def restore_samples(*args) #TODO - restore extra information as annotations default_restore_table('Sample', *args) do |attr| { 'name' => attr['nickname'], 'external_id' => attr['name'], 'project_id' => attr['project_id'] } end end def restore_process_nodes(*args) default_restore_table('ProcessNode', *args) end def restore_domains(rows, mapping, associations) def grab(item, base_key) %w{x y z}.map { |axis| item["#{base_key}_#{axis}"] } end @domains = [] custom_restore_table(rows, mapping, associations) do |item| mapping[item['id']] = @domains.count @domains << { 'domain_origin' => grab(item, 'domain_origin'), 'domain_size' => grab(item, 'domain_size'), 'voxel_size' => grab(item, 'voxel_size'), 'voxel_unit' => item['voxel_unit'] } end end def restore_data_nodes(*args) #TODO - add fingerprints default_restore_table('DataNode', *args) do |attr| attr.reject { |k| %w{process_node_id domain_id}.include? k }. merge({ 'producer_id' => attr['process_node_id'] }). merge(attr['domain_id'].blank? ? {} : @domains[attr['domain_id']]) end ProcessNode.transaction do DataNode.all.each do |v| v.producer.update_attribute(:sample, v.sample) if v.producer end end end def restore_external_resources(*args) DataNode.transaction do custom_restore_table(*args) do |attr| node = DataNode.find_by_id(attr['data_node_id']) if node node.filename = attr['name'] node.synchronized_at = attr['synchronized_at'] node.save!(:validate => false) end end end end def restore_input_links(*args) ProcessNode.transaction do custom_restore_table(*args) do |attr| data = DataNode.find(attr['data_node_id']) process = ProcessNode.find(attr['process_node_id']) process.add_input(data) if data and process end end end def restore_process_attributes(*args) parameters = {} custom_restore_table(*args) do |attr| val = attr['numerical_value'] val = attr['text_value'] if val.nil? (parameters[attr['process_node_id']] ||= {})[attr['name']] = val end ProcessNode.transaction do ProcessNode.all.each do |p| p.update_attribute(:parameters, parameters[p.id] || {}) end end end def restore_data_pictures(*args) excluded = %w{storage_path data_node_id parent_id thumbnail process_node_id} default_restore_table('Image', *args) do |attr| unless attr['data_node_id'].blank? or attr['storage_path'].blank? extra = { :stored_path => attr['storage_path'], :illustratable_id => attr['data_node_id'], :illustratable_type => 'DataNode' } attr.reject { |k, v| excluded.include? k }.merge(extra) end end end def restore_comments(*args) default_restore_table('Comment', *args) do |attr| { :text => attr['value'], :commentable_id => attr['asset_id'], :commentable_type => attr['asset_type'] } end end def restore_imports(rows, mapping, associations) excluded = %w{replace content import_log} Import.transaction do custom_restore_table(rows, mapping, associations) do |item| attr = item.reject { |k, v| excluded.include? k } if attr instance = Import.new(attr) %w{content import_log}.each do |key| instance.instance_eval { write_attribute(key, item[key]) } end instance.save!(:validate => false) mapping[item['id']] = instance.id end end end end # def restore_imports(*args) # default_restore_table('Import', *args) do |attr| # attr.reject { |k| k == 'replace' } # end # end #TODO - restore_data_logs (needs a model to write to) #TODO - restore_access_restrictions (Projects only) #TODO - restore_data_attachments #TODO - restore_version_stamps end Loader.new(:path => ARGV[2]).restore_all
module SmartAnswer::Calculators class RatesQuery def self.from_file(rates_filename, load_path: nil) new(rates_filename, load_path: load_path) end attr_reader :load_path def initialize(rates_filename, load_path: nil) @load_path = load_path || File.join("lib", "data", "rates") @rates_filename = rates_filename end def rates(relevant_date = Date.today) relevant_rates = data.find do |rates_hash| rates_hash[:start_date] <= relevant_date && rates_hash[:end_date] >= relevant_date end relevant_rates ||= data.last OpenStruct.new(relevant_rates) end private def data @data ||= YAML.load_file(Rails.root.join(load_path, "#{@rates_filename}.yml")).map(&:with_indifferent_access) end end end Update RatesQuery#initialize So that it accepts an array of rates hashes, instead of a filename. This should make it easier to test some changes I want to make to this class. module SmartAnswer::Calculators class RatesQuery def self.from_file(rates_filename, load_path: nil) load_path ||= File.join("lib", "data", "rates") rates_data_path = Rails.root.join(load_path, "#{rates_filename}.yml") rates_data = YAML.load_file(rates_data_path).map(&:with_indifferent_access) new(rates_data) end attr_reader :data def initialize(rates_data) @data = rates_data end def rates(relevant_date = Date.today) relevant_rates = data.find do |rates_hash| rates_hash[:start_date] <= relevant_date && rates_hash[:end_date] >= relevant_date end relevant_rates ||= data.last OpenStruct.new(relevant_rates) end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "inbox" s.version = "2.0.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Ben Gotow", "Karim Hamidou", "Jennie Lees"] s.date = "2016-02-06" s.description = "Gem for interacting with the Nylas API." s.email = "ben@nylas.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "lib/account.rb", "lib/api_account.rb", "lib/api_thread.rb", "lib/calendar.rb", "lib/contact.rb", "lib/draft.rb", "lib/event.rb", "lib/file.rb", "lib/folder.rb", "lib/inbox.rb", "lib/label.rb", "lib/message.rb", "lib/mixins.rb", "lib/nylas.rb", "lib/parameters.rb", "lib/restful_model.rb", "lib/restful_model_collection.rb", "lib/time_attr_accessor.rb", "lib/version.rb" ] s.homepage = "http://github.com/nylas/nylas-ruby" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "2.0.14" s.summary = "Gem for interacting with the Nylas API" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rest-client>, ["~> 1.6"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_runtime_dependency(%q<em-http-request>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, [">= 1.3.5"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_development_dependency(%q<pry>, [">= 0"]) s.add_development_dependency(%q<pry-nav>, [">= 0"]) s.add_development_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_development_dependency(%q<webmock>, [">= 0"]) s.add_development_dependency(%q<sinatra>, [">= 0"]) else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end end Regenerate gemspec for version 2.0.1 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "inbox" s.version = "2.0.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Ben Gotow", "Karim Hamidou", "Jennie Lees"] s.date = "2016-02-12" s.description = "Gem for interacting with the Nylas API." s.email = "ben@nylas.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "lib/account.rb", "lib/api_account.rb", "lib/api_thread.rb", "lib/calendar.rb", "lib/contact.rb", "lib/draft.rb", "lib/event.rb", "lib/file.rb", "lib/folder.rb", "lib/inbox.rb", "lib/label.rb", "lib/message.rb", "lib/mixins.rb", "lib/nylas.rb", "lib/parameters.rb", "lib/restful_model.rb", "lib/restful_model_collection.rb", "lib/time_attr_accessor.rb", "lib/version.rb" ] s.homepage = "http://github.com/nylas/nylas-ruby" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "2.0.14" s.summary = "Gem for interacting with the Nylas API" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rest-client>, ["~> 1.6"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_runtime_dependency(%q<em-http-request>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, [">= 1.3.5"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_development_dependency(%q<pry>, [">= 0"]) s.add_development_dependency(%q<pry-nav>, [">= 0"]) s.add_development_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_development_dependency(%q<webmock>, [">= 0"]) s.add_development_dependency(%q<sinatra>, [">= 0"]) else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "inbox" s.version = "1.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Ben Gotow", "Karim Hamidou", "Jennie Lees"] s.date = "2015-11-20" s.description = "Gem for interacting with the Nylas API." s.email = "ben@nylas.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "lib/account.rb", "lib/api_account.rb", "lib/api_thread.rb", "lib/calendar.rb", "lib/contact.rb", "lib/draft.rb", "lib/event.rb", "lib/file.rb", "lib/folder.rb", "lib/inbox.rb", "lib/label.rb", "lib/message.rb", "lib/nylas.rb", "lib/parameters.rb", "lib/restful_model.rb", "lib/restful_model_collection.rb", "lib/tag.rb", "lib/time_attr_accessor.rb", "lib/version.rb" ] s.homepage = "http://github.com/nylas/nylas-ruby" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "2.0.14" s.summary = "Gem for interacting with the Nylas API" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rest-client>, ["~> 1.6"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_runtime_dependency(%q<em-http-request>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, [">= 1.3.5"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_development_dependency(%q<pry>, [">= 0"]) s.add_development_dependency(%q<pry-nav>, [">= 0"]) s.add_development_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_development_dependency(%q<webmock>, [">= 0"]) s.add_development_dependency(%q<sinatra>, [">= 0"]) else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end end Regenerate gemspec for version 1.3.0 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "inbox" s.version = "1.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Ben Gotow", "Karim Hamidou", "Jennie Lees"] s.date = "2015-12-07" s.description = "Gem for interacting with the Nylas API." s.email = "ben@nylas.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "lib/account.rb", "lib/api_account.rb", "lib/api_thread.rb", "lib/calendar.rb", "lib/contact.rb", "lib/draft.rb", "lib/event.rb", "lib/file.rb", "lib/folder.rb", "lib/inbox.rb", "lib/label.rb", "lib/message.rb", "lib/mixins.rb", "lib/nylas.rb", "lib/parameters.rb", "lib/restful_model.rb", "lib/restful_model_collection.rb", "lib/time_attr_accessor.rb", "lib/version.rb" ] s.homepage = "http://github.com/nylas/nylas-ruby" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "2.0.14" s.summary = "Gem for interacting with the Nylas API" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rest-client>, ["~> 1.6"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_runtime_dependency(%q<em-http-request>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, [">= 1.3.5"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_development_dependency(%q<pry>, [">= 0"]) s.add_development_dependency(%q<pry-nav>, [">= 0"]) s.add_development_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_development_dependency(%q<webmock>, [">= 0"]) s.add_development_dependency(%q<sinatra>, [">= 0"]) else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end else s.add_dependency(%q<rest-client>, ["~> 1.6"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<em-http-request>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<pry>, [">= 0"]) s.add_dependency(%q<pry-nav>, [">= 0"]) s.add_dependency(%q<pry-stack_explorer>, [">= 0"]) s.add_dependency(%q<webmock>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) end end
require "test/unit" require "atom/feed" class TestXMLNamespaceConformance < Test::Unit::TestCase def test_baseline feed = Atom::Feed.new "http://plasmasturm.org/attic/atom-tests/nondefaultnamespace-baseline.atom" feed.update! assert_baseline feed end def assert_baseline feed assert_equal Time.parse("2006-01-18T12:26:54+01:00"), feed.updated assert_equal "http://example.org/tests/namespace/result.html", feed.links.first["href"] assert_equal "urn:uuid:f8195e66-863f-11da-9fcb-dd680b0526e0", feed.id assert_equal "Aristotle Pagaltzis", feed.authors.first.name assert_equal "pagaltzis@gmx.de", feed.authors.first.email entry = feed.entries.first assert_equal "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", entry.id assert_equal Time.parse("2006-01-18T12:26:54+01:00"), entry.updated assert_equal "http://example.org/tests/namespace/result.html", entry.links.first["href"] # XXX content.html should strip namespace prefixes e = entry.content.xml assert_equal "http://www.w3.org/1999/xhtml", e[1].namespace assert_equal "p", e[1].name assert_equal "For information, see:", e[1].text end def test_1 feed = Atom::Feed.new "http://plasmasturm.org/attic/atom-tests/nondefaultnamespace.atom" feed.update! assert_baseline feed end def test_2 feed = Atom::Feed.new "http://plasmasturm.org/attic/atom-tests/nondefaultnamespace-xhtml.atom" feed.update! assert_baseline feed end def test_3 # XXX FINISHME end end [project @ whateley@gmail.com-20061109222144-80ce85c096c07f86] assert a failure to remind me to finish that test darcs-hash:20061109222144-ce558-5375107fcb5b359ff0b8021b4cd42692c6596b41.gz require "test/unit" require "atom/feed" class TestXMLNamespaceConformance < Test::Unit::TestCase def test_baseline feed = Atom::Feed.new "http://plasmasturm.org/attic/atom-tests/nondefaultnamespace-baseline.atom" feed.update! assert_baseline feed end def assert_baseline feed assert_equal Time.parse("2006-01-18T12:26:54+01:00"), feed.updated assert_equal "http://example.org/tests/namespace/result.html", feed.links.first["href"] assert_equal "urn:uuid:f8195e66-863f-11da-9fcb-dd680b0526e0", feed.id assert_equal "Aristotle Pagaltzis", feed.authors.first.name assert_equal "pagaltzis@gmx.de", feed.authors.first.email entry = feed.entries.first assert_equal "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", entry.id assert_equal Time.parse("2006-01-18T12:26:54+01:00"), entry.updated assert_equal "http://example.org/tests/namespace/result.html", entry.links.first["href"] # XXX content.html should strip namespace prefixes e = entry.content.xml assert_equal "http://www.w3.org/1999/xhtml", e[1].namespace assert_equal "p", e[1].name assert_equal "For information, see:", e[1].text end def test_1 feed = Atom::Feed.new "http://plasmasturm.org/attic/atom-tests/nondefaultnamespace.atom" feed.update! assert_baseline feed end def test_2 feed = Atom::Feed.new "http://plasmasturm.org/attic/atom-tests/nondefaultnamespace-xhtml.atom" feed.update! assert_baseline feed end def test_3 assert(false, "I haven't written the last test") # XXX FINISHME end end
require 'test_helper' class KnockTest < ActiveSupport::TestCase end add missing test for Knock.setup method require 'test_helper' class KnockTest < ActiveSupport::TestCase test 'setup block yields self' do Knock.setup do |config| assert_equal Knock, config end end end
class Project class << self def base_class self end end include ActiveModel::Model include ElasticRecord::Model attr_accessor :id, :name alias_method :as_json, :as_search_document elastic_index.type = 'project' elastic_index.load_from_source = true def as_search_document { name: name } end end Unnecessary type specification class Project class << self def base_class self end end include ActiveModel::Model include ElasticRecord::Model attr_accessor :id, :name alias_method :as_json, :as_search_document elastic_index.load_from_source = true def as_search_document { name: name } end end
require_relative 'boot' require 'rails/all' Bundler.require(*Rails.groups) require "minimalist_authentication" module Dummy class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end load defaults for rails 5.2 require_relative 'boot' require 'rails/all' Bundler.require(*Rails.groups) require "minimalist_authentication" module Dummy class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require "gintonic-rails" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end Avoid active record erros require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require "gintonic-rails" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. # config.active_record.raise_in_transactional_callbacks = true end end
class ModelStub < ActiveRecord::Base validates :b, :presence => true has_one :other_model, :class_name => 'ModelStub' has_many :other_models, :class_name => 'ModelStub' cattr_accessor :stubbed_columns self.stubbed_columns = [:a, :b, :c, :d, :id, :created_at] attr_accessor *stubbed_columns self.primary_key = :id @@nested_scope_calls = [] cattr_accessor :nested_scope_calls scope :a_is_defined, -> { where.not(:a => nil) } scope :b_like, ->(pattern) { where('b like ?', pattern) } def self.a_is_defined @@nested_scope_calls << :a_is_defined self end def self.b_like(pattern) @@nested_scope_calls << :b_like self end attr_writer :other_model def other_model @other_model || nil end attr_writer :other_models def other_models @other_models || [] end def self.columns @columns ||= stubbed_columns.map do |c| column = ColumnMock.new(c.to_s, '', 'varchar(255)') column.primary = true if c.to_s == self.primary_key.to_s column end end def self.columns_hash @columns_hash ||= columns.each_with_object({}) { |column, hash| hash[column.name.to_s] = column } end # column-level security methods, used for testing def self.a_authorized_for_bar? true end def self.b_authorized? false end def self.c_authorized_for_create? false end end fix test for rails 4.2 class ModelStub < ActiveRecord::Base validates :b, :presence => true has_one :other_model, :class_name => 'ModelStub' has_many :other_models, :class_name => 'ModelStub' cattr_accessor :stubbed_columns self.stubbed_columns = [:a, :b, :c, :d, :id, :created_at] attr_accessor *stubbed_columns self.primary_key = :id @@nested_scope_calls = [] cattr_accessor :nested_scope_calls scope :a_is_defined, -> { where.not(:a => nil) } scope :b_like, ->(pattern) { where('b like ?', pattern) } def self.a_is_defined @@nested_scope_calls << :a_is_defined self end def self.b_like(pattern) @@nested_scope_calls << :b_like self end attr_writer :other_model def other_model @other_model || nil end attr_writer :other_models def other_models @other_models || [] end def self.columns @columns ||= stubbed_columns.map do |c| column = ColumnMock.new(c.to_s, '', 'varchar(255)') column.primary = true if c.to_s == self.primary_key.to_s && column.respond_to?(:primary=) column end end def self.columns_hash @columns_hash ||= columns.each_with_object({}) { |column, hash| hash[column.name.to_s] = column } end # column-level security methods, used for testing def self.a_authorized_for_bar? true end def self.b_authorized? false end def self.c_authorized_for_create? false end end
require_relative 'test_helper' module MyGem describe MyGem do it "says 'Hello, MyGem'" do proc do @argv = [] MyGem.run(@argv) end.must_output "Hello, MyGem" end end end Forget that puts adds a newline require_relative 'test_helper' module MyGem describe MyGem do it "says 'Hello, MyGem'" do proc do @argv = [] MyGem.run(@argv) end.must_output "Hello, MyGem\n" end end end
#-*- coding:utf-8 require File.join(File.dirname(__FILE__),'..','lib','okura') require File.join(File.dirname(__FILE__),'..','lib','okura','loader') def as_io str StringIO.new str end def w surface,l,r,cost l=f(l) unless l.respond_to? :id r=f(r) unless r.respond_to? :id Okura::Word.new surface,l,r,cost end def f id,name="F#{id}" Okura::Feature.new id,name end def n *args Okura::Node.new *args end describe Okura::Loader::MeCab do subject { Okura::Loader::MeCab.new } describe '#load_matrix' do describe 'left=right,マトリクスの全データがあるとき' do it 'インスタンスを構築できる' do m=subject.load_matrix as_io(<<-EOS) 2 2 0 0 0 0 1 1 1 0 2 1 1 3 EOS m.rsize.should == 2 m.lsize.should == 2 end # TODO: エラー処理とかその他のパターン end end describe '#load_words' do it 'インスタンスを構築できる' do fs=Okura::Features.new fs.add 854,'F1' fs.add 645,'F2' wd=subject.load_words(<<-EOS,fs,fs) あがなう,854,854,6636,動詞,自立,*,*,五段・ワ行促音便,基本形,あがなう,アガナウ,アガナウ,あがなう/購う/贖う, あがめる,645,645,6636,動詞,自立,*,*,一段,基本形,あがめる,アガメル,アガメル,あがめる/崇める, EOS wd.size.should == 2 end end describe '#load_features' do it 'インスタンスを構築できる' do fs=subject.load_features(<<-EOS) 0 BOS/EOS,*,*,*,*,*,BOS/EOS 1 その他,間投,*,*,*,*,* 2 フィラー,*,*,*,*,*,* 3 感動詞,*,*,*,*,*,* 4 記号,アルファベット,*,*,*,*,* EOS fs.size.should == 5 fs.from_id(0).id.should == 0 fs.from_id(0).text.should == 'BOS/EOS,*,*,*,*,*,BOS/EOS' end end describe '#load_char_types' do it 'インスタンスを構築できる' do cts=subject.load_char_types(<<-EOS) DEFAULT 0 1 0 TYPE1 1 0 0 TYPE2 0 1 0 TYPE3 0 1 3 # comment 0x0021 TYPE1 0x0022 TYPE2 # comment 0x0023..0x0040 TYPE3 0x0099 TYPE1 TYPE2 # 互換カテゴリ 0xABCd TYPE1 DEFAULT EOS cts.type_for(0x21).name.should == 'TYPE1' cts.type_for(0x22).name.should == 'TYPE2' cts.type_for(0x23).name.should == 'TYPE3' cts.type_for(0x40).name.should == 'TYPE3' cts.type_for(0x41).name.should == 'DEFAULT' cts.type_for(0x99).name.should == 'TYPE1' t1,t2,t3=cts.named('TYPE1'), cts.named('TYPE2'), cts.named('TYPE3') t1.name.should == 'TYPE1' t1.invoke?.should be_true t2.invoke?.should be_false t1.group?.should be_false t2.group?.should be_true t2.length.should == 0 t3.length.should == 3 t1.should be_accept(0x21) t1.should_not be_accept(0x22) t2.should be_accept(0x22) t1.should be_accept(0x99) end end describe '#load_from_io' do it 'インスタンスを構築できる' do cts=Okura::CharTypes.new cts.define_type 'A',true,true,10 cts.define_type 'Z',true,true,10 cts.define_map 'A'.ord, cts.named('A'), [] cts.define_map 'Z'.ord, cts.named('Z'), [] fs=Okura::Features.new fs.add 5,'hoge' fs.add 9,'fuga' unk=subject.load_unk_dic(<<-EOS,cts,fs,fs) A,5,5,3274,記号,一般,*,*,*,*,* Z,9,9,5244,記号,空白,*,*,*,*,* EOS unk.possible_words('AZ',0,false).should == [w('A',f(5),f(5),3274)] end end end describe Okura::Matrix do describe '#cost' do it '渡された二つのFeature idを元にコストを返せる' do m=Okura::Loader::MeCab.new.load_matrix as_io(<<-EOS) 2 2 0 0 0 0 1 1 1 0 2 1 1 3 EOS m.cost(1,1).should == 3 end end end shared_examples_for 'WordDic' do # subject = dict builder def w surface Okura::Word.new surface,f(1),f(1),1 end describe '#possible_words' do it '文字列と位置から、辞書に登録された単語を返せる' do subject.define w('aaa') subject.define w('bbb') subject.define w('aa') subject.define w('aaaa') subject.define w('aaaaa') wd=subject.build wd.possible_words('bbbaaa',0).should == [w('bbb')] wd.possible_words('bbbaaa',1).should == [] wd.possible_words('bbbaaa',3).should == [w('aa'),w('aaa')] end it 'マルチバイト文字にも対応している' do subject.define w('ニワトリ') wd=subject.build wd.possible_words('ニワトリ',0).should == [w('ニワトリ')] wd.possible_words('ニワトリ',1).should == [] end def matches words,str,dest words.each{|word| subject.define w(word) } dic=subject.build dic.possible_words(str,0).should == dest.map{|d|w(d)} end it { matches %w() , '' , %w() } it { matches %w() , 'aaa' , %w() } it { matches %w(a) , '' , %w() } it { matches %w(a) , 'a' , %w(a) } it { matches %w(a) , 'aa' , %w(a) } it { matches %w(a) , 'b' , %w() } it { matches %w(aa) , 'a' , %w() } it { matches %w(aa) , 'aa' , %w(aa) } it { matches %w(aa) , 'aaa' , %w(aa) } it { matches %w(aa) , 'ab' , %w() } it { matches %w(a aa) , 'a' , %w(a) } it { matches %w(a aa) , 'aa' , %w(a aa) } it { matches %w(a aa) , 'aaa' , %w(a aa) } it { matches %w(a aa) , 'aab' , %w(a aa) } it { matches %w(a aa ab) , 'aab' , %w(a aa) } it { matches %w(a aa ab) , 'ab' , %w(a ab) } it { matches %w(a aa ab) , 'aa' , %w(a aa) } it { matches %w(a b) , 'ba' , %w(b) } it { matches %w(アイウ) , 'アイウ' , %w(アイウ) } it { matches %w(ア アイ) , 'アイウ' , %w(ア アイ) } it { matches %w(ア アイ) , 'aアイウ' , %w() } end end describe Okura::WordDic::Naive do class NaiveBuilder def initialize @wd=Okura::WordDic::Naive.new end def define *args @wd.define *args end def build @wd end end subject { NaiveBuilder.new } it_should_behave_like 'WordDic' end describe Okura::WordDic::DoubleArray do subject { Okura::WordDic::DoubleArray::Builder.new } def base(dic) dic.instance_eval{@base} end def check(dic) dic.instance_eval{@check} end def words(dic) dic.instance_eval{@words} end it_should_behave_like 'WordDic' describe 'when empty' do it 'should one-element arrays' do dic=subject.build base(dic).should == [0] check(dic).should == [nil] end end describe 'when a single-char word defined' do it 'should 4-elements arrays' do subject.define w("\u0001",1,2,3) dic=subject.build words(dic).should == [w("\u0001",1,2,3)] base(dic).should == [0,-1,1] check(dic).should == [nil,2,0] end end end describe Okura::Features do end describe Okura::CharTypes do describe '#type_for' do describe '文字に対するCharTypeが定義されていない場合' do describe '文字種DEFAULTが定義されている場合' do subject { cts=Okura::CharTypes.new cts.define_type 'DEFAULT',false,false,0 cts } it 'CharType#default_typeが返る' do subject.type_for('a'.ord).name.should == subject.default_type.name end end describe '文字種DEFAULTが定義されてない場合' do subject { cts=Okura::CharTypes.new } it 'エラーになる' do expect { subject.type_for('a'.ord) }.to raise_error end end end end describe '#define_map' do describe '互換カテゴリが指定された場合' do subject { cts=Okura::CharTypes.new cts.define_type 'A',true,true,10 cts.define_type 'B',true,true,10 cts.define_map 1,cts.named('A'),[cts.named('B')] cts } it '互換カテゴリが正しく認識される' do subject.named('A').accept?(1).should be_true subject.named('B').accept?(1).should be_true end end end end describe Okura::UnkDic do describe '#possible_words' do describe '互換カテゴリ' do subject { cts=Okura::CharTypes.new cts.define_type 'KATAKANA',false,true,0 cts.define_type 'HIRAGANA',false,true,0 cts.define_map 'ア'.ord,cts.named('KATAKANA'),[] cts.define_map 'ー'.ord,cts.named('HIRAGANA'),[cts.named('KATAKANA')] ud=Okura::UnkDic.new cts ud.define 'KATAKANA',f(10),f(20),1000 ud.define 'HIRAGANA',f(1),f(2),1000 ud } it '互換カテゴリを正しく解釈する' do subject.possible_words('アーー',0,false).should == [w('アーー',10,20,1000)] end end describe '未知語定義' do describe '同一文字種に複数の未知語定義があった場合' do subject do cts=Okura::CharTypes.new cts.define_type 'A',true,true,0 cts.define_map 'A'.ord,cts.named('A'),[] ud=Okura::UnkDic.new cts ud.define 'A',f(10),f(20),1000 ud.define 'A',f(11),f(21),1111 ud end it 'すべての定義から未知語を抽出する' do subject.possible_words('A',0,false).should == [ w('A',10,20,1000), w('A',11,21,1111) ] end end end end describe '#possible_words: 文字コードによる挙動:' do subject do cts=Okura::CharTypes.new cts.define_type 'A',true,true,0 cts.define_map 'あ'.ord,cts.named('A'),[] ud=Okura::UnkDic.new cts ud.define 'A',f(10),f(20),1000 ud end describe 'UTF8文字列が来たとき' do it '正しく解析できる' do subject.possible_words('あいう'.encode('UTF-8'),0,false).map(&:surface).should == %w(あ) end end describe 'UTF8じゃない文字列が来たとき' do it 'エラーになる' do expect { subject.possible_words('あいう'.encode('SHIFT_JIS'),0,false) }.to raise_error end end end describe '#possible_words: 先頭文字のカテゴリによる挙動:' do def create_chartypes typename_under_test cts=Okura::CharTypes.new cts.define_type 'T000',false,false,0 cts.define_type 'T012',false,true,2 cts.define_type 'T100',true,false,0 cts.define_type 'T102',true,false,2 cts.define_type 'T110',true,true,0 cts.define_type 'T112',true,true,2 cts.define_type 'ZZZZ',true,true,2 cts.define_map 'A'.ord,cts.named(typename_under_test),[] cts.define_map 'Z'.ord,cts.named('ZZZZ'),[] cts end def create_subject typename_under_test udic=Okura::UnkDic.new create_chartypes(typename_under_test) udic.define typename_under_test,f(10),(20),1000 udic end describe 'invoke=0のとき' do subject { create_subject 'T012' } describe '辞書に単語がある場合' do it '未知語を抽出しない' do subject.possible_words('AAA',0,true).should be_empty end end end describe 'invoke=1のとき' do describe '辞書に単語がある場合' do subject { create_subject 'T102' } it 'も、未知語を抽出する' do subject.possible_words('AAAZ',0,true).should_not be_empty end end describe '先頭文字のカテゴリに対応する未知語定義がなかった場合' do subject { create_subject 'T112' } it '未知語を抽出しない' do subject.possible_words('ZZ',0,false).should be_empty end end describe '辞書に単語がない場合' do describe 'group=0のとき' do describe 'length=0のとき' do subject { create_subject 'T100' } it '未知語を抽出しない' do subject.possible_words('AAAZ',0,false).should be_empty end end describe 'length=2のとき' do subject { create_subject 'T102' } it '2文字までの同種文字列を未知語とする' do subject.possible_words('AAAZ',0,false).map(&:surface).should == %w(A AA) end end end describe 'group=1のとき' do describe 'length=0のとき' do subject { create_subject 'T110' } it '同種の文字列を長さ制限なしでまとめて未知語とする' do subject.possible_words('AAAAAZ',0,false).map(&:surface).should == %w(AAAAA) end it '連続が一文字の場合も未知語として取れる' do subject.possible_words('AZZZ',0,false).map(&:surface).should == %w(A) end it '1文字しかなくても正しく扱える' do subject.possible_words('A',0,false).map(&:surface).should == %w(A) end end describe 'length=2のとき' do subject { create_subject 'T112' } it 'length=0の結果に加え、2文字までの同種文字列を未知語とする' do subject.possible_words('AAAAAZ',0,false).map(&:surface).should == %w(A AA AAAAA) end it '1文字しかなくても正しく扱える' do subject.possible_words('A',0,false).map(&:surface).should == %w(A) end it '2文字しかなくても正しく扱える' do subject.possible_words('AA',0,false).map(&:surface).should == %w(A AA) end it '3文字しかなくても正しく扱える' do subject.possible_words('AAA',0,false).map(&:surface).should == %w(A AA AAA) end end end end end end end describe Okura::Tagger do describe '#parse' do it '文字列を解析してNodesを返せる' do dic=Okura::WordDic::Naive.new dic.define w('a',1,1,0) dic.define w('aa',1,1,10) dic.define w('b',2,2,3) tagger=Okura::Tagger.new dic,nil nodes=tagger.parse('aab') nodes[0][0].word.should == w('BOS/EOS',0,0,0) nodes[4][0].word.should == w('BOS/EOS',0,0,0) nodes[1].size.should == 2 nodes[3][0].word.should == w('b',2,2,3) end end end describe Okura::Node do describe '#make_bos_eos' do describe '#length' do it 'returns 1' do Okura::Node.mk_bos_eos.length.should == 1 end end end end describe Okura::Nodes do describe '#mincost_path' do it '最小コストのパスを返せる' do mat=Okura::Matrix.new 2,2 mat.set(0,1,10) mat.set(1,0,10) nodes=Okura::Nodes.new 3,mat nodes.add(0,Okura::Node.mk_bos_eos) nodes.add(1,n(w('a',1,1,10))) nodes.add(1,n(w('b',1,1,0))) nodes.add(2,Okura::Node.mk_bos_eos) mcp=nodes.mincost_path mcp.length.should == 3 mcp[0].word.surface.should == 'BOS/EOS' mcp[1].word.surface.should == 'b' mcp[2].word.surface.should == 'BOS/EOS' end it '単語長が1を超えても動く' do mat=Okura::Matrix.new 2,2 mat.set(0,1,10) mat.set(1,0,10) mat.set(1,1,10) nodes=Okura::Nodes.new 4,mat nodes.add(0,Okura::Node.mk_bos_eos) nodes.add(1,n(w('a',1,1,10))) nodes.add(1,n(w('bb',1,1,0))) nodes.add(2,n(w('a',1,1,10))) nodes.add(3,Okura::Node.mk_bos_eos) mcp=nodes.mincost_path mcp.length.should == 3 mcp[0].word.surface.should == 'BOS/EOS' mcp[1].word.surface.should == 'bb' mcp[2].word.surface.should == 'BOS/EOS' end end end trivial change(format source) #-*- coding:utf-8 require File.join(File.dirname(__FILE__),'..','lib','okura') require File.join(File.dirname(__FILE__),'..','lib','okura','loader') def as_io str StringIO.new str end def w surface,l,r,cost l=f(l) unless l.respond_to? :id r=f(r) unless r.respond_to? :id Okura::Word.new surface,l,r,cost end def f id,name="F#{id}" Okura::Feature.new id,name end def n *args Okura::Node.new *args end describe Okura::Loader::MeCab do subject { Okura::Loader::MeCab.new } describe '#load_matrix' do describe 'left=right,マトリクスの全データがあるとき' do it 'インスタンスを構築できる' do m=subject.load_matrix as_io(<<-EOS) 2 2 0 0 0 0 1 1 1 0 2 1 1 3 EOS m.rsize.should == 2 m.lsize.should == 2 end # TODO: エラー処理とかその他のパターン end end describe '#load_words' do it 'インスタンスを構築できる' do fs=Okura::Features.new fs.add 854,'F1' fs.add 645,'F2' wd=subject.load_words(<<-EOS,fs,fs) あがなう,854,854,6636,動詞,自立,*,*,五段・ワ行促音便,基本形,あがなう,アガナウ,アガナウ,あがなう/購う/贖う, あがめる,645,645,6636,動詞,自立,*,*,一段,基本形,あがめる,アガメル,アガメル,あがめる/崇める, EOS wd.size.should == 2 end end describe '#load_features' do it 'インスタンスを構築できる' do fs=subject.load_features(<<-EOS) 0 BOS/EOS,*,*,*,*,*,BOS/EOS 1 その他,間投,*,*,*,*,* 2 フィラー,*,*,*,*,*,* 3 感動詞,*,*,*,*,*,* 4 記号,アルファベット,*,*,*,*,* EOS fs.size.should == 5 fs.from_id(0).id.should == 0 fs.from_id(0).text.should == 'BOS/EOS,*,*,*,*,*,BOS/EOS' end end describe '#load_char_types' do it 'インスタンスを構築できる' do cts=subject.load_char_types(<<-EOS) DEFAULT 0 1 0 TYPE1 1 0 0 TYPE2 0 1 0 TYPE3 0 1 3 # comment 0x0021 TYPE1 0x0022 TYPE2 # comment 0x0023..0x0040 TYPE3 0x0099 TYPE1 TYPE2 # 互換カテゴリ 0xABCd TYPE1 DEFAULT EOS cts.type_for(0x21).name.should == 'TYPE1' cts.type_for(0x22).name.should == 'TYPE2' cts.type_for(0x23).name.should == 'TYPE3' cts.type_for(0x40).name.should == 'TYPE3' cts.type_for(0x41).name.should == 'DEFAULT' cts.type_for(0x99).name.should == 'TYPE1' t1,t2,t3=cts.named('TYPE1'), cts.named('TYPE2'), cts.named('TYPE3') t1.name.should == 'TYPE1' t1.invoke?.should be_true t2.invoke?.should be_false t1.group?.should be_false t2.group?.should be_true t2.length.should == 0 t3.length.should == 3 t1.should be_accept(0x21) t1.should_not be_accept(0x22) t2.should be_accept(0x22) t1.should be_accept(0x99) end end describe '#load_from_io' do it 'インスタンスを構築できる' do cts=Okura::CharTypes.new cts.define_type 'A',true,true,10 cts.define_type 'Z',true,true,10 cts.define_map 'A'.ord, cts.named('A'), [] cts.define_map 'Z'.ord, cts.named('Z'), [] fs=Okura::Features.new fs.add 5,'hoge' fs.add 9,'fuga' unk=subject.load_unk_dic(<<-EOS,cts,fs,fs) A,5,5,3274,記号,一般,*,*,*,*,* Z,9,9,5244,記号,空白,*,*,*,*,* EOS unk.possible_words('AZ',0,false).should == [w('A',f(5),f(5),3274)] end end end describe Okura::Matrix do describe '#cost' do it '渡された二つのFeature idを元にコストを返せる' do m=Okura::Loader::MeCab.new.load_matrix as_io(<<-EOS) 2 2 0 0 0 0 1 1 1 0 2 1 1 3 EOS m.cost(1,1).should == 3 end end end shared_examples_for 'WordDic' do # subject = dict builder def w surface Okura::Word.new surface,f(1),f(1),1 end describe '#possible_words' do it '文字列と位置から、辞書に登録された単語を返せる' do subject.define w('aaa') subject.define w('bbb') subject.define w('aa') subject.define w('aaaa') subject.define w('aaaaa') wd=subject.build wd.possible_words('bbbaaa',0).should == [w('bbb')] wd.possible_words('bbbaaa',1).should == [] wd.possible_words('bbbaaa',3).should == [w('aa'),w('aaa')] end it 'マルチバイト文字にも対応している' do subject.define w('ニワトリ') wd=subject.build wd.possible_words('ニワトリ',0).should == [w('ニワトリ')] wd.possible_words('ニワトリ',1).should == [] end def matches words,str,dest words.each{|word| subject.define w(word) } dic=subject.build dic.possible_words(str,0).should == dest.map{|d|w(d)} end it { matches %w() , '' , %w() } it { matches %w() , 'aaa' , %w() } it { matches %w(a) , '' , %w() } it { matches %w(a) , 'a' , %w(a) } it { matches %w(a) , 'aa' , %w(a) } it { matches %w(a) , 'b' , %w() } it { matches %w(aa) , 'a' , %w() } it { matches %w(aa) , 'aa' , %w(aa) } it { matches %w(aa) , 'aaa' , %w(aa) } it { matches %w(aa) , 'ab' , %w() } it { matches %w(a aa) , 'a' , %w(a) } it { matches %w(a aa) , 'aa' , %w(a aa) } it { matches %w(a aa) , 'aaa' , %w(a aa) } it { matches %w(a aa) , 'aab' , %w(a aa) } it { matches %w(a aa ab) , 'aab' , %w(a aa) } it { matches %w(a aa ab) , 'ab' , %w(a ab) } it { matches %w(a aa ab) , 'aa' , %w(a aa) } it { matches %w(a b) , 'ba' , %w(b) } it { matches %w(アイウ) , 'アイウ' , %w(アイウ) } it { matches %w(ア アイ) , 'アイウ' , %w(ア アイ) } it { matches %w(ア アイ) , 'aアイウ' , %w() } end end describe Okura::WordDic::Naive do class NaiveBuilder def initialize @wd=Okura::WordDic::Naive.new end def define *args @wd.define *args end def build @wd end end subject { NaiveBuilder.new } it_should_behave_like 'WordDic' end describe Okura::WordDic::DoubleArray do subject { Okura::WordDic::DoubleArray::Builder.new } def base(dic) dic.instance_eval{@base} end def check(dic) dic.instance_eval{@check} end def words(dic) dic.instance_eval{@words} end it_should_behave_like 'WordDic' describe 'when empty' do it 'should one-element arrays' do dic=subject.build base(dic).should == [0] check(dic).should == [nil] end end describe 'when a single-char word defined' do it 'should 4-elements arrays' do subject.define w("\u0001",1,2,3) dic=subject.build words(dic).should == [w("\u0001",1,2,3)] base(dic).should == [0,-1,1] check(dic).should == [nil,2,0] end end end describe Okura::Features do end describe Okura::CharTypes do describe '#type_for' do describe '文字に対するCharTypeが定義されていない場合' do describe '文字種DEFAULTが定義されている場合' do subject { cts=Okura::CharTypes.new cts.define_type 'DEFAULT',false,false,0 cts } it 'CharType#default_typeが返る' do subject.type_for('a'.ord).name.should == subject.default_type.name end end describe '文字種DEFAULTが定義されてない場合' do subject { cts=Okura::CharTypes.new } it 'エラーになる' do expect { subject.type_for('a'.ord) }.to raise_error end end end end describe '#define_map' do describe '互換カテゴリが指定された場合' do subject { cts=Okura::CharTypes.new cts.define_type 'A',true,true,10 cts.define_type 'B',true,true,10 cts.define_map 1,cts.named('A'),[cts.named('B')] cts } it '互換カテゴリが正しく認識される' do subject.named('A').accept?(1).should be_true subject.named('B').accept?(1).should be_true end end end end describe Okura::UnkDic do describe '#possible_words' do describe '互換カテゴリ' do subject { cts=Okura::CharTypes.new cts.define_type 'KATAKANA',false,true,0 cts.define_type 'HIRAGANA',false,true,0 cts.define_map 'ア'.ord,cts.named('KATAKANA'),[] cts.define_map 'ー'.ord,cts.named('HIRAGANA'),[cts.named('KATAKANA')] ud=Okura::UnkDic.new cts ud.define 'KATAKANA',f(10),f(20),1000 ud.define 'HIRAGANA',f(1),f(2),1000 ud } it '互換カテゴリを正しく解釈する' do subject.possible_words('アーー',0,false).should == [w('アーー',10,20,1000)] end end describe '未知語定義' do describe '同一文字種に複数の未知語定義があった場合' do subject do cts=Okura::CharTypes.new cts.define_type 'A',true,true,0 cts.define_map 'A'.ord,cts.named('A'),[] ud=Okura::UnkDic.new cts ud.define 'A',f(10),f(20),1000 ud.define 'A',f(11),f(21),1111 ud end it 'すべての定義から未知語を抽出する' do subject.possible_words('A',0,false).should == [ w('A',10,20,1000), w('A',11,21,1111) ] end end end end describe '#possible_words: 文字コードによる挙動:' do subject do cts=Okura::CharTypes.new cts.define_type 'A',true,true,0 cts.define_map 'あ'.ord,cts.named('A'),[] ud=Okura::UnkDic.new cts ud.define 'A',f(10),f(20),1000 ud end describe 'UTF8文字列が来たとき' do it '正しく解析できる' do subject.possible_words('あいう'.encode('UTF-8'),0,false).map(&:surface).should == %w(あ) end end describe 'UTF8じゃない文字列が来たとき' do it 'エラーになる' do expect { subject.possible_words('あいう'.encode('SHIFT_JIS'),0,false) }.to raise_error end end end describe '#possible_words: 先頭文字のカテゴリによる挙動:' do def create_chartypes typename_under_test cts=Okura::CharTypes.new cts.define_type 'T000',false,false,0 cts.define_type 'T012',false,true,2 cts.define_type 'T100',true,false,0 cts.define_type 'T102',true,false,2 cts.define_type 'T110',true,true,0 cts.define_type 'T112',true,true,2 cts.define_type 'ZZZZ',true,true,2 cts.define_map 'A'.ord,cts.named(typename_under_test),[] cts.define_map 'Z'.ord,cts.named('ZZZZ'),[] cts end def create_subject typename_under_test udic=Okura::UnkDic.new create_chartypes(typename_under_test) udic.define typename_under_test,f(10),(20),1000 udic end describe 'invoke=0のとき' do subject { create_subject 'T012' } describe '辞書に単語がある場合' do it '未知語を抽出しない' do subject.possible_words('AAA',0,true).should be_empty end end end describe 'invoke=1のとき' do describe '辞書に単語がある場合' do subject { create_subject 'T102' } it 'も、未知語を抽出する' do subject.possible_words('AAAZ',0,true).should_not be_empty end end describe '先頭文字のカテゴリに対応する未知語定義がなかった場合' do subject { create_subject 'T112' } it '未知語を抽出しない' do subject.possible_words('ZZ',0,false).should be_empty end end describe '辞書に単語がない場合' do describe 'group=0のとき' do describe 'length=0のとき' do subject { create_subject 'T100' } it '未知語を抽出しない' do subject.possible_words('AAAZ',0,false).should be_empty end end describe 'length=2のとき' do subject { create_subject 'T102' } it '2文字までの同種文字列を未知語とする' do subject.possible_words('AAAZ',0,false).map(&:surface).should == %w(A AA) end end end describe 'group=1のとき' do describe 'length=0のとき' do subject { create_subject 'T110' } it '同種の文字列を長さ制限なしでまとめて未知語とする' do subject.possible_words('AAAAAZ',0,false).map(&:surface).should == %w(AAAAA) end it '連続が一文字の場合も未知語として取れる' do subject.possible_words('AZZZ',0,false).map(&:surface).should == %w(A) end it '1文字しかなくても正しく扱える' do subject.possible_words('A',0,false).map(&:surface).should == %w(A) end end describe 'length=2のとき' do subject { create_subject 'T112' } it 'length=0の結果に加え、2文字までの同種文字列を未知語とする' do subject.possible_words('AAAAAZ',0,false).map(&:surface).should == %w(A AA AAAAA) end it '1文字しかなくても正しく扱える' do subject.possible_words('A',0,false).map(&:surface).should == %w(A) end it '2文字しかなくても正しく扱える' do subject.possible_words('AA',0,false).map(&:surface).should == %w(A AA) end it '3文字しかなくても正しく扱える' do subject.possible_words('AAA',0,false).map(&:surface).should == %w(A AA AAA) end end end end end end end describe Okura::Tagger do describe '#parse' do it '文字列を解析してNodesを返せる' do dic=Okura::WordDic::Naive.new dic.define w('a',1,1,0) dic.define w('aa',1,1,10) dic.define w('b',2,2,3) tagger=Okura::Tagger.new dic,nil nodes=tagger.parse('aab') nodes[0][0].word.should == w('BOS/EOS',0,0,0) nodes[4][0].word.should == w('BOS/EOS',0,0,0) nodes[1].size.should == 2 nodes[3][0].word.should == w('b',2,2,3) end end end describe Okura::Node do describe '#make_bos_eos' do describe '#length' do it 'returns 1' do Okura::Node.mk_bos_eos.length.should == 1 end end end end describe Okura::Nodes do describe '#mincost_path' do it '最小コストのパスを返せる' do mat=Okura::Matrix.new 2,2 mat.set(0,1,10) mat.set(1,0,10) nodes=Okura::Nodes.new 3,mat nodes.add(0,Okura::Node.mk_bos_eos) nodes.add(1,n(w('a',1,1,10))) nodes.add(1,n(w('b',1,1,0))) nodes.add(2,Okura::Node.mk_bos_eos) mcp=nodes.mincost_path mcp.length.should == 3 mcp[0].word.surface.should == 'BOS/EOS' mcp[1].word.surface.should == 'b' mcp[2].word.surface.should == 'BOS/EOS' end it '単語長が1を超えても動く' do mat=Okura::Matrix.new 2,2 mat.set(0,1,10) mat.set(1,0,10) mat.set(1,1,10) nodes=Okura::Nodes.new 4,mat nodes.add(0,Okura::Node.mk_bos_eos) nodes.add(1,n(w('a',1,1,10))) nodes.add(1,n(w('bb',1,1,0))) nodes.add(2,n(w('a',1,1,10))) nodes.add(3,Okura::Node.mk_bos_eos) mcp=nodes.mincost_path mcp.length.should == 3 mcp[0].word.surface.should == 'BOS/EOS' mcp[1].word.surface.should == 'bb' mcp[2].word.surface.should == 'BOS/EOS' end end end
def main() if ARGF.argv.empty? puts "Usage: #{$PROGRAM_NAME} [list_of_msgcount_logs]" exit 1 end global_sum = 0.0 global_count = 0 empty_files = 0 total_files = ARGF.argv.length ARGF.argv.each do |path| stats = get_stats(path) if stats[:count] == 0 empty_files += 1 else puts "#{path}: #{stats[:sum] / stats[:count]}" end global_sum += stats[:sum] global_count += stats[:count] end puts "---------------" puts "Global Average: #{global_sum / global_count}. Empty files: #{empty_files} / #{total_files}" end def get_stats(path) sum = 0.0 count = 0 File.readlines(path).each do |line| l = line.split(",")[2..4].map {|x| x.strip.to_i } node_count = l[0] + l[1] if node_count > 1 empty_count = l[0] ratio = 1.0 * empty_count / node_count sum += ratio count += 1 end end return {:sum => sum, :count => count} end if __FILE__ == $0 main end Changing msgcounts permissions def main() if ARGF.argv.empty? puts "Usage: #{$PROGRAM_NAME} [list_of_msgcount_logs]" exit 1 end global_sum = 0.0 global_count = 0 empty_files = 0 total_files = ARGF.argv.length ARGF.argv.each do |path| stats = get_stats(path) if stats[:count] == 0 empty_files += 1 else puts "#{path}: #{stats[:sum] / stats[:count]}" end global_sum += stats[:sum] global_count += stats[:count] end puts "---------------" puts "Global Average: #{global_sum / global_count}. Empty files: #{empty_files} / #{total_files}" end def get_stats(path) sum = 0.0 count = 0 File.readlines(path).each do |line| l = line.split(",")[2..4].map {|x| x.strip.to_i } node_count = l[0] + l[1] if node_count > 1 empty_count = l[0] ratio = 1.0 * empty_count / node_count sum += ratio count += 1 end end return {:sum => sum, :count => count} end if __FILE__ == $0 main end
require 'test_helper' class GlobalizeAccessorsTest < ActiveSupport::TestCase class Unit < ActiveRecord::Base translates :name, :title globalize_accessors end class UnitTranslatedWithOptions < ActiveRecord::Base self.table_name = :units translates :name globalize_accessors :locales => [:pl], :attributes => [:name] end class UnitInherited < UnitTranslatedWithOptions end class UnitInheritedWithOptions < ActiveRecord::Base self.table_name = :units translates :color globalize_accessors :locales => [:de], :attributes => [:color] end class UnitWithAttrAccessible < ActiveRecord::Base self.table_name = :units translates :name, :title globalize_accessors end class UnitWithDashedLocales < ActiveRecord::Base self.table_name = :units translates :name globalize_accessors :locales => [:"pt-BR", :"en-AU"], :attributes => [:name] end class UnitWithoutAccessors < ActiveRecord::Base self.table_name = :units end setup do assert_equal :en, I18n.locale end test "return localized attribute names" do u = UnitWithDashedLocales.new assert_equal "name_en", u.localized_attr_name_for(:name, :en) assert_equal "name_pt_br", u.localized_attr_name_for(:name, :"pt-BR") assert_equal "name_zh_cn", u.class.localized_attr_name_for(:name, :"zh-CN") end test "read and write on new object" do u = Unit.new(:name_en => "Name en", :title_pl => "Title pl") assert_equal "Name en", u.name assert_equal "Name en", u.name_en assert_equal "Title pl", u.title_pl assert_nil u.name_pl assert_nil u.title_en end test "build translations for a new object" do u = Unit.new(:name_en => "Name en", :title_pl => "Title pl") assert_equal 2, u.translations.size # size of the collection assert_equal 0, u.translations.count # count from database end test "doesn't build translations without values" do u = Unit.new(:name_en => nil, :title_pl => " ") assert_equal 0, u.translations.size end test "doesn't build translations without values even after saving" do u = Unit.new(:name_en => nil, :title_pl => " ") u.save # On Rails 4, Globalize will always create an empty translation for # the default locale # On Rails 3, Globalize will never create a translation assert u.translated_locales.exclude?(:pl) end test "persisted translations can be set to empty values" do u = Unit.new(:name_en => "test") u.save u.name_en = "" assert_equal "", u.translations.first.name end test "not persisted translations can be set to empty values" do u = Unit.new(:name_en => "test") u.name_en = "" assert_equal "", u.translations.first.name end test "write on new object and read on saved" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") assert_equal "Name en", u.name assert_equal "Name en", u.name_en assert_equal "Title pl", u.title_pl assert_nil u.name_pl assert_nil u.title_en end test "updates translations for existing object" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u.name_en = "New name en" assert_equal "New name en", u.translations.find {|t| t.locale == :en }.name assert_equal "Title pl", u.translations.find {|t| t.locale == :pl }.title assert_equal 2, u.translations.count end test "read on existing object" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u = Unit.find(u.id) assert_equal "Name en", u.name assert_equal "Name en", u.name_en assert_equal "Title pl", u.title_pl assert_nil u.name_pl assert_nil u.title_en end test "read and write on existing object" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u = Unit.find(u.id) u.name_pl = "Name pl" u.name_en = "Name en2" u.save! assert_equal "Name en2", u.name assert_equal "Name en2", u.name_en assert_equal "Name pl", u.name_pl assert_equal "Title pl", u.title_pl assert_nil u.title_en end test "read and write on class with options" do u = UnitTranslatedWithOptions.new() assert u.respond_to?(:name_pl) assert u.respond_to?(:name_pl=) assert ! u.respond_to?(:name_en) assert ! u.respond_to?(:name_en=) u.name = "Name en" u.name_pl = "Name pl" assert_equal "Name en", u.name assert_equal "Name pl", u.name_pl end test "globalize locales on class without locales specified in options" do assert_equal [:en, :pl], Unit.globalize_locales end test "globalize locales on class with locales specified in options" do assert_equal [:pl], UnitTranslatedWithOptions.globalize_locales end test "read and write on class with dashed locales" do u = UnitWithDashedLocales.new() assert u.respond_to?(:name_pt_br) assert u.respond_to?(:name_pt_br=) assert u.respond_to?(:name_en_au) assert u.respond_to?(:name_en_au=) u.name = "Name en" u.name_pt_br = "Name pt-BR" u.name_en_au = "Name en-AU" assert_equal "Name en", u.name assert_equal "Name pt-BR", u.name_pt_br assert_equal "Name en-AU", u.name_en_au end test "read when fallbacks present" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u = Unit.find(u.id) def u.globalize_fallbacks(locale) locale == :pl ? [:pl, :en] : [:en, :pl] end assert_equal "Name en", u.name assert_nil u.title_en end test "globalize attribute names on class without attributes specified in options" do assert_equal [:name_en, :name_pl, :title_en, :title_pl], Unit.globalize_attribute_names end test "globalize attribute names on class with attributes specified in options" do assert_equal [:name_pl], UnitTranslatedWithOptions.globalize_attribute_names end test "inherit globalize locales and attributes" do assert_equal [:name_pl], UnitInherited.globalize_attribute_names assert_equal [:pl], UnitInherited.globalize_locales end test "overwrite inherited globalize locales and attributes" do assert_equal [:color_de], UnitInheritedWithOptions.globalize_attribute_names assert_equal [:de], UnitInheritedWithOptions.globalize_locales end test "instance cannot set globalize locales or attributes" do assert_raise(NoMethodError) { Unit.new.globalize_attribute_names = [:name] } assert_raise(NoMethodError) { Unit.new.globalize_locales = [:en, :de] } end test "instance without accessors" do refute UnitWithoutAccessors.new.respond_to?(:localized_attr_name_for) end end Rails3 test class removed require 'test_helper' class GlobalizeAccessorsTest < ActiveSupport::TestCase class Unit < ActiveRecord::Base translates :name, :title globalize_accessors end class UnitTranslatedWithOptions < ActiveRecord::Base self.table_name = :units translates :name globalize_accessors :locales => [:pl], :attributes => [:name] end class UnitInherited < UnitTranslatedWithOptions end class UnitInheritedWithOptions < ActiveRecord::Base self.table_name = :units translates :color globalize_accessors :locales => [:de], :attributes => [:color] end class UnitWithDashedLocales < ActiveRecord::Base self.table_name = :units translates :name globalize_accessors :locales => [:"pt-BR", :"en-AU"], :attributes => [:name] end class UnitWithoutAccessors < ActiveRecord::Base self.table_name = :units end setup do assert_equal :en, I18n.locale end test "return localized attribute names" do u = UnitWithDashedLocales.new assert_equal "name_en", u.localized_attr_name_for(:name, :en) assert_equal "name_pt_br", u.localized_attr_name_for(:name, :"pt-BR") assert_equal "name_zh_cn", u.class.localized_attr_name_for(:name, :"zh-CN") end test "read and write on new object" do u = Unit.new(:name_en => "Name en", :title_pl => "Title pl") assert_equal "Name en", u.name assert_equal "Name en", u.name_en assert_equal "Title pl", u.title_pl assert_nil u.name_pl assert_nil u.title_en end test "build translations for a new object" do u = Unit.new(:name_en => "Name en", :title_pl => "Title pl") assert_equal 2, u.translations.size # size of the collection assert_equal 0, u.translations.count # count from database end test "doesn't build translations without values" do u = Unit.new(:name_en => nil, :title_pl => " ") assert_equal 0, u.translations.size end test "doesn't build translations without values even after saving" do u = Unit.new(:name_en => nil, :title_pl => " ") u.save # On Rails 4, Globalize will always create an empty translation for # the default locale # On Rails 3, Globalize will never create a translation assert u.translated_locales.exclude?(:pl) end test "persisted translations can be set to empty values" do u = Unit.new(:name_en => "test") u.save u.name_en = "" assert_equal "", u.translations.first.name end test "not persisted translations can be set to empty values" do u = Unit.new(:name_en => "test") u.name_en = "" assert_equal "", u.translations.first.name end test "write on new object and read on saved" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") assert_equal "Name en", u.name assert_equal "Name en", u.name_en assert_equal "Title pl", u.title_pl assert_nil u.name_pl assert_nil u.title_en end test "updates translations for existing object" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u.name_en = "New name en" assert_equal "New name en", u.translations.find {|t| t.locale == :en }.name assert_equal "Title pl", u.translations.find {|t| t.locale == :pl }.title assert_equal 2, u.translations.count end test "read on existing object" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u = Unit.find(u.id) assert_equal "Name en", u.name assert_equal "Name en", u.name_en assert_equal "Title pl", u.title_pl assert_nil u.name_pl assert_nil u.title_en end test "read and write on existing object" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u = Unit.find(u.id) u.name_pl = "Name pl" u.name_en = "Name en2" u.save! assert_equal "Name en2", u.name assert_equal "Name en2", u.name_en assert_equal "Name pl", u.name_pl assert_equal "Title pl", u.title_pl assert_nil u.title_en end test "read and write on class with options" do u = UnitTranslatedWithOptions.new() assert u.respond_to?(:name_pl) assert u.respond_to?(:name_pl=) assert ! u.respond_to?(:name_en) assert ! u.respond_to?(:name_en=) u.name = "Name en" u.name_pl = "Name pl" assert_equal "Name en", u.name assert_equal "Name pl", u.name_pl end test "globalize locales on class without locales specified in options" do assert_equal [:en, :pl], Unit.globalize_locales end test "globalize locales on class with locales specified in options" do assert_equal [:pl], UnitTranslatedWithOptions.globalize_locales end test "read and write on class with dashed locales" do u = UnitWithDashedLocales.new() assert u.respond_to?(:name_pt_br) assert u.respond_to?(:name_pt_br=) assert u.respond_to?(:name_en_au) assert u.respond_to?(:name_en_au=) u.name = "Name en" u.name_pt_br = "Name pt-BR" u.name_en_au = "Name en-AU" assert_equal "Name en", u.name assert_equal "Name pt-BR", u.name_pt_br assert_equal "Name en-AU", u.name_en_au end test "read when fallbacks present" do u = Unit.create!(:name_en => "Name en", :title_pl => "Title pl") u = Unit.find(u.id) def u.globalize_fallbacks(locale) locale == :pl ? [:pl, :en] : [:en, :pl] end assert_equal "Name en", u.name assert_nil u.title_en end test "globalize attribute names on class without attributes specified in options" do assert_equal [:name_en, :name_pl, :title_en, :title_pl], Unit.globalize_attribute_names end test "globalize attribute names on class with attributes specified in options" do assert_equal [:name_pl], UnitTranslatedWithOptions.globalize_attribute_names end test "inherit globalize locales and attributes" do assert_equal [:name_pl], UnitInherited.globalize_attribute_names assert_equal [:pl], UnitInherited.globalize_locales end test "overwrite inherited globalize locales and attributes" do assert_equal [:color_de], UnitInheritedWithOptions.globalize_attribute_names assert_equal [:de], UnitInheritedWithOptions.globalize_locales end test "instance cannot set globalize locales or attributes" do assert_raise(NoMethodError) { Unit.new.globalize_attribute_names = [:name] } assert_raise(NoMethodError) { Unit.new.globalize_locales = [:en, :de] } end test "instance without accessors" do refute UnitWithoutAccessors.new.respond_to?(:localized_attr_name_for) end end
$:.unshift File.expand_path('../../test', __dir__) require 'test_helper' require 'haml' require 'minitest/autorun' # This is a spec converted by haml-spec. # See: https://github.com/haml/haml-spec class UglyTest < MiniTest::Test HAML_DEFAULT_OPTIONS = { escape_html: true, escape_attrs: true }.freeze HAMLIT_DEFAULT_OPTIONS = { escape_html: true }.freeze def self.haml_result(haml, options, locals) Haml::Engine.new(haml, HAML_DEFAULT_OPTIONS.merge(options)).render(Object.new, locals) end def self.hamlit_result(haml, options, locals) Hamlit::Template.new(HAMLIT_DEFAULT_OPTIONS.merge(options)) { haml }.render(Object.new, locals) end class Headers < MiniTest::Test def test_an_XHTML_XML_prolog haml = %q{!!! XML} html = %q{<?xml version='1.0' encoding='utf-8' ?>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_default_transitional_doctype haml = %q{!!!} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_1_doctype haml = %q{!!! 1.1} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_2_mobile_doctype haml = %q{!!! mobile} html = %q{<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_1_basic_doctype haml = %q{!!! basic} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_0_frameset_doctype haml = %q{!!! frameset} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_5_doctype_with_XHTML_syntax haml = %q{!!! 5} html = %q{<!DOCTYPE html>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_5_XML_prolog_silent_ haml = %q{!!! XML} html = %q{} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_5_doctype haml = %q{!!!} html = %q{<!DOCTYPE html>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_XML_prolog_silent_ haml = %q{!!! XML} html = %q{} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_default_transitional_doctype haml = %q{!!!} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_frameset_doctype haml = %q{!!! frameset} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_strict_doctype haml = %q{!!! strict} html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Basichamltagsandcss < MiniTest::Test def test_a_simple_Haml_tag haml = %q{%p} html = %q{<p></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_XHTML_ haml = %q{%meta} html = %q{<meta />} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_HTML4_ haml = %q{%meta} html = %q{<meta>} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_HTML5_ haml = %q{%meta} html = %q{<meta>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_modifier_XHTML_ haml = %q{%zzz/} html = %q{<zzz />} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_modifier_HTML5_ haml = %q{%zzz/} html = %q{<zzz>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_a_CSS_class haml = %q{%p.class1} html = %q{<p class='class1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_multiple_CSS_classes haml = %q{%p.class1.class2} html = %q{<p class='class1 class2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_a_CSS_id haml = %q{%p#id1} html = %q{<p id='id1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_multiple_CSS_id_s haml = %q{%p#id1#id2} html = %q{<p id='id2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_a_class_followed_by_an_id haml = %q{%p.class1#id1} html = %q{<p class='class1' id='id1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_an_id_followed_by_a_class haml = %q{%p#id1.class1} html = %q{<p class='class1' id='id1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_implicit_div_with_a_CSS_id haml = %q{#id1} html = %q{<div id='id1'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_implicit_div_with_a_CSS_class haml = %q{.class1} html = %q{<div class='class1'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_multiple_simple_Haml_tags haml = %q{%div %div %p} html = %q{<div> <div> <p></p> </div> </div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithunusualhtmlcharacters < MiniTest::Test def test_a_tag_with_colons haml = %q{%ns:tag} html = %q{<ns:tag></ns:tag>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_underscores haml = %q{%snake_case} html = %q{<snake_case></snake_case>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_dashes haml = %q{%dashed-tag} html = %q{<dashed-tag></dashed-tag>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_camelCase haml = %q{%camelCase} html = %q{<camelCase></camelCase>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_PascalCase haml = %q{%PascalCase} html = %q{<PascalCase></PascalCase>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithunusualcssidentifiers < MiniTest::Test def test_an_all_numeric_class haml = %q{.123} html = %q{<div class='123'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_class_with_underscores haml = %q{.__} html = %q{<div class='__'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_class_with_dashes haml = %q{.--} html = %q{<div class='--'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithinlinecontent < MiniTest::Test def test_Inline_content_simple_tag haml = %q{%p hello} html = %q{<p>hello</p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Inline_content_tag_with_CSS haml = %q{%p.class1 hello} html = %q{<p class='class1'>hello</p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Inline_content_multiple_simple_tags haml = %q{%div %div %p text} html = %q{<div> <div> <p>text</p> </div> </div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithnestedcontent < MiniTest::Test def test_Nested_content_simple_tag haml = %q{%p hello} html = %q{<p> hello </p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Nested_content_tag_with_CSS haml = %q{%p.class1 hello} html = %q{<p class='class1'> hello </p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Nested_content_multiple_simple_tags haml = %q{%div %div %p text} html = %q{<div> <div> <p> text </p> </div> </div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithhtmlstyleattributes < MiniTest::Test def test_HTML_style_one_attribute haml = %q{%p(a='b')} html = %q{<p a='b'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_multiple_attributes haml = %q{%p(a='b' c='d')} html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_attributes_separated_with_newlines haml = %q{%p(a='b' c='d')} html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_interpolated_attribute haml = %q{%p(a="#{var}")} html = %q{<p a='value'></p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_class_as_an_attribute haml = %q{%p(class='class1')} html = %q{<p class='class1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_CSS_class_and_class_as_an_attribute haml = %q{%p.class2(class='class1')} html = %q{<p class='class1 class2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_id_as_an_attribute haml = %q{%p(id='1')} html = %q{<p id='1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_CSS_id_and_id_as_an_attribute haml = %q{%p#id(id='1')} html = %q{<p id='id_1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_variable_attribute haml = %q{%p(class=var)} html = %q{<p class='hello'></p>} locals = {:var=>"hello"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_CSS_class_and_class_as_a_variable_attribute haml = %q{.hello(class=var)} html = %q{<div class='hello world'></div>} locals = {:var=>"world"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_multiple_CSS_classes_sorted_correctly_ haml = %q{.z(class=var)} html = %q{<div class='a z'></div>} locals = {:var=>"a"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_an_atomic_attribute skip '[INCOMPATIBILITY] Hamlit limits boolean attributes' haml = %q{%a(flag)} html = %q{<a flag></a>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithrubystyleattributes < MiniTest::Test def test_Ruby_style_one_attribute haml = %q{%p{:a => 'b'}} html = %q{<p a='b'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_attributes_hash_with_whitespace haml = %q{%p{ :a => 'b' }} html = %q{<p a='b'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_interpolated_attribute haml = %q{%p{:a =>"#{var}"}} html = %q{<p a='value'></p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_multiple_attributes haml = %q{%p{ :a => 'b', 'c' => 'd' }} html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_attributes_separated_with_newlines haml = %q{%p{ :a => 'b', 'c' => 'd' }} html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_class_as_an_attribute haml = %q{%p{:class => 'class1'}} html = %q{<p class='class1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_class_and_class_as_an_attribute haml = %q{%p.class2{:class => 'class1'}} html = %q{<p class='class1 class2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_id_as_an_attribute haml = %q{%p{:id => '1'}} html = %q{<p id='1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_id_and_id_as_an_attribute haml = %q{%p#id{:id => '1'}} html = %q{<p id='id_1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_id_and_a_numeric_id_as_an_attribute haml = %q{%p#id{:id => 1}} html = %q{<p id='id_1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_variable_attribute haml = %q{%p{:class => var}} html = %q{<p class='hello'></p>} locals = {:var=>"hello"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_class_and_class_as_a_variable_attribute haml = %q{.hello{:class => var}} html = %q{<div class='hello world'></div>} locals = {:var=>"world"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_multiple_CSS_classes_sorted_correctly_ haml = %q{.z{:class => var}} html = %q{<div class='a z'></div>} locals = {:var=>"a"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Silentcomments < MiniTest::Test def test_an_inline_silent_comment haml = %q{-# hello} html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_nested_silent_comment haml = %q{-# hello} html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_multiply_nested_silent_comment haml = %q{-# %div foo} html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_multiply_nested_silent_comment_with_inconsistent_indents haml = %q{-# %div foo} html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Markupcomments < MiniTest::Test def test_an_inline_markup_comment haml = %q{/ comment} html = %q{<!-- comment -->} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_nested_markup_comment haml = %q{/ comment comment2} html = %q{<!-- comment comment2 -->} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Conditionalcomments < MiniTest::Test def test_a_conditional_comment haml = %q{/[if IE] %p a} html = %q{<!--[if IE]> <p>a</p> <![endif]-->} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Internalfilters < MiniTest::Test def test_content_in_an_escaped_filter haml = %q{:escaped <&">} html = %q{&lt;&amp;&quot;&gt;} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_preserve_filter haml = %q{:preserve hello %p} html = %q{hello&#x000A; <p></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_plain_filter haml = %q{:plain hello %p} html = %q{hello <p></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_css_filter_XHTML_ haml = %q{:css hello %p} html = %q{<style type='text/css'> /*<![CDATA[*/ hello /*]]>*/ </style> <p></p>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_javascript_filter_XHTML_ haml = %q{:javascript a(); %p} html = %q{<script type='text/javascript'> //<![CDATA[ a(); //]]> </script> <p></p>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_css_filter_HTML_ haml = %q{:css hello %p} html = %q{<style> hello </style> <p></p>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_javascript_filter_HTML_ haml = %q{:javascript a(); %p} html = %q{<script> a(); </script> <p></p>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Rubystyleinterpolation < MiniTest::Test def test_interpolation_inside_inline_content haml = %q{%p #{var}} html = %q{<p>value</p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_no_interpolation_when_escaped haml = %q{%p \#{var}} html = %q{<p>#{var}</p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_interpolation_when_the_escape_character_is_escaped haml = %q{%p \\#{var}} html = %q{<p>\value</p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_interpolation_inside_filtered_content haml = %q{:plain #{var} interpolated: #{var}} html = %q{value interpolated: value} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Htmlescaping < MiniTest::Test def test_code_following_ haml = %q{&= '<"&>'} html = %q{&lt;&quot;&amp;&gt;} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_code_following_when_escape_haml_is_set_to_true haml = %q{= '<"&>'} html = %q{&lt;&quot;&amp;&gt;} locals = {} options = {:escape_html=>"true"} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_code_following_when_escape_haml_is_set_to_true haml = %q{!= '<"&>'} html = %q{<"&>} locals = {} options = {:escape_html=>"true"} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Booleanattributes < MiniTest::Test def test_boolean_attribute_with_XHTML haml = %q{%input(checked=true)} html = %q{<input checked='checked' />} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_boolean_attribute_with_HTML haml = %q{%input(checked=true)} html = %q{<input checked>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Whitespacepreservation < MiniTest::Test def test_following_the_operator haml = %q{~ "Foo\n<pre>Bar\nBaz</pre>"} html = %q{Foo <pre>Bar&#x000A;Baz</pre>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_inside_a_textarea_tag haml = %q{%textarea hello hello} html = %q{<textarea>hello hello</textarea>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_inside_a_pre_tag haml = %q{%pre hello hello} html = %q{<pre>hello hello</pre>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Whitespaceremoval < MiniTest::Test def test_a_tag_with_appended_and_inline_content haml = %q{%li hello %li> world %li again} html = %q{<li>hello</li><li>world</li><li>again</li>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_appended_and_nested_content haml = %q{%li hello %li> world %li again} html = %q{<li>hello</li><li> world </li><li>again</li>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_appended haml = %q{%p< hello world} html = %q{<p>hello world</p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end end Suppress unused variable assignment warning $:.unshift File.expand_path('../../test', __dir__) require 'test_helper' require 'haml' require 'minitest/autorun' # This is a spec converted by haml-spec. # See: https://github.com/haml/haml-spec class UglyTest < MiniTest::Test HAML_DEFAULT_OPTIONS = { escape_html: true, escape_attrs: true }.freeze HAMLIT_DEFAULT_OPTIONS = { escape_html: true }.freeze def self.haml_result(haml, options, locals) Haml::Engine.new(haml, HAML_DEFAULT_OPTIONS.merge(options)).render(Object.new, locals) end def self.hamlit_result(haml, options, locals) Hamlit::Template.new(HAMLIT_DEFAULT_OPTIONS.merge(options)) { haml }.render(Object.new, locals) end class Headers < MiniTest::Test def test_an_XHTML_XML_prolog haml = %q{!!! XML} _html = %q{<?xml version='1.0' encoding='utf-8' ?>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_default_transitional_doctype haml = %q{!!!} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_1_doctype haml = %q{!!! 1.1} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_2_mobile_doctype haml = %q{!!! mobile} _html = %q{<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_1_basic_doctype haml = %q{!!! basic} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_XHTML_1_0_frameset_doctype haml = %q{!!! frameset} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_5_doctype_with_XHTML_syntax haml = %q{!!! 5} _html = %q{<!DOCTYPE html>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_5_XML_prolog_silent_ haml = %q{!!! XML} _html = %q{} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_5_doctype haml = %q{!!!} _html = %q{<!DOCTYPE html>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_XML_prolog_silent_ haml = %q{!!! XML} _html = %q{} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_default_transitional_doctype haml = %q{!!!} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_frameset_doctype haml = %q{!!! frameset} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_HTML_4_strict_doctype haml = %q{!!! strict} _html = %q{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Basichamltagsandcss < MiniTest::Test def test_a_simple_Haml_tag haml = %q{%p} _html = %q{<p></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_XHTML_ haml = %q{%meta} _html = %q{<meta />} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_HTML4_ haml = %q{%meta} _html = %q{<meta>} locals = {} options = {:format=>:html4} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_HTML5_ haml = %q{%meta} _html = %q{<meta>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_modifier_XHTML_ haml = %q{%zzz/} _html = %q{<zzz />} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_self_closing_tag_modifier_HTML5_ haml = %q{%zzz/} _html = %q{<zzz>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_a_CSS_class haml = %q{%p.class1} _html = %q{<p class='class1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_multiple_CSS_classes haml = %q{%p.class1.class2} _html = %q{<p class='class1 class2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_a_CSS_id haml = %q{%p#id1} _html = %q{<p id='id1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_multiple_CSS_id_s haml = %q{%p#id1#id2} _html = %q{<p id='id2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_a_class_followed_by_an_id haml = %q{%p.class1#id1} _html = %q{<p class='class1' id='id1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_an_id_followed_by_a_class haml = %q{%p#id1.class1} _html = %q{<p class='class1' id='id1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_implicit_div_with_a_CSS_id haml = %q{#id1} _html = %q{<div id='id1'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_an_implicit_div_with_a_CSS_class haml = %q{.class1} _html = %q{<div class='class1'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_multiple_simple_Haml_tags haml = %q{%div %div %p} _html = %q{<div> <div> <p></p> </div> </div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithunusualhtmlcharacters < MiniTest::Test def test_a_tag_with_colons haml = %q{%ns:tag} _html = %q{<ns:tag></ns:tag>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_underscores haml = %q{%snake_case} _html = %q{<snake_case></snake_case>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_dashes haml = %q{%dashed-tag} _html = %q{<dashed-tag></dashed-tag>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_camelCase haml = %q{%camelCase} _html = %q{<camelCase></camelCase>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_PascalCase haml = %q{%PascalCase} _html = %q{<PascalCase></PascalCase>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithunusualcssidentifiers < MiniTest::Test def test_an_all_numeric_class haml = %q{.123} _html = %q{<div class='123'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_class_with_underscores haml = %q{.__} _html = %q{<div class='__'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_class_with_dashes haml = %q{.--} _html = %q{<div class='--'></div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithinlinecontent < MiniTest::Test def test_Inline_content_simple_tag haml = %q{%p hello} _html = %q{<p>hello</p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Inline_content_tag_with_CSS haml = %q{%p.class1 hello} _html = %q{<p class='class1'>hello</p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Inline_content_multiple_simple_tags haml = %q{%div %div %p text} _html = %q{<div> <div> <p>text</p> </div> </div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithnestedcontent < MiniTest::Test def test_Nested_content_simple_tag haml = %q{%p hello} _html = %q{<p> hello </p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Nested_content_tag_with_CSS haml = %q{%p.class1 hello} _html = %q{<p class='class1'> hello </p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Nested_content_multiple_simple_tags haml = %q{%div %div %p text} _html = %q{<div> <div> <p> text </p> </div> </div>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithhtmlstyleattributes < MiniTest::Test def test_HTML_style_one_attribute haml = %q{%p(a='b')} _html = %q{<p a='b'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_multiple_attributes haml = %q{%p(a='b' c='d')} _html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_attributes_separated_with_newlines haml = %q{%p(a='b' c='d')} _html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_interpolated_attribute haml = %q{%p(a="#{var}")} _html = %q{<p a='value'></p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_class_as_an_attribute haml = %q{%p(class='class1')} _html = %q{<p class='class1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_CSS_class_and_class_as_an_attribute haml = %q{%p.class2(class='class1')} _html = %q{<p class='class1 class2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_id_as_an_attribute haml = %q{%p(id='1')} _html = %q{<p id='1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_CSS_id_and_id_as_an_attribute haml = %q{%p#id(id='1')} _html = %q{<p id='id_1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_variable_attribute haml = %q{%p(class=var)} _html = %q{<p class='hello'></p>} locals = {:var=>"hello"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_a_CSS_class_and_class_as_a_variable_attribute haml = %q{.hello(class=var)} _html = %q{<div class='hello world'></div>} locals = {:var=>"world"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_multiple_CSS_classes_sorted_correctly_ haml = %q{.z(class=var)} _html = %q{<div class='a z'></div>} locals = {:var=>"a"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_HTML_style_tag_with_an_atomic_attribute skip '[INCOMPATIBILITY] Hamlit limits boolean attributes' haml = %q{%a(flag)} _html = %q{<a flag></a>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Tagswithrubystyleattributes < MiniTest::Test def test_Ruby_style_one_attribute haml = %q{%p{:a => 'b'}} _html = %q{<p a='b'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_attributes_hash_with_whitespace haml = %q{%p{ :a => 'b' }} _html = %q{<p a='b'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_interpolated_attribute haml = %q{%p{:a =>"#{var}"}} _html = %q{<p a='value'></p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_multiple_attributes haml = %q{%p{ :a => 'b', 'c' => 'd' }} _html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_attributes_separated_with_newlines haml = %q{%p{ :a => 'b', 'c' => 'd' }} _html = %q{<p a='b' c='d'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_class_as_an_attribute haml = %q{%p{:class => 'class1'}} _html = %q{<p class='class1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_class_and_class_as_an_attribute haml = %q{%p.class2{:class => 'class1'}} _html = %q{<p class='class1 class2'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_id_as_an_attribute haml = %q{%p{:id => '1'}} _html = %q{<p id='1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_id_and_id_as_an_attribute haml = %q{%p#id{:id => '1'}} _html = %q{<p id='id_1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_id_and_a_numeric_id_as_an_attribute haml = %q{%p#id{:id => 1}} _html = %q{<p id='id_1'></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_variable_attribute haml = %q{%p{:class => var}} _html = %q{<p class='hello'></p>} locals = {:var=>"hello"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_with_a_CSS_class_and_class_as_a_variable_attribute haml = %q{.hello{:class => var}} _html = %q{<div class='hello world'></div>} locals = {:var=>"world"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_Ruby_style_tag_multiple_CSS_classes_sorted_correctly_ haml = %q{.z{:class => var}} _html = %q{<div class='a z'></div>} locals = {:var=>"a"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Silentcomments < MiniTest::Test def test_an_inline_silent_comment haml = %q{-# hello} _html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_nested_silent_comment haml = %q{-# hello} _html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_multiply_nested_silent_comment haml = %q{-# %div foo} _html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_multiply_nested_silent_comment_with_inconsistent_indents haml = %q{-# %div foo} _html = %q{} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Markupcomments < MiniTest::Test def test_an_inline_markup_comment haml = %q{/ comment} _html = %q{<!-- comment -->} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_nested_markup_comment haml = %q{/ comment comment2} _html = %q{<!-- comment comment2 -->} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Conditionalcomments < MiniTest::Test def test_a_conditional_comment haml = %q{/[if IE] %p a} _html = %q{<!--[if IE]> <p>a</p> <![endif]-->} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Internalfilters < MiniTest::Test def test_content_in_an_escaped_filter haml = %q{:escaped <&">} _html = %q{&lt;&amp;&quot;&gt;} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_preserve_filter haml = %q{:preserve hello %p} _html = %q{hello&#x000A; <p></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_plain_filter haml = %q{:plain hello %p} _html = %q{hello <p></p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_css_filter_XHTML_ haml = %q{:css hello %p} _html = %q{<style type='text/css'> /*<![CDATA[*/ hello /*]]>*/ </style> <p></p>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_javascript_filter_XHTML_ haml = %q{:javascript a(); %p} _html = %q{<script type='text/javascript'> //<![CDATA[ a(); //]]> </script> <p></p>} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_css_filter_HTML_ haml = %q{:css hello %p} _html = %q{<style> hello </style> <p></p>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_content_in_a_javascript_filter_HTML_ haml = %q{:javascript a(); %p} _html = %q{<script> a(); </script> <p></p>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Rubystyleinterpolation < MiniTest::Test def test_interpolation_inside_inline_content haml = %q{%p #{var}} _html = %q{<p>value</p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_no_interpolation_when_escaped haml = %q{%p \#{var}} _html = %q{<p>#{var}</p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_interpolation_when_the_escape_character_is_escaped haml = %q{%p \\#{var}} _html = %q{<p>\value</p>} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_interpolation_inside_filtered_content haml = %q{:plain #{var} interpolated: #{var}} _html = %q{value interpolated: value} locals = {:var=>"value"} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Htmlescaping < MiniTest::Test def test_code_following_ haml = %q{&= '<"&>'} _html = %q{&lt;&quot;&amp;&gt;} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_code_following_when_escape_haml_is_set_to_true haml = %q{= '<"&>'} _html = %q{&lt;&quot;&amp;&gt;} locals = {} options = {:escape_html=>"true"} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_code_following_when_escape_haml_is_set_to_true haml = %q{!= '<"&>'} _html = %q{<"&>} locals = {} options = {:escape_html=>"true"} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Booleanattributes < MiniTest::Test def test_boolean_attribute_with_XHTML haml = %q{%input(checked=true)} _html = %q{<input checked='checked' />} locals = {} options = {:format=>:xhtml} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_boolean_attribute_with_HTML haml = %q{%input(checked=true)} _html = %q{<input checked>} locals = {} options = {:format=>:html5} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Whitespacepreservation < MiniTest::Test def test_following_the_operator haml = %q{~ "Foo\n<pre>Bar\nBaz</pre>"} _html = %q{Foo <pre>Bar&#x000A;Baz</pre>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_inside_a_textarea_tag haml = %q{%textarea hello hello} _html = %q{<textarea>hello hello</textarea>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_inside_a_pre_tag haml = %q{%pre hello hello} _html = %q{<pre>hello hello</pre>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end class Whitespaceremoval < MiniTest::Test def test_a_tag_with_appended_and_inline_content haml = %q{%li hello %li> world %li again} _html = %q{<li>hello</li><li>world</li><li>again</li>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_appended_and_nested_content haml = %q{%li hello %li> world %li again} _html = %q{<li>hello</li><li> world </li><li>again</li>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end def test_a_tag_with_appended haml = %q{%p< hello world} _html = %q{<p>hello world</p>} locals = {} options = {} haml_result = UglyTest.haml_result(haml, options, locals) hamlit_result = UglyTest.hamlit_result(haml, options, locals) assert_equal haml_result, hamlit_result end end end
require "test/unit" $LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib') require 'fix_microsoft_links' class RegexTest < Test::Unit::TestCase def test_outook assert_no_match "Microsoft Office/14.0 (Windows NT 6.0; Microsoft Outlook 14.0.4760; Pro)" assert_no_match "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; InfoPath.3; Microsoft Outlook 14.0.6131; ms-office; MSOffice 14)" end def test_other_microsoft_apps # Office 2011 on Mac assert_match "Mozilla/5.0 (Macintosh; Intel Mac OS X) Word/14.20.0" assert_match "Mozilla/5.0 (Macintosh; Intel Mac OS X) Excel/14.20.0" assert_match "Mozilla/5.0 (Macintosh; Intel Mac OS X) PowerPoint/14.20.0" # some others on windows 7 assert_match "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; ms-office)" end def test_konqueror_kio # LibreOffice on KDE will check links just like MSOffice assert_match "Mozilla/5.0 (X11; Linux x86_64) KHTML/5.37.0 (like Gecko) Konqueror/5 KIO/5.37" assert_match "Mozilla/5.0 (X11; Linux x86_64) KHTML/5.36.0 (like Gecko) Konqueror/5 KIO/5.36" assert_match "Mozilla/5.0 (X11; Linux x86_64) KHTML/5.33.0 (like Gecko) Konqueror/5 KIO/5.33" end def test_others assert_no_match "aldsfjlkads asdljfjl Words" assert_no_match "1.5 - Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.21 (KHTML, like Gecko) konqueror/4.14.22 Safari/537.21" assert_no_match "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5" end private def assert_match(user_agent) assert FixMicrosoftLinks::Rack::Response.new(nil).matching_user_agent?(user_agent), "Expected middleware to apply to user agent: #{user_agent}" end def assert_no_match(user_agent) assert !FixMicrosoftLinks::Rack::Response.new(nil).matching_user_agent?(user_agent), "Did not expect middleware to apply to user agent: #{user_agent}" end end Removed erronious number in string require "test/unit" $LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib') require 'fix_microsoft_links' class RegexTest < Test::Unit::TestCase def test_outook assert_no_match "Microsoft Office/14.0 (Windows NT 6.0; Microsoft Outlook 14.0.4760; Pro)" assert_no_match "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; InfoPath.3; Microsoft Outlook 14.0.6131; ms-office; MSOffice 14)" end def test_other_microsoft_apps # Office 2011 on Mac assert_match "Mozilla/5.0 (Macintosh; Intel Mac OS X) Word/14.20.0" assert_match "Mozilla/5.0 (Macintosh; Intel Mac OS X) Excel/14.20.0" assert_match "Mozilla/5.0 (Macintosh; Intel Mac OS X) PowerPoint/14.20.0" # some others on windows 7 assert_match "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; ms-office)" end def test_konqueror_kio # LibreOffice on KDE will check links just like MSOffice assert_match "Mozilla/5.0 (X11; Linux x86_64) KHTML/5.37.0 (like Gecko) Konqueror/5 KIO/5.37" assert_match "Mozilla/5.0 (X11; Linux x86_64) KHTML/5.36.0 (like Gecko) Konqueror/5 KIO/5.36" assert_match "Mozilla/5.0 (X11; Linux x86_64) KHTML/5.33.0 (like Gecko) Konqueror/5 KIO/5.33" end def test_others assert_no_match "aldsfjlkads asdljfjl Words" assert_no_match "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.21 (KHTML, like Gecko) konqueror/4.14.22 Safari/537.21" assert_no_match "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5" end private def assert_match(user_agent) assert FixMicrosoftLinks::Rack::Response.new(nil).matching_user_agent?(user_agent), "Expected middleware to apply to user agent: #{user_agent}" end def assert_no_match(user_agent) assert !FixMicrosoftLinks::Rack::Response.new(nil).matching_user_agent?(user_agent), "Did not expect middleware to apply to user agent: #{user_agent}" end end
require 'sinatra' require 'sinatra/json' class SimpleApp < Sinatra::Base # disable: show_exceptions SECRET = SecureRandom.hex # The expire argument is added to current server time as seconds use SimpleSession::Session, secret: SECRET, max_age: 10 def authenticated? &block if session[:user_id] == '!Green3ggsandHam!' status 200 json yield else status 401 json msg: "You must sign in" end end def user_id_hash {user_id: session[:user_id]} end get '/' do authenticated? do user_id_hash end end get '/signin' do session[:user_id] ? "Signed in" : session[:user_id] = '!Green3ggsandHam!' json user_id: session[:user_id] end get '/signout' do authenticated? do session.clear user_id_hash end end # List all the options for expire, used as an expired request test get '/expire' do json session: session.merge(request.session_options).to_json end post '/options' do sanitize = ['expires', 'max_age', 'path', 'domain', 'secure', 'http_only'] hashed_params = Hash.new params.each { |k, v| hashed_params[k.to_sym] = v if sanitize.include?(k)} old_expire = request.session_options[:max_age] request.session_options.merge!(hashed_params) json old: old_expire, new: request.session_options[:max_age] end end remove sinatra/json call require 'sinatra' class SimpleApp < Sinatra::Base # disable: show_exceptions SECRET = SecureRandom.hex # The expire argument is added to current server time as seconds use SimpleSession::Session, secret: SECRET, max_age: 10 def authenticated? &block if session[:user_id] == '!Green3ggsandHam!' status 200 json yield else status 401 json msg: "You must sign in" end end def user_id_hash {user_id: session[:user_id]} end get '/' do authenticated? do user_id_hash end end get '/signin' do session[:user_id] ? "Signed in" : session[:user_id] = '!Green3ggsandHam!' json user_id: session[:user_id] end get '/signout' do authenticated? do session.clear user_id_hash end end # List all the options for expire, used as an expired request test get '/expire' do json session: session.merge(request.session_options).to_json end post '/options' do sanitize = ['expires', 'max_age', 'path', 'domain', 'secure', 'http_only'] hashed_params = Hash.new params.each { |k, v| hashed_params[k.to_sym] = v if sanitize.include?(k)} old_expire = request.session_options[:max_age] request.session_options.merge!(hashed_params) json old: old_expire, new: request.session_options[:max_age] end end
fix log disconnected
module FelyneBot module Commands module UserFind extend Discordrb::Commands::CommandContainer command( :userfind, description: "Finds a user on the database", useage: "userfind <search>", min_args: 1, max_args: 1 ) do |event, search| i=0 found=[] begin if $users[i].id!=nil && $users[i].id==search then found.push($users[i]) end if $users[i].name!=nil && $users[i].name.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].ign!=nil && $users[i].ign.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].guild!=nil && $users[i].guild.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].timezone!=nil && $users[i].timezone.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].server!=nil && $users[i].server.downcase.include?(search.downcase) then found.push($users[i]) end i+=1 end while $users[i]!=nil found.uniq! if !found.empty? i=0 event << "Found User Database:" event << "```Name IGN Guild Timezone Server" begin namel = found[i].name.to_s.length ignl = found[i].ign.to_s.length guildl = found[i].guild.to_s.length namec = found[i].name.to_s ignc = found[i].ign.to_s guildc = found[i].guild.to_s just1 = 15 just2 = 30 just3 = 45 just4 = 60 if namec then just2 = just2 - namel end if ignc then just3 = just3 - ignl end if guildc then just4 = just4 - guildl end str = "" if found[i].name!=nil then str << "#{found[i].name.to_s}" end str=str.ljust(just1) if found[i].ign!=nil then str << "#{found[i].ign.to_s}" end str=str.ljust(just2) if found[i].guild!=nil then str << "#{found[i].guild.to_s}" end str=str.ljust(just3) if found[i].timezone!=nil then str << "#{found[i].timezone.to_s}" end str=str.ljust(just4) if found[i].server!=nil then str << "#{found[i].server.to_s}" end event << str i+=1 end while i < found.length event << "```" else event << "Search string was not found in database." end puts "#{event.timestamp}: #{event.user.name}: CMD: userfind" nil end end end end divide by 2 module FelyneBot module Commands module UserFind extend Discordrb::Commands::CommandContainer command( :userfind, description: "Finds a user on the database", useage: "userfind <search>", min_args: 1, max_args: 1 ) do |event, search| i=0 found=[] begin if $users[i].id!=nil && $users[i].id==search then found.push($users[i]) end if $users[i].name!=nil && $users[i].name.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].ign!=nil && $users[i].ign.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].guild!=nil && $users[i].guild.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].timezone!=nil && $users[i].timezone.downcase.include?(search.downcase) then found.push($users[i]) end if $users[i].server!=nil && $users[i].server.downcase.include?(search.downcase) then found.push($users[i]) end i+=1 end while $users[i]!=nil found.uniq! if !found.empty? i=0 event << "Found User Database:" event << "```Name IGN Guild Timezone Server" begin namel = found[i].name.to_s.length ignl = found[i].ign.to_s.length guildl = found[i].guild.to_s.length namec = found[i].name.to_s ignc = found[i].ign.to_s guildc = found[i].guild.to_s just1 = 15 just2 = 30 just3 = 45 just4 = 60 if namec then just2 = just2 - namel/2 end if ignc then just3 = just3 - ignl/2 end if guildc then just4 = just4 - guildl/2 end str = "" if found[i].name!=nil then str << "#{found[i].name.to_s}" end str=str.ljust(just1) if found[i].ign!=nil then str << "#{found[i].ign.to_s}" end str=str.ljust(just2) if found[i].guild!=nil then str << "#{found[i].guild.to_s}" end str=str.ljust(just3) if found[i].timezone!=nil then str << "#{found[i].timezone.to_s}" end str=str.ljust(just4) if found[i].server!=nil then str << "#{found[i].server.to_s}" end event << str i+=1 end while i < found.length event << "```" else event << "Search string was not found in database." end puts "#{event.timestamp}: #{event.user.name}: CMD: userfind" nil end end end end
include YARD::Templates::Helpers::HtmlHelper def init super # Additional javascript that power the additional menus, collapsing, etc. asset("js/cucumber.js",file("js/cucumber.js",true)) serialize_object_type :feature serialize_object_type :tag # Generates the requirements splash page with the 'requirements' template serialize(YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE) # Generates a page for step definitions and step transforms with the 'steptransformers' template serialize(YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE) # Generates the tags page with the 'featuretags' template serialize(YARD::CodeObjects::Cucumber::CUCUMBER_TAG_NAMESPACE) serialize_feature_directories end # # Generate pages for the objects if there are objects of this type contained # within the Registry. # def serialize_object_type(type) objects = Registry.all(type.to_sym) Array(objects).each {|object| serialize(object) } end # # Generates pages for the feature directories found. Starting with all root-level feature # directories and then recursively finding all child feature directories. # def serialize_feature_directories directories = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) } serialize_feature_directories_recursively(directories) Array(directories).each {|directory| serialize(directory) } end # # Generate a page for each Feature Directory. This is called recursively to # ensure that all feature directories contained as children are rendered to # pages. # def serialize_feature_directories_recursively(namespaces) namespaces.each do |namespace| Templates::Engine.with_serializer(namespace, options[:serializer]) do options[:object] = namespace T('layout').run(options) end serialize_feature_directories_recursively(namespace.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)}) end end # Generate feature list # @note this method is called automatically by YARD based on the menus defined in the layout def generate_feature_list @features = Registry.all(:feature) generate_full_list @features.sort {|x,y| x.value.to_s <=> y.value.to_s }, :features end # Generate tag list # @note this method is called automatically by YARD based on the menus defined in the layout def generate_tag_list @tags = Registry.all(:tag) generate_full_list @tags.sort {|x,y| y.all_scenarios.size <=> x.all_scenarios.size }, :tags end # Generate a step definition list # @note this menu is not automatically added until yard configuration has this menu added # See the layout template method that loads the menus def generate_stepdefinition_list generate_full_list YARD::Registry.all(:stepdefinition), :stepdefinitions end # Generate a step list # @note this menu is not automatically added until yard configuration has this menu added # See the layout template method that loads the menus def generate_step_list generate_full_list YARD::Registry.all(:step), :steps end # Generate feature list # @note this menu is not automatically added until yard configuration has this menu added # See the layout template method that loads the menus def generate_featuredirectories_list @feature_directories = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) } feature_directories = @feature_directories.sort {|x,y| x.value.to_s <=> y.value.to_s } generate_full_list feature_directories, :featuredirectories, nil, :featuredirectories end # Helpler method to generate a full_list page of the specified objects with the # specified type. def generate_full_list(objects,list_type,friendly_name=nil,asset_name=nil) @items = objects @list_type = list_type @list_title = "#{friendly_name || list_type.to_s.capitalize} List" @list_class = "class" asset_name ||= list_type.to_s.gsub(/s$/,'') asset("#{asset_name}_list.html",erb(:full_list)) end # # The existing 'Class List' search field would normally contain the Cucumber # Namespace object that has been added. Here we call the class_list method # that is contained in the YARD template and we remove the namespace. Returning # it when we are done. # def class_list(root = Registry.root) root.instance_eval { children.delete YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE } if root == Registry.root out = super(root) root.instance_eval { children << YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE } if root == Registry.root out end # # Generate a link to the 'All Features' in the features_list.html # # When there are no feature directories or multiple top-level feature directories # then we want to link to the 'Requirements' page # # When there are is just one feature directory then we want to link to that directory # def all_features_link root_feature_directories = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)} if root_feature_directories.length == 0 || root_feature_directories.length > 1 linkify YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE, "All Features" else linkify root_feature_directories.first, "All Features" end end def directory_node(directory) @directory = directory erb(:directories) end Removed whitespace include YARD::Templates::Helpers::HtmlHelper def init super # Additional javascript that power the additional menus, collapsing, etc. asset("js/cucumber.js",file("js/cucumber.js",true)) serialize_object_type :feature serialize_object_type :tag # Generates the requirements splash page with the 'requirements' template serialize(YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE) # Generates a page for step definitions and step transforms with the 'steptransformers' template serialize(YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE) # Generates the tags page with the 'featuretags' template serialize(YARD::CodeObjects::Cucumber::CUCUMBER_TAG_NAMESPACE) serialize_feature_directories end # # Generate pages for the objects if there are objects of this type contained # within the Registry. # def serialize_object_type(type) objects = Registry.all(type.to_sym) Array(objects).each {|object| serialize(object) } end # # Generates pages for the feature directories found. Starting with all root-level feature # directories and then recursively finding all child feature directories. # def serialize_feature_directories directories = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) } serialize_feature_directories_recursively(directories) Array(directories).each {|directory| serialize(directory) } end # # Generate a page for each Feature Directory. This is called recursively to # ensure that all feature directories contained as children are rendered to # pages. # def serialize_feature_directories_recursively(namespaces) namespaces.each do |namespace| Templates::Engine.with_serializer(namespace, options[:serializer]) do options[:object] = namespace T('layout').run(options) end serialize_feature_directories_recursively(namespace.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)}) end end # Generate feature list # @note this method is called automatically by YARD based on the menus defined in the layout def generate_feature_list @features = Registry.all(:feature) generate_full_list @features.sort {|x,y| x.value.to_s <=> y.value.to_s }, :features end # Generate tag list # @note this method is called automatically by YARD based on the menus defined in the layout def generate_tag_list @tags = Registry.all(:tag) generate_full_list @tags.sort {|x,y| y.all_scenarios.size <=> x.all_scenarios.size }, :tags end # Generate a step definition list # @note this menu is not automatically added until yard configuration has this menu added # See the layout template method that loads the menus def generate_stepdefinition_list generate_full_list YARD::Registry.all(:stepdefinition), :stepdefinitions end # Generate a step list # @note this menu is not automatically added until yard configuration has this menu added # See the layout template method that loads the menus def generate_step_list generate_full_list YARD::Registry.all(:step), :steps end # Generate feature list # @note this menu is not automatically added until yard configuration has this menu added # See the layout template method that loads the menus def generate_featuredirectories_list @feature_directories = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) } feature_directories = @feature_directories.sort {|x,y| x.value.to_s <=> y.value.to_s } generate_full_list feature_directories, :featuredirectories, nil, :featuredirectories end # Helpler method to generate a full_list page of the specified objects with the # specified type. def generate_full_list(objects,list_type,friendly_name=nil,asset_name=nil) @items = objects @list_type = list_type @list_title = "#{friendly_name || list_type.to_s.capitalize} List" @list_class = "class" asset_name ||= list_type.to_s.gsub(/s$/,'') asset("#{asset_name}_list.html",erb(:full_list)) end # # The existing 'Class List' search field would normally contain the Cucumber # Namespace object that has been added. Here we call the class_list method # that is contained in the YARD template and we remove the namespace. Returning # it when we are done. # def class_list(root = Registry.root) root.instance_eval { children.delete YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE } if root == Registry.root out = super(root) root.instance_eval { children << YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE } if root == Registry.root out end # # Generate a link to the 'All Features' in the features_list.html # # When there are no feature directories or multiple top-level feature directories # then we want to link to the 'Requirements' page # # When there are is just one feature directory then we want to link to that directory # def all_features_link root_feature_directories = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)} if root_feature_directories.length == 0 || root_feature_directories.length > 1 linkify YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE, "All Features" else linkify root_feature_directories.first, "All Features" end end def directory_node(directory) @directory = directory erb(:directories) end
require 'delayed_job' require 'thinking_sphinx' # Delayed Deltas for Thinking Sphinx, using Delayed Job. # # This documentation is aimed at those reading the code. If you're looking for # a guide to Thinking Sphinx and/or deltas, I recommend you start with the # Thinking Sphinx site instead - or the README for this library at the very # least. # # @author Patrick Allan # @see http://ts.freelancing-gods.com Thinking Sphinx # class ThinkingSphinx::Deltas::DelayedDelta < ThinkingSphinx::Deltas::DefaultDelta def self.cancel_jobs Delayed::Job.delete_all([ "handler LIKE (?) AND locked_at IS NULL AND locked_by IS NULL AND failed_at IS NULL", "--- !ruby/object:ThinkingSphinx::Deltas::%" ]) end def self.enqueue_unless_duplicates(object) if Delayed::Job.respond_to?(:where) return if Delayed::Job.where( :handler => object.to_yaml, :locked_at => nil, :failed_at => nil ).count > 0 else return if Delayed::Job.count( :conditions => {:handler => object.to_yaml, :locked_at => nil, :failed_at => nil} ) > 0 end Delayed::Job.enqueue object, job_options end def self.job_options if Gem.loaded_specs['delayed_job'].version.to_s.match(/^2\.0\./) # Fallback for compatibility with old release 2.0.x of DJ # Only priority option is supported for these versions ThinkingSphinx::Configuration.instance.delayed_job_priority || 0 else { :priority => job_option(:delayed_job_priority, 0), :queue => job_option(:delayed_job_queue) } end end def self.job_option(setting, default = nil) configuration = ThinkingSphinx::Configuration.instance if configuration.respond_to? setting configuration.send(setting) elsif configuration.respond_to? :settings configuration.settings[setting.to_s] || default else default end end module Binary # Adds a job to the queue for processing the given model's delta index. A job # for hiding the instance in the core index is also created, if an instance is # provided. # # Neither job will be queued if updates or deltas are disabled, or if the # instance (when given) is not toggled to be in the delta index. The first two # options are controlled via ThinkingSphinx.updates_enabled? and # ThinkingSphinx.deltas_enabled?. # # @param [Class] model the ActiveRecord model to index. # @param [ActiveRecord::Base] instance the instance of the given model that # has changed. Optional. # @return [Boolean] true # def index(model, instance = nil) return true if skip? instance self.class.enqueue_unless_duplicates( ThinkingSphinx::Deltas::DelayedDelta::DeltaJob.new( model.delta_index_names ) ) Delayed::Job.enqueue( ThinkingSphinx::Deltas::DelayedDelta::FlagAsDeletedJob.new( model.core_index_names, instance.sphinx_document_id ), self.class.job_options ) if instance true end private # Checks whether jobs should be enqueued. Only true if updates and deltas are # enabled, and the instance (if there is one) is toggled. # # @param [ActiveRecord::Base, NilClass] instance # @return [Boolean] # def skip?(instance) !ThinkingSphinx.updates_enabled? || !ThinkingSphinx.deltas_enabled? || (instance && !toggled(instance)) end end module SphinxQL def delete(index, instance) Delayed::Job.enqueue( ThinkingSphinx::Deltas::DelayedDelta::FlagAsDeletedJob.new( index.name, index.document_id_for_key(instance.id) ), self.class.job_options ) end # Adds a job to the queue for processing the given index. # # @param [Class] index the Thinking Sphinx index object. # def index(index) self.class.enqueue_unless_duplicates( ThinkingSphinx::Deltas::DelayedDelta::DeltaJob.new(index.name) ) end end if [:delayed_job_priority, 'delayed_job_priority'].any? { |method| ThinkingSphinx::Configuration.instance_methods.include?(method) } include Binary else include SphinxQL end end require 'thinking_sphinx/deltas/delayed_delta/delta_job' require 'thinking_sphinx/deltas/delayed_delta/flag_as_deleted_job' ThinkingSphinx.before_index_hooks << Proc.new { ThinkingSphinx::Deltas::DelayedDelta.cancel_jobs } added default thinking_sphinx_delayed_delta as queue_name require 'delayed_job' require 'thinking_sphinx' # Delayed Deltas for Thinking Sphinx, using Delayed Job. # # This documentation is aimed at those reading the code. If you're looking for # a guide to Thinking Sphinx and/or deltas, I recommend you start with the # Thinking Sphinx site instead - or the README for this library at the very # least. # # @author Patrick Allan # @see http://ts.freelancing-gods.com Thinking Sphinx # class ThinkingSphinx::Deltas::DelayedDelta < ThinkingSphinx::Deltas::DefaultDelta def self.cancel_jobs Delayed::Job.delete_all([ "handler LIKE (?) AND locked_at IS NULL AND locked_by IS NULL AND failed_at IS NULL", "--- !ruby/object:ThinkingSphinx::Deltas::%" ]) end def self.enqueue_unless_duplicates(object) if Delayed::Job.respond_to?(:where) return if Delayed::Job.where( :handler => object.to_yaml, :locked_at => nil, :failed_at => nil ).count > 0 else return if Delayed::Job.count( :conditions => {:handler => object.to_yaml, :locked_at => nil, :failed_at => nil} ) > 0 end Delayed::Job.enqueue object, job_options end def self.job_options if Gem.loaded_specs['delayed_job'].version.to_s.match(/^2\.0\./) # Fallback for compatibility with old release 2.0.x of DJ # Only priority option is supported for these versions ThinkingSphinx::Configuration.instance.delayed_job_priority || 0 else { :priority => job_option(:delayed_job_priority, 0), :queue => job_option(:delayed_job_queue, 'thinking_sphinx_delayed_delta') } end end def self.job_option(setting, default = nil) configuration = ThinkingSphinx::Configuration.instance if configuration.respond_to? setting configuration.send(setting) elsif configuration.respond_to? :settings configuration.settings[setting.to_s] || default else default end end module Binary # Adds a job to the queue for processing the given model's delta index. A job # for hiding the instance in the core index is also created, if an instance is # provided. # # Neither job will be queued if updates or deltas are disabled, or if the # instance (when given) is not toggled to be in the delta index. The first two # options are controlled via ThinkingSphinx.updates_enabled? and # ThinkingSphinx.deltas_enabled?. # # @param [Class] model the ActiveRecord model to index. # @param [ActiveRecord::Base] instance the instance of the given model that # has changed. Optional. # @return [Boolean] true # def index(model, instance = nil) return true if skip? instance self.class.enqueue_unless_duplicates( ThinkingSphinx::Deltas::DelayedDelta::DeltaJob.new( model.delta_index_names ) ) Delayed::Job.enqueue( ThinkingSphinx::Deltas::DelayedDelta::FlagAsDeletedJob.new( model.core_index_names, instance.sphinx_document_id ), self.class.job_options ) if instance true end private # Checks whether jobs should be enqueued. Only true if updates and deltas are # enabled, and the instance (if there is one) is toggled. # # @param [ActiveRecord::Base, NilClass] instance # @return [Boolean] # def skip?(instance) !ThinkingSphinx.updates_enabled? || !ThinkingSphinx.deltas_enabled? || (instance && !toggled(instance)) end end module SphinxQL def delete(index, instance) Delayed::Job.enqueue( ThinkingSphinx::Deltas::DelayedDelta::FlagAsDeletedJob.new( index.name, index.document_id_for_key(instance.id) ), self.class.job_options ) end # Adds a job to the queue for processing the given index. # # @param [Class] index the Thinking Sphinx index object. # def index(index) self.class.enqueue_unless_duplicates( ThinkingSphinx::Deltas::DelayedDelta::DeltaJob.new(index.name) ) end end if [:delayed_job_priority, 'delayed_job_priority'].any? { |method| ThinkingSphinx::Configuration.instance_methods.include?(method) } include Binary else include SphinxQL end end require 'thinking_sphinx/deltas/delayed_delta/delta_job' require 'thinking_sphinx/deltas/delayed_delta/flag_as_deleted_job' ThinkingSphinx.before_index_hooks << Proc.new { ThinkingSphinx::Deltas::DelayedDelta.cancel_jobs }
module TivoHMO module Adapters module StreamIO # Transcodes video to tivo format using the streamio gem (ffmpeg) class Transcoder include TivoHMO::API::Transcoder include GemLogger::LoggerSupport # TODO: add ability to pass through data (copy codec) # for files that are already (partially?) in the right # format for tivo. Check against a mapping of # tivo serial->allowed_formats # https://code.google.com/p/streambaby/wiki/video_compatibility def transcode(writeable_io, format="video/x-tivo-mpeg") tmpfile = Tempfile.new('tivohmo_transcode') begin transcode_thread = run_transcode(tmpfile.path, format) # give the transcode thread a chance to start up before we # start copying from it. Not strictly necessary, but makes # the log messages show up in the right order sleep 0.1 run_copy(tmpfile.path, writeable_io, transcode_thread) ensure tmpfile.close tmpfile.unlink end nil end def transcoder_options(format="video/x-tivo-mpeg") opts = { video_max_bitrate: 30_000_000, buffer_size: 4096, audio_bitrate: 448_000, format: format, custom: [] } opts = select_video_frame_rate(opts) opts = select_video_dimensions(opts) opts = select_video_codec(opts) opts = select_video_bitrate(opts) opts = select_audio_codec(opts) opts = select_audio_bitrate(opts) opts = select_audio_sample_rate(opts) opts = select_container(opts) opts = select_subtitle(opts) custom = opts.delete(:custom) opts[:custom] = custom.join(" ") if custom opts.delete(:format) opts end protected def movie @movie ||= FFMPEG::Movie.new(item.file) end def video_info @video_info ||= begin info_attrs = %w[ path duration time bitrate rotation creation_time video_stream video_codec video_bitrate colorspace dar audio_stream audio_codec audio_bitrate audio_sample_rate calculated_aspect_ratio size audio_channels frame_rate container resolution width height ] Hash[info_attrs.collect {|attr| [attr.to_sym, movie.send(attr)] }] end end def select_container(opts) if opts[:format] == 'video/x-tivo-mpeg-ts' opts[:custom] << "-f mpegts" else opts[:custom] << "-f vob" end opts end def select_audio_sample_rate(opts) if video_info[:audio_sample_rate] if AUDIO_SAMPLE_RATES.include?(video_info[:audio_sample_rate]) opts[:audio_sample_rate] = video_info[:audio_sample_rate] else opts[:audio_sample_rate] = 48000 end end opts end def select_audio_bitrate(opts) # transcode assumes unit of Kbit, whilst video_info has unit of bit opts[:audio_bitrate] = (opts[:audio_bitrate] / 1000).to_i opts end def select_audio_codec(opts) if video_info[:audio_codec] if AUDIO_CODECS.any? { |ac| video_info[:audio_codec] =~ /#{ac}/ } opts[:audio_codec] = 'copy' if video_info[:video_codec] =~ /mpeg2video/ opts[:custom] << "-copyts" end else opts[:audio_codec] = 'ac3' end end opts end def select_video_bitrate(opts) vbr = video_info[:video_bitrate] default_vbr = 16_384_000 if vbr && vbr > 0 if vbr >= opts[:video_max_bitrate] opts[:video_bitrate] = (opts[:video_max_bitrate] * 0.95).to_i elsif vbr > default_vbr opts[:video_bitrate] = vbr else opts[:video_bitrate] = default_vbr end end opts[:video_bitrate] ||= default_vbr # transcode assumes unit of Kbit, whilst video_info has unit of bit opts[:video_bitrate] = (opts[:video_bitrate] / 1000).to_i opts[:video_max_bitrate] = (opts[:video_max_bitrate] / 1000).to_i opts end def select_video_codec(opts) if VIDEO_CODECS.any? { |vc| video_info[:video_codec] =~ /#{vc}/ } opts[:video_codec] = 'copy' if video_info[:video_codec] =~ /h264/ opts[:custom] << "-bsf h264_mp4toannexb" end else opts[:video_codec] = 'mpeg2video' opts[:custom] << "-pix_fmt yuv420p" end opts end def select_video_dimensions(opts) video_width = video_info[:width].to_i VIDEO_WIDTHS.each do |w| w = w.to_i if video_width >= w video_width = w opts[:preserve_aspect_ratio] = :width break end end video_width = VIDEO_WIDTHS.last.to_i unless video_width video_height = video_info[:height].to_i VIDEO_WIDTHS.each do |h| h = h.to_i if video_height >= h video_height = h opts[:preserve_aspect_ratio] = :height break end end video_height = VIDEO_HEIGHTS.last.to_i unless video_height opts[:resolution] = "#{video_width}x#{video_height}" opts[:preserve_aspect_ratio] ||= :height opts end def select_video_frame_rate(opts) frame_rate = video_info[:frame_rate] if frame_rate =~ /\A[0-9\.]+\Z/ frame_rate = frame_rate.to_f elsif frame_rate =~ /\A\((\d+)\/(\d+)\)\Z/ frame_rate = $1.to_f / $2.to_f end VIDEO_FRAME_RATES.each do |r| opts[:frame_rate] = r break if frame_rate >= r.to_f end opts end def select_subtitle(opts) st = item.subtitle if st case st.type when :file code = st.language_code file = st.location if File.exist?(file) logger.info "Using subtitles present at: #{file}" opts[:custom] << "-vf subtitles=\"#{file}\"" else logger.error "Subtitle doesn't exist at: #{file}" end when :embedded file = item.file idx = st.location logger.info "Using embedded subtitles [#{idx}] present at: #{file}" opts[:custom] << "-vf subtitles=\"#{file}\":si=#{idx}" else logger.error "Unknown subtitle type: #{st.type}" end end opts end def run_transcode(output_filename, format) logger.info "Movie Info: " + video_info.collect {|k, v| "#{k}=#{v.inspect}"}.join(' ') opts = transcoder_options(format) logger.info "Transcoding options: " + opts.collect {|k, v| "#{k}='#{v}'"}.join(' ') aspect_opt = opts.delete(:preserve_aspect_ratio) t_opts = {} t_opts[:preserve_aspect_ratio] = aspect_opt if aspect_opt transcode_thread = Thread.new do begin logger.info "Starting transcode of '#{movie.path}' to '#{output_filename}'" transcoded_movie = movie.transcode(output_filename, opts, t_opts) do |progress| logger.debug ("[%3i%%] Transcoding #{File.basename(movie.path)}" % (progress * 100).to_i) raise "Halted" if Thread.current[:halt] end logger.info "Transcoding completed, transcoded file size: #{File.size(output_filename)}" rescue => e logger.error ("Transcode failed: #{e}") end end return transcode_thread end # we could avoid this if streamio-ffmpeg had a way to output to an IO, but # it only supports file based output for now, so have to manually copy the # file's bytes to our output stream def run_copy(transcoded_filename, writeable_io, transcode_thread) logger.info "Starting stream copy from: #{transcoded_filename}" file = File.open(transcoded_filename, 'rb') begin bytes_copied = 0 # copying the IO from transcoded file to web output # stream is faster than the transcoding, and thus we # hit eof before transcode is done. Therefore we need # to keep retrying while the transcode thread is alive, # then to avoid a race condition at the end, we keep # going till we've copied all the bytes while transcode_thread.alive? || bytes_copied < File.size(transcoded_filename) # sleep a bit at start of thread so we don't have a # wasteful tight loop when transcoding is really slow sleep 0.2 while data = file.read(4096) break unless data.size > 0 writeable_io << data bytes_copied += data.size end end logger.info "Stream copy completed, #{bytes_copied} bytes copied" rescue => e logger.error ("Stream copy failed: #{e}") transcode_thread[:halt] = true ensure file.close end end end end end end fix indent module TivoHMO module Adapters module StreamIO # Transcodes video to tivo format using the streamio gem (ffmpeg) class Transcoder include TivoHMO::API::Transcoder include GemLogger::LoggerSupport # TODO: add ability to pass through data (copy codec) # for files that are already (partially?) in the right # format for tivo. Check against a mapping of # tivo serial->allowed_formats # https://code.google.com/p/streambaby/wiki/video_compatibility def transcode(writeable_io, format="video/x-tivo-mpeg") tmpfile = Tempfile.new('tivohmo_transcode') begin transcode_thread = run_transcode(tmpfile.path, format) # give the transcode thread a chance to start up before we # start copying from it. Not strictly necessary, but makes # the log messages show up in the right order sleep 0.1 run_copy(tmpfile.path, writeable_io, transcode_thread) ensure tmpfile.close tmpfile.unlink end nil end def transcoder_options(format="video/x-tivo-mpeg") opts = { video_max_bitrate: 30_000_000, buffer_size: 4096, audio_bitrate: 448_000, format: format, custom: [] } opts = select_video_frame_rate(opts) opts = select_video_dimensions(opts) opts = select_video_codec(opts) opts = select_video_bitrate(opts) opts = select_audio_codec(opts) opts = select_audio_bitrate(opts) opts = select_audio_sample_rate(opts) opts = select_container(opts) opts = select_subtitle(opts) custom = opts.delete(:custom) opts[:custom] = custom.join(" ") if custom opts.delete(:format) opts end protected def movie @movie ||= FFMPEG::Movie.new(item.file) end def video_info @video_info ||= begin info_attrs = %w[ path duration time bitrate rotation creation_time video_stream video_codec video_bitrate colorspace dar audio_stream audio_codec audio_bitrate audio_sample_rate calculated_aspect_ratio size audio_channels frame_rate container resolution width height ] Hash[info_attrs.collect {|attr| [attr.to_sym, movie.send(attr)] }] end end def select_container(opts) if opts[:format] == 'video/x-tivo-mpeg-ts' opts[:custom] << "-f mpegts" else opts[:custom] << "-f vob" end opts end def select_audio_sample_rate(opts) if video_info[:audio_sample_rate] if AUDIO_SAMPLE_RATES.include?(video_info[:audio_sample_rate]) opts[:audio_sample_rate] = video_info[:audio_sample_rate] else opts[:audio_sample_rate] = 48000 end end opts end def select_audio_bitrate(opts) # transcode assumes unit of Kbit, whilst video_info has unit of bit opts[:audio_bitrate] = (opts[:audio_bitrate] / 1000).to_i opts end def select_audio_codec(opts) if video_info[:audio_codec] if AUDIO_CODECS.any? { |ac| video_info[:audio_codec] =~ /#{ac}/ } opts[:audio_codec] = 'copy' if video_info[:video_codec] =~ /mpeg2video/ opts[:custom] << "-copyts" end else opts[:audio_codec] = 'ac3' end end opts end def select_video_bitrate(opts) vbr = video_info[:video_bitrate] default_vbr = 16_384_000 if vbr && vbr > 0 if vbr >= opts[:video_max_bitrate] opts[:video_bitrate] = (opts[:video_max_bitrate] * 0.95).to_i elsif vbr > default_vbr opts[:video_bitrate] = vbr else opts[:video_bitrate] = default_vbr end end opts[:video_bitrate] ||= default_vbr # transcode assumes unit of Kbit, whilst video_info has unit of bit opts[:video_bitrate] = (opts[:video_bitrate] / 1000).to_i opts[:video_max_bitrate] = (opts[:video_max_bitrate] / 1000).to_i opts end def select_video_codec(opts) if VIDEO_CODECS.any? { |vc| video_info[:video_codec] =~ /#{vc}/ } opts[:video_codec] = 'copy' if video_info[:video_codec] =~ /h264/ opts[:custom] << "-bsf h264_mp4toannexb" end else opts[:video_codec] = 'mpeg2video' opts[:custom] << "-pix_fmt yuv420p" end opts end def select_video_dimensions(opts) video_width = video_info[:width].to_i VIDEO_WIDTHS.each do |w| w = w.to_i if video_width >= w video_width = w opts[:preserve_aspect_ratio] = :width break end end video_width = VIDEO_WIDTHS.last.to_i unless video_width video_height = video_info[:height].to_i VIDEO_WIDTHS.each do |h| h = h.to_i if video_height >= h video_height = h opts[:preserve_aspect_ratio] = :height break end end video_height = VIDEO_HEIGHTS.last.to_i unless video_height opts[:resolution] = "#{video_width}x#{video_height}" opts[:preserve_aspect_ratio] ||= :height opts end def select_video_frame_rate(opts) frame_rate = video_info[:frame_rate] if frame_rate =~ /\A[0-9\.]+\Z/ frame_rate = frame_rate.to_f elsif frame_rate =~ /\A\((\d+)\/(\d+)\)\Z/ frame_rate = $1.to_f / $2.to_f end VIDEO_FRAME_RATES.each do |r| opts[:frame_rate] = r break if frame_rate >= r.to_f end opts end def select_subtitle(opts) st = item.subtitle if st case st.type when :file code = st.language_code file = st.location if File.exist?(file) logger.info "Using subtitles present at: #{file}" opts[:custom] << "-vf subtitles=\"#{file}\"" else logger.error "Subtitle doesn't exist at: #{file}" end when :embedded file = item.file idx = st.location logger.info "Using embedded subtitles [#{idx}] present at: #{file}" opts[:custom] << "-vf subtitles=\"#{file}\":si=#{idx}" else logger.error "Unknown subtitle type: #{st.type}" end end opts end def run_transcode(output_filename, format) logger.info "Movie Info: " + video_info.collect {|k, v| "#{k}=#{v.inspect}"}.join(' ') opts = transcoder_options(format) logger.info "Transcoding options: " + opts.collect {|k, v| "#{k}='#{v}'"}.join(' ') aspect_opt = opts.delete(:preserve_aspect_ratio) t_opts = {} t_opts[:preserve_aspect_ratio] = aspect_opt if aspect_opt transcode_thread = Thread.new do begin logger.info "Starting transcode of '#{movie.path}' to '#{output_filename}'" transcoded_movie = movie.transcode(output_filename, opts, t_opts) do |progress| logger.debug ("[%3i%%] Transcoding #{File.basename(movie.path)}" % (progress * 100).to_i) raise "Halted" if Thread.current[:halt] end logger.info "Transcoding completed, transcoded file size: #{File.size(output_filename)}" rescue => e logger.error ("Transcode failed: #{e}") end end return transcode_thread end # we could avoid this if streamio-ffmpeg had a way to output to an IO, but # it only supports file based output for now, so have to manually copy the # file's bytes to our output stream def run_copy(transcoded_filename, writeable_io, transcode_thread) logger.info "Starting stream copy from: #{transcoded_filename}" file = File.open(transcoded_filename, 'rb') begin bytes_copied = 0 # copying the IO from transcoded file to web output # stream is faster than the transcoding, and thus we # hit eof before transcode is done. Therefore we need # to keep retrying while the transcode thread is alive, # then to avoid a race condition at the end, we keep # going till we've copied all the bytes while transcode_thread.alive? || bytes_copied < File.size(transcoded_filename) # sleep a bit at start of thread so we don't have a # wasteful tight loop when transcoding is really slow sleep 0.2 while data = file.read(4096) break unless data.size > 0 writeable_io << data bytes_copied += data.size end end logger.info "Stream copy completed, #{bytes_copied} bytes copied" rescue => e logger.error ("Stream copy failed: #{e}") transcode_thread[:halt] = true ensure file.close end end end end end end
require 'travis/api/app' class Travis::Api::App module StackInstrumentation class Middleware def initialize(app, title = nil) @app = app @title = title || "Rack: use #{app.class.name}" end def call(env) instrument { @app.call(env) } end def instrument(&block) return yield unless instrument? ::Skylight.instrument(title: title, &block) end def instrument? defined? ::Skylight end end def use(*) super(Middleware) super end def run(app) super Middleware.new(app, "Rack: run %p" % app.class) end def map(path, &block) super(path) do use(Middleware, "Rack: map %p" % path) extend StackInstrumentation instance_eval(&block) end end end end fix typo require 'travis/api/app' class Travis::Api::App module StackInstrumentation class Middleware def initialize(app, title = nil) @app = app @title = title || "Rack: use #{app.class.name}" end def call(env) instrument { @app.call(env) } end def instrument(&block) return yield unless instrument? ::Skylight.instrument(title: @title, &block) end def instrument? defined? ::Skylight end end def use(*) super(Middleware) super end def run(app) super Middleware.new(app, "Rack: run %p" % app.class) end def map(path, &block) super(path) do use(Middleware, "Rack: map %p" % path) extend StackInstrumentation instance_eval(&block) end end end end
require_relative '../../../extensions/matcher' module Tritium module Engines class Standard < Base module BaseFunctions def base_invocation(ins, ctx, args, kwds) case ins.name when :var @env[args.first] when :match @matchers.push(args.first) run_children(ins, ctx) @matchers.pop when :not regex = Regexp.new(args.first) regex.opposite = true return regex when :with matcher = @matchers.last with = args.first with = Regexp.new(with) unless with.is_a?(Regexp) if with.match?(matcher) run_children(ins, ctx) return false # signal to stop! end when :dump return ctx.value.to_s else throw "Method #{ins.name} not implemented in Base scope" end end end end end end Implement debug() #ignore it require_relative '../../../extensions/matcher' module Tritium module Engines class Standard < Base module BaseFunctions def base_invocation(ins, ctx, args, kwds) case ins.name when :var @env[args.first] when :match @matchers.push(args.first) run_children(ins, ctx) @matchers.pop when :not regex = Regexp.new(args.first) regex.opposite = true return regex when :with matcher = @matchers.last with = args.first with = Regexp.new(with) unless with.is_a?(Regexp) if with.match?(matcher) run_children(ins, ctx) return false # signal to stop! end when :dump return ctx.value.to_s when :debug # Ignore this run_children(ins, ctx) else throw "Method #{ins.name} not implemented in Base scope" end end end end end end
# ReportingCloud Ruby Wrapper # # Official wrapper (authored by Text Control GmbH, publisher of ReportingCloud) to access # ReportingCloud in Ruby. # # Go to http://www.reporting.cloud to learn more about ReportingCloud # Go to https://github.com/TextControl/txtextcontrol-reportingcloud-ruby for the # canonical source repository. # # License: https://raw.githubusercontent.com/TextControl/txtextcontrol-reportingcloud-ruby/master/LICENSE.md # # Copyright: © 2016 Text Control GmbH module TXTextControl module ReportingCloud VERSION = "0.1.0" end end Changing version to 1.0.0 # ReportingCloud Ruby Wrapper # # Official wrapper (authored by Text Control GmbH, publisher of ReportingCloud) to access # ReportingCloud in Ruby. # # Go to http://www.reporting.cloud to learn more about ReportingCloud # Go to https://github.com/TextControl/txtextcontrol-reportingcloud-ruby for the # canonical source repository. # # License: https://raw.githubusercontent.com/TextControl/txtextcontrol-reportingcloud-ruby/master/LICENSE.md # # Copyright: © 2016 Text Control GmbH module TXTextControl module ReportingCloud VERSION = "1.0.0" end end
require 'rails/generators' module Typekit module Generators class InstallGenerator < ::Rails::Generators::Base desc 'Inject Typekit helpers into application code' def inject_javascript application_js_path = 'app/assets/javascripts/application.js' if ::File.exists?(::File.join(destination_root, application_js_path)) inject_into_file application_js_path, before: '//= require_tree' do "//= require typekit\n" end end end # def inject_view_helper # application_controller_path = 'app/controllers/application_controller.rb' # if ::File.exists?(::File.join(destination_root, application_controller_path)) # inject_into_file application_controller_path, after: "class ApplicationController < ActionController::Base\n" do # " helper :typekit\n" # end # end # end def inject_into_layout application_layout_path_prefix = 'app/views/layouts/application.html' api_key = ask 'What is your kit ID (leave blank to specify later):' api_key = '- YOUR KIT ID HERE -' if api_key.blank? layout_templates = { slim: { content: " = typekit '#{api_key}'", after: "head\n" }} layout_templates[:erb] = { content: " <%#{layout_templates[:slim][:content]} %>", after: "<head>\n" } layout_templates.each_pair do |lang,options| path = ::File.join(destination_root, "#{application_layout_path_prefix}.#{lang}") if ::File.exists?(path) inject_into_file path, after: options[:after] do "#{options[:content]}\n" end end end end end end end erb generator require 'rails/generators' module Typekit module Generators class InstallGenerator < ::Rails::Generators::Base desc 'Inject Typekit helpers into application code' def inject_javascript application_js_path = 'app/assets/javascripts/application.js' if ::File.exists?(::File.join(destination_root, application_js_path)) inject_into_file application_js_path, before: '//= require_tree' do "//= require typekit\n" end end end # def inject_view_helper # application_controller_path = 'app/controllers/application_controller.rb' # if ::File.exists?(::File.join(destination_root, application_controller_path)) # inject_into_file application_controller_path, after: "class ApplicationController < ActionController::Base\n" do # " helper :typekit\n" # end # end # end def inject_into_layout application_layout_path_prefix = 'app/views/layouts/application.html' api_key = ask 'What is your kit ID (leave blank to specify later):' api_key = '- YOUR KIT ID HERE -' if api_key.blank? layout_templates = { slim: { content: " = typekit '#{api_key}'", after: "head\n" }} layout_templates[:erb] = { content: " <%#{layout_templates[:slim][:content].lstrip} %>", after: "<head>\n" } layout_templates.each_pair do |lang,options| path = ::File.join(destination_root, "#{application_layout_path_prefix}.#{lang}") if ::File.exists?(path) inject_into_file path, after: options[:after] do "#{options[:content]}\n" end end end end end end end
require 'vagrant-simplecloud/helpers/client' module VagrantPlugins module SimpleCloud module Actions class PowerOn include Helpers::Client def initialize(app, env) @app = app @machine = env[:machine] @client = client @simple_client = simple_client @logger = Log4r::Logger.new('vagrant::simplecloud::power_on') end def call(env) # submit power on droplet request result = JSON.parse(@simple_client.droplet_actions.power_on(droplet_id: @machine.id.to_s)) #result = @client.post("/v2/droplets/#{@machine.id}/actions", { #:type => 'power_on' #}) # wait for request to complete env[:ui].info I18n.t('vagrant_simple_cloud.info.powering_on') @client.wait_for_event(env, result['action']['id']) # refresh droplet state with provider Provider.droplet(@machine, :refresh => true) @app.call(env) end end end end end fix power_on require 'vagrant-simplecloud/helpers/client' module VagrantPlugins module SimpleCloud module Actions class PowerOn include Helpers::Client def initialize(app, env) @app = app @machine = env[:machine] @client = client @simple_client = simple_client @logger = Log4r::Logger.new('vagrant::simplecloud::power_on') end def call(env) # submit power on droplet request result = @simple_client.post("/v2/droplets/#{@machine.id}/actions", {:type => 'power_on'}) # wait for request to complete env[:ui].info I18n.t('vagrant_simple_cloud.info.powering_on') @client.wait_for_event(env, result['action']['id']) # refresh droplet state with provider Provider.droplet(@machine, :refresh => true) @app.call(env) end end end end end
Add POSIX capability parent module for documentation purposes # Here for documentation purposes only module VagrantPlugins module AnsibleAuto # Capabilities on guests and hosts module Cap # Capabilities on guests module Guest # Capabilities on POSIX hosts module POSIX end end end end end
require 'vagrant/smartos/zones/models/zone_user' require 'vagrant/smartos/zones/util/global_zone/helper' require 'vagrant/smartos/zones/util/public_key' module Vagrant module Smartos module Zones module Util class ZoneUser include GlobalZone::Helper attr_reader :machine, :zone def initialize(machine, zone) @machine = machine @zone = zone end def find(username) Models::ZoneUser.new.tap do |u| u.name = username machine.communicate.gz_execute("#{sudo} zlogin #{zone.uuid} id -u #{username}") do |_type, output| u.uid = output.chomp end end end def create(username, group, role = nil) zlogin(zone, "useradd #{flags(group)} #{username}") grant_role(username, role) install_public_key(group) end private def flags(group) return "-m -s /bin/bash -g #{group}" if zone.lx_brand? "-m -s /bin/bash -G #{group}" end def grant_role(username, role) if zone.lx_brand? return if zlogin_test(zone, %('test -f /etc/sudoers.d/vagrant')) zlogin(zone, %('echo "#{username} ALL=(ALL:ALL) ALL" >> /etc/sudoers.d/vagrant')) else zlogin(zone, "usermod -P\\'#{role}\\' #{username}") if role zlogin(zone, 'cp /opt/local/etc/sudoers.d/admin /opt/local/etc/sudoers.d/vagrant') zlogin(zone, 'sed -i -e \\\'s@admin@vagrant@\\\' /opt/local/etc/sudoers.d/vagrant') end end def install_public_key(group) zlogin(zone, 'mkdir -p /home/vagrant/.ssh') zlogin(zone, 'touch /home/vagrant/.ssh/authorized_keys') zlogin(zone, %('echo "#{PublicKey.new}" > /home/vagrant/.ssh/authorized_keys')) zlogin(zone, "chown -R vagrant:#{group} /home/vagrant/.ssh") zlogin(zone, 'chmod 600 /home/vagrant/.ssh/authorized_keys') end end end end end end vagrant user in lx zones get passwordless sudo - [refs #12] require 'vagrant/smartos/zones/models/zone_user' require 'vagrant/smartos/zones/util/global_zone/helper' require 'vagrant/smartos/zones/util/public_key' module Vagrant module Smartos module Zones module Util class ZoneUser include GlobalZone::Helper attr_reader :machine, :zone def initialize(machine, zone) @machine = machine @zone = zone end def find(username) Models::ZoneUser.new.tap do |u| u.name = username machine.communicate.gz_execute("#{sudo} zlogin #{zone.uuid} id -u #{username}") do |_type, output| u.uid = output.chomp end end end def create(username, group, role = nil) zlogin(zone, "useradd #{flags(group)} #{username}") grant_role(username, role) install_public_key(group) end private def flags(group) return "-m -s /bin/bash -g #{group}" if zone.lx_brand? "-m -s /bin/bash -G #{group}" end def grant_role(username, role) if zone.lx_brand? return if zlogin_test(zone, %('test -f /etc/sudoers.d/vagrant')) zlogin(zone, %('echo "#{username} ALL=(ALL:ALL) NOPASSWD:ALL" >> /etc/sudoers.d/vagrant')) else zlogin(zone, "usermod -P\\'#{role}\\' #{username}") if role zlogin(zone, 'cp /opt/local/etc/sudoers.d/admin /opt/local/etc/sudoers.d/vagrant') zlogin(zone, 'sed -i -e \\\'s@admin@vagrant@\\\' /opt/local/etc/sudoers.d/vagrant') end end def install_public_key(group) zlogin(zone, 'mkdir -p /home/vagrant/.ssh') zlogin(zone, 'touch /home/vagrant/.ssh/authorized_keys') zlogin(zone, %('echo "#{PublicKey.new}" > /home/vagrant/.ssh/authorized_keys')) zlogin(zone, "chown -R vagrant:#{group} /home/vagrant/.ssh") zlogin(zone, 'chmod 600 /home/vagrant/.ssh/authorized_keys') end end end end end end
module Veritas module SQL module Compiler class Generator < Visitor # Generates an SQL statement for a logic expression module Logic include Attribute include Literal EQUAL_TO = ' = '.freeze EQUAL_TO_NULL = ' IS '.freeze NOT_EQUAL_TO = ' <> '.freeze NOT_EQUAL_TO_NULL = ' IS NOT '.freeze GREATER_THAN = ' > '.freeze GREATER_THAN_OR_EQUAL_TO = ' >= '.freeze LESS_THAN = ' < '.freeze LESS_THAN_OR_EQUAL_TO = ' <= '.freeze IN = ' IN '.freeze NOT_IN = ' NOT IN '.freeze BETWEEN = ' BETWEEN '.freeze NOT_BETWEEN = ' NOT BETWEEN '.freeze AND = ' AND '.freeze OR = ' OR '.freeze MATCH_ALL = '1 = 1'.freeze MATCH_NONE = '1 = 0'.freeze EMPTY_ARRAY = [].freeze # Visit an Equality predicate # # @param [Logic::Predicate::Equality] equality # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_equality(equality) binary_operation_sql(equality.right.nil? ? EQUAL_TO_NULL : EQUAL_TO, equality) end # Visit an Inequality predicate # # @param [Logic::Predicate::Inequality] inequality # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_inequality(inequality) expressions = inequality_expressions(inequality) if expressions.one? expressions.first else "(#{expressions.join(OR)})" end end # Visit an GreaterThan predicate # # @param [Logic::Predicate::GreaterThan] greater_than # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_greater_than(greater_than) binary_operation_sql(GREATER_THAN, greater_than) end # Visit an GreaterThanOrEqualTo predicate # # @param [Logic::Predicate::GreaterThanOrEqualTo] greater_than_or_equal_to # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_greater_than_or_equal_to(greater_than_or_equal_to) binary_operation_sql(GREATER_THAN_OR_EQUAL_TO, greater_than_or_equal_to) end # Visit an LessThan predicate # # @param [Logic::Predicate::LessThan] less_than # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_less_than(less_than) binary_operation_sql(LESS_THAN, less_than) end # Visit an LessThanOrEqualTo predicate # # @param [Logic::Predicate::LessThanOrEqualTo] less_than_or_equal_to # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_less_than_or_equal_to(less_than_or_equal_to) binary_operation_sql(LESS_THAN_OR_EQUAL_TO, less_than_or_equal_to) end # Visit an Inclusion predicate # # @param [Logic::Predicate::Inclusion] inclusion # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_inclusion(inclusion) case inclusion.right when Range then range_inclusion_sql(inclusion) when EMPTY_ARRAY then MATCH_NONE else binary_operation_sql(IN, inclusion) end end # Visit an Exclusion predicate # # @param [Logic::Predicate::Exclusion] exclusion # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_exclusion(exclusion) case exclusion.right when Range then range_exclusion_sql(exclusion) when EMPTY_ARRAY then MATCH_ALL else binary_operation_sql(NOT_IN, exclusion) end end # Visit an Conjunction connective # # @param [Logic::Connective::Conjunction] conjunction # # @return [#to_s] # # @api private def visit_veritas_logic_connective_conjunction(conjunction) binary_connective_sql(AND, conjunction) end # Visit an Disjunction connective # # @param [Logic::Connective::Disjunction] disjunction # # @return [#to_s] # # @api private def visit_veritas_logic_connective_disjunction(disjunction) binary_connective_sql(OR, disjunction) end # Visit an Negation connective # # @param [Logic::Connective::Negation] negation # # @return [#to_s] # # @api private def visit_veritas_logic_connective_negation(negation) "NOT #{dispatch negation.operand}" end private # Return the SQL for an Inclusion using a Range # # @param [Logic::Predicate::Inclusion] predicate # # @return [#to_s] # # @api private def range_inclusion_sql(inclusion) if inclusion.right.exclude_end? exclusive_range_inclusion_sql(inclusion) else inclusive_range_sql(BETWEEN, inclusion) end end # Return the SQL for an Exclusion using a Range # # @param [Logic::Predicate::Exclusion] exclusion # # @return [#to_s] # # @api private def range_exclusion_sql(exclusion) if exclusion.right.exclude_end? exclusive_range_exclusion_sql(exclusion) else inclusive_range_sql(NOT_BETWEEN, exclusion) end end # Return the SQL for an Inclusion using an exclusive Range # # @param [Logic::Predicate::Inclusion] inclusion # # @return [#to_s] # # @api private def exclusive_range_inclusion_sql(inclusion) left = new_from_enumerable_predicate(Veritas::Logic::Predicate::GreaterThanOrEqualTo, inclusion, :first) right = new_from_enumerable_predicate(Veritas::Logic::Predicate::LessThan, inclusion, :last) dispatch left.and(right) end # Return the SQL for an Exclusion using an exclusive Range # # @param [Logic::Predicate::Exclusion] exclusion # # @return [#to_s] # # @api private def exclusive_range_exclusion_sql(exclusion) left = new_from_enumerable_predicate(Veritas::Logic::Predicate::LessThan, exclusion, :first) right = new_from_enumerable_predicate(Veritas::Logic::Predicate::GreaterThanOrEqualTo, exclusion, :last) dispatch left.or(right) end # Instantiate a new Predicate object from an Enumerable Predicate # # @param [Class<Logic::Predicate>] klass # the type of predicate to create # @param [Logic::Predicate::Enumerable] predicate # the enumerable predicate # @param [Symbol] method # the method to call on the right operand of the predicate # @return [Logic::Predicate] # # @api private def new_from_enumerable_predicate(klass, predicate, method) klass.new(predicate.left, predicate.right.send(method)) end # Return the expressions for an inequality # # @param [Logic::Predicate::Inequality] inequality # # @return [Array<#to_s>] # # @api private def inequality_expressions(inequality) expressions = [ inequality_sql(inequality), optional_is_null_sql(inequality.left), optional_is_null_sql(inequality.right), ] expressions.compact! expressions end # Return the SQL for an inequality predicate # # @param [Logic::Predicate::Inequality] inequality # # @return [#to_s] # # @api private def inequality_sql(inequality) binary_operation_sql(inequality.right.nil? ? NOT_EQUAL_TO_NULL : NOT_EQUAL_TO, inequality) end # Return the SQL for a Binary Connective # # @param [#to_s] operator # # @param [Logic::Connective::Binary] binary_connective # # @return [#to_s] # # @api private def binary_connective_sql(operator, binary_connective) "(#{binary_operation_sql(operator, binary_connective)})" end # Return the SQL for a predicate # # @param [#to_s] operator # # @param [Logic::Predicate] predicate # # @return [#to_s] # # @api private def binary_operation_sql(operator, predicate) "#{dispatch(predicate.left)}#{operator}#{dispatch(predicate.right)}" end # Return the SQL for an operation using an inclusive Range # # @param [#to_s] operator # # @param [Logic::Predicate::Enumerable] predicate # # @return [#to_s] # # @api private def inclusive_range_sql(operator, predicate) right = predicate.right "#{dispatch(predicate.left)}#{operator}#{dispatch(right.first)}#{AND}#{dispatch(right.last)}" end # Return SQL for an Equality with a nil value for optional attributes # # @param [Attribute] attribute # # @return [#to_sql, nil] # # @api private def optional_is_null_sql(attribute) dispatch(attribute.eq(nil)) if optional?(attribute) end # Test if the object is not required # # @param [Object] operand # # @return [Boolean] # # @api private def optional?(operand) operand.respond_to?(:required?) && !operand.required? end end # module Logic end # class Generator end # module Compiler end # module SQL end # module Veritas Minor simplification of Logic#visit_veritas_logic_predicate_inequality module Veritas module SQL module Compiler class Generator < Visitor # Generates an SQL statement for a logic expression module Logic include Attribute include Literal EQUAL_TO = ' = '.freeze EQUAL_TO_NULL = ' IS '.freeze NOT_EQUAL_TO = ' <> '.freeze NOT_EQUAL_TO_NULL = ' IS NOT '.freeze GREATER_THAN = ' > '.freeze GREATER_THAN_OR_EQUAL_TO = ' >= '.freeze LESS_THAN = ' < '.freeze LESS_THAN_OR_EQUAL_TO = ' <= '.freeze IN = ' IN '.freeze NOT_IN = ' NOT IN '.freeze BETWEEN = ' BETWEEN '.freeze NOT_BETWEEN = ' NOT BETWEEN '.freeze AND = ' AND '.freeze OR = ' OR '.freeze MATCH_ALL = '1 = 1'.freeze MATCH_NONE = '1 = 0'.freeze EMPTY_ARRAY = [].freeze # Visit an Equality predicate # # @param [Logic::Predicate::Equality] equality # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_equality(equality) binary_operation_sql(equality.right.nil? ? EQUAL_TO_NULL : EQUAL_TO, equality) end # Visit an Inequality predicate # # @param [Logic::Predicate::Inequality] inequality # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_inequality(inequality) expressions = inequality_expressions(inequality) expressions.one? ? expressions.first : "(#{expressions.join(OR)})" end # Visit an GreaterThan predicate # # @param [Logic::Predicate::GreaterThan] greater_than # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_greater_than(greater_than) binary_operation_sql(GREATER_THAN, greater_than) end # Visit an GreaterThanOrEqualTo predicate # # @param [Logic::Predicate::GreaterThanOrEqualTo] greater_than_or_equal_to # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_greater_than_or_equal_to(greater_than_or_equal_to) binary_operation_sql(GREATER_THAN_OR_EQUAL_TO, greater_than_or_equal_to) end # Visit an LessThan predicate # # @param [Logic::Predicate::LessThan] less_than # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_less_than(less_than) binary_operation_sql(LESS_THAN, less_than) end # Visit an LessThanOrEqualTo predicate # # @param [Logic::Predicate::LessThanOrEqualTo] less_than_or_equal_to # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_less_than_or_equal_to(less_than_or_equal_to) binary_operation_sql(LESS_THAN_OR_EQUAL_TO, less_than_or_equal_to) end # Visit an Inclusion predicate # # @param [Logic::Predicate::Inclusion] inclusion # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_inclusion(inclusion) case inclusion.right when Range then range_inclusion_sql(inclusion) when EMPTY_ARRAY then MATCH_NONE else binary_operation_sql(IN, inclusion) end end # Visit an Exclusion predicate # # @param [Logic::Predicate::Exclusion] exclusion # # @return [#to_s] # # @api private def visit_veritas_logic_predicate_exclusion(exclusion) case exclusion.right when Range then range_exclusion_sql(exclusion) when EMPTY_ARRAY then MATCH_ALL else binary_operation_sql(NOT_IN, exclusion) end end # Visit an Conjunction connective # # @param [Logic::Connective::Conjunction] conjunction # # @return [#to_s] # # @api private def visit_veritas_logic_connective_conjunction(conjunction) binary_connective_sql(AND, conjunction) end # Visit an Disjunction connective # # @param [Logic::Connective::Disjunction] disjunction # # @return [#to_s] # # @api private def visit_veritas_logic_connective_disjunction(disjunction) binary_connective_sql(OR, disjunction) end # Visit an Negation connective # # @param [Logic::Connective::Negation] negation # # @return [#to_s] # # @api private def visit_veritas_logic_connective_negation(negation) "NOT #{dispatch negation.operand}" end private # Return the SQL for an Inclusion using a Range # # @param [Logic::Predicate::Inclusion] predicate # # @return [#to_s] # # @api private def range_inclusion_sql(inclusion) if inclusion.right.exclude_end? exclusive_range_inclusion_sql(inclusion) else inclusive_range_sql(BETWEEN, inclusion) end end # Return the SQL for an Exclusion using a Range # # @param [Logic::Predicate::Exclusion] exclusion # # @return [#to_s] # # @api private def range_exclusion_sql(exclusion) if exclusion.right.exclude_end? exclusive_range_exclusion_sql(exclusion) else inclusive_range_sql(NOT_BETWEEN, exclusion) end end # Return the SQL for an Inclusion using an exclusive Range # # @param [Logic::Predicate::Inclusion] inclusion # # @return [#to_s] # # @api private def exclusive_range_inclusion_sql(inclusion) left = new_from_enumerable_predicate(Veritas::Logic::Predicate::GreaterThanOrEqualTo, inclusion, :first) right = new_from_enumerable_predicate(Veritas::Logic::Predicate::LessThan, inclusion, :last) dispatch left.and(right) end # Return the SQL for an Exclusion using an exclusive Range # # @param [Logic::Predicate::Exclusion] exclusion # # @return [#to_s] # # @api private def exclusive_range_exclusion_sql(exclusion) left = new_from_enumerable_predicate(Veritas::Logic::Predicate::LessThan, exclusion, :first) right = new_from_enumerable_predicate(Veritas::Logic::Predicate::GreaterThanOrEqualTo, exclusion, :last) dispatch left.or(right) end # Instantiate a new Predicate object from an Enumerable Predicate # # @param [Class<Logic::Predicate>] klass # the type of predicate to create # @param [Logic::Predicate::Enumerable] predicate # the enumerable predicate # @param [Symbol] method # the method to call on the right operand of the predicate # @return [Logic::Predicate] # # @api private def new_from_enumerable_predicate(klass, predicate, method) klass.new(predicate.left, predicate.right.send(method)) end # Return the expressions for an inequality # # @param [Logic::Predicate::Inequality] inequality # # @return [Array<#to_s>] # # @api private def inequality_expressions(inequality) expressions = [ inequality_sql(inequality), optional_is_null_sql(inequality.left), optional_is_null_sql(inequality.right), ] expressions.compact! expressions end # Return the SQL for an inequality predicate # # @param [Logic::Predicate::Inequality] inequality # # @return [#to_s] # # @api private def inequality_sql(inequality) binary_operation_sql(inequality.right.nil? ? NOT_EQUAL_TO_NULL : NOT_EQUAL_TO, inequality) end # Return the SQL for a Binary Connective # # @param [#to_s] operator # # @param [Logic::Connective::Binary] binary_connective # # @return [#to_s] # # @api private def binary_connective_sql(operator, binary_connective) "(#{binary_operation_sql(operator, binary_connective)})" end # Return the SQL for a predicate # # @param [#to_s] operator # # @param [Logic::Predicate] predicate # # @return [#to_s] # # @api private def binary_operation_sql(operator, predicate) "#{dispatch(predicate.left)}#{operator}#{dispatch(predicate.right)}" end # Return the SQL for an operation using an inclusive Range # # @param [#to_s] operator # # @param [Logic::Predicate::Enumerable] predicate # # @return [#to_s] # # @api private def inclusive_range_sql(operator, predicate) right = predicate.right "#{dispatch(predicate.left)}#{operator}#{dispatch(right.first)}#{AND}#{dispatch(right.last)}" end # Return SQL for an Equality with a nil value for optional attributes # # @param [Attribute] attribute # # @return [#to_sql, nil] # # @api private def optional_is_null_sql(attribute) dispatch(attribute.eq(nil)) if optional?(attribute) end # Test if the object is not required # # @param [Object] operand # # @return [Boolean] # # @api private def optional?(operand) operand.respond_to?(:required?) && !operand.required? end end # module Logic end # class Generator end # module Compiler end # module SQL end # module Veritas
module Xcodeproj class Project module Object class PBXBuildFile < AbstractPBXObject # [Hash] the list of build settings for this file attribute :settings has_one :file, :uuid => :file_ref end class PBXBuildPhase < AbstractPBXObject has_many :build_files, :uuids => :file_references #, :class => PBXBuildFile # [String] some kind of magic number which seems to always be '2147483647' attribute :build_action_mask # [String] wether or not this should only be processed before deployment # (I guess). This cane be either '0', or '1' attribute :run_only_for_deployment_postprocessing def initialize(*) super self.file_references ||= [] # These are always the same, no idea what they are. self.build_action_mask ||= "2147483647" self.run_only_for_deployment_postprocessing ||= "0" end def files PBXObjectList.new(PBXFileReference, @project) do |list| list.let(:uuid_scope) { self.build_files.map(&:file_ref) } list.let(:push) do |file| self.build_files << file.build_files.new end end end def <<(file) files << file end end class PBXCopyFilesBuildPhase < PBXBuildPhase # [String] the path where this file should be copied to attribute :dst_path # [String] a magic number which always seems to be "16" attribute :dst_subfolder_spec def initialize(*) super self.dst_path ||= '$(PRODUCT_NAME)' self.dst_subfolder_spec ||= "16" end end class PBXSourcesBuildPhase < PBXBuildPhase; end class PBXFrameworksBuildPhase < PBXBuildPhase; end # @todo Should `files`, `input_paths`, and `output_paths` be has_many # associations with file references? class PBXShellScriptBuildPhase < PBXBuildPhase attribute :name attribute :files attribute :input_paths attribute :output_paths # [String] The path to the script interpreter. Defaults to `/bin/sh`. attribute :shell_path # [String] The actual script to perform. attribute :shell_script def initialize(*) super self.files ||= [] self.input_paths ||= [] self.output_paths ||= [] self.shell_path ||= '/bin/sh' self.shell_script ||= '' end end end end end Small cleanup. module Xcodeproj class Project module Object class PBXBuildFile < AbstractPBXObject # [Hash] the list of build settings for this file attribute :settings has_one :file, :uuid => :file_ref end class PBXBuildPhase < AbstractPBXObject has_many :build_files, :uuids => :file_references # [String] some kind of magic number which seems to always be '2147483647' attribute :build_action_mask # [String] wether or not this should only be processed before deployment # (I guess). This cane be either '0', or '1' attribute :run_only_for_deployment_postprocessing def initialize(*) super self.file_references ||= [] # These are always the same, no idea what they are. self.build_action_mask ||= "2147483647" self.run_only_for_deployment_postprocessing ||= "0" end def files PBXObjectList.new(PBXFileReference, @project) do |list| list.let(:uuid_scope) { self.build_files.map(&:file_ref) } list.let(:push) do |file| self.build_files << file.build_files.new end end end def <<(file) files << file end end class PBXCopyFilesBuildPhase < PBXBuildPhase # [String] the path where this file should be copied to attribute :dst_path # [String] a magic number which always seems to be "16" attribute :dst_subfolder_spec def initialize(*) super self.dst_path ||= '$(PRODUCT_NAME)' self.dst_subfolder_spec ||= "16" end end class PBXSourcesBuildPhase < PBXBuildPhase; end class PBXFrameworksBuildPhase < PBXBuildPhase; end # @todo Should `files`, `input_paths`, and `output_paths` be has_many # associations with file references? class PBXShellScriptBuildPhase < PBXBuildPhase attribute :name attribute :files attribute :input_paths attribute :output_paths # [String] The path to the script interpreter. Defaults to `/bin/sh`. attribute :shell_path # [String] The actual script to perform. attribute :shell_script def initialize(*) super self.files ||= [] self.input_paths ||= [] self.output_paths ||= [] self.shell_path ||= '/bin/sh' self.shell_script ||= '' end end end end end
# Handles +attr_*+ statements in modules/classes class YARD::Handlers::Ruby::AttributeHandler < YARD::Handlers::Ruby::Base handles method_call(:attr) handles method_call(:attr_reader) handles method_call(:attr_writer) handles method_call(:attr_accessor) namespace_only process do return if statement.type == :var_ref || statement.type == :vcall read, write = true, false params = statement.parameters(false).dup # Change read/write based on attr_reader/writer/accessor case statement.method_name(true) when :attr # In the case of 'attr', the second parameter (if given) isn't a symbol. if params.size == 2 write = true if params.pop == s(:var_ref, s(:kw, "true")) end when :attr_accessor write = true when :attr_reader # change nothing when :attr_writer read, write = false, true end # Add all attributes validated_attribute_names(params).each do |name| namespace.attributes[scope][name] ||= SymbolHash[:read => nil, :write => nil] # Show their methods as well {:read => name, :write => "#{name}="}.each do |type, meth| if (type == :read ? read : write) namespace.attributes[scope][name][type] = MethodObject.new(namespace, meth, scope) do |o| if type == :write o.parameters = [['value', nil]] src = "def #{meth}(value)" full_src = "#{src}\n @#{name} = value\nend" doc = "Sets the attribute #{name}\n@param value the value to set the attribute #{name} to." else src = "def #{meth}" full_src = "#{src}\n @#{name}\nend" doc = "Returns the value of attribute #{name}" end o.source ||= full_src o.signature ||= src o.docstring = statement.comments.to_s.empty? ? doc : statement.comments o.visibility = visibility end # Register the objects explicitly register namespace.attributes[scope][name][type] elsif obj = namespace.children.find {|o| o.name == meth.to_sym && o.scope == scope } # register an existing method as attribute namespace.attributes[scope][name][type] = obj end end end end protected # Strips out any non-essential arguments from the attr statement. # # @param [Array<Parser::Ruby::AstNode>] params a list of the parameters # in the attr call. # @return [Array<String>] the validated attribute names # @raise [Parser::UndocumentableError] if the arguments are not valid. def validated_attribute_names(params) params.map do |obj| case obj.type when :symbol_literal obj.jump(:ident, :op, :kw, :const).source when :string_literal obj.jump(:string_content).source else raise YARD::Parser::UndocumentableError, obj.source end end end end Refactor attribute handler to handle the fact that statement.comments might be filled with directives but no docstring data # Handles +attr_*+ statements in modules/classes class YARD::Handlers::Ruby::AttributeHandler < YARD::Handlers::Ruby::Base handles method_call(:attr) handles method_call(:attr_reader) handles method_call(:attr_writer) handles method_call(:attr_accessor) namespace_only process do return if statement.type == :var_ref || statement.type == :vcall read, write = true, false params = statement.parameters(false).dup # Change read/write based on attr_reader/writer/accessor case statement.method_name(true) when :attr # In the case of 'attr', the second parameter (if given) isn't a symbol. if params.size == 2 write = true if params.pop == s(:var_ref, s(:kw, "true")) end when :attr_accessor write = true when :attr_reader # change nothing when :attr_writer read, write = false, true end # Add all attributes validated_attribute_names(params).each do |name| namespace.attributes[scope][name] ||= SymbolHash[:read => nil, :write => nil] # Show their methods as well {:read => name, :write => "#{name}="}.each do |type, meth| if (type == :read ? read : write) o = MethodObject.new(namespace, meth, scope) if type == :write o.parameters = [['value', nil]] src = "def #{meth}(value)" full_src = "#{src}\n @#{name} = value\nend" doc = "Sets the attribute #{name}\n@param value the value to set the attribute #{name} to." else src = "def #{meth}" full_src = "#{src}\n @#{name}\nend" doc = "Returns the value of attribute #{name}" end o.source ||= full_src o.signature ||= src register(o) if Docstring.new(statement.comments.to_s).blank?(false) o.docstring = doc end o.visibility = visibility # Regsiter the object explicitly namespace.attributes[scope][name][type] = o elsif obj = namespace.children.find {|o| o.name == meth.to_sym && o.scope == scope } # register an existing method as attribute namespace.attributes[scope][name][type] = obj end end end end protected # Strips out any non-essential arguments from the attr statement. # # @param [Array<Parser::Ruby::AstNode>] params a list of the parameters # in the attr call. # @return [Array<String>] the validated attribute names # @raise [Parser::UndocumentableError] if the arguments are not valid. def validated_attribute_names(params) params.map do |obj| case obj.type when :symbol_literal obj.jump(:ident, :op, :kw, :const).source when :string_literal obj.jump(:string_content).source else raise YARD::Parser::UndocumentableError, obj.source end end end end
require 'yummydata/http_helper' module Yummydata module Criteria module LinkedDataRules include Yummydata::HTTPHelper def prepare(uri) @client = SPARQL::Client.new(uri, {'read_timeout': 5 * 60}) if @uri == uri && @client == nil @uri = uri end def uri_subject?(uri) self.prepare(uri) sparql_query = <<-'SPARQL' SELECT * WHERE { GRAPH ?g { ?s ?p ?o } . filter (!isURI(?s) AND !isBLANK(?s) AND ?g NOT IN ( <http://www.openlinksw.com/schemas/virtrdf#> )) } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count == 0 end def http_subject?(uri) self.prepare(uri) sparql_query = <<-'SPARQL' SELECT * WHERE { GRAPH ?g { ?s ?p ?o } . filter (!regex(?s, "http://", "i") AND !isBLANK(?s) AND ?g NOT IN ( <http://www.openlinksw.com/schemas/virtrdf#> )) } LIMIT 1 SPARQL begin results = @client.query(sparql_query) puts results rescue => e puts e return false end results != nil && results.count == 0 end def uri_provides_info?(uri) self.prepare(uri) uri = self.get_subject_randomly() if uri == nil return false end begin response = http_get(URI(uri), {}) rescue => e puts "INVALID URI: #{uri}" return false end response.is_a?(Net::HTTPSuccess) && !response.body.empty? end def get_subject_randomly sparql_query = <<-'SPARQL' SELECT ?s WHERE { GRAPH ?g { ?s ?p ?o } . filter (isURI(?s)) } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return nil end if results != nil && results[0] != nil results[0][:s] else nil end end def contains_links?(uri) self.prepare(uri) self.contains_same_as?() || self.contains_see_also?() end def contains_same_as? sparql_query = <<-'SPARQL' PREFIX owl:<http://www.w3.org/2002/07/owl#> SELECT * WHERE { GRAPH ?g { ?s owl:sameAs ?o } . } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count > 0 end def contains_see_also? sparql_query = <<-'SPARQL' PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT * WHERE { GRAPH ?g { ?s rdfs:seeAlso ?o } . } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count > 0 end end end end remove unnecessary puts command. require 'yummydata/http_helper' module Yummydata module Criteria module LinkedDataRules include Yummydata::HTTPHelper def prepare(uri) @client = SPARQL::Client.new(uri, {'read_timeout': 5 * 60}) if @uri == uri && @client == nil @uri = uri end def uri_subject?(uri) self.prepare(uri) sparql_query = <<-'SPARQL' SELECT * WHERE { GRAPH ?g { ?s ?p ?o } . filter (!isURI(?s) AND !isBLANK(?s) AND ?g NOT IN ( <http://www.openlinksw.com/schemas/virtrdf#> )) } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count == 0 end def http_subject?(uri) self.prepare(uri) sparql_query = <<-'SPARQL' SELECT * WHERE { GRAPH ?g { ?s ?p ?o } . filter (!regex(?s, "http://", "i") AND !isBLANK(?s) AND ?g NOT IN ( <http://www.openlinksw.com/schemas/virtrdf#> )) } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count == 0 end def uri_provides_info?(uri) self.prepare(uri) uri = self.get_subject_randomly() if uri == nil return false end begin response = http_get(URI(uri), {}) rescue => e puts "INVALID URI: #{uri}" return false end response.is_a?(Net::HTTPSuccess) && !response.body.empty? end def get_subject_randomly sparql_query = <<-'SPARQL' SELECT ?s WHERE { GRAPH ?g { ?s ?p ?o } . filter (isURI(?s)) } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return nil end if results != nil && results[0] != nil results[0][:s] else nil end end def contains_links?(uri) self.prepare(uri) self.contains_same_as?() || self.contains_see_also?() end def contains_same_as? sparql_query = <<-'SPARQL' PREFIX owl:<http://www.w3.org/2002/07/owl#> SELECT * WHERE { GRAPH ?g { ?s owl:sameAs ?o } . } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count > 0 end def contains_see_also? sparql_query = <<-'SPARQL' PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT * WHERE { GRAPH ?g { ?s rdfs:seeAlso ?o } . } LIMIT 1 SPARQL begin results = @client.query(sparql_query) rescue => e return false end results != nil && results.count > 0 end end end end
require File.dirname(__FILE__) + '/../test_helper' # Integration tests class AdapterTest < Test::Unit::TestCase require File.dirname(__FILE__) + "/#{ENV['DB']}_tests" include "#{ENV['DB'].capitalize}Tests".constantize def select_value(query) value = connection.select_value(query) value = Integer(value) if ENV['DB'] =~ /postgresql/ value end def test_add_select_into_table new_table_name = 'new_people' sql_query = 'select * from people' assert_equal "CREATE TABLE #{new_table_name} #{sql_query}", connection.add_select_into_table(new_table_name, sql_query) end def test_truncate connection.delete("delete from truncate_test") %w|a b c|.each do |value| connection.execute("insert into truncate_test (x) values ('#{value}')") end assert_equal 3, select_value("SELECT count(*) FROM truncate_test") assert_nothing_raised { connection.truncate('truncate_test') } assert_equal 0, select_value("SELECT count(*) FROM truncate_test") end def test_bulk_load connection.truncate('people') assert_equal 0, select_value("SELECT count(*) FROM people") assert_nothing_raised do connection.bulk_load(File.join(File.dirname(__FILE__), 'people.txt'), 'people') end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_csv connection.truncate('people') assert_nothing_raised do options = {:fields => {:delimited_by => ','}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_with_enclosed_by connection.truncate('people') assert_nothing_raised do options = {:fields => {:delimited_by => ',', :enclosed_by => '"'}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_with_null_string connection.truncate('people') assert_nothing_raised do options = {:fields => {:delimited_by => ',', :null_string => ''}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_interprets_empty_strings_as_empty_strings connection.truncate('people') options = {:fields => {:delimited_by => ','}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people_with_empties.csv'), 'people', options) assert_equal 0, select_value("SELECT count(*) FROM people WHERE first_name IS NULL") end def test_bulk_load_interprets_empty_strings_as_nulls connection.truncate('people') options = {:fields => {:delimited_by => ',', :null_string => ''}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people_with_empties.csv'), 'people', options) assert_equal 1, select_value("SELECT count(*) FROM people WHERE first_name IS NULL"), "NOTE: this is a known issue with MySQL - any other db should work correctly" end def test_bulk_load_with_empty_file connection.truncate('people') assert_nothing_raised do connection.bulk_load(File.dirname(__FILE__) + '/empty.csv', 'people') end end def test_add_select_into_table sql_query = 'SELECT foo FROM bar' new_table_name = 'new_table' case ENV['DB'] when 'sqlserver', 'postgresql' assert_equal 'SELECT foo INTO new_table FROM bar', connection.add_select_into_table(new_table_name, sql_query) when 'mysql' assert_equal 'CREATE TABLE new_table SELECT foo FROM bar', connection.add_select_into_table(new_table_name, sql_query) else puts "Don't know how to add select into table for #{ENV['DB']}" end end def test_copy_table_should_copy_structure_and_data table_name = 'people' dest_table_name = "temp_#{table_name}" begin connection.drop_table(dest_table_name); rescue; end; connection.execute("DELETE FROM #{table_name}") options = {:fields => {:delimited_by => ',', :enclosed_by => '"'}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) connection.copy_table(table_name, dest_table_name) assert_equal 3, select_value("SELECT count(*) FROM #{dest_table_name}").to_i end private def connection ActiveRecord::Base.connection end end Ensure both mysql and mysql2 load the same mysql-specific tests require File.dirname(__FILE__) + '/../test_helper' # Integration tests class AdapterTest < Test::Unit::TestCase # quick hack to load adapter-specific tests - TODO: refactor # this also allows to run the same tests for mysql and mysql2 adapter_tests = ENV['DB'] raise "Missing DB environment variable" unless adapter_tests adapter_tests = 'mysql' if adapter_tests == 'mysql2' require File.dirname(__FILE__) + "/#{adapter_tests}_tests" include "#{adapter_tests.capitalize}Tests".constantize # end of hack def select_value(query) value = connection.select_value(query) value = Integer(value) if ENV['DB'] =~ /postgresql/ value end def test_add_select_into_table new_table_name = 'new_people' sql_query = 'select * from people' assert_equal "CREATE TABLE #{new_table_name} #{sql_query}", connection.add_select_into_table(new_table_name, sql_query) end def test_truncate connection.delete("delete from truncate_test") %w|a b c|.each do |value| connection.execute("insert into truncate_test (x) values ('#{value}')") end assert_equal 3, select_value("SELECT count(*) FROM truncate_test") assert_nothing_raised { connection.truncate('truncate_test') } assert_equal 0, select_value("SELECT count(*) FROM truncate_test") end def test_bulk_load connection.truncate('people') assert_equal 0, select_value("SELECT count(*) FROM people") assert_nothing_raised do connection.bulk_load(File.join(File.dirname(__FILE__), 'people.txt'), 'people') end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_csv connection.truncate('people') assert_nothing_raised do options = {:fields => {:delimited_by => ','}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_with_enclosed_by connection.truncate('people') assert_nothing_raised do options = {:fields => {:delimited_by => ',', :enclosed_by => '"'}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_with_null_string connection.truncate('people') assert_nothing_raised do options = {:fields => {:delimited_by => ',', :null_string => ''}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) end assert_equal 3, select_value("SELECT count(*) FROM people") end def test_bulk_load_interprets_empty_strings_as_empty_strings connection.truncate('people') options = {:fields => {:delimited_by => ','}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people_with_empties.csv'), 'people', options) assert_equal 0, select_value("SELECT count(*) FROM people WHERE first_name IS NULL") end def test_bulk_load_interprets_empty_strings_as_nulls connection.truncate('people') options = {:fields => {:delimited_by => ',', :null_string => ''}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people_with_empties.csv'), 'people', options) assert_equal 1, select_value("SELECT count(*) FROM people WHERE first_name IS NULL"), "NOTE: this is a known issue with MySQL - any other db should work correctly" end def test_bulk_load_with_empty_file connection.truncate('people') assert_nothing_raised do connection.bulk_load(File.dirname(__FILE__) + '/empty.csv', 'people') end end def test_add_select_into_table sql_query = 'SELECT foo FROM bar' new_table_name = 'new_table' case ENV['DB'] when 'sqlserver', 'postgresql' assert_equal 'SELECT foo INTO new_table FROM bar', connection.add_select_into_table(new_table_name, sql_query) when 'mysql' assert_equal 'CREATE TABLE new_table SELECT foo FROM bar', connection.add_select_into_table(new_table_name, sql_query) else puts "Don't know how to add select into table for #{ENV['DB']}" end end def test_copy_table_should_copy_structure_and_data table_name = 'people' dest_table_name = "temp_#{table_name}" begin connection.drop_table(dest_table_name); rescue; end; connection.execute("DELETE FROM #{table_name}") options = {:fields => {:delimited_by => ',', :enclosed_by => '"'}} connection.bulk_load(File.join(File.dirname(__FILE__), 'people.csv'), 'people', options) connection.copy_table(table_name, dest_table_name) assert_equal 3, select_value("SELECT count(*) FROM #{dest_table_name}").to_i end private def connection ActiveRecord::Base.connection end end
require_relative '../model/player' class HumanPlayer < Player private public def initialize end end human player contracted require_relative '../model/player' class HumanPlayer < Player private public def initialize end def get_column(list) return nil end end
send correct params for pagination to spotify API calls
works
#! /usr/bin/env ruby # encoding: UTF-8 require 'helper' class TestImage < MagickTitle::TestCase should "create an instance of MagickTitle::Image" do @title = MagickTitle::Image.create("created using class method") end should "set a title's line-height" do @title = MagickTitle::Image.create("Default\nLine\nHeight") assert_equal 183, @title.identify[:height] @title2 = MagickTitle::Image.create("Default\nLine\nHeight", :line_height => -25) assert_equal 133, @title2.identify[:height] end context "an invalid title" do setup do @title = MagickTitle::Image.new("") end should "not allow empty string" do assert !@title.valid? assert !@title.save assert !@title.fullpath end should "not allow update" do assert !@title.update("") assert !@title.save assert !@title.fullpath end should "allow update to valid title" do assert @title.update("Hello!") assert @title.save assert File.exists?(@title.fullpath) end end context "a valid title" do setup do @title = MagickTitle::Image.new("hello!") end should "save and create an image" do assert @title.save assert @title.fullpath.match(/\.png$/) assert File.exists?(@title.fullpath) end should "delete it's image" do assert @title.save assert @title.delete assert !File.exists?(@title.fullpath) end end context "an existing title" do setup do @title = MagickTitle::Image.create("hello!") end should "return convert_command" do assert @title.convert_command.match('echo "hello!" | convert') assert @title.convert_command.match(/\.png$/) end should "identify its dimensions and size" do hash = @title.identify assert_equal Hash, hash.class assert_equal 3, hash.values.length assert_equal 155, hash[:width] assert_equal 40, hash[:height] assert_equal 3858, hash[:size] end should "cache when asked to" do # make sure cache is turned ON assert @title.options.cache mod = File::mtime(@title.fullpath) # delay for timestamp.. sleep 1 # make sure we really don't need to update assert !@title.dirty? @title.save mod2 = File::mtime(@title.fullpath) assert_equal mod, mod2 end should "not cache when asked to" do # make sure cache is turned OFF @title.options[:cache] = false assert !@title.options.cache mod = File::mtime(@title.fullpath) # delay for timestamp.. sleep 1 # make sure we really don't need to update assert !@title.dirty? @title.save mod2 = File::mtime(@title.fullpath) assert mod != mod2 end end context "titles with the same text" do setup do @title1 = MagickTitle::Image.create("hello!") @title2 = MagickTitle::Image.create("hello!", :color => '#000') @title3 = MagickTitle::Image.create("hello!", :color => '#000', :font_size => 16) @title4 = MagickTitle::Image.create("hello!", :size => 16) @title5 = MagickTitle::Image.create("HELLO!") end should "each have uniq filenames" do assert @title1.filename != @title2.filename assert @title2.filename != @title3.filename assert @title3.filename != @title4.filename assert @title4.filename != @title5.filename assert @title5.filename != @title1.filename end end context "an unusual title" do should "allow one letter titles" do @title = MagickTitle::Image.create("a") end should "truncate filename when long" do @title = MagickTitle::Image.create("Quisque commodo hendrerit lorem quis egestas. Maecenas quis tortor arcu. Vivamus rutrum nunc non neque consectetur quis placerat neque lobortis. Nam vestibulum, arcu sodales feugiat consectetur, nisl orci bibendum elit, eu euismod magna sapien ut nibh. Donec semper quam scelerisque tortor dictum gravida. In hac habitasse platea dictumst. Nam pulvinar, odio sed rhoncus suscipit, sem diam ultrices mauris, eu consequat purus metus eu velit. Proin metus odio, aliquam eget molestie nec, gravida ut sapien. Phasellus quis est sed turpis sollicitudin venenatis sed eu odio. Praesent eget neque eu eros interdum malesuada non vel leo. Sed fringilla porta ligula egestas tincidunt. Nullam risus magna, ornare vitae varius eget, scelerisque a libero. Morbi eu porttitor ipsum. Nullam lorem nisi, posuere quis volutpat eget, luctus nec massa. Pellentesque aliquam lacinia tellus sit amet bibendum. Ut posuere justo in enim pretium scelerisque. Etiam ornare vehicula euismod. Vestibulum at.") assert @title.filename.length < 100 end should "allow utf8 characters" do @title = MagickTitle::Image.create("J'aime Café Chèvre et Crêpes") end should "allow single quotes" do @title = MagickTitle::Image.create("It's pretty nifty") end should "allow double quotes" do @title = MagickTitle::Image.create('Then he said; "Ruby rocks"') end should "allow mixed quotes" do @title = MagickTitle::Image.create(%("Ruby rocks" - it's what she said)) end should "allow escaped quotes" do @title = MagickTitle::Image.create(%(he said, "\"Ruby rocks\" - it\'s what she said")) end teardown do assert @title.valid? assert @title.save end end end fix broken image tests.. probably shouldn`t be using hard-coded values there anyways :/ #! /usr/bin/env ruby # encoding: UTF-8 require 'helper' class TestImage < MagickTitle::TestCase should "create an instance of MagickTitle::Image" do @title = MagickTitle::Image.create("created using class method") end should "set a title's line-height" do @title = MagickTitle::Image.create("Default\nLine\nHeight") assert_equal 181, @title.identify[:height] @title2 = MagickTitle::Image.create("Default\nLine\nHeight", :line_height => -25) assert_equal 131, @title2.identify[:height] end context "an invalid title" do setup do @title = MagickTitle::Image.new("") end should "not allow empty string" do assert !@title.valid? assert !@title.save assert !@title.fullpath end should "not allow update" do assert !@title.update("") assert !@title.save assert !@title.fullpath end should "allow update to valid title" do assert @title.update("Hello!") assert @title.save assert File.exists?(@title.fullpath) end end context "a valid title" do setup do @title = MagickTitle::Image.new("hello!") end should "save and create an image" do assert @title.save assert @title.fullpath.match(/\.png$/) assert File.exists?(@title.fullpath) end should "delete it's image" do assert @title.save assert @title.delete assert !File.exists?(@title.fullpath) end end context "an existing title" do setup do @title = MagickTitle::Image.create("hello!") end should "return convert_command" do assert @title.convert_command.match('echo "hello!" | convert') assert @title.convert_command.match(/\.png$/) end should "identify its dimensions and size" do hash = @title.identify assert_equal Hash, hash.class assert_equal 3, hash.values.length assert_equal 155, hash[:width] assert_equal 40, hash[:height] assert_equal 2746, hash[:size] end should "cache when asked to" do # make sure cache is turned ON assert @title.options.cache mod = File::mtime(@title.fullpath) # delay for timestamp.. sleep 1 # make sure we really don't need to update assert !@title.dirty? @title.save mod2 = File::mtime(@title.fullpath) assert_equal mod, mod2 end should "not cache when asked to" do # make sure cache is turned OFF @title.options[:cache] = false assert !@title.options.cache mod = File::mtime(@title.fullpath) # delay for timestamp.. sleep 1 # make sure we really don't need to update assert !@title.dirty? @title.save mod2 = File::mtime(@title.fullpath) assert mod != mod2 end end context "titles with the same text" do setup do @title1 = MagickTitle::Image.create("hello!") @title2 = MagickTitle::Image.create("hello!", :color => '#000') @title3 = MagickTitle::Image.create("hello!", :color => '#000', :font_size => 16) @title4 = MagickTitle::Image.create("hello!", :size => 16) @title5 = MagickTitle::Image.create("HELLO!") end should "each have uniq filenames" do assert @title1.filename != @title2.filename assert @title2.filename != @title3.filename assert @title3.filename != @title4.filename assert @title4.filename != @title5.filename assert @title5.filename != @title1.filename end end context "an unusual title" do should "allow one letter titles" do @title = MagickTitle::Image.create("a") end should "truncate filename when long" do @title = MagickTitle::Image.create("Quisque commodo hendrerit lorem quis egestas. Maecenas quis tortor arcu. Vivamus rutrum nunc non neque consectetur quis placerat neque lobortis. Nam vestibulum, arcu sodales feugiat consectetur, nisl orci bibendum elit, eu euismod magna sapien ut nibh. Donec semper quam scelerisque tortor dictum gravida. In hac habitasse platea dictumst. Nam pulvinar, odio sed rhoncus suscipit, sem diam ultrices mauris, eu consequat purus metus eu velit. Proin metus odio, aliquam eget molestie nec, gravida ut sapien. Phasellus quis est sed turpis sollicitudin venenatis sed eu odio. Praesent eget neque eu eros interdum malesuada non vel leo. Sed fringilla porta ligula egestas tincidunt. Nullam risus magna, ornare vitae varius eget, scelerisque a libero. Morbi eu porttitor ipsum. Nullam lorem nisi, posuere quis volutpat eget, luctus nec massa. Pellentesque aliquam lacinia tellus sit amet bibendum. Ut posuere justo in enim pretium scelerisque. Etiam ornare vehicula euismod. Vestibulum at.") assert @title.filename.length < 100 end should "allow utf8 characters" do @title = MagickTitle::Image.create("J'aime Café Chèvre et Crêpes") end should "allow single quotes" do @title = MagickTitle::Image.create("It's pretty nifty") end should "allow double quotes" do @title = MagickTitle::Image.create('Then he said; "Ruby rocks"') end should "allow mixed quotes" do @title = MagickTitle::Image.create(%("Ruby rocks" - it's what she said)) end should "allow escaped quotes" do @title = MagickTitle::Image.create(%(he said, "\"Ruby rocks\" - it\'s what she said")) end teardown do assert @title.valid? assert @title.save end end end
require 'setup' module Enzyme extend self @@commands = {} def run # Only shift the first argument off the ARGV if help flags haven't been passed. command = (ARGV.delete("-h") || ARGV.delete("--help")) ? 'help' : ARGV.shift puts # Show info, help or run the requested command if it has been registered. begin if command.nil? info help elsif command.eql?('info') info elsif command.eql?('help') help else if @@commands.include?(command) @@commands[command][:class].run else raise UnknownCommand.new(command) end end rescue StandardError => e error(e) end end def info puts '+-------------------------------------------------+' puts '| ##### ## ## ###### ## ## ## ## ##### |' puts '| ## ### ## ## ## ## ### ### ## |' puts '| ##### ###### ## ### ######## ##### |' puts '| ## ## ### ## ## ## ## ## ## |' puts '| ##### ## ## ###### ## ## ## ##### |' puts '+-------------------------------------------------+' puts puts "#{$format.bold}DESCRIPTION#{$format.normal}" puts ' Katalyst\'s project collaboration tool.' puts puts "#{$format.bold}VERSION#{$format.normal}" puts " #{$system_settings.version}" puts end def help ARGV.reject { |x| x.start_with?("-") } command = ARGV.shift if command if @@commands.include?(command.to_s.downcase) @@commands[command.to_s.downcase][:help].call else error("No help available for `#{command}`.") end else puts "#{$format.bold}SYNOPSIS#{$format.normal}" puts ' enzyme <command> [<options>]' puts puts "#{$format.bold}HELP#{$format.normal}" puts ' enzyme help [<command>]' puts ' enzyme [<command>] --help' puts ' enzyme [<command>] -h' puts puts "#{$format.bold}COMMANDS#{$format.normal}" ([ "info" ]+@@commands.keys).sort.each { |command| puts " #{command}" } puts puts "#{$format.bold}DEBUGGING#{$format.normal}" puts ' Use `--trace` at anytime to get full stacktraces.' puts ' Use `--skip-sync-server` to prevent the sync server from mounting automatically.' puts end end def error(error) if $system_settings.trace_errors raise error else puts "#{$format.bold}ERROR: #{error}#{$format.normal}" puts puts ' Run `enzyme help` for help or use the `--trace` option to get a full stacktrace.' puts end end def register(command, command_class, &block) @@commands[command] = { :class => command_class, :help => block } end end Improve the feedback when using (or incorrectly using) the help and info commands. require 'setup' module Enzyme extend self @@commands = {} def run # If "-h" or "--help" was passed, delete the first one found and set the command to "help". # Otherwise, assume the command is the first argument passed. command = ARGV.delete((ARGV & [ "-h", "--help" ]).first) ? 'help' : ARGV.shift puts # Show info, help or run the requested command if it has been registered. begin if command.nil? || command.eql?('info') info elsif command.eql?('help') help else if @@commands.include?(command) @@commands[command][:class].run else raise UnknownCommand.new(command) end end rescue StandardError => e error(e) end end def info ARGV.each { |x| raise UnknownOption.new(x) if x.start_with?("-") } ARGV.each { |x| raise UnknownArgument.new(x) } puts '+-------------------------------------------------+' puts '| ##### ## ## ###### ## ## ## ## ##### |' puts '| ## ### ## ## ## ## ### ### ## |' puts '| ##### ###### ## ### ######## ##### |' puts '| ## ## ### ## ## ## ## ## ## |' puts '| ##### ## ## ###### ## ## ## ##### |' puts '+-------------------------------------------------+' puts puts "#{$format.bold}DESCRIPTION#{$format.normal}" puts ' Katalyst\'s project collaboration tool.' puts puts "#{$format.bold}VERSION#{$format.normal}" puts " #{$system_settings.version}" puts puts "Run `enzyme help` for usage." puts end def help ARGV.each { |x| raise UnknownOption.new(x) if x.start_with?("-") } command = ARGV.shift ARGV.each { |x| raise UnknownArgument.new(x) } if command if @@commands.include?(command.to_s.downcase) @@commands[command.to_s.downcase][:help].call else error("No help available for `#{command}`.") end else puts "#{$format.bold}SYNOPSIS#{$format.normal}" puts ' enzyme <command> [<options>]' puts puts "#{$format.bold}HELP#{$format.normal}" puts ' enzyme help [<command>]' puts ' enzyme [<command>] --help' puts ' enzyme [<command>] -h' puts puts "#{$format.bold}COMMANDS#{$format.normal}" ([ "info" ]+@@commands.keys).sort.each { |command| puts " #{command}" } puts puts "#{$format.bold}DEBUGGING#{$format.normal}" puts ' Use `--trace` at anytime to get full stacktraces.' puts ' Use `--skip-sync-server` to prevent the sync server from mounting automatically.' puts end end def error(error) if $system_settings.trace_errors raise error else puts "#{$format.bold}ERROR: #{error}#{$format.normal}" puts puts ' Run `enzyme help` for help or use the `--trace` option to get a full stacktrace.' puts end end def register(command, command_class, &block) @@commands[command] = { :class => command_class, :help => block } end end
# Allow test to be run in-place without requiring a gem install $LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib' $LOAD_PATH.unshift File.dirname(__FILE__) require 'rubygems' require 'test/unit' require 'shoulda' require 'ruby_skynet' require 'simple_server' require 'multi_json' SemanticLogger::Logger.default_level = :trace SemanticLogger::Logger.appenders << SemanticLogger::Appender::File.new('test.log') # Unit Test for ResilientSocket::TCPClient class RubySkynetClientTest < Test::Unit::TestCase context RubySkynet::Client do context "without server" do should "raise exception when cannot reach server after 5 retries" do exception = assert_raise RubySkynet::ServiceUnavailable do client = RubySkynet::Client.new('SomeService') client.call(:test, :hello => 'there') end assert_match /No servers available for service: SomeService with version: \* in region: Development/, exception.message end end context "with server" do setup do @port = 2000 @read_timeout = 3.0 @server = SimpleServer.new(@port) @server_name = "localhost:#{@port}" # Register service in doozer @service_name = "TestService" @version = 1 @region = 'Test' @ip_address = "127.0.0.1" config = { "Config" => { "UUID" => "3978b371-15e9-40f8-9b7b-59ae88d8c7ec", "Name" => @service_name, "Version" => @version.to_s, "Region" => @region, "ServiceAddr" => { "IPAddress" => @ip_address, "Port" => @port, "MaxPort" => @port + 999 }, }, "Registered" => true } RubySkynet::Registry.doozer_pool.with_connection do |doozer| doozer["/services/#{@service_name}/#{@version}/#{@region}/#{@ip_address}/#{@port}"] = MultiJson.encode(config) end end teardown do @server.stop if @server # De-register server in doozer RubySkynet::Registry.doozer_pool.with_connection do |doozer| doozer.delete("/services/#{@service_name}/#{@version}/#{@region}/#{@ip_address}/#{@port}") rescue nil end end context "with client connection" do setup do @client = RubySkynet::Client.new(@service_name, @version, @region) end should "successfully send and receive data" do reply = @client.call(:test1, 'some' => 'parameters') assert_equal 'test1', reply['result'] end should "timeout on receive" do request = { 'duration' => @read_timeout + 0.5} exception = assert_raise ResilientSocket::ReadTimeout do # Read 4 bytes from server @client.call('sleep', request, :read_timeout => @read_timeout) end assert_match /Timedout after #{@read_timeout} seconds trying to read/, exception.message end end end end end CLA-408 Include test # Allow test to be run in-place without requiring a gem install $LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib' require 'rubygems' require 'test/unit' require 'shoulda' require 'ruby_skynet' # Register an appender if one is not already registered if SemanticLogger::Logger.appenders.size == 0 SemanticLogger::Logger.default_level = :trace SemanticLogger::Logger.appenders << SemanticLogger::Appender::File.new('test.log') end # Unit Test for ResilientSocket::TCPClient class RubySkynetServiceTest < Test::Unit::TestCase context 'RubySkynet::Service' do context "with server" do setup do RubySkynet::Server.port = 2100 RubySkynet::Server.region = 'Test' RubySkynet::Server.hostname = 'localhost' @server = RubySkynet::Server.new @service_name = 'RubySkynet.Service' @version = 1 @region = 'Test' @doozer_key = "/services/#{@service_name}/#{@version}/#{@region}/localhost/2100" # Register Service RubySkynet::Service end teardown do begin @server.terminate if @server rescue Celluloid::DeadActorError end end should "have correct service key" do assert_equal @doozer_key, RubySkynet::Service.service_key end should "register service" do RubySkynet::Registry.doozer_pool.with_connection do |doozer| assert_equal true, doozer[@doozer_key].length > 20 end end context "calling with a client" do setup do @client = RubySkynet::Client.new(@service_name, @version, @region) end should "successfully send and receive data" do reply = @client.call(:echo, 'some' => 'parameters') assert_equal 'test1', reply #['result'] end # should "timeout on receive" do # request = { 'duration' => @read_timeout + 0.5} # # exception = assert_raise ResilientSocket::ReadTimeout do # # Read 4 bytes from server # @client.call('sleep', request, :read_timeout => @read_timeout) # end # assert_match /Timedout after #{@read_timeout} seconds trying to read/, exception.message # end end end end end
# encoding: UTF-8 require 'test_helper' describe Vines::Stream::Server::Ready do STANZAS = [] before do @stream = MiniTest::Mock.new @state = Vines::Stream::Server::Ready.new(@stream, nil) def @state.to_stanza(node) Vines::Stanza.from_node(node, @stream).tap do |stanza| def stanza.process STANZAS << self end if stanza end end end after do STANZAS.clear end def test_good_node_processes config = MiniTest::Mock.new config.expect(:local_jid?, true, [Vines::JID.new('romeo@verona.lit')]) @stream.expect(:config, config) @stream.expect(:remote_domain, 'wonderland.lit') @stream.expect(:domain, 'verona.lit') @stream.expect(:user=, nil, [Vines::User.new(jid: 'alice@wonderland.lit')]) node = node(%Q{<message from="alice@wonderland.lit" to="romeo@verona.lit"/>}) @state.node(node) assert_equal 1, STANZAS.size assert @stream.verify assert config.verify end def test_unsupported_stanza_type node = node('<bogus/>') assert_raises(Vines::StreamErrors::UnsupportedStanzaType) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end def test_improper_addressing_missing_to node = node(%Q{<message from="alice@wonderland.lit"/>}) assert_raises(Vines::StreamErrors::ImproperAddressing) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end def test_improper_addressing_invalid_to node = node(%Q{<message from="alice@wonderland.lit" to=" "/>}) assert_raises(Vines::StanzaErrors::JidMalformed) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end def test_improper_addressing_missing_from node = node(%Q{<message to="romeo@verona.lit"/>}) assert_raises(Vines::StreamErrors::ImproperAddressing) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end def test_improper_addressing_invalid_from node = node(%Q{<message from=" " to="romeo@verona.lit"/>}) assert_raises(Vines::StanzaErrors::JidMalformed) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end def test_invalid_from @stream.expect(:remote_domain, 'wonderland.lit') node = node(%Q{<message from="alice@bogus.lit" to="romeo@verona.lit"/>}) assert_raises(Vines::StreamErrors::InvalidFrom) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end def test_host_unknown @stream.expect(:remote_domain, 'wonderland.lit') @stream.expect(:domain, 'verona.lit') node = node(%Q{<message from="alice@wonderland.lit" to="romeo@bogus.lit"/>}) assert_raises(Vines::StreamErrors::HostUnknown) { @state.node(node) } assert STANZAS.empty? assert @stream.verify end private def node(xml) Nokogiri::XML(xml).root end end Fix constant name warning. # encoding: UTF-8 require 'test_helper' describe Vines::Stream::Server::Ready do subject { Vines::Stream::Server::Ready.new(stream, nil) } let(:stream) { MiniTest::Mock.new } SERVER_STANZAS = [] before do def subject.to_stanza(node) Vines::Stanza.from_node(node, stream).tap do |stanza| def stanza.process SERVER_STANZAS << self end if stanza end end end after do SERVER_STANZAS.clear end it 'processes a valid node' do config = MiniTest::Mock.new config.expect(:local_jid?, true, [Vines::JID.new('romeo@verona.lit')]) stream.expect(:config, config) stream.expect(:remote_domain, 'wonderland.lit') stream.expect(:domain, 'verona.lit') stream.expect(:user=, nil, [Vines::User.new(jid: 'alice@wonderland.lit')]) node = node(%Q{<message from="alice@wonderland.lit" to="romeo@verona.lit"/>}) subject.node(node) assert_equal 1, SERVER_STANZAS.size assert stream.verify assert config.verify end it 'raises unsupported-stanza-type stream error' do node = node('<bogus/>') -> { subject.node(node) }.must_raise Vines::StreamErrors::UnsupportedStanzaType assert SERVER_STANZAS.empty? assert stream.verify end it 'raises improper-addressing stream error when to address is missing' do node = node(%Q{<message from="alice@wonderland.lit"/>}) -> { subject.node(node) }.must_raise Vines::StreamErrors::ImproperAddressing assert SERVER_STANZAS.empty? assert stream.verify end it 'raises jid-malformed stanza error when to address is invalid' do node = node(%Q{<message from="alice@wonderland.lit" to=" "/>}) -> { subject.node(node) }.must_raise Vines::StanzaErrors::JidMalformed assert SERVER_STANZAS.empty? assert stream.verify end it 'raises improper-addressing stream error' do node = node(%Q{<message to="romeo@verona.lit"/>}) -> { subject.node(node) }.must_raise Vines::StreamErrors::ImproperAddressing assert SERVER_STANZAS.empty? assert stream.verify end it 'raises jid-malformed stanza error for invalid from address' do node = node(%Q{<message from=" " to="romeo@verona.lit"/>}) -> { subject.node(node) }.must_raise Vines::StanzaErrors::JidMalformed assert SERVER_STANZAS.empty? assert stream.verify end it 'raises invalid-from stream error' do stream.expect(:remote_domain, 'wonderland.lit') node = node(%Q{<message from="alice@bogus.lit" to="romeo@verona.lit"/>}) -> { subject.node(node) }.must_raise Vines::StreamErrors::InvalidFrom assert SERVER_STANZAS.empty? assert stream.verify end it 'raises host-unknown stream error' do stream.expect(:remote_domain, 'wonderland.lit') stream.expect(:domain, 'verona.lit') node = node(%Q{<message from="alice@wonderland.lit" to="romeo@bogus.lit"/>}) -> { subject.node(node) }.must_raise Vines::StreamErrors::HostUnknown assert SERVER_STANZAS.empty? assert stream.verify end private def node(xml) Nokogiri::XML(xml).root end end
cask :v1 => 'with-suite' do version '1.2.3' sha256 'd1302a0dc25aff72ad395ed01a830468b92253ffd28269574f3ac0b5eb8aad54' url TestHelper.local_binary_url('caffeine_suite.zip') homepage 'http://example.com/with-suite' suite 'caffeine_suite' end add license stanza to test Cask to make tests pass after requiring `license` cask :v1 => 'with-suite' do version '1.2.3' sha256 'd1302a0dc25aff72ad395ed01a830468b92253ffd28269574f3ac0b5eb8aad54' url TestHelper.local_binary_url('caffeine_suite.zip') homepage 'http://example.com/with-suite' license :unknown suite 'caffeine_suite' end
Add a test for TextBringer::Buffer. require "test/unit" require "text_bringer/buffer" class TestBuffer < Test::Unit::TestCase include TextBringer def test_delete_char buffer = Buffer.new buffer.insert("abc") buffer.backward_char(2) buffer.delete_char assert_equal("ac", buffer.to_s) end end
require File.dirname(__FILE__) + '/../test_helper' class ProfileHelperTest < ActiveSupport::TestCase include ProfileHelper include ApplicationHelper include ActionView::Helpers::TagHelper def setup @profile = mock @helper = mock helper.extend(ProfileHelper) end attr_reader :profile, :helper should 'display field if may display it' do self.stubs(:user).returns(nil) profile.expects(:may_display_field_to?).returns(true) profile.expects(:field).returns('value') expects(:title).with(:field, anything).returns('Title') assert_match /Title.*value/, display_field(:field) end should 'not display field if may not display it and not forced' do self.stubs(:user).returns(nil) profile.expects(:may_display_field_to?).returns(false) profile.expects(:field).never assert_equal '', display_field(:field) end should 'display field if may not display it but is forced' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).returns(false) profile.stubs(:kind_of?).with(Person).returns(:person) FORCE.merge!({:person => [:field]}) profile.expects(:field).returns('value') expects(:title).with(:field, anything).returns('Title') assert_match /Title.*value/, display_field(:field) end should 'display work info if at least one of the fields should be displayed' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).with(:organization, nil).returns(true) profile.stubs(:may_display_field_to?).with(:organization_website, nil).returns(false) profile.stubs(:may_display_field_to?).with(:professional_activity, nil).returns(false) profile.stubs(:kind_of?).with(Person).returns(:person) profile.expects(:organization).returns('Organization Name') profile.expects(:organization_website).never profile.expects(:professional_activity).never assert_match /Work.*Organization Name/, display_work end should 'not display work info if none of the fields should be displayed' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).returns(false) profile.stubs(:kind_of?).with(Person).returns(:person) profile.expects(:organization).never profile.expects(:organization_website).never assert_equal '', display_work end should 'display work info if both fields should be displayed' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).returns(true) profile.stubs(:kind_of?).with(Person).returns(:person) profile.expects(:organization).returns('Organization Name') profile.expects(:organization_website).returns('') assert_match /Work.*Organization Name/, display_work end end ProfileHelper: fix broken test *sigh* require File.dirname(__FILE__) + '/../test_helper' class ProfileHelperTest < ActiveSupport::TestCase include ProfileHelper include ApplicationHelper include ActionView::Helpers::TagHelper def setup @profile = mock @helper = mock helper.extend(ProfileHelper) end attr_reader :profile, :helper should 'display field if may display it' do self.stubs(:user).returns(nil) profile.expects(:may_display_field_to?).returns(true) profile.expects(:field).returns('value') expects(:title).with(:field, anything).returns('Title') assert_match /Title.*value/, display_field(:field) end should 'not display field if may not display it and not forced' do self.stubs(:user).returns(nil) profile.expects(:may_display_field_to?).returns(false) profile.expects(:field).never assert_equal '', display_field(:field) end should 'display field if may not display it but is forced' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).returns(false) profile.stubs(:kind_of?).with(Person).returns(:person) FORCE.merge!({:person => [:field]}) profile.expects(:field).returns('value') expects(:title).with(:field, anything).returns('Title') assert_match /Title.*value/, display_field(:field) end should 'display work info if at least one of the fields should be displayed' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).with(:organization, nil).returns(true) profile.stubs(:may_display_field_to?).with(:organization_website, nil).returns(false) profile.stubs(:may_display_field_to?).with(:professional_activity, nil).returns(false) profile.stubs(:kind_of?).with(Person).returns(:person) profile.expects(:organization).returns('Organization Name') profile.expects(:organization_website).never profile.expects(:professional_activity).never assert_match /Work.*Organization Name/, display_work end should 'not display work info if none of the fields should be displayed' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).returns(false) profile.stubs(:kind_of?).with(Person).returns(:person) profile.expects(:organization).never profile.expects(:organization_website).never assert_equal '', display_work end should 'display work info if any of the fields is to be displayed' do self.stubs(:user).returns(nil) profile.stubs(:may_display_field_to?).returns(true) profile.stubs(:kind_of?).with(Person).returns(:person) profile.expects(:organization).returns('Organization Name') profile.expects(:organization_website).returns('') profile.expects(:professional_activity).returns('') assert_match /Work.*Organization Name/, display_work end end
require File.expand_path("../../../test_helper", __FILE__) module Unit module Require class TestMocker < MiniTest::Unit::TestCase describe MotionBundler::Require::Mocker do describe "hooks" do it "should have MotionBundler::Require::Mocker::Hooks included" do assert_equal true, MotionBundler::Require::Mocker.included_modules.include?(MotionBundler::Require::Mocker::Hooks) end end describe "calling `yield`" do it "should start, yield and stop" do object = mock "object" object.expects :do_something MotionBundler::Require::Mocker.expects :start MotionBundler::Require::Mocker.expects :stop MotionBundler::Require::Mocker.yield do object.do_something end end it "should stop when error raised" do MotionBundler::Require::Mocker.expects :start MotionBundler::Require::Mocker.expects :stop begin MotionBundler::Require::Mocker.yield do raise end rescue end end end describe "calling `start`" do it "should hook into mock related core methods" do MotionBundler::Require::Mocker.expects :hook MotionBundler::Require::Mocker.send :start end end describe "calling `stop`" do it "should unhook from mock related core methods" do MotionBundler::Require::Mocker.expects :unhook MotionBundler::Require::Mocker.send :stop end end end end end end Trivial change within test_mocker.rb require File.expand_path("../../../test_helper", __FILE__) module Unit module Require class TestMocker < MiniTest::Unit::TestCase describe MotionBundler::Require::Mocker do describe "hooks" do it "should have MotionBundler::Require::Mocker::Hooks included" do assert_equal true, MotionBundler::Require::Mocker.included_modules.include?(MotionBundler::Require::Mocker::Hooks) end end describe "calling `yield`" do it "should start, yield and stop" do object = mock "object" object.expects :do_something MotionBundler::Require::Mocker.expects :start MotionBundler::Require::Mocker.expects :stop MotionBundler::Require::Mocker.yield do object.do_something end end describe "when error raised" do it "should stop" do MotionBundler::Require::Mocker.expects :start MotionBundler::Require::Mocker.expects :stop begin MotionBundler::Require::Mocker.yield do raise end rescue end end end end describe "calling `start`" do it "should hook into mock related core methods" do MotionBundler::Require::Mocker.expects :hook MotionBundler::Require::Mocker.send :start end end describe "calling `stop`" do it "should unhook from mock related core methods" do MotionBundler::Require::Mocker.expects :unhook MotionBundler::Require::Mocker.send :stop end end end end end end