CombinedText
stringlengths
4
3.42M
class RegistrationsController < Devise::RegistrationsController before_filter :check_registration_state, :except => [:edit, :update, :destroy] end Remove devise stuff
require File.expand_path('../boot', __FILE__) # require 'rails/all' # Require individual railtie frameworks, excluding rails/test_unit require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "sprockets/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module P4IDX 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 end end Cleaned up application.rb after switch to rspec. require File.expand_path('../boot', __FILE__) # Require individual railtie frameworks, excluding rails/test_unit require 'active_record/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'sprockets/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module P4IDX 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 end end
require 'contexts/user_requests_password_reset' require 'contexts/user_confirms_account' require 'contexts/user_reverts_email_confirmation' class RegistrationsController < ApplicationController skip_before_action :authenticate_staging before_action :authenticate_user!, :only => [:show, :update, :resend_confirmation] # POST /sign_up def create user = User.new(registration_params) if user.save establish_session user user.send_confirmation render :json => { :location => return_location } else render :status => :unauthorized, :json => { :error => :email_taken, :message => "Looks like that email address is taken. Have you forgotten your password?" } end end # GET /profile def show end # POST /profile def update user = current_user #if password_params[:password].present? || password_params[:current_password].present? # if user.authenticate(password_params[:current_password]) && # user.update_attributes(registration_params) # render :json => { :user => user } # else # render :status => :bad_request, :json => { :messages => user.errors.full_messages } # end #else if user.update_attributes(registration_params) render :json => { :user => user } else render :status => :bad_request, :json => { :messages => user.errors.full_messages } end #end end # POST /resend_confirmation def resend_confirmation current_user.send_confirmation render :json => { :message => "Confirmation email sent to #{current_user.email}" } end # User's email is marked as confirmed def confirm if @user = UserConfirmsAccount.new(:token => params[:token]).call self.establish_session @user redirect_to profile_url, :notice => "Thanks for confirming #{@user.email}" else redirect_to profile_url, :notice => "There was a problem confirming - try re-sending the email?" end end # GET /revert/:token # Reverts an email change def revert user = UserRevertsEmailConfirmation.new(:token => params[:token]).call if current_user == user redirect_to profile_url else # render a 404 end end # POST /forgot_password # Calls the context and if it returns a user, we send a password reset email # to that address # # Always responds with a 204 def forgot_password user = UserRequestsPasswordReset.new(:email => registration_params[:email]).call UserMailer.password_reset_email(user).deliver if user head 204 end # Creates a session for the user based on a token that was emailed to them # and sends them to their profile page. # Token is destroyed on sign in. def reset_password user = User.find_by(:reset_password_token => params[:token]) if user self.establish_session user redirect_to profile_url else # render a 404 end end private def registration_params params.require(:user).permit(:email, :password) end def password_params params.require(:user).permit(:password, :current_password) end end Handle the error case with email revert require 'contexts/user_requests_password_reset' require 'contexts/user_confirms_account' require 'contexts/user_reverts_email_confirmation' class RegistrationsController < ApplicationController skip_before_action :authenticate_staging before_action :authenticate_user!, :only => [:show, :update, :resend_confirmation] # POST /sign_up def create user = User.new(registration_params) if user.save establish_session user user.send_confirmation render :json => { :location => return_location } else render :status => :unauthorized, :json => { :error => :email_taken, :message => "Looks like that email address is taken. Have you forgotten your password?" } end end # GET /profile def show end # POST /profile def update user = current_user #if password_params[:password].present? || password_params[:current_password].present? # if user.authenticate(password_params[:current_password]) && # user.update_attributes(registration_params) # render :json => { :user => user } # else # render :status => :bad_request, :json => { :messages => user.errors.full_messages } # end #else if user.update_attributes(registration_params) render :json => { :user => user } else render :status => :bad_request, :json => { :messages => user.errors.full_messages } end #end end # POST /resend_confirmation def resend_confirmation current_user.send_confirmation render :json => { :message => "Confirmation email sent to #{current_user.email}" } end # User's email is marked as confirmed def confirm if @user = UserConfirmsAccount.new(:token => params[:token]).call self.establish_session @user redirect_to profile_url, :notice => "Thanks for confirming #{@user.email}" else redirect_to profile_url, :notice => "There was a problem confirming - try re-sending the email?" end end # GET /revert/:token # Reverts an email change def revert user = UserRevertsEmailConfirmation.new(:token => params[:token]).call if current_user == user redirect_to profile_url else redirect_to profile_url, :notice => "There was a problem reverting the email change - try again?" end end # POST /forgot_password # Calls the context and if it returns a user, we send a password reset email # to that address # # Always responds with a 204 def forgot_password user = UserRequestsPasswordReset.new(:email => registration_params[:email]).call UserMailer.password_reset_email(user).deliver if user head 204 end # Creates a session for the user based on a token that was emailed to them # and sends them to their profile page. # Token is destroyed on sign in. def reset_password user = User.find_by(:reset_password_token => params[:token]) if user self.establish_session user redirect_to profile_url else # render a 404 end end private def registration_params params.require(:user).permit(:email, :password) end def password_params params.require(:user).permit(:password, :current_password) end end
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" # require "action_mailer/railtie" # require "action_view/railtie" # require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SolicitorSearchApi class Application < Rails::Application config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', headers: :any, methods: [:get] end end # 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 return cors headers in responses for OPTIONS and HEAD requests require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" # require "action_mailer/railtie" # require "action_view/railtie" # require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SolicitorSearchApi class Application < Rails::Application config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', headers: :any, methods: [:get, :options, :head] end end # 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
# Copyright (c) 2010-2011, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. class RegistrationsController < Devise::RegistrationsController before_filter :check_registrations_open_or_vaild_invite!, :check_valid_invite! layout "post", :only => :new def create @user = User.build(params[:user]) @user.process_invite_acceptence(invite) if invite.present? if @user.save flash[:notice] = I18n.t 'registrations.create.success' @user.seed_aspects Role.add_beta(@user.person) if invite.present? && invite.beta? sign_in_and_redirect(:user, @user) Rails.logger.info("event=registration status=successful user=#{@user.diaspora_handle}") else @user.errors.delete(:person) flash[:error] = @user.errors.full_messages.join(";") Rails.logger.info("event=registration status=failure errors='#{@user.errors.full_messages.join(', ')}'") render :new end end def new super end private def check_valid_invite! return true unless AppConfig[:registrations_closed] #this sucks return true if invite && invite.can_be_used? flash[:error] = t('registrations.invalid_invite') redirect_to new_user_session_path end def check_registrations_open_or_vaild_invite! return true if invite.present? if AppConfig[:registrations_closed] flash[:error] = t('registrations.closed') redirect_to new_user_session_path end end def invite if params[:invite].present? @invite ||= InvitationCode.find_by_token(params[:invite][:token]) end end helper_method :invite end dont beta0fiy users. going all in # Copyright (c) 2010-2011, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. class RegistrationsController < Devise::RegistrationsController before_filter :check_registrations_open_or_vaild_invite!, :check_valid_invite! layout "post", :only => :new def create @user = User.build(params[:user]) @user.process_invite_acceptence(invite) if invite.present? if @user.save flash[:notice] = I18n.t 'registrations.create.success' @user.seed_aspects sign_in_and_redirect(:user, @user) Rails.logger.info("event=registration status=successful user=#{@user.diaspora_handle}") else @user.errors.delete(:person) flash[:error] = @user.errors.full_messages.join(";") Rails.logger.info("event=registration status=failure errors='#{@user.errors.full_messages.join(', ')}'") render :new end end def new super end private def check_valid_invite! return true unless AppConfig[:registrations_closed] #this sucks return true if invite && invite.can_be_used? flash[:error] = t('registrations.invalid_invite') redirect_to new_user_session_path end def check_registrations_open_or_vaild_invite! return true if invite.present? if AppConfig[:registrations_closed] flash[:error] = t('registrations.closed') redirect_to new_user_session_path end end def invite if params[:invite].present? @invite ||= InvitationCode.find_by_token(params[:invite][:token]) end end helper_method :invite end
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "active_resource/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end # https://gist.github.com/1184843 config.assets.precompile << /(^[^_]|\/[^_])[^\/]*/ config.sass.preferred_syntax = :sass module StaffPlan 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 = :en # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' config.generators do |g| g.template_engine :haml g.test_framework :rspec, :fixture => true, :views => false g.fixture_replacement :factory_girl, :dir => "spec/factories" end end end ridiculous rob require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "active_resource/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module StaffPlan 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 = :en # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' config.generators do |g| g.template_engine :haml g.test_framework :rspec, :fixture => true, :views => false g.fixture_replacement :factory_girl, :dir => "spec/factories" end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' require 'trashed/railtie' require 'statsd' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module CodeTriage class Application < Rails::Application config.trashed.statsd = Statsd.new('localhost', ENV["PORT"]) if ENV["PORT"] # 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. config.active_job.queue_adapter = :sidekiq config.encoding = "utf-8" # Enable the asset pipeline config.assets.enabled = true config.assets.initialize_on_precompile = false # Set i18n.enforce_available_locales to true config.i18n.enforce_available_locales = true config.force_ssl = ENV["APPLICATION_HOST"] config.middleware.insert_after ActionDispatch::SSL, Rack::CanonicalHost, ENV["APPLICATION_HOST"] if ENV["APPLICATION_HOST"] end end Switch to periodic require File.expand_path('../boot', __FILE__) require 'rails/all' require 'trashed/railclock' require 'statsd' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module CodeTriage class Application < Rails::Application config.trashed_periodic.statsd = Statsd.new('localhost', ENV["PORT"]) if ENV["PORT"] # 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. config.active_job.queue_adapter = :sidekiq config.encoding = "utf-8" # Enable the asset pipeline config.assets.enabled = true config.assets.initialize_on_precompile = false # Set i18n.enforce_available_locales to true config.i18n.enforce_available_locales = true config.force_ssl = ENV["APPLICATION_HOST"] config.middleware.insert_after ActionDispatch::SSL, Rack::CanonicalHost, ENV["APPLICATION_HOST"] if ENV["APPLICATION_HOST"] end end
class Voeis::SamplesController < Voeis::BaseController # Properly override defaults to ensure proper controller behavior # @see Voeis::BaseController defaults :route_collection_name => 'samples', :route_instance_name => 'sample', :collection_name => 'samples', :instance_name => 'sample', :resource_class => Voeis::Sample has_widgets do |root| root << widget(:flot_graph) end def index @project = parent site_id = params[:site_id] @site = @project.managed_repository{Voeis::Site.first(:id=>site_id)} if site_id #Voeis::Site.get(params[:site_id]) if site_id if site_id && @site #@samples = @site.samples.all(:order=>[:local_date_time.desc], :limit=>100) @samples = @site.samples.all(:limit=>100) else #@samples = parent.managed_repository{Voeis::Sample.all(:order=>[:local_date_time.desc], :limit=>100)} @samples = parent.managed_repository{Voeis::Sample.all(:limit=>100)} end @site_id = site_id end def show @project = parent #@samples = parent.managed_repository{Voeis::Sample.all} #@sample = parent.managed_repository{Voeis::Sample.get(params[:id].to_i)} parent.managed_repository{ @samples = Voeis::Sample.all @sample = Voeis::Sample.get(params[:id].to_i) } if !@sample.nil? @site = @sample.sites.first end @sample_properties = [ {:label=>"Sample ID", :name=>"id"}, {:label=>"Lab Code", :name=>"lab_sample_code"}, {:label=>"Sample Type", :name=>"sample_type"}, {:label=>"Sample Medium", :name=>"material"}, {:label=>"Updated", :name=>"updated_at"}, {:label=>"Updated By", :name=>"updated_by"}, {:label=>"Update Comment", :name=>"updated_comment"}, {:label=>"Created", :name=>"created_at"} ] #@project.managed_repository{ # @sample = Voeis::Sample.get(params[:id].to_i) # @sites = Voeis::Site.all # if !params[:site_id].nil? # @site = Voeis::Site.get(params[:site_id].to_i) # @site_variable_stats = Voeis::SiteDataCatalog.all(:variable_id=>params[:id].to_i, :site_id=>params[:site_id].to_i) # @graph_data = @variable.last_ten_values_graph(@site) # @data = @variable.last_ten_values(@site) # # @TEST = 'TESTING controller' # end #} end def new @project = parent @sample = @project.managed_repository{Voeis::Sample.new} @sample_types = Voeis::SampleTypeCV.all @sample_materials = Voeis::SampleMaterial.all @project_sample_materials = @project.managed_repository{Voeis::SampleMaterial.all} @sites = @project.managed_repository{Voeis::Site.all} @lab_methods = @project.managed_repository{Voeis::LabMethod.all} @label_array = Array["Sample Type","Lab Sample Code","Sample Medium","Site","Timestamp"] @current_samples = Array.new @samples = @project.managed_repository{Voeis::Sample.all} @samples.all(:order => [:lab_sample_code.asc]).each do |samp| @temp_array = Array.new @temp_array=Array[samp.sample_type, samp.lab_sample_code, samp.material,samp.sites.first.name, samp.local_date_time.to_s] @current_samples << @temp_array end end def edit @sample = parent.managed_repository{Voeis::Sample.get(params[:id])} @project = parent end def create puts "TIME" puts d_time = DateTime.parse("#{params[:time]["stamp(1i)"]}-#{params[:time]["stamp(2i)"]}-#{params[:time]["stamp(3i)"]}T#{params[:time]["stamp(4i)"]}:#{params[:time]["stamp(5i)"]}:00#{ActiveSupport::TimeZone[params[:time][:zone]].utc_offset/(60*60)}:00") parent.managed_repository do @sample = Voeis::Sample.new(:sample_type => params[:sample][:sample_type], :material => params[:sample][:material], :lab_sample_code => params[:sample][:lab_sample_code], :lab_method_id => params[:sample][:lab_method_id].to_i, :local_date_time => d_time) puts @sample.valid? puts @sample.errors.inspect() if @sample.save @sample.sites << Voeis::Site.get(params[:site].to_i) @sample.save flash[:notice] = 'Sample was successfully created.' redirect_to :action => 'new' end end end def upload end def add_sample @samples = Sample.all end def save_sample puts "TIME" puts d_time = DateTime.parse("#{params[:time]["stamp(1i)"]}-#{params[:time]["stamp(2i)"]}-#{params[:time]["stamp(3i)"]}T#{params[:time]["stamp(4i)"]}:#{params[:time]["stamp(5i)"]}:00#{ActiveSupport::TimeZone[params[:time][:zone]].utc_offset/(60*60)}:00") sys_sample = Sample.first(:id => params[:sample]) parent.managed_repository{Voeis::Sample.first_or_create( :sample_type=> sys_sample.sample_type, :lab_sample_code=> sys_sample.sample_code, :lab_method_id=> sys_sample.lab_method_id, :local_date_time => d_time)} redirect_to project_url(parent) end def site_sample_variables parent.managed_repository do site = Voeis::Site.get(params[:site_id]) @variable_hash = Hash.new i = 1 @variable_hash['variables'] = Array.new @variable_hash['variables'] = site.variables.map do |var| if data_catalog = Voeis::SiteDataCatalog.first(:site_id => site.id, :variable_id => var.id) var_hash = Hash.new var_hash['id'] = var.id if !data_catalog.starting_timestamp.nil? var_hash['name'] = var.variable_name+":"+var.data_type + "(" + data_catalog.starting_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + " - " + data_catalog.ending_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + ')' else var_hash['name'] = var.variable_name+":"+var.data_type end var_hash end #@variable_hash['variables'] << @var_hash end end respond_to do |format| format.json do format.html render :json => @variable_hash.to_json, :callback => params[:jsoncallback] end end end def query #q = repository.adapter.send(:select_statement,VOEISMODELQUERY.query) #sql = q[0].gsub!("?").each_with_index{|v,i| "\'#{q[1][i]}\'" } siteid = params[:site_id] varid = params[:var_id] dt_start = params[:start_date] dt_end = params[:end_date] @project_uid= parent.id parent.managed_repository do @site = Voeis::Site.get(siteid) if !siteid.nil? && siteid.to_i>0 # @start_year = Voeis::DataValue.first(:order => [:local_date_time.asc]) # @end_year = Voeis::DataValue.last(:order => [:local_date_time.asc]) @start_year = Voeis::SiteDataCatalog.first(:starting_timestamp.not => nil, :order => [:starting_timestamp.asc]) @end_year = Voeis::SiteDataCatalog.last(:ending_timestamp.not => nil, :order => [:ending_timestamp.asc]) #sensor_start_year = Voeis::SensorValue.first(:order => [:timestamp.asc]) #sensor_end_year = Voeis::SensorValue.last(:order => [:timestamp.asc]) if @start_year.nil? || @end_year.nil? @start_date = DateTime.now.strftime('%Y-%m-%d') @end_date = DateTime.now.strftime('%Y-%m-%d') @start_year = DateTime.now.year @end_year = DateTime.now.year else @start_date = @start_year.starting_timestamp.strftime('%Y-%m-%d') @end_date = @end_year.ending_timestamp.strftime('%Y-%m-%d') @start_year = @start_year.starting_timestamp.to_date.year @end_year = @end_year.ending_timestamp.to_date.year end @sites = Voeis::Site.all @variable_opt_array = Array.new if !@sites.empty? if !@sites.all(:order => [:name.asc]).first.variables.empty? #variable_opt_array << ["All", "All"] @sites.all(:order => [:name.asc]).first.variables.each do |var| data_catalog = Voeis::SiteDataCatalog.first(:site_id => @sites.all(:order => [:name.asc]).first.id, :variable_id => var.id) if !data_catalog.starting_timestamp.nil? @variable_opt_array << [var.variable_name+":"+var.data_type + "(" + data_catalog.starting_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + " - " + data_catalog.ending_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + ')', var.id.to_s] else @variable_opt_array << [var.variable_name+":"+var.data_type, var.id.to_s] end end @variable_count = @variable_opt_array.count else @variable_opt_array << ["None", "None"] @variable_count = 0 end end @variable_opts = opts_for_select(@variable_opt_array, selected=varid) #end end logger.info "######### @variable_opts" logger.info @variable_opt_array @site_opts_array = Array.new @sites.all(:order => [:name.asc]).each do |site| @site_opts_array << [site.name.capitalize+" | "+site.code, site.id.to_s] end @site_options = opts_for_select(@site_opts_array, selected=siteid) end def search @tabId = params[:tab_id] #@start_date = Date.civil(params[:range][:"start_date(1i)"].to_i,params[:range] [:"start_date(2i)"].to_i,params[:range][:"start_date(3i)"].to_i) #@end_date = Date.civil(params[:range][:"end_date(1i)"].to_i,params[:range] [:"end_date(2i)"].to_i,params[:range][:"end_date(3i)"].to_i) @start_date = Date.parse(params[:start_date]) @end_date = Date.parse(params[:end_date]) @start_date = @start_date.to_datetime @end_date = @end_date.to_datetime + 23.hour + 59.minute @project_uid = parent.id @data_set = parent.managed_repository{Voeis::DataSet.all} @data_set_opts_array = Array.new @data_set.all(:order => [:name.asc]).each do |ds| @data_set_opts_array << [ds.name.capitalize+' (DataSet)', ds.id.to_s] end @data_set_options = opts_for_select(@data_set_opts_array) @variables = parent.variables.all(:order=>[:variable_name.asc]) @variables_opts_array = @variables.reject{|v| v.id.to_s==params[:varaible_select]} .map{|v| ["%s | %s [%s]"%[v.variable_name.slice(0,32),v.variable_units.units_abbreviation,v.id],v.id.to_s]} @variables_options = opts_for_select(@variables_opts_array) site = parent.managed_repository{Voeis::Site.get(params[:site_select])} @site_name = site.name @site = site if params[:variable] != "None" variable = parent.managed_repository{Voeis::Variable.get(params[:variable_select])} @var_name = variable.variable_name @variable = variable @units = Voeis::Unit.get(variable.variable_units_id).units_name @graph_data = Array.new @data_structs = "" @meta_tags = "" parent.managed_repository do # q = repository.adapter.send(:select_statement, Voeis::DataValue.all(:site_id => site.id, :variable_id => variable.id, :local_date_time.gte => @start_date, :local_date_time.lte => @end_date, :order=>[:local_date_time.asc],:fields=>[:id,:data_value,:local_date_time,:string_value,:datatype, :vertical_offset,:quality_control_level, :published, :date_time_utc, :site_id,:variable_id,:utc_offset,:end_vertical_offset, :value_accuracy,:replicate]).query) #sql = q[0].gsub!("?").each_with_index{|v,i| "\'#{q[1][i]}\'" } #@data_structs = repository.adapter.select(sql) standard_query = {:site_id => site.id, :variable_id => variable.id, :local_date_time.gte => @start_date, :local_date_time.lte => @end_date, :order=>[:local_date_time.asc],:fields=>[:id,:data_value,:local_date_time,:string_value,:datatype, :vertical_offset,:quality_control_level, :published, :date_time_utc, :site_id,:variable_id,:utc_offset,:end_vertical_offset, :value_accuracy,:replicate]} if params[:first_value_select] != "blank" temp_query1 = build_value_query_stmt(params[:first_value_select], params[:first_value_text]) if params[:second_value_select] != "blank" temp_query2 = build_value_query_stmt(params[:second_value_select], params[:second_value_text]) if params[:and_or_select] == "and" @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query) & (Voeis::DataValue.all(temp_query1) & Voeis::DataValue.all(temp_query2))) debugger else debugger @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query) & (Voeis::DataValue.all(temp_query1) | Voeis::DataValue.all(temp_query2))) end else @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query) & Voeis::DataValue.all(temp_query1)) end else @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query)) end @meta_tags = DataMapper.raw_select(Voeis::DataValueMetaTag.all(:data_value_id=>@data_structs.map{|d| d.id})) end @meta_tag_hash=Hash.new @data_structs.each do |data_val| tz0 = data_val.utc_offset.to_s.split('.') tz = (tz0[0][0]=='-' ? '-' : '+')+('00'+tz0[0].to_i.abs.to_s)[-2,2]+':' tz += tz0.count>1 ? ('0'+((('.'+tz0[1]).to_f*100).to_i*0.6).to_i.to_s)[-2,2] : '00' data_val.local_date_time = data_val.local_date_time.to_s[0..18]+tz data_val.date_time_utc = data_val.date_time_utc.to_s[0..18]+"+00:00" dateval = DateTime.parse(data_val.date_time_utc).to_i*1000 #@graph_data << Array[data_val.date_time_utc.to_datetime.to_i*1000, data_val.data_value] @graph_data << Array[dateval, data_val.data_value] #@meta_tag_hash[data_val.id] = @meta_tags.map{|m| m.data_value_id == data_val.id}.to_a end @scripts = parent.managed_repository{Voeis::Script.all} @scripts_opts_array = Array.new @scripts.all(:order=>[:name.asc]).each do |scr| @scripts_opts_array << ['>> '+scr.name, scr.id.to_s] end @scripts_options = opts_for_select(@scripts_opts_array) respond_to do |format| format.js if format.json format.html if format.html end#end format else @var_name = "None" end #end if !site.empty? ##@variables = parent.managed_repository{parent.variables} #@variables_opts_array = @variables.reject{|v| v.id==@variable.id}.map{|v| [v.variable_name,v.id.to_s]} #variables_opts_array = [] #@variables.each do |v| # variables_opts_array << [v.variable_name, v.id.to_s] #end #@variables_options = opts_for_select(@variables_opts_array) #@testing = "<option value='TEST'>TESTING-1-2-3</option>\n" #debugger #render 'search.html.haml' end #end def def opts_for_select(opt_array, selected = nil) option_string ="" if !opt_array.empty? opt_array.each do |opt| if opt[1] == selected option_string = option_string + '<option selected="selected" value='+opt[1]+'>'+opt[0]+'</option>' else option_string = option_string + '<option value='+opt[1]+'>'+opt[0]+'</option>' end end end option_string end #export the results of search/browse to a csv file def export if params[:site_select] site="" variable="" parent.managed_repository do site = JSON[Voeis::Site.get(params[:site_select].to_i).to_json] variable = JSON[Voeis::Variable.get(params[:variable_select].to_i).to_json] end else site = JSON[params[:site]] variable = JSON[params[:variable]] end #if params[:site_select] export_q = parent.managed_repository{repository.adapter.send(:select_statement, Voeis::DataValue.all(:site_id => site["id"].to_i, :variable_id => variable["id"].to_i, :local_date_time.gte => params[:start_date], :local_date_time.lte => params[:end_date], :order=>[:local_date_time.asc]).query)} export_sql = export_q[0].gsub!("?").each_with_index{|v,i| "\'#{export_q[1][i]}\'" } rows=JSON[parent.managed_repository{repository.adapter.select(export_sql).sql_to_json}] csv_string = CSV.generate do |csv| #csv << column_names csv<< ["Site Information"] csv<< site.keys csv<< site.values csv<< ["Variable Information"] csv<< variable.keys csv<< variable.values csv<< ["Data"] csv << rows.first.keys rows.each do |row| csv << row.values end end #csv_string =JSON[params[:data_vals]].to_csv filename = site["name"] + ".csv" send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => filename) end private def build_value_query_stmt(operation_name, value) result = case operation_name when "eql" then {:data_value=>value.to_f} when "gte" then {:data_value.gte=>value.to_f} when "lte" then {:data_value.lte=>value.to_f} end end end UPDATE: bumped Samples limit: 100 --> 500 class Voeis::SamplesController < Voeis::BaseController # Properly override defaults to ensure proper controller behavior # @see Voeis::BaseController defaults :route_collection_name => 'samples', :route_instance_name => 'sample', :collection_name => 'samples', :instance_name => 'sample', :resource_class => Voeis::Sample has_widgets do |root| root << widget(:flot_graph) end def index @project = parent site_id = params[:site_id] @site = @project.managed_repository{Voeis::Site.first(:id=>site_id)} if site_id #Voeis::Site.get(params[:site_id]) if site_id if site_id && @site #@samples = @site.samples.all(:order=>[:local_date_time.desc], :limit=>100) @samples = @site.samples.all(:limit=>500) else #@samples = parent.managed_repository{Voeis::Sample.all(:order=>[:local_date_time.desc], :limit=>100)} @samples = parent.managed_repository{Voeis::Sample.all(:limit=>500)} end @site_id = site_id end def show @project = parent #@samples = parent.managed_repository{Voeis::Sample.all} #@sample = parent.managed_repository{Voeis::Sample.get(params[:id].to_i)} parent.managed_repository{ @samples = Voeis::Sample.all @sample = Voeis::Sample.get(params[:id].to_i) } if !@sample.nil? @site = @sample.sites.first end @sample_properties = [ {:label=>"Sample ID", :name=>"id"}, {:label=>"Lab Code", :name=>"lab_sample_code"}, {:label=>"Sample Type", :name=>"sample_type"}, {:label=>"Sample Medium", :name=>"material"}, {:label=>"Updated", :name=>"updated_at"}, {:label=>"Updated By", :name=>"updated_by"}, {:label=>"Update Comment", :name=>"updated_comment"}, {:label=>"Created", :name=>"created_at"} ] #@project.managed_repository{ # @sample = Voeis::Sample.get(params[:id].to_i) # @sites = Voeis::Site.all # if !params[:site_id].nil? # @site = Voeis::Site.get(params[:site_id].to_i) # @site_variable_stats = Voeis::SiteDataCatalog.all(:variable_id=>params[:id].to_i, :site_id=>params[:site_id].to_i) # @graph_data = @variable.last_ten_values_graph(@site) # @data = @variable.last_ten_values(@site) # # @TEST = 'TESTING controller' # end #} end def new @project = parent @sample = @project.managed_repository{Voeis::Sample.new} @sample_types = Voeis::SampleTypeCV.all @sample_materials = Voeis::SampleMaterial.all @project_sample_materials = @project.managed_repository{Voeis::SampleMaterial.all} @sites = @project.managed_repository{Voeis::Site.all} @lab_methods = @project.managed_repository{Voeis::LabMethod.all} @label_array = Array["Sample Type","Lab Sample Code","Sample Medium","Site","Timestamp"] @current_samples = Array.new @samples = @project.managed_repository{Voeis::Sample.all} @samples.all(:order => [:lab_sample_code.asc]).each do |samp| @temp_array = Array.new @temp_array=Array[samp.sample_type, samp.lab_sample_code, samp.material,samp.sites.first.name, samp.local_date_time.to_s] @current_samples << @temp_array end end def edit @sample = parent.managed_repository{Voeis::Sample.get(params[:id])} @project = parent end def create puts "TIME" puts d_time = DateTime.parse("#{params[:time]["stamp(1i)"]}-#{params[:time]["stamp(2i)"]}-#{params[:time]["stamp(3i)"]}T#{params[:time]["stamp(4i)"]}:#{params[:time]["stamp(5i)"]}:00#{ActiveSupport::TimeZone[params[:time][:zone]].utc_offset/(60*60)}:00") parent.managed_repository do @sample = Voeis::Sample.new(:sample_type => params[:sample][:sample_type], :material => params[:sample][:material], :lab_sample_code => params[:sample][:lab_sample_code], :lab_method_id => params[:sample][:lab_method_id].to_i, :local_date_time => d_time) puts @sample.valid? puts @sample.errors.inspect() if @sample.save @sample.sites << Voeis::Site.get(params[:site].to_i) @sample.save flash[:notice] = 'Sample was successfully created.' redirect_to :action => 'new' end end end def upload end def add_sample @samples = Sample.all end def save_sample puts "TIME" puts d_time = DateTime.parse("#{params[:time]["stamp(1i)"]}-#{params[:time]["stamp(2i)"]}-#{params[:time]["stamp(3i)"]}T#{params[:time]["stamp(4i)"]}:#{params[:time]["stamp(5i)"]}:00#{ActiveSupport::TimeZone[params[:time][:zone]].utc_offset/(60*60)}:00") sys_sample = Sample.first(:id => params[:sample]) parent.managed_repository{Voeis::Sample.first_or_create( :sample_type=> sys_sample.sample_type, :lab_sample_code=> sys_sample.sample_code, :lab_method_id=> sys_sample.lab_method_id, :local_date_time => d_time)} redirect_to project_url(parent) end def site_sample_variables parent.managed_repository do site = Voeis::Site.get(params[:site_id]) @variable_hash = Hash.new i = 1 @variable_hash['variables'] = Array.new @variable_hash['variables'] = site.variables.map do |var| if data_catalog = Voeis::SiteDataCatalog.first(:site_id => site.id, :variable_id => var.id) var_hash = Hash.new var_hash['id'] = var.id if !data_catalog.starting_timestamp.nil? var_hash['name'] = var.variable_name+":"+var.data_type + "(" + data_catalog.starting_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + " - " + data_catalog.ending_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + ')' else var_hash['name'] = var.variable_name+":"+var.data_type end var_hash end #@variable_hash['variables'] << @var_hash end end respond_to do |format| format.json do format.html render :json => @variable_hash.to_json, :callback => params[:jsoncallback] end end end def query #q = repository.adapter.send(:select_statement,VOEISMODELQUERY.query) #sql = q[0].gsub!("?").each_with_index{|v,i| "\'#{q[1][i]}\'" } siteid = params[:site_id] varid = params[:var_id] dt_start = params[:start_date] dt_end = params[:end_date] @project_uid= parent.id parent.managed_repository do @site = Voeis::Site.get(siteid) if !siteid.nil? && siteid.to_i>0 # @start_year = Voeis::DataValue.first(:order => [:local_date_time.asc]) # @end_year = Voeis::DataValue.last(:order => [:local_date_time.asc]) @start_year = Voeis::SiteDataCatalog.first(:starting_timestamp.not => nil, :order => [:starting_timestamp.asc]) @end_year = Voeis::SiteDataCatalog.last(:ending_timestamp.not => nil, :order => [:ending_timestamp.asc]) #sensor_start_year = Voeis::SensorValue.first(:order => [:timestamp.asc]) #sensor_end_year = Voeis::SensorValue.last(:order => [:timestamp.asc]) if @start_year.nil? || @end_year.nil? @start_date = DateTime.now.strftime('%Y-%m-%d') @end_date = DateTime.now.strftime('%Y-%m-%d') @start_year = DateTime.now.year @end_year = DateTime.now.year else @start_date = @start_year.starting_timestamp.strftime('%Y-%m-%d') @end_date = @end_year.ending_timestamp.strftime('%Y-%m-%d') @start_year = @start_year.starting_timestamp.to_date.year @end_year = @end_year.ending_timestamp.to_date.year end @sites = Voeis::Site.all @variable_opt_array = Array.new if !@sites.empty? if !@sites.all(:order => [:name.asc]).first.variables.empty? #variable_opt_array << ["All", "All"] @sites.all(:order => [:name.asc]).first.variables.each do |var| data_catalog = Voeis::SiteDataCatalog.first(:site_id => @sites.all(:order => [:name.asc]).first.id, :variable_id => var.id) if !data_catalog.starting_timestamp.nil? @variable_opt_array << [var.variable_name+":"+var.data_type + "(" + data_catalog.starting_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + " - " + data_catalog.ending_timestamp.to_date.to_formatted_s(:long).gsub('00:00','') + ')', var.id.to_s] else @variable_opt_array << [var.variable_name+":"+var.data_type, var.id.to_s] end end @variable_count = @variable_opt_array.count else @variable_opt_array << ["None", "None"] @variable_count = 0 end end @variable_opts = opts_for_select(@variable_opt_array, selected=varid) #end end logger.info "######### @variable_opts" logger.info @variable_opt_array @site_opts_array = Array.new @sites.all(:order => [:name.asc]).each do |site| @site_opts_array << [site.name.capitalize+" | "+site.code, site.id.to_s] end @site_options = opts_for_select(@site_opts_array, selected=siteid) end def search @tabId = params[:tab_id] #@start_date = Date.civil(params[:range][:"start_date(1i)"].to_i,params[:range] [:"start_date(2i)"].to_i,params[:range][:"start_date(3i)"].to_i) #@end_date = Date.civil(params[:range][:"end_date(1i)"].to_i,params[:range] [:"end_date(2i)"].to_i,params[:range][:"end_date(3i)"].to_i) @start_date = Date.parse(params[:start_date]) @end_date = Date.parse(params[:end_date]) @start_date = @start_date.to_datetime @end_date = @end_date.to_datetime + 23.hour + 59.minute @project_uid = parent.id @data_set = parent.managed_repository{Voeis::DataSet.all} @data_set_opts_array = Array.new @data_set.all(:order => [:name.asc]).each do |ds| @data_set_opts_array << [ds.name.capitalize+' (DataSet)', ds.id.to_s] end @data_set_options = opts_for_select(@data_set_opts_array) @variables = parent.variables.all(:order=>[:variable_name.asc]) @variables_opts_array = @variables.reject{|v| v.id.to_s==params[:varaible_select]} .map{|v| ["%s | %s [%s]"%[v.variable_name.slice(0,32),v.variable_units.units_abbreviation,v.id],v.id.to_s]} @variables_options = opts_for_select(@variables_opts_array) site = parent.managed_repository{Voeis::Site.get(params[:site_select])} @site_name = site.name @site = site if params[:variable] != "None" variable = parent.managed_repository{Voeis::Variable.get(params[:variable_select])} @var_name = variable.variable_name @variable = variable @units = Voeis::Unit.get(variable.variable_units_id).units_name @graph_data = Array.new @data_structs = "" @meta_tags = "" parent.managed_repository do # q = repository.adapter.send(:select_statement, Voeis::DataValue.all(:site_id => site.id, :variable_id => variable.id, :local_date_time.gte => @start_date, :local_date_time.lte => @end_date, :order=>[:local_date_time.asc],:fields=>[:id,:data_value,:local_date_time,:string_value,:datatype, :vertical_offset,:quality_control_level, :published, :date_time_utc, :site_id,:variable_id,:utc_offset,:end_vertical_offset, :value_accuracy,:replicate]).query) #sql = q[0].gsub!("?").each_with_index{|v,i| "\'#{q[1][i]}\'" } #@data_structs = repository.adapter.select(sql) standard_query = {:site_id => site.id, :variable_id => variable.id, :local_date_time.gte => @start_date, :local_date_time.lte => @end_date, :order=>[:local_date_time.asc],:fields=>[:id,:data_value,:local_date_time,:string_value,:datatype, :vertical_offset,:quality_control_level, :published, :date_time_utc, :site_id,:variable_id,:utc_offset,:end_vertical_offset, :value_accuracy,:replicate]} if params[:first_value_select] != "blank" temp_query1 = build_value_query_stmt(params[:first_value_select], params[:first_value_text]) if params[:second_value_select] != "blank" temp_query2 = build_value_query_stmt(params[:second_value_select], params[:second_value_text]) if params[:and_or_select] == "and" @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query) & (Voeis::DataValue.all(temp_query1) & Voeis::DataValue.all(temp_query2))) debugger else debugger @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query) & (Voeis::DataValue.all(temp_query1) | Voeis::DataValue.all(temp_query2))) end else @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query) & Voeis::DataValue.all(temp_query1)) end else @data_structs = DataMapper.raw_select(Voeis::DataValue.all(standard_query)) end @meta_tags = DataMapper.raw_select(Voeis::DataValueMetaTag.all(:data_value_id=>@data_structs.map{|d| d.id})) end @meta_tag_hash=Hash.new @data_structs.each do |data_val| tz0 = data_val.utc_offset.to_s.split('.') tz = (tz0[0][0]=='-' ? '-' : '+')+('00'+tz0[0].to_i.abs.to_s)[-2,2]+':' tz += tz0.count>1 ? ('0'+((('.'+tz0[1]).to_f*100).to_i*0.6).to_i.to_s)[-2,2] : '00' data_val.local_date_time = data_val.local_date_time.to_s[0..18]+tz data_val.date_time_utc = data_val.date_time_utc.to_s[0..18]+"+00:00" dateval = DateTime.parse(data_val.date_time_utc).to_i*1000 #@graph_data << Array[data_val.date_time_utc.to_datetime.to_i*1000, data_val.data_value] @graph_data << Array[dateval, data_val.data_value] #@meta_tag_hash[data_val.id] = @meta_tags.map{|m| m.data_value_id == data_val.id}.to_a end @scripts = parent.managed_repository{Voeis::Script.all} @scripts_opts_array = Array.new @scripts.all(:order=>[:name.asc]).each do |scr| @scripts_opts_array << ['>> '+scr.name, scr.id.to_s] end @scripts_options = opts_for_select(@scripts_opts_array) respond_to do |format| format.js if format.json format.html if format.html end#end format else @var_name = "None" end #end if !site.empty? ##@variables = parent.managed_repository{parent.variables} #@variables_opts_array = @variables.reject{|v| v.id==@variable.id}.map{|v| [v.variable_name,v.id.to_s]} #variables_opts_array = [] #@variables.each do |v| # variables_opts_array << [v.variable_name, v.id.to_s] #end #@variables_options = opts_for_select(@variables_opts_array) #@testing = "<option value='TEST'>TESTING-1-2-3</option>\n" #debugger #render 'search.html.haml' end #end def def opts_for_select(opt_array, selected = nil) option_string ="" if !opt_array.empty? opt_array.each do |opt| if opt[1] == selected option_string = option_string + '<option selected="selected" value='+opt[1]+'>'+opt[0]+'</option>' else option_string = option_string + '<option value='+opt[1]+'>'+opt[0]+'</option>' end end end option_string end #export the results of search/browse to a csv file def export if params[:site_select] site="" variable="" parent.managed_repository do site = JSON[Voeis::Site.get(params[:site_select].to_i).to_json] variable = JSON[Voeis::Variable.get(params[:variable_select].to_i).to_json] end else site = JSON[params[:site]] variable = JSON[params[:variable]] end #if params[:site_select] export_q = parent.managed_repository{repository.adapter.send(:select_statement, Voeis::DataValue.all(:site_id => site["id"].to_i, :variable_id => variable["id"].to_i, :local_date_time.gte => params[:start_date], :local_date_time.lte => params[:end_date], :order=>[:local_date_time.asc]).query)} export_sql = export_q[0].gsub!("?").each_with_index{|v,i| "\'#{export_q[1][i]}\'" } rows=JSON[parent.managed_repository{repository.adapter.select(export_sql).sql_to_json}] csv_string = CSV.generate do |csv| #csv << column_names csv<< ["Site Information"] csv<< site.keys csv<< site.values csv<< ["Variable Information"] csv<< variable.keys csv<< variable.values csv<< ["Data"] csv << rows.first.keys rows.each do |row| csv << row.values end end #csv_string =JSON[params[:data_vals]].to_csv filename = site["name"] + ".csv" send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => filename) end private def build_value_query_stmt(operation_name, value) result = case operation_name when "eql" then {:data_value=>value.to_f} when "gte" then {:data_value.gte=>value.to_f} when "lte" then {:data_value.lte=>value.to_f} end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' require 'devise' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Blog 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 add thing require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Blog 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
require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Walkrr 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end include path encode & decode from config/application.rb require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end require './lib/geometry_encode_util' require './lib/line_string_ext' require './lib/multi_polygon_ext' module Walkrr 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end
module Binco class BootstrapFormBuilder < ActionView::Helpers::FormBuilder def text_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def telephone_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def select(method, choices = nil, options = {}, html_options = {}, &block) html_options = add_class_to_options('form-control', html_options) super method, choices, options, html_options, &block end def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block) if block_given? super(method, collection, value_method, text_method, options, html_options, &block) else super method, collection, value_method, text_method, options, html_options do |b| group_tag class: 'checkbox' do b.label do b.check_box + b.text end end end end end # Since select2 support multiple choices (checkboxes) def collection_check_boxes2(method, collection, value_method, text_method, options = {}, html_options = {}) options ||= {} options[:multiple] = 'multiple' collection_select2 method, collection, value_method, text_method, options, html_options end def collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) html_options = add_class_to_options('form-control', options) super method, collection, value_method, text_method, options, html_options end def collection_select2(method, collection, value_method, text_method, options = {}, html_options = {}, &block) options = add_class_to_options('select2-rails', options) collection_select(method, collection, value_method, text_method, options, html_options) end def email_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def number_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def password_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def datepicker(method, options = {}) options = add_data_to_options({ provide: 'datepicker' }, options) text_field(method, options) end def text_area(method, options = {}) options = add_class_to_options('form-control', options) super(method, options) end def radio_button(method, tag_value, options = {}) options = add_class_to_options('radio', options) super method, tag_value, options end def check_box(method, options = {}, checked_value = "1", unchecked_value = "0") options = add_class_to_options('checkbox', options) super method, options, checked_value, unchecked_value end def submit(value = nil, options = {}) options = add_class_to_options('btn btn-success', options) super value, options end def form_group(options = {}, &block) options = add_class_to_options('form-group', options) group_tag options, &block end def radio_group(options = {}, &block) options = add_class_to_options('radio', options) group_tag options, &block end def checkbox_group(options = {}, &block) options = add_class_to_options('checkbox', options) group_tag options, &block end def input_group(options = {}, &block) options = add_class_to_options('input-group', options) group_tag options, &block end private # Add the specified class_name the the options hash def add_class_to_options(class_name, options = {}) options[:class] ||= '' options[:class] << " #{class_name}" options end # Add the specified data-attributes the the options hash def add_data_to_options(data, options = {}) options[:data] ||= {} options[:data].merge! data options end def group_tag(attributes = {}, &block) @template.content_tag :div, attributes do yield end end end end Add alias to original collection_select module Binco class BootstrapFormBuilder < ActionView::Helpers::FormBuilder alias_method :collection_select_original, :collection_select def text_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def telephone_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def select(method, choices = nil, options = {}, html_options = {}, &block) html_options = add_class_to_options('form-control', html_options) super method, choices, options, html_options, &block end def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block) if block_given? super(method, collection, value_method, text_method, options, html_options, &block) else super method, collection, value_method, text_method, options, html_options do |b| group_tag class: 'checkbox' do b.label do b.check_box + b.text end end end end end # Since select2 support multiple choices (checkboxes) def collection_check_boxes2(method, collection, value_method, text_method, options = {}, html_options = {}) options ||= {} options[:multiple] = 'multiple' collection_select2 method, collection, value_method, text_method, options, html_options end def collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) html_options = add_class_to_options('form-control', options) super method, collection, value_method, text_method, options, html_options end def collection_select2(method, collection, value_method, text_method, options = {}, html_options = {}, &block) options = add_class_to_options('select2-rails', options) collection_select(method, collection, value_method, text_method, options, html_options) end def email_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def number_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def password_field(name, options = {}) options = add_class_to_options('form-control', options) super name, options end def datepicker(method, options = {}) options = add_data_to_options({ provide: 'datepicker' }, options) text_field(method, options) end def text_area(method, options = {}) options = add_class_to_options('form-control', options) super(method, options) end def radio_button(method, tag_value, options = {}) options = add_class_to_options('radio', options) super method, tag_value, options end def check_box(method, options = {}, checked_value = "1", unchecked_value = "0") options = add_class_to_options('checkbox', options) super method, options, checked_value, unchecked_value end def submit(value = nil, options = {}) options = add_class_to_options('btn btn-success', options) super value, options end def form_group(options = {}, &block) options = add_class_to_options('form-group', options) group_tag options, &block end def radio_group(options = {}, &block) options = add_class_to_options('radio', options) group_tag options, &block end def checkbox_group(options = {}, &block) options = add_class_to_options('checkbox', options) group_tag options, &block end def input_group(options = {}, &block) options = add_class_to_options('input-group', options) group_tag options, &block end private # Add the specified class_name the the options hash def add_class_to_options(class_name, options = {}) options[:class] ||= '' options[:class] << " #{class_name}" options end # Add the specified data-attributes the the options hash def add_data_to_options(data, options = {}) options[:data] ||= {} options[:data].merge! data options end def group_tag(attributes = {}, &block) @template.content_tag :div, attributes do yield end end end end
module CamaleonCms::UploaderHelper include ActionView::Helpers::NumberHelper # upload a file into server # settings: # folder: Directory where the file will be saved (default: "") # sample: temporal => will save in /rails_path/public/temporal # generate_thumb: true, # generate thumb image if this is image format (default true) # maximum: maximum bytes permitted to upload (default: 1000MG) # dimension: dimension for the image (sample: 30x30 | x30 | 30x | 300x300?) # formats: extensions permitted, sample: jpg,png,... or generic: images | videos | audios | documents (default *) # remove_source: Boolean (delete source file after saved if this is true, default false) # same_name: Boolean (save the file with the same name if defined true, else search for a non used name) # versions: (String) Create addtional multiple versions of the image uploaded, sample: '300x300,505x350' ==> Will create two extra images with these dimensions # sample "test.png", versions: '200x200,450x450' will generate: thumb/test-png_200x200.png, test-png_450x450.png # thumb_size: String (redefine the dimensions of the thumbnail, sample: '100x100' ==> only for images) # temporal_time: if great than 0 seconds, then this file will expire (removed) in that time (default: 0) # To manage jobs, please check http://edgeguides.rubyonrails.org/active_job_basics.html # Note: if you are using temporal_time, you will need to copy the file to another directory later # sample: upload_file(params[:my_file], {formats: "images", folder: "temporal"}) # sample: upload_file(params[:my_file], {formats: "jpg,png,gif,mp3,mp4", temporal_time: 10.minutes, maximum: 10.megabytes}) def upload_file(uploaded_io, settings = {}) cached_name = uploaded_io.is_a?(ActionDispatch::Http::UploadedFile) ? uploaded_io.original_filename : nil return {error: "File is empty", file: nil, size: nil} unless uploaded_io.present? if uploaded_io.is_a?(String) && (uploaded_io.start_with?("http://") || uploaded_io.start_with?("https://")) # download url file tmp = cama_tmp_upload(uploaded_io) return tmp if tmp[:error].present? settings[:remove_source] = true uploaded_io = tmp[:file_path] end uploaded_io = File.open(uploaded_io) if uploaded_io.is_a?(String) uploaded_io = File.open(cama_resize_upload(uploaded_io.path, settings[:dimension])) if settings[:dimension].present? # resize file into specific dimensions settings = settings.to_sym settings[:uploaded_io] = uploaded_io settings = { folder: "", maximum: current_site.get_option('filesystem_max_size', 100).to_f.megabytes, formats: "*", generate_thumb: true, temporal_time: 0, filename: ((cached_name || uploaded_io.original_filename) rescue uploaded_io.path.split("/").last).cama_fix_filename, file_size: File.size(uploaded_io.to_io), remove_source: false, same_name: false, versions: '', thumb_size: nil }.merge(settings) hooks_run("before_upload", settings) res = {error: nil} # formats validations return {error: "#{ct("file_format_error")} (#{settings[:formats]})"} unless cama_uploader.class.validate_file_format(uploaded_io.path, settings[:formats]) # file size validations if settings[:maximum] < settings[:file_size] res[:error] = "#{ct("file_size_exceeded", default: "File size exceeded")} (#{number_to_human_size(settings[:maximum])})" return res end # save file key = File.join(settings[:folder], settings[:filename]).to_s.cama_fix_slash res = cama_uploader.add_file(settings[:uploaded_io], key, {same_name: settings[:same_name]}) {} if settings[:temporal_time] > 0 # temporal file upload (always put as local for temporal files) (TODO: use delayjob) # generate image versions if res['file_type'] == 'image' settings[:versions].to_s.gsub(' ', '').split(',').each do |v| version_path = cama_resize_upload(settings[:uploaded_io].path, v, {replace: false}) cama_uploader.add_file(version_path, cama_uploader.version_path(res['key'], v), is_thumb: true, same_name: true) FileUtils.rm_f(version_path) end end # generate thumb cama_uploader_generate_thumbnail(uploaded_io.path, res['key'], settings[:thumb_size]) if settings[:generate_thumb] && res['thumb'].present? FileUtils.rm_f(uploaded_io.path) if settings[:remove_source] hooks_run('after_upload', settings) res end # generate thumbnail of a existent image # key: key of the current file # the thumbnail will be saved in my_images/my_img.png => my_images/thumb/my_img.png def cama_uploader_generate_thumbnail(uploaded_io, key, thumb_size = nil) w, h = cama_uploader.thumb[:w], cama_uploader.thumb[:h] w, h = thumb_size.split('x') if thumb_size.present? uploaded_io = File.open(uploaded_io) if uploaded_io.is_a?(String) path_thumb = cama_resize_and_crop(uploaded_io.path, w, h) thumb = cama_uploader.add_file(path_thumb, cama_uploader.version_path(key).sub('.svg', '.jpg'), is_thumb: true, same_name: true) FileUtils.rm_f(path_thumb) thumb end # helper to find an available filename for file_path in that directory # sample: uploader_verify_name("/var/www/my_image.jpg") # return "/var/www/my_image_1.jpg" => if "/var/www/my_image.jpg" exist # return "/var/www/my_image.jpg" => if "/var/www/my_image.jpg" doesn't exist def uploader_verify_name(file_path) dir, filename = File.dirname(file_path), File.basename(file_path).to_s.cama_fix_filename files = Dir.entries(dir) if files.include?(filename) i, _filename = 1, filename while files.include?(_filename) do _filename = "#{File.basename(filename, File.extname(filename))}_#{i}#{File.extname(filename)}" i += 1 end filename = _filename end "#{File.dirname(file_path)}/#{filename}" end # convert downloaded file path into public url def cama_file_path_to_url(file_path) file_path.sub(Rails.public_path.to_s, (root_url rescue cama_root_url)) end # convert public url to file path def cama_url_to_file_path(url) File.join(Rails.public_path, URI(url.to_s).path) end # crop and image and saved as imagename_crop.ext # file: file path # w: new width # h: new height # w_offset: left offset # w_offset: top offset # resize: true/false # (true => resize the image to this dimension) # (false => crop the image with this dimension) # replace: Boolean (replace current image or create another file) def cama_crop_image(file_path, w=nil, h=nil, w_offset = 0, h_offset = 0, resize = false , replace = true) force = "" force = "!" if w.present? && h.present? && !w.include?("?") && !h.include?("?") image = MiniMagick::Image.open(file_path) w = image[:width].to_f > w.sub('?', '').to_i ? w.sub('?', "") : image[:width] if w.present? && w.to_s.include?('?') h = image[:height].to_f > h.sub('?', '').to_i ? h.sub('?', "") : image[:height] if h.present? && h.to_s.include?('?') image.combine_options do |i| i.resize("#{w if w.present?}x#{h if h.present?}#{force}") if resize i.crop "#{w if w.present?}x#{h if h.present?}+#{w_offset}+#{h_offset}#{force}" unless resize end res = file_path unless replace ext = File.extname(file_path) res = file_path.gsub(ext, "_crop#{ext}") end image.write res res end # resize and crop a file # SVGs are converted to JPEGs for editing # Params: # file: (String) File path # w: (Integer) width # h: (Integer) height # settings: # gravity: (Sym, default :north_east) Crop position: :north_west, :north, :north_east, :east, :south_east, :south, :south_west, :west, :center # overwrite: (Boolean, default true) true for overwrite current image with resized resolutions, false: create other file called with prefix "crop_" # output_name: (String, default prefixd name with crop_), permit to define the output name of the thumbnail if overwrite = true # Return: (String) file path where saved this cropped # sample: cama_resize_and_crop(my_file, 200, 200, {gravity: :north_east, overwrite: false}) def cama_resize_and_crop(file, w, h, settings = {}) settings = {gravity: :north_east, overwrite: true, output_name: ""}.merge(settings) img = MiniMagick::Image.open(file) if file.end_with? '.svg' img.format 'jpg' file.sub! '.svg', '.jpg' settings[:output_name]&.sub! 'svg', 'jpg' end w = img[:width].to_f > w.sub('?', '').to_i ? w.sub('?', "") : img[:width] if w.present? && w.to_s.include?('?') h = img[:height].to_f > h.sub('?', '').to_i ? h.sub('?', "") : img[:height] if h.present? && h.to_s.include?('?') w_original, h_original = [img[:width].to_f, img[:height].to_f] w = w.to_i if w.present? h = h.to_i if h.present? # check proportions if w_original * h < h_original * w op_resize = "#{w.to_i}x" w_result = w h_result = (h_original * w / w_original) else op_resize = "x#{h.to_i}" w_result = (w_original * h / h_original) h_result = h end w_offset, h_offset = cama_crop_offsets_by_gravity(settings[:gravity], [w_result, h_result], [w, h]) data = {img: img, w: w, h: h, w_offset: w_offset, h_offset: h_offset, op_resize: op_resize, settings: settings}; hooks_run("before_resize_crop", data) data[:img].combine_options do |i| i.resize(data[:op_resize]) i.gravity(settings[:gravity]) i.crop "#{data[:w].to_i}x#{data[:h].to_i}+#{data[:w_offset]}+#{data[:h_offset]}!" end if settings[:overwrite] data[:img].write(file.sub '.svg', '.jpg') else if settings[:output_name].present? data[:img].write(file = File.join(File.dirname(file), settings[:output_name]).to_s) else data[:img].write(file = uploader_verify_name(File.join(File.dirname(file), "crop_#{File.basename(file.sub '.svg', '.jpg')}"))) end end file end # upload tmp file # support for url and local path # sample: # cama_tmp_upload('http://camaleon.tuzitio.com/media/132/logo2.png') ==> /var/rails/my_project/public/tmp/1/logo2.png # cama_tmp_upload('/var/www/media/132/logo 2.png') ==> /var/rails/my_project/public/tmp/1/logo-2.png # accept args: # name: to indicate the name to use, sample: cama_tmp_upload('/var/www/media/132/logo 2.png', {name: 'owen.png', formats: 'images'}) # formats: extensions permitted, sample: jpg,png,... or generic: images | videos | audios | documents (default *) # dimension: 20x30 # return: {file_path, error} def cama_tmp_upload(uploaded_io, args = {}) tmp_path = args[:path] || File.join(Rails.public_path, "tmp", current_site.id.to_s).to_s FileUtils.mkdir_p(tmp_path) unless Dir.exist?(tmp_path) saved = false if uploaded_io.is_a?(String) && (uploaded_io.start_with?("data:")) # create tmp file using base64 format _tmp_name = args[:name] return {error: "#{cama_t("camaleon_cms.admin.media.name_required")}"} unless params[:name].present? return {error: "#{ct("file_format_error")} (#{args[:formats]})"} unless cama_uploader.class.validate_file_format(_tmp_name, args[:formats]) path = uploader_verify_name(File.join(tmp_path, _tmp_name)) File.open(path, 'wb'){|f| f.write(Base64.decode64(uploaded_io.split(';base64,').last)) } uploaded_io = File.open(path) saved = true elsif uploaded_io.is_a?(String) && (uploaded_io.start_with?("http://") || uploaded_io.start_with?("https://")) return {error: "#{ct("file_format_error")} (#{args[:formats]})"} unless cama_uploader.class.validate_file_format(uploaded_io, args[:formats]) uploaded_io = File.join(Rails.public_path, uploaded_io.sub(current_site.the_url(locale: nil), '')).to_s if uploaded_io.include?(current_site.the_url(locale: nil)) # local file _tmp_name = uploaded_io.split("/").last.split('?').first; args[:name] = args[:name] || _tmp_name uploaded_io = open(uploaded_io) end uploaded_io = File.open(uploaded_io) if uploaded_io.is_a?(String) return {error: "#{ct("file_format_error")} (#{args[:formats]})"} unless cama_uploader.class.validate_file_format(_tmp_name || uploaded_io.path, args[:formats]) return {error: "#{ct("file_size_exceeded", default: "File size exceeded")} (#{number_to_human_size(args[:maximum])})"} if args[:maximum].present? && args[:maximum] < (uploaded_io.size rescue File.size(uploaded_io)) name = args[:name] || uploaded_io.try(:original_filename) || uploaded_io.path.split("/").last; name = "#{File.basename(name, File.extname(name)).underscore}#{File.extname(name)}" path ||= uploader_verify_name(File.join(tmp_path, name)) File.open(path, "wb"){|f| f.write(uploaded_io.read) } unless saved path = cama_resize_upload(path, args[:dimension]) if args[:dimension].present? {file_path: path, error: nil} end # resize image if the format is correct # return resized file path def cama_resize_upload(image_path, dimesion, args = {}) if cama_uploader.class.validate_file_format(image_path, 'image') && dimesion.present? r= {file: image_path, w: dimesion.split('x')[0], h: dimesion.split('x')[1], w_offset: 0, h_offset: 0, resize: !dimesion.split('x')[2] || dimesion.split('x')[2] == "resize", replace: true, gravity: :north_east}.merge(args); hooks_run("on_uploader_resize", r) if r[:w].present? && r[:h].present? image_path = cama_resize_and_crop(r[:file], r[:w], r[:h], {overwrite: r[:replace], gravity: r[:gravity] }) else image_path = cama_crop_image(r[:file], r[:w], r[:h], r[:w_offset], r[:h_offset], r[:resize] , r[:replace]) end end image_path end # return the current uploader def cama_uploader @cama_uploader ||= lambda{ thumb = current_site.get_option('filesystem_thumb_size', '100x100').split('x') args= { server: current_site.get_option("filesystem_type", "local").downcase, thumb: {w: thumb[0], h: thumb[1]}, aws_settings: { region: current_site.get_option("filesystem_region", 'us-west-2'), access_key: current_site.get_option("filesystem_s3_access_key"), secret_key: current_site.get_option("filesystem_s3_secret_key"), bucket: current_site.get_option("filesystem_s3_bucket_name"), cloud_front: current_site.get_option("filesystem_s3_cloudfront"), aws_file_upload_settings: lambda{|settings| settings }, # permit to add your custom attributes for file_upload http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Object.html#upload_file-instance_method aws_file_read_settings: lambda{|data, s3_file| data } # permit to read custom attributes from aws file and add to file parsed object }, custom_uploader: nil # posibility to use custom file uploader } hooks_run("on_uploader", args) return args[:custom_uploader] if args[:custom_uploader].present? case args[:server] when 's3', 'aws' CamaleonCmsAwsUploader.new({current_site: current_site, thumb: args[:thumb], aws_settings: args[:aws_settings]}, self) else CamaleonCmsLocalUploader.new({current_site: current_site, thumb: args[:thumb]}, self) end }.call end def slugify(val) val.to_s.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') end def slugify_folder(val) splitted_folder = val.split('/') splitted_folder[-1] = slugify(splitted_folder.last) splitted_folder.join('/') end private # helper for resize and crop method def cama_crop_offsets_by_gravity(gravity, original_dimensions, cropped_dimensions) original_width, original_height = original_dimensions cropped_width, cropped_height = cropped_dimensions vertical_offset = case gravity when :north_west, :north, :north_east then 0 when :center, :east, :west then [ ((original_height - cropped_height) / 2.0).to_i, 0 ].max when :south_west, :south, :south_east then (original_height - cropped_height).to_i end horizontal_offset = case gravity when :north_west, :west, :south_west then 0 when :center, :north, :south then [ ((original_width - cropped_width) / 2.0).to_i, 0 ].max when :north_east, :east, :south_east then (original_width - cropped_width).to_i end return [ horizontal_offset, vertical_offset ] end # convert file path into thumb path format # return the image name into thumb format: owewen.png into thumb/owen-png.png def cama_parse_for_thumb_name(file_path) "#{@fog_connection_hook_res[:thumb_folder_name]}/#{File.basename(file_path).parameterize}#{File.extname(file_path)}" end end Fix typo module CamaleonCms::UploaderHelper include ActionView::Helpers::NumberHelper # upload a file into server # settings: # folder: Directory where the file will be saved (default: "") # sample: temporal => will save in /rails_path/public/temporal # generate_thumb: true, # generate thumb image if this is image format (default true) # maximum: maximum bytes permitted to upload (default: 1000MG) # dimension: dimension for the image (sample: 30x30 | x30 | 30x | 300x300?) # formats: extensions permitted, sample: jpg,png,... or generic: images | videos | audios | documents (default *) # remove_source: Boolean (delete source file after saved if this is true, default false) # same_name: Boolean (save the file with the same name if defined true, else search for a non used name) # versions: (String) Create addtional multiple versions of the image uploaded, sample: '300x300,505x350' ==> Will create two extra images with these dimensions # sample "test.png", versions: '200x200,450x450' will generate: thumb/test-png_200x200.png, test-png_450x450.png # thumb_size: String (redefine the dimensions of the thumbnail, sample: '100x100' ==> only for images) # temporal_time: if great than 0 seconds, then this file will expire (removed) in that time (default: 0) # To manage jobs, please check http://edgeguides.rubyonrails.org/active_job_basics.html # Note: if you are using temporal_time, you will need to copy the file to another directory later # sample: upload_file(params[:my_file], {formats: "images", folder: "temporal"}) # sample: upload_file(params[:my_file], {formats: "jpg,png,gif,mp3,mp4", temporal_time: 10.minutes, maximum: 10.megabytes}) def upload_file(uploaded_io, settings = {}) cached_name = uploaded_io.is_a?(ActionDispatch::Http::UploadedFile) ? uploaded_io.original_filename : nil return {error: "File is empty", file: nil, size: nil} unless uploaded_io.present? if uploaded_io.is_a?(String) && (uploaded_io.start_with?("http://") || uploaded_io.start_with?("https://")) # download url file tmp = cama_tmp_upload(uploaded_io) return tmp if tmp[:error].present? settings[:remove_source] = true uploaded_io = tmp[:file_path] end uploaded_io = File.open(uploaded_io) if uploaded_io.is_a?(String) uploaded_io = File.open(cama_resize_upload(uploaded_io.path, settings[:dimension])) if settings[:dimension].present? # resize file into specific dimensions settings = settings.to_sym settings[:uploaded_io] = uploaded_io settings = { folder: "", maximum: current_site.get_option('filesystem_max_size', 100).to_f.megabytes, formats: "*", generate_thumb: true, temporal_time: 0, filename: ((cached_name || uploaded_io.original_filename) rescue uploaded_io.path.split("/").last).cama_fix_filename, file_size: File.size(uploaded_io.to_io), remove_source: false, same_name: false, versions: '', thumb_size: nil }.merge(settings) hooks_run("before_upload", settings) res = {error: nil} # formats validations return {error: "#{ct("file_format_error")} (#{settings[:formats]})"} unless cama_uploader.class.validate_file_format(uploaded_io.path, settings[:formats]) # file size validations if settings[:maximum] < settings[:file_size] res[:error] = "#{ct("file_size_exceeded", default: "File size exceeded")} (#{number_to_human_size(settings[:maximum])})" return res end # save file key = File.join(settings[:folder], settings[:filename]).to_s.cama_fix_slash res = cama_uploader.add_file(settings[:uploaded_io], key, {same_name: settings[:same_name]}) {} if settings[:temporal_time] > 0 # temporal file upload (always put as local for temporal files) (TODO: use delayjob) # generate image versions if res['file_type'] == 'image' settings[:versions].to_s.gsub(' ', '').split(',').each do |v| version_path = cama_resize_upload(settings[:uploaded_io].path, v, {replace: false}) cama_uploader.add_file(version_path, cama_uploader.version_path(res['key'], v), is_thumb: true, same_name: true) FileUtils.rm_f(version_path) end end # generate thumb cama_uploader_generate_thumbnail(uploaded_io.path, res['key'], settings[:thumb_size]) if settings[:generate_thumb] && res['thumb'].present? FileUtils.rm_f(uploaded_io.path) if settings[:remove_source] hooks_run('after_upload', settings) res end # generate thumbnail of a existent image # key: key of the current file # the thumbnail will be saved in my_images/my_img.png => my_images/thumb/my_img.png def cama_uploader_generate_thumbnail(uploaded_io, key, thumb_size = nil) w, h = cama_uploader.thumb[:w], cama_uploader.thumb[:h] w, h = thumb_size.split('x') if thumb_size.present? uploaded_io = File.open(uploaded_io) if uploaded_io.is_a?(String) path_thumb = cama_resize_and_crop(uploaded_io.path, w, h) thumb = cama_uploader.add_file(path_thumb, cama_uploader.version_path(key).sub('.svg', '.jpg'), is_thumb: true, same_name: true) FileUtils.rm_f(path_thumb) thumb end # helper to find an available filename for file_path in that directory # sample: uploader_verify_name("/var/www/my_image.jpg") # return "/var/www/my_image_1.jpg" => if "/var/www/my_image.jpg" exist # return "/var/www/my_image.jpg" => if "/var/www/my_image.jpg" doesn't exist def uploader_verify_name(file_path) dir, filename = File.dirname(file_path), File.basename(file_path).to_s.cama_fix_filename files = Dir.entries(dir) if files.include?(filename) i, _filename = 1, filename while files.include?(_filename) do _filename = "#{File.basename(filename, File.extname(filename))}_#{i}#{File.extname(filename)}" i += 1 end filename = _filename end "#{File.dirname(file_path)}/#{filename}" end # convert downloaded file path into public url def cama_file_path_to_url(file_path) file_path.sub(Rails.public_path.to_s, (root_url rescue cama_root_url)) end # convert public url to file path def cama_url_to_file_path(url) File.join(Rails.public_path, URI(url.to_s).path) end # crop and image and saved as imagename_crop.ext # file: file path # w: new width # h: new height # w_offset: left offset # w_offset: top offset # resize: true/false # (true => resize the image to this dimension) # (false => crop the image with this dimension) # replace: Boolean (replace current image or create another file) def cama_crop_image(file_path, w=nil, h=nil, w_offset = 0, h_offset = 0, resize = false , replace = true) force = "" force = "!" if w.present? && h.present? && !w.include?("?") && !h.include?("?") image = MiniMagick::Image.open(file_path) w = image[:width].to_f > w.sub('?', '').to_i ? w.sub('?', "") : image[:width] if w.present? && w.to_s.include?('?') h = image[:height].to_f > h.sub('?', '').to_i ? h.sub('?', "") : image[:height] if h.present? && h.to_s.include?('?') image.combine_options do |i| i.resize("#{w if w.present?}x#{h if h.present?}#{force}") if resize i.crop "#{w if w.present?}x#{h if h.present?}+#{w_offset}+#{h_offset}#{force}" unless resize end res = file_path unless replace ext = File.extname(file_path) res = file_path.gsub(ext, "_crop#{ext}") end image.write res res end # resize and crop a file # SVGs are converted to JPEGs for editing # Params: # file: (String) File path # w: (Integer) width # h: (Integer) height # settings: # gravity: (Sym, default :north_east) Crop position: :north_west, :north, :north_east, :east, :south_east, :south, :south_west, :west, :center # overwrite: (Boolean, default true) true for overwrite current image with resized resolutions, false: create other file called with prefix "crop_" # output_name: (String, default prefixd name with crop_), permit to define the output name of the thumbnail if overwrite = true # Return: (String) file path where saved this cropped # sample: cama_resize_and_crop(my_file, 200, 200, {gravity: :north_east, overwrite: false}) def cama_resize_and_crop(file, w, h, settings = {}) settings = {gravity: :north_east, overwrite: true, output_name: ""}.merge(settings) img = MiniMagick::Image.open(file) if file.end_with? '.svg' img.format 'jpg' file.sub! '.svg', '.jpg' settings[:output_name].sub!('.svg', '.jpg') if settings[:output_name] end w = img[:width].to_f > w.sub('?', '').to_i ? w.sub('?', "") : img[:width] if w.present? && w.to_s.include?('?') h = img[:height].to_f > h.sub('?', '').to_i ? h.sub('?', "") : img[:height] if h.present? && h.to_s.include?('?') w_original, h_original = [img[:width].to_f, img[:height].to_f] w = w.to_i if w.present? h = h.to_i if h.present? # check proportions if w_original * h < h_original * w op_resize = "#{w.to_i}x" w_result = w h_result = (h_original * w / w_original) else op_resize = "x#{h.to_i}" w_result = (w_original * h / h_original) h_result = h end w_offset, h_offset = cama_crop_offsets_by_gravity(settings[:gravity], [w_result, h_result], [w, h]) data = {img: img, w: w, h: h, w_offset: w_offset, h_offset: h_offset, op_resize: op_resize, settings: settings}; hooks_run("before_resize_crop", data) data[:img].combine_options do |i| i.resize(data[:op_resize]) i.gravity(settings[:gravity]) i.crop "#{data[:w].to_i}x#{data[:h].to_i}+#{data[:w_offset]}+#{data[:h_offset]}!" end if settings[:overwrite] data[:img].write(file.sub '.svg', '.jpg') else if settings[:output_name].present? data[:img].write(file = File.join(File.dirname(file), settings[:output_name]).to_s) else data[:img].write(file = uploader_verify_name(File.join(File.dirname(file), "crop_#{File.basename(file.sub '.svg', '.jpg')}"))) end end file end # upload tmp file # support for url and local path # sample: # cama_tmp_upload('http://camaleon.tuzitio.com/media/132/logo2.png') ==> /var/rails/my_project/public/tmp/1/logo2.png # cama_tmp_upload('/var/www/media/132/logo 2.png') ==> /var/rails/my_project/public/tmp/1/logo-2.png # accept args: # name: to indicate the name to use, sample: cama_tmp_upload('/var/www/media/132/logo 2.png', {name: 'owen.png', formats: 'images'}) # formats: extensions permitted, sample: jpg,png,... or generic: images | videos | audios | documents (default *) # dimension: 20x30 # return: {file_path, error} def cama_tmp_upload(uploaded_io, args = {}) tmp_path = args[:path] || File.join(Rails.public_path, "tmp", current_site.id.to_s).to_s FileUtils.mkdir_p(tmp_path) unless Dir.exist?(tmp_path) saved = false if uploaded_io.is_a?(String) && (uploaded_io.start_with?("data:")) # create tmp file using base64 format _tmp_name = args[:name] return {error: "#{cama_t("camaleon_cms.admin.media.name_required")}"} unless params[:name].present? return {error: "#{ct("file_format_error")} (#{args[:formats]})"} unless cama_uploader.class.validate_file_format(_tmp_name, args[:formats]) path = uploader_verify_name(File.join(tmp_path, _tmp_name)) File.open(path, 'wb'){|f| f.write(Base64.decode64(uploaded_io.split(';base64,').last)) } uploaded_io = File.open(path) saved = true elsif uploaded_io.is_a?(String) && (uploaded_io.start_with?("http://") || uploaded_io.start_with?("https://")) return {error: "#{ct("file_format_error")} (#{args[:formats]})"} unless cama_uploader.class.validate_file_format(uploaded_io, args[:formats]) uploaded_io = File.join(Rails.public_path, uploaded_io.sub(current_site.the_url(locale: nil), '')).to_s if uploaded_io.include?(current_site.the_url(locale: nil)) # local file _tmp_name = uploaded_io.split("/").last.split('?').first; args[:name] = args[:name] || _tmp_name uploaded_io = open(uploaded_io) end uploaded_io = File.open(uploaded_io) if uploaded_io.is_a?(String) return {error: "#{ct("file_format_error")} (#{args[:formats]})"} unless cama_uploader.class.validate_file_format(_tmp_name || uploaded_io.path, args[:formats]) return {error: "#{ct("file_size_exceeded", default: "File size exceeded")} (#{number_to_human_size(args[:maximum])})"} if args[:maximum].present? && args[:maximum] < (uploaded_io.size rescue File.size(uploaded_io)) name = args[:name] || uploaded_io.try(:original_filename) || uploaded_io.path.split("/").last; name = "#{File.basename(name, File.extname(name)).underscore}#{File.extname(name)}" path ||= uploader_verify_name(File.join(tmp_path, name)) File.open(path, "wb"){|f| f.write(uploaded_io.read) } unless saved path = cama_resize_upload(path, args[:dimension]) if args[:dimension].present? {file_path: path, error: nil} end # resize image if the format is correct # return resized file path def cama_resize_upload(image_path, dimesion, args = {}) if cama_uploader.class.validate_file_format(image_path, 'image') && dimesion.present? r= {file: image_path, w: dimesion.split('x')[0], h: dimesion.split('x')[1], w_offset: 0, h_offset: 0, resize: !dimesion.split('x')[2] || dimesion.split('x')[2] == "resize", replace: true, gravity: :north_east}.merge(args); hooks_run("on_uploader_resize", r) if r[:w].present? && r[:h].present? image_path = cama_resize_and_crop(r[:file], r[:w], r[:h], {overwrite: r[:replace], gravity: r[:gravity] }) else image_path = cama_crop_image(r[:file], r[:w], r[:h], r[:w_offset], r[:h_offset], r[:resize] , r[:replace]) end end image_path end # return the current uploader def cama_uploader @cama_uploader ||= lambda{ thumb = current_site.get_option('filesystem_thumb_size', '100x100').split('x') args= { server: current_site.get_option("filesystem_type", "local").downcase, thumb: {w: thumb[0], h: thumb[1]}, aws_settings: { region: current_site.get_option("filesystem_region", 'us-west-2'), access_key: current_site.get_option("filesystem_s3_access_key"), secret_key: current_site.get_option("filesystem_s3_secret_key"), bucket: current_site.get_option("filesystem_s3_bucket_name"), cloud_front: current_site.get_option("filesystem_s3_cloudfront"), aws_file_upload_settings: lambda{|settings| settings }, # permit to add your custom attributes for file_upload http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Object.html#upload_file-instance_method aws_file_read_settings: lambda{|data, s3_file| data } # permit to read custom attributes from aws file and add to file parsed object }, custom_uploader: nil # posibility to use custom file uploader } hooks_run("on_uploader", args) return args[:custom_uploader] if args[:custom_uploader].present? case args[:server] when 's3', 'aws' CamaleonCmsAwsUploader.new({current_site: current_site, thumb: args[:thumb], aws_settings: args[:aws_settings]}, self) else CamaleonCmsLocalUploader.new({current_site: current_site, thumb: args[:thumb]}, self) end }.call end def slugify(val) val.to_s.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') end def slugify_folder(val) splitted_folder = val.split('/') splitted_folder[-1] = slugify(splitted_folder.last) splitted_folder.join('/') end private # helper for resize and crop method def cama_crop_offsets_by_gravity(gravity, original_dimensions, cropped_dimensions) original_width, original_height = original_dimensions cropped_width, cropped_height = cropped_dimensions vertical_offset = case gravity when :north_west, :north, :north_east then 0 when :center, :east, :west then [ ((original_height - cropped_height) / 2.0).to_i, 0 ].max when :south_west, :south, :south_east then (original_height - cropped_height).to_i end horizontal_offset = case gravity when :north_west, :west, :south_west then 0 when :center, :north, :south then [ ((original_width - cropped_width) / 2.0).to_i, 0 ].max when :north_east, :east, :south_east then (original_width - cropped_width).to_i end return [ horizontal_offset, vertical_offset ] end # convert file path into thumb path format # return the image name into thumb format: owewen.png into thumb/owen-png.png def cama_parse_for_thumb_name(file_path) "#{@fog_connection_hook_res[:thumb_folder_name]}/#{File.basename(file_path).parameterize}#{File.extname(file_path)}" end end
module Pageflow module SocialShareHelper include EntriesHelper include PagesHelper include RevisionFileHelper def social_share_meta_tags_for(target) if target.is_a?(Page) render('pageflow/social_share/page_meta_tags', entry: @entry, page: @entry.share_target) else render('pageflow/social_share/entry_meta_tags', entry: @entry) end end def social_share_entry_url(entry) entry.share_url.presence || pretty_entry_url(entry) end def social_share_page_url(entry, page_or_perma_id) perma_id = if page_or_perma_id.respond_to?(:perma_id) page_or_perma_id.perma_id else page_or_perma_id end pretty_entry_url(entry, page: perma_id) end def social_share_page_title(page) entry = page.chapter.entry title = ["#{entry.title}:"] title << page.title title << '-' if entry.theming.cname_domain.present? title << entry.theming.cname_domain title.join(' ') end def social_share_page_description(entry, page) return social_share_sanitize(page.configuration['text']) if page.configuration['text'].present? return social_share_sanitize(page.configuration['description']) if page.configuration['description'].present? social_share_entry_description(entry) end def social_share_entry_description(entry) return social_share_sanitize(entry.summary) if entry.summary.present? entry.pages.each do |page| return social_share_sanitize(page.configuration['text']) if page.configuration['text'].present? end '' end def social_share_entry_image_tags(entry) image_urls = [] image_file = find_file_in_entry(ImageFile, entry.share_image_id) if image_file image_urls << image_file.thumbnail_url(:medium) else entry.pages.each do |page| if image_urls.size >= 4 break else image_urls << page_thumbnail_url(page, :medium) image_urls.uniq! end end end render 'pageflow/social_share/image_tags', image_urls: image_urls end def social_share_normalize_protocol(url) url.gsub(%r{^//}, 'https://') end private def social_share_sanitize(text) HTMLEntities.new.decode(strip_tags(text.gsub(/<br ?\/?>|&nbsp;/, ' ').squish)) end end end use hardcoded width and height values for files without width and height module Pageflow module SocialShareHelper include EntriesHelper include PagesHelper include RevisionFileHelper def social_share_meta_tags_for(target) if target.is_a?(Page) render('pageflow/social_share/page_meta_tags', entry: @entry, page: @entry.share_target) else render('pageflow/social_share/entry_meta_tags', entry: @entry) end end def social_share_entry_url(entry) entry.share_url.presence || pretty_entry_url(entry) end def social_share_page_url(entry, page_or_perma_id) perma_id = if page_or_perma_id.respond_to?(:perma_id) page_or_perma_id.perma_id else page_or_perma_id end pretty_entry_url(entry, page: perma_id) end def social_share_page_title(page) entry = page.chapter.entry title = ["#{entry.title}:"] title << page.title title << '-' if entry.theming.cname_domain.present? title << entry.theming.cname_domain title.join(' ') end def social_share_page_description(entry, page) return social_share_sanitize(page.configuration['text']) if page.configuration['text'].present? return social_share_sanitize(page.configuration['description']) if page.configuration['description'].present? social_share_entry_description(entry) end def social_share_entry_description(entry) return social_share_sanitize(entry.summary) if entry.summary.present? entry.pages.each do |page| return social_share_sanitize(page.configuration['text']) if page.configuration['text'].present? end '' end def social_share_entry_image_tags(entry) share_images = [] image_file = find_file_in_entry(ImageFile, entry.share_image_id) if image_file image_url = image_file.thumbnail_url(:medium) share_images.push(image_url: image_url, width: image_file.width, height: image_file.height) else entry.pages.each do |page| break if share_images.size >= 4 thumbnail_file = page_thumbnail_file(page) next unless thumbnail_file.present? image_url = thumbnail_file.thumbnail_url(:medium) thumbnail_width = 1200 thumbnail_height = 630 if thumbnail_file.file.methods.include?(:width) thumbnail_width = thumbnail_file.file.width thumbnail_height = thumbnail_file.file.height end share_images.push(image_url: image_url, width: thumbnail_width, height: thumbnail_height) share_images.uniq! end end render 'pageflow/social_share/image_tags', share_images: share_images end def social_share_normalize_protocol(url) url.gsub(%r{^//}, 'https://') end private def social_share_sanitize(text) HTMLEntities.new.decode(strip_tags(text.gsub(/<br ?\/?>|&nbsp;/, ' ').squish)) end end end
Stub Eve::MarketGroupsImporter # frozen_string_literal: true module Eve class MarketGroupsImporter def import end end end
module API module V2 module CaseWorkers class Claim < Grape::API helpers API::V2::CriteriaHelper namespace :case_workers do params do optional :api_key, type: String, desc: 'REQUIRED: The API authentication key of the user' optional :status, type: String, values: %w(allocated archived), default: 'allocated', desc: 'REQUIRED: Returns allocated claims or archived claims' use :searching use :sorting use :pagination end helpers do def search_options options = [:case_number, :maat_reference, :defendant_name] options << :case_worker_name_or_email if current_user.persona.admin? options end def search_terms params.search.to_s.strip end def allocated_claims current_user.claims.caseworker_dashboard_under_assessment.search( search_terms, Claims::StateMachine::CASEWORKER_DASHBOARD_UNDER_ASSESSMENT_STATES, *search_options) end def archived_claims ::Claim::BaseClaim.active.caseworker_dashboard_archived.search( search_terms, Claims::StateMachine::CASEWORKER_DASHBOARD_ARCHIVED_STATES, *search_options) end def claims_scope params.status == 'allocated' ? allocated_claims : archived_claims end def claims claims_scope.sort(params.sorting, params.direction).page(params.page).per(params.limit) end end after do header 'Cache-Control', 'max-age=15' end resource :claims, desc: 'Operations on allocated claims' do desc 'Retrieve list of allocated or archived claims' get do present claims, with: API::Entities::PaginatedCollection, user: current_user end end end end end end end Do not cache this endpoint. module API module V2 module CaseWorkers class Claim < Grape::API helpers API::V2::CriteriaHelper namespace :case_workers do params do optional :api_key, type: String, desc: 'REQUIRED: The API authentication key of the user' optional :status, type: String, values: %w(allocated archived), default: 'allocated', desc: 'REQUIRED: Returns allocated claims or archived claims' use :searching use :sorting use :pagination end helpers do def search_options options = [:case_number, :maat_reference, :defendant_name] options << :case_worker_name_or_email if current_user.persona.admin? options end def search_terms params.search.to_s.strip end def allocated_claims current_user.claims.caseworker_dashboard_under_assessment.search( search_terms, Claims::StateMachine::CASEWORKER_DASHBOARD_UNDER_ASSESSMENT_STATES, *search_options) end def archived_claims ::Claim::BaseClaim.active.caseworker_dashboard_archived.search( search_terms, Claims::StateMachine::CASEWORKER_DASHBOARD_ARCHIVED_STATES, *search_options) end def claims_scope params.status == 'allocated' ? allocated_claims : archived_claims end def claims claims_scope.sort(params.sorting, params.direction).page(params.page).per(params.limit) end end resource :claims, desc: 'Operations on allocated claims' do desc 'Retrieve list of allocated or archived claims' get do present claims, with: API::Entities::PaginatedCollection, user: current_user end end end end end end end
#!/usr/bin/env ruby # # Created by Mark James Adams on 2007-05-14. # Copyright (c) 2007. All rights reserved. require 'rubygems' require 'hpricot' require 'uri' require 'fileutils' require 'optparse' require 'yaml' require 'oauth' require 'time' class RetrieveError < StandardError attr_reader :reason def initialize(reason) @reason = reason end end class FailWhaleError < StandardError attr_reader :reason def initialize(reason) @reason = reason end end class TwitterArchiver def prepare_access_token(oauth_token, oauth_token_secret) consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "http://api.twitter.com", :scheme => :header }) # now create the access token object from passed values token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret } access_token = OAuth::AccessToken.from_hash(consumer, token_hash ) return access_token end def initialize(user, token, secret) @user = user @token = token @secret = secret @access_token = prepare_access_token($options[:token], $options[:secret]) @replies = Array.new() File.foreach("#{@user}/replies.txt") { |line| track_reply(line.strip) } end def log_replies() File.open("#{@user}/replies.txt", 'w') { |rf| @replies.each { |reply| rf << reply.to_s << "\n" } } end def track_reply(id) @replies.push(id) end def got_reply(id) @replies.delete(id) end def hark(since_id, page) FileUtils.mkdir_p @user # Create a directory to hold the tweets listening = true # Exchange our oauth_token and oauth_token secret for the AccessToken instance. while listening do # parse the account archive until we come to the last page (all) # or we see a tweet we've alrady downloaded begin unless since_id.nil? since_id_parameter = "&since_id=#{since_id}" else since_id_parameter = "" end page_parameter = "&page=#{page}" count_parameter = "count=200" screen_name_parameter = "&screen_name=#{@user}" query = count_parameter + since_id_parameter + page_parameter + screen_name_parameter user_timeline_url = 'http://api.twitter.com/1/statuses/user_timeline.xml?' + query puts "Fetching #{user_timeline_url}" user_timeline_resource = @access_token.request(:get, user_timeline_url) user_timeline_xml = user_timeline_resource.body File.open("debug.log", 'w') { |data| data << user_timeline_xml } puts "Retrieved page #{page} ..." hp = Hpricot(user_timeline_xml) tweets = (hp/"status") if tweets.length == 0 body = (hp/"body") raise FailWhaleError, "Fail Whale. Wait 5 seconds and try again" unless body.length == 0 # Fail Whale HTML page end puts "Parsing #{tweets.length} tweets..." tweets.each {|tweet| id = tweet.at("id").inner_html puts "Saving tweet #{id}" save_tweet_disk(id, tweet) } unless tweets.empty? page = page + 1 else listening = false end rescue FailWhaleError => e puts e.reason sleep(5) retry # rescue RestClient::Unauthorized => e # puts "Could not authenticate with Twitter. Doublecheck your username (#{user}) and password" # listening = false # rescue RestClient::RequestFailed => e # puts "Twitter isn't responding: #{e.message}" # listening = false end end # listening end def check_status_disk(id) $statuses = Array.new FileUtils.mkdir_p @user Dir.new(@user).select {|file| file =~ /\d+.xml$/}.each{|id_xml| $statuses.push(id_xml.gsub('.xml', '').to_i) } return $statuses.index(id.to_i) end def get_single_tweet(id) tweet_url = "http://api.twitter.com/1/statuses/show/#{id}.xml" puts "Retrieving tweet " + id tweet_resource = @access_token.request(:get, tweet_url) tweet_xml = tweet_resource.body tweet = (Hpricot(tweet_xml)/"status").first error = (Hpricot(tweet_xml)/"hash").first raise RetrieveError, "auth problem?" unless error.nil? return tweet end def save_tweet_disk(id, tweet) begin if not check_status_disk(id) if tweet.nil? while tweet.nil? do tweet = get_single_tweet(id) end#while tweet.nil? do end#if tweet.nil? at = Time.parse(tweet.at("created_at").inner_html).iso8601 puts "Saving tweet #{id}" File.open("#{@user}/#{id}.xml", 'w') { |tweet_xml| tweet_xml << tweet.to_s} reply_to = tweet.at("in_reply_to_status_id").inner_html if (not reply_to.nil?) and (not reply_to.eql?("")) track_reply(reply_to) end#if reply_to else #status is on disk. load it and check for replies fn = "#{@user}/#{id}.xml" tweet = (Hpricot(open(fn))/"status") reply_to = tweet.at("in_reply_to_status_id").inner_html if (not reply_to.nil?) and (not reply_to.eql?("")) track_reply(reply_to) end#if reply_to end#if status already exists rescue RetrieveError => e puts "Couldn't download tweet #{e.reason}" end#begin block end#def save_tweet end # Exchange your oauth_token and oauth_token_secret for an AccessToken instance. # concatinate an array of XML status files into a single XML file def concatenate(archive) File.open("#{$user}.xml", "w") { |archive_xml| builder = Builder::XmlMarkup.new builder.instruct! builder.statuses do |b| builder << "\n" archive.each {|tweet| b << tweet.gsub('<?xml version="1.0" encoding="UTF-8"?>' + "\n", "")} end archive_xml << builder } end begin CONFIG = YAML.load_file('config.yml') $options = {} $options[:user] = CONFIG['username'] $options[:secret] = CONFIG['secret'] $options[:token] = CONFIG['token'] OptionParser.new do |opts| opts.banner = "Usage: aviary.rb --updates [new|all] --page XXX" $options[:updates] = :new opts.on("--updates [new|all]", [:new, :all], "Fetch only new or all updates") {|updates| $options[:updates] = updates} $options[:page] = 1 opts.on("--page XXX", Integer, "Page") {|page| $options[:page] = page} end.parse! if [:updates].map {|opt| $options[opt].nil?}.include?(nil) puts "Usage: aviary.rb --updates [new|all] --page XXX" exit end $statuses = Array.new FileUtils.mkdir_p $options[:user] Dir.new($options[:user]).select {|file| file =~ /\d+.xml$/}.each{|id_xml| $statuses.push(id_xml.gsub('.xml', '').to_i) } case $options[:updates] when :new # find the most recent status since_id = $statuses.sort.reverse.first else :all since_id = nil end ta = TwitterArchiver.new($options[:user], $options[:token], $options[:secret]) ta.hark(since_id, $options[:page]) ta.log_replies() rescue Errno::ENOENT puts "Whoops!" puts "There is no configuration file." puts "Place your username and password in a file called `config.yml`. See config-example.yml." rescue StandardError ta.log_replies() end Switch Nokogiri for Hpricot #!/usr/bin/env ruby # # Created by Mark James Adams on 2007-05-14. # Copyright (c) 2007. All rights reserved. require 'rubygems' require 'nokogiri' require 'uri' require 'fileutils' require 'optparse' require 'yaml' require 'oauth' require 'time' class RetrieveError < StandardError attr_reader :reason def initialize(reason) @reason = reason end end class FailWhaleError < StandardError attr_reader :reason def initialize(reason) @reason = reason end end class TwitterArchiver def prepare_access_token(oauth_token, oauth_token_secret) consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "http://api.twitter.com", :scheme => :header }) # now create the access token object from passed values token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret } access_token = OAuth::AccessToken.from_hash(consumer, token_hash ) return access_token end def initialize(user, token, secret) @user = user @token = token @secret = secret @access_token = prepare_access_token($options[:token], $options[:secret]) @replies = Array.new() File.foreach("#{@user}/replies.txt") { |line| track_reply(line.strip) } end def log_replies() File.open("#{@user}/replies.txt", 'w') { |rf| @replies.each { |reply| rf << reply.to_s << "\n" } } end def track_reply(id) @replies.push(id) end def got_reply(id) @replies.delete(id) end def hark(since_id, page) FileUtils.mkdir_p @user # Create a directory to hold the tweets listening = true # Exchange our oauth_token and oauth_token secret for the AccessToken instance. while listening do # parse the account archive until we come to the last page (all) # or we see a tweet we've alrady downloaded begin unless since_id.nil? since_id_parameter = "&since_id=#{since_id}" else since_id_parameter = "" end page_parameter = "&page=#{page}" count_parameter = "count=200" screen_name_parameter = "&screen_name=#{@user}" query = count_parameter + since_id_parameter + page_parameter + screen_name_parameter # user_timeline_url = 'http://api.twitter.com/1/statuses/mentions.xml?' + query user_timeline_url = 'http://api.twitter.com/1/statuses/user_timeline.xml?' + query puts "Fetching #{user_timeline_url}" user_timeline_resource = @access_token.request(:get, user_timeline_url) user_timeline_xml = user_timeline_resource.body File.open("debug.log", 'w') { |data| data << user_timeline_xml } puts "Retrieved page #{page} ..." hp = Nokogiri(user_timeline_xml) tweets = (hp/"status") if tweets.length == 0 body = (hp/"body") raise FailWhaleError, "Fail Whale. Wait 5 seconds and try again" unless body.length == 0 # Fail Whale HTML page end puts "Parsing #{tweets.length} tweets..." tweets.each {|tweet| id = tweet.at("id").inner_html puts "Saving tweet #{id}" save_tweet_disk(id, tweet) } unless tweets.empty? page = page + 1 else listening = false end rescue FailWhaleError => e puts e.reason sleep(5) retry # rescue RestClient::Unauthorized => e # puts "Could not authenticate with Twitter. Doublecheck your username (#{user}) and password" # listening = false # rescue RestClient::RequestFailed => e # puts "Twitter isn't responding: #{e.message}" # listening = false end end # listening end def check_status_disk(id) $statuses = Array.new FileUtils.mkdir_p @user Dir.new(@user).select {|file| file =~ /\d+.xml$/}.each{|id_xml| $statuses.push(id_xml.gsub('.xml', '').to_i) } return $statuses.index(id.to_i) end def get_single_tweet(id) tweet_url = "http://api.twitter.com/1/statuses/show/#{id}.xml" puts "Retrieving tweet " + id tweet_resource = @access_token.request(:get, tweet_url) tweet_xml = tweet_resource.body tweet = (Nokogiri(tweet_xml)/"status").first error = (Nokogiri(tweet_xml)/"hash").first raise RetrieveError, "auth problem?" unless error.nil? return tweet end def save_tweet_disk(id, tweet) begin if not check_status_disk(id) if tweet.nil? while tweet.nil? do tweet = get_single_tweet(id) end#while tweet.nil? do end#if tweet.nil? at = Time.parse(tweet.at("created_at").inner_html).iso8601 puts "Saving tweet #{id}" File.open("#{@user}/#{id}.xml", 'w') { |tweet_xml| tweet_xml << tweet.to_s} reply_to = tweet.at("in_reply_to_status_id").inner_html if (not reply_to.nil?) and (not reply_to.eql?("")) track_reply(reply_to) end#if reply_to else #status is on disk. load it and check for replies fn = "#{@user}/#{id}.xml" tweet = (Nokogiri(open(fn))/"status") reply_to = tweet.at("in_reply_to_status_id").inner_html if (not reply_to.nil?) and (not reply_to.eql?("")) track_reply(reply_to) end#if reply_to end#if status already exists rescue RetrieveError => e puts "Couldn't download tweet #{e.reason}" end#begin block end#def save_tweet end # Exchange your oauth_token and oauth_token_secret for an AccessToken instance. # concatinate an array of XML status files into a single XML file def concatenate(archive) File.open("#{$user}.xml", "w") { |archive_xml| builder = Builder::XmlMarkup.new builder.instruct! builder.statuses do |b| builder << "\n" archive.each {|tweet| b << tweet.gsub('<?xml version="1.0" encoding="UTF-8"?>' + "\n", "")} end archive_xml << builder } end begin CONFIG = YAML.load_file('config.yml') $options = {} $options[:user] = CONFIG['username'] $options[:secret] = CONFIG['secret'] $options[:token] = CONFIG['token'] OptionParser.new do |opts| opts.banner = "Usage: aviary.rb --updates [new|all] --page XXX" $options[:updates] = :new opts.on("--updates [new|all]", [:new, :all], "Fetch only new or all updates") {|updates| $options[:updates] = updates} $options[:page] = 1 opts.on("--page XXX", Integer, "Page") {|page| $options[:page] = page} end.parse! if [:updates].map {|opt| $options[opt].nil?}.include?(nil) puts "Usage: aviary.rb --updates [new|all] --page XXX" exit end $statuses = Array.new FileUtils.mkdir_p $options[:user] Dir.new($options[:user]).select {|file| file =~ /\d+.xml$/}.each{|id_xml| $statuses.push(id_xml.gsub('.xml', '').to_i) } case $options[:updates] when :new # find the most recent status since_id = $statuses.sort.reverse.first else :all since_id = nil end ta = TwitterArchiver.new($options[:user], $options[:token], $options[:secret]) ta.hark(since_id, $options[:page]) ta.log_replies() rescue Errno::ENOENT puts "Whoops!" puts "There is no configuration file." puts "Place your username and password in a file called `config.yml`. See config-example.yml." rescue StandardError ta.log_replies() end
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details # Uncomment the :secret if you're not using the cookie session store protect_from_forgery # :secret => '<%= app_secret %>' # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters # from your application log (in this case, all fields with names like "password"). # filter_parameter_logging :password end Update the generated controller to not include the deprecated :secret option to protect_from_forgery # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details protect_from_forgery # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters # from your application log (in this case, all fields with names like "password"). # filter_parameter_logging :password end
desc "Print out all defined initializers in the order they are invoked by Rails." task initializer: :environment do Rails.application.initializers.tsort_each do |initializer| puts initializer.name end end Actually rename to `rake initializers` desc "Print out all defined initializers in the order they are invoked by Rails." task initializers: :environment do Rails.application.initializers.tsort_each do |initializer| puts initializer.name end end
require 'zip/zip' require 'tempfile' require 'find' module Selenium module WebDriver module Zipper EXTENSIONS = %w[.zip .xpi] def self.unzip(path) destination = Dir.mktmpdir("unzip") FileReaper << destination Zip::ZipFile.open(path) do |zip| zip.each do |entry| to = File.join(destination, entry.name) dirname = File.dirname(to) FileUtils.mkdir_p dirname unless File.exist? dirname zip.extract(entry, to) end end destination end def self.zip(path) tmp_zip = Tempfile.new("webdriver-zip") begin zos = Zip::ZipOutputStream.new(tmp_zip.path) ::Find.find(path) do |file| next if File.directory?(file) entry = file.sub("#{path}/", '') zos.put_next_entry(entry) zos << File.read(file) p :added => file, :as => entry end zos.close tmp_zip.rewind [tmp_zip.read].pack("m") ensure tmp_zip.close end end end # Zipper end # WebDriver end # Selenium JariBakken: Remove debug output. git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@11250 07704840-8298-11de-bf8c-fd130f914ac9 require 'zip/zip' require 'tempfile' require 'find' module Selenium module WebDriver module Zipper EXTENSIONS = %w[.zip .xpi] def self.unzip(path) destination = Dir.mktmpdir("unzip") FileReaper << destination Zip::ZipFile.open(path) do |zip| zip.each do |entry| to = File.join(destination, entry.name) dirname = File.dirname(to) FileUtils.mkdir_p dirname unless File.exist? dirname zip.extract(entry, to) end end destination end def self.zip(path) tmp_zip = Tempfile.new("webdriver-zip") begin zos = Zip::ZipOutputStream.new(tmp_zip.path) ::Find.find(path) do |file| next if File.directory?(file) entry = file.sub("#{path}/", '') zos.put_next_entry(entry) zos << File.read(file) end zos.close tmp_zip.rewind [tmp_zip.read].pack("m") ensure tmp_zip.close end end end # Zipper end # WebDriver end # Selenium
if defined?(ActionMailer) # Mailer for email notification of ActivityNotificaion. class ActivityNotification::Mailer < ActivityNotification.config.parent_mailer.constantize include ActivityNotification::Mailers::Helpers # Sends notification email. # @param [Notification] notification Notification instance to send email # @param [Hash] options Options for notification email # @option options [String, Symbol] :fallback (:default) Fallback template to use when MissingTemplate is raised def send_notification_email(notification, options = {}) options[:fallback] ||= :default options.delete(:fallback) if options[:fallback] == :none if notification.target.notification_email_allowed?(notification.notifiable, notification.key) and notification.notifiable.notification_email_allowed?(notification.target, notification.key) notification_mail(notification, options) end end end end Update mailer to complete docs if defined?(ActionMailer) # Mailer for email notification of ActivityNotificaion. class ActivityNotification::Mailer < ActivityNotification.config.parent_mailer.constantize include ActivityNotification::Mailers::Helpers # Sends notification email. # @param [Notification] notification Notification instance to send email # @param [Hash] options Options for notification email # @option options [String, Symbol] :fallback (:default) Fallback template to use when MissingTemplate is raised def send_notification_email(notification, options = {}) options[:fallback] ||= :default if options[:fallback] == :none options.delete(:fallback) end if notification.target.notification_email_allowed?(notification.notifiable, notification.key) and notification.notifiable.notification_email_allowed?(notification.target, notification.key) notification_mail(notification, options) end end end end
require 'net/ssh' # A private SSH key file. class Metasploit::Credential::SSHKey < Metasploit::Credential::Private # # Attributes # # @!attribute data # A private SSH key file's content including the `-----BEGIN <type> PRIVATE KEY-----` header and # `-----END <type> PRIVATE KEY-----` footer with everything in between. # # # Validations # # # # Attribute Validations # validates :data, presence: true # # Method Validations # validate :private validate :readable validate :unencrypted # # Instance Methods # # Whether the key data in {#data} is encrypted. Encrypted keys cannot be saved and should be decrypted before saving # in a {Metasploit::Credential::SSHKey}. # # @return [false] if {#data} does not contain `'ENCRYPTED'` or {#data} is `nil`. # @return [true] if {#data} contains `'ENCRYPTED'`. def encrypted? if data # see https://github.com/net-ssh/net-ssh/blob/1b5db680fee66e1d846d0396eb1a68d3fabdc3de/lib/net/ssh/key_factory.rb#L72 data.match(/ENCRYPTED/) else false end end # Whether the key data in {#data} is a private key. Only private keys are supported as public keys cannot be used # as {Metasploit::Credential::Public#data}. # # @return [false] if {#data} does not contain `'-----BEGIN <type> PRIVATE KEY-----'` or {#data} is `nil`. # @return [true] if {#data} contains `'-----BEGIN <type> PRIVATE KEY-----'`. def private? if data # @see https://github.com/net-ssh/net-ssh/blob/1b5db680fee66e1d846d0396eb1a68d3fabdc3de/lib/net/ssh/key_factory.rb#L56-L69 data.match(/-----BEGIN (.+) PRIVATE KEY-----/) else false end end private # Converts the private key file data in {#data} to an `OpenSSL::PKey::PKey` subclass instance. # # @return [OpenSSL::PKey::PKey] # @raise [ArgumentError, OpenSSL::PKey::PKeyError] if {#data} cannot be loaded def openssl_pkey_pkey if data ask_passphrase = false filename = "#{self.class}#data" passphrase = nil Net::SSH::KeyFactory.load_data_private_key(data, passphrase, ask_passphrase, filename) end end # Validates that {#data} contains a private key and NOT a public key or some other non-key data. # # @return [void] def private unless private? errors.add(:data, :not_private) end end # Validates that {#data} can be read by Net::SSH and a `OpenSSL::PKey::PKey` created from {#data}. Any exception # raised will be reported as a validation error. # # @return [void] def readable if data begin openssl_pkey_pkey rescue ArgumentError, OpenSSL::PKey::PKeyError => error errors[:data] << "#{error.class} #{error}" end end end # Validates that the private key is not encrypted as unencrypting the private key with its password is not supported: # the unencrypted version of the key should be generated using the password and stored instead. # # @return [void] def unencrypted if encrypted? errors.add(:data, :encrypted) end end end Add return type for SSHKey#data MSP-9605 require 'net/ssh' # A private SSH key file. class Metasploit::Credential::SSHKey < Metasploit::Credential::Private # # Attributes # # @!attribute data # A private SSH key file's content including the `-----BEGIN <type> PRIVATE KEY-----` header and # `-----END <type> PRIVATE KEY-----` footer with everything in between. # # @return [String] # # # Validations # # # # Attribute Validations # validates :data, presence: true # # Method Validations # validate :private validate :readable validate :unencrypted # # Instance Methods # # Whether the key data in {#data} is encrypted. Encrypted keys cannot be saved and should be decrypted before saving # in a {Metasploit::Credential::SSHKey}. # # @return [false] if {#data} does not contain `'ENCRYPTED'` or {#data} is `nil`. # @return [true] if {#data} contains `'ENCRYPTED'`. def encrypted? if data # see https://github.com/net-ssh/net-ssh/blob/1b5db680fee66e1d846d0396eb1a68d3fabdc3de/lib/net/ssh/key_factory.rb#L72 data.match(/ENCRYPTED/) else false end end # Whether the key data in {#data} is a private key. Only private keys are supported as public keys cannot be used # as {Metasploit::Credential::Public#data}. # # @return [false] if {#data} does not contain `'-----BEGIN <type> PRIVATE KEY-----'` or {#data} is `nil`. # @return [true] if {#data} contains `'-----BEGIN <type> PRIVATE KEY-----'`. def private? if data # @see https://github.com/net-ssh/net-ssh/blob/1b5db680fee66e1d846d0396eb1a68d3fabdc3de/lib/net/ssh/key_factory.rb#L56-L69 data.match(/-----BEGIN (.+) PRIVATE KEY-----/) else false end end private # Converts the private key file data in {#data} to an `OpenSSL::PKey::PKey` subclass instance. # # @return [OpenSSL::PKey::PKey] # @raise [ArgumentError, OpenSSL::PKey::PKeyError] if {#data} cannot be loaded def openssl_pkey_pkey if data ask_passphrase = false filename = "#{self.class}#data" passphrase = nil Net::SSH::KeyFactory.load_data_private_key(data, passphrase, ask_passphrase, filename) end end # Validates that {#data} contains a private key and NOT a public key or some other non-key data. # # @return [void] def private unless private? errors.add(:data, :not_private) end end # Validates that {#data} can be read by Net::SSH and a `OpenSSL::PKey::PKey` created from {#data}. Any exception # raised will be reported as a validation error. # # @return [void] def readable if data begin openssl_pkey_pkey rescue ArgumentError, OpenSSL::PKey::PKeyError => error errors[:data] << "#{error.class} #{error}" end end end # Validates that the private key is not encrypted as unencrypting the private key with its password is not supported: # the unencrypted version of the key should be generated using the password and stored instead. # # @return [void] def unencrypted if encrypted? errors.add(:data, :encrypted) end end end
require 'state_machine' require 'sidekiq' module NotifyUser class BaseNotification < ActiveRecord::Base include ActionView::Helpers::TextHelper if ActiveRecord::VERSION::MAJOR < 4 attr_accessible :params, :target, :type, :state end # Override point in case of collisions, plus keeps the table name tidy. self.table_name = "notify_user_notifications" #checks if user has unsubscribed from this notif type validate :unsubscribed_validation # Params for creating the notification message. serialize :params, Hash # The user to send the notification to belongs_to :target, polymorphic: true validates_presence_of :target_id, :target_type, :target, :type, :state state_machine :state, initial: :pending do # Created, not sent yet. Possibly waiting for aggregation. state :pending do end # Email/SMS/APNS has been sent. state :sent do end # The user has seen this notification. state :read do end # Record that we have sent message(s) to the user about this notification. event :mark_as_sent do transition :pending => :sent end # Record that the user has seen this notification, usually on a page or in the app. # A notification can go straight from pending to read if it's seen in a view before # sent in an email. event :mark_as_read do transition [:pending, :sent] => :read end end def message ActionView::Base.new( Rails.configuration.paths["app/views"]).render( :template => self.class.views[:mobile_sdk][:template_path].call(self), :formats => [:html], :locals => { :params => self.params}, :layout => false) end def mobile_message(length=115) puts length truncate(ActionView::Base.new( Rails.configuration.paths["app/views"]).render( :template => self.class.views[:mobile_sdk][:template_path].call(self), :formats => [:html], :locals => { :params => self.params}, :layout => false), :length => length) end ## Public Interface def to(user) self.target = user self end def with(*args) self.params = args.reduce({}, :update) self end def notify! save # Bang version of 'notify' ignores aggregation self.deliver! end # Send any Emails/SMS/APNS def notify save #if aggregation is false bypass aggregation completely self.channels.each do |channel_name, options| if(options[:aggregate_per] == false) self.class.delay.deliver_notification_channel(self.id, channel_name) else if not aggregation_pending? self.class.delay_for(options[:aggregate_per] || @@aggregate_per).notify_aggregated_channel(self.id, channel_name) end end end end def generate_unsubscribe_hash #check if a hash already exists for that user otherwise create a new one return user_hash = NotifyUser::UserHash.find_or_create_by(target: self.target, type: self.type, active: true) end ## Notification description mattr_accessor :description @@description = "" ## Channels mattr_accessor :channels @@channels = { action_mailer: {description: 'Email notifications'}, apns: {description: 'Apple Push Notifications'} } # Not sure about this. The JSON and web feeds don't fit into channels, because nothing is broadcast through # them. Not sure if they really need another concept though, they could just be formats on the controller. mattr_accessor :views @@views = { mobile_sdk: { template_path: Proc.new {|n| "notify_user/#{n.class.name.underscore}/mobile_sdk/notification" } } } # Configure a channel def self.channel(name, options={}) channels[name] = options end ## Aggregation mattr_accessor :aggregate_per @@aggregate_per = 1.minute ## Sending def self.for_target(target) where(target_id: target.id) .where(target_type: target.class.base_class) end def self.pending_aggregation_with(notification) where(type: notification.type) .for_target(notification.target) .where(state: :pending) end def aggregation_pending? # A notification of the same type, that would have an aggregation job associated with it, # already exists. return (self.class.pending_aggregation_with(self).where('id != ?', id).count > 0) end def deliver unless user_has_unsubscribed? self.mark_as_sent self.save self.class.delay.deliver_channels(self.id) end end def deliver! unless user_has_unsubscribed? self.mark_as_sent self.save self.class.deliver_channels(self.id) end end # Deliver a single notification across each channel. def self.deliver_channels(notification_id) notification = self.where(id: notification_id).first return unless notification self.channels.each do |channel_name, options| unless unsubscribed_from_channel?(notification.target, channel_name) channel = (channel_name.to_s + "_channel").camelize.constantize channel.deliver(notification, options) end end end # Deliver multiple notifications across each channel as an aggregate message. def self.deliver_channels_aggregated(notifications) self.channels.each do |channel_name, options| if options[:aggregate_per] != false && !unsubscribed_from_channel?(notifications.first.target, channel_name) channel = (channel_name.to_s + "_channel").camelize.constantize channel.deliver_aggregated(notifications, options) end end end #deliver to specific channel methods # Deliver a single notification to a specific channel. def self.deliver_notification_channel(notification_id, channel_name) notification = self.where(id: notification_id).first return unless notification channel_options = channels[channel_name.to_sym] channel = (channel_name.to_s + "_channel").camelize.constantize unless self.unsubscribed_from_channel?(notification.target, channel_name) channel.deliver(notification, channel_options) end end # Deliver a aggregated notifications to a specific channel. def self.deliver_notifications_channel(notifications, channel_name) channel_options = channels[channel_name.to_sym] channel = (channel_name.to_s + "_channel").camelize.constantize #check if user unsubsribed from channel type unless self.unsubscribed_from_channel?(notifications.first.target, channel_name) channel.deliver_aggregated(notifications, channel_options) end end #notifies a single channel for aggregation def self.notify_aggregated_channel(notification_id, channel_name) notification = self.find(notification_id) # Raise an exception if not found. # Find any pending notifications with the same type and target, which can all be sent in one message. notifications = self.pending_aggregation_with(notification) notifications.map(&:mark_as_sent) notifications.map(&:save) return if notifications.empty? if notifications.length == 1 # Despite waiting for more to aggregate, we only got one in the end. self.deliver_notification_channel(notifications.first.id, channel_name) else # We got several notifications while waiting, send them aggregated. self.deliver_notifications_channel(notifications, channel_name) end end def self.notify_aggregated(notification_id) notification = self.find(notification_id) # Raise an exception if not found. # Find any pending notifications with the same type and target, which can all be sent in one message. notifications = self.pending_aggregation_with(notification) notifications.map(&:mark_as_sent) notifications.map(&:save) return if notifications.empty? if notifications.length == 1 # Despite waiting for more to aggregate, we only got one in the end. self.deliver_channels(notifications.first.id) else # We got several notifications while waiting, send them aggregated. self.deliver_channels_aggregated(notifications) end end private def unsubscribed_validation errors.add(:target, (" has unsubscribed from this type")) if user_has_unsubscribed? end def user_has_unsubscribed? #return true if user has unsubscribed return true unless NotifyUser::Unsubscribe.has_unsubscribed_from(self.target, self.type).empty? return false end def self.unsubscribed_from_channel?(user, type) #return true if user has unsubscribed return true unless NotifyUser::Unsubscribe.has_unsubscribed_from(user, type).empty? return false end end end unused method require 'state_machine' require 'sidekiq' module NotifyUser class BaseNotification < ActiveRecord::Base include ActionView::Helpers::TextHelper if ActiveRecord::VERSION::MAJOR < 4 attr_accessible :params, :target, :type, :state end # Override point in case of collisions, plus keeps the table name tidy. self.table_name = "notify_user_notifications" #checks if user has unsubscribed from this notif type validate :unsubscribed_validation # Params for creating the notification message. serialize :params, Hash # The user to send the notification to belongs_to :target, polymorphic: true validates_presence_of :target_id, :target_type, :target, :type, :state state_machine :state, initial: :pending do # Created, not sent yet. Possibly waiting for aggregation. state :pending do end # Email/SMS/APNS has been sent. state :sent do end # The user has seen this notification. state :read do end # Record that we have sent message(s) to the user about this notification. event :mark_as_sent do transition :pending => :sent end # Record that the user has seen this notification, usually on a page or in the app. # A notification can go straight from pending to read if it's seen in a view before # sent in an email. event :mark_as_read do transition [:pending, :sent] => :read end end def message ActionView::Base.new( Rails.configuration.paths["app/views"]).render( :template => self.class.views[:mobile_sdk][:template_path].call(self), :formats => [:html], :locals => { :params => self.params}, :layout => false) end def mobile_message(length=115) puts length truncate(ActionView::Base.new( Rails.configuration.paths["app/views"]).render( :template => self.class.views[:mobile_sdk][:template_path].call(self), :formats => [:html], :locals => { :params => self.params}, :layout => false), :length => length) end ## Public Interface def to(user) self.target = user self end def with(*args) self.params = args.reduce({}, :update) self end def notify! save # Bang version of 'notify' ignores aggregation self.deliver! end # Send any Emails/SMS/APNS def notify save #if aggregation is false bypass aggregation completely self.channels.each do |channel_name, options| if(options[:aggregate_per] == false) self.class.delay.deliver_notification_channel(self.id, channel_name) else if not aggregation_pending? self.class.delay_for(options[:aggregate_per] || @@aggregate_per).notify_aggregated_channel(self.id, channel_name) end end end end def generate_unsubscribe_hash #check if a hash already exists for that user otherwise create a new one return user_hash = NotifyUser::UserHash.find_or_create_by(target: self.target, type: self.type, active: true) end ## Notification description mattr_accessor :description @@description = "" ## Channels mattr_accessor :channels @@channels = { action_mailer: {description: 'Email notifications'}, apns: {description: 'Apple Push Notifications'} } # Not sure about this. The JSON and web feeds don't fit into channels, because nothing is broadcast through # them. Not sure if they really need another concept though, they could just be formats on the controller. mattr_accessor :views @@views = { mobile_sdk: { template_path: Proc.new {|n| "notify_user/#{n.class.name.underscore}/mobile_sdk/notification" } } } # Configure a channel def self.channel(name, options={}) channels[name] = options end ## Aggregation mattr_accessor :aggregate_per @@aggregate_per = 1.minute ## Sending def self.for_target(target) where(target_id: target.id) .where(target_type: target.class.base_class) end def self.pending_aggregation_with(notification) where(type: notification.type) .for_target(notification.target) .where(state: :pending) end def aggregation_pending? # A notification of the same type, that would have an aggregation job associated with it, # already exists. return (self.class.pending_aggregation_with(self).where('id != ?', id).count > 0) end # def deliver # unless user_has_unsubscribed? # self.mark_as_sent # self.save # self.class.delay.deliver_channels(self.id) # end # end def deliver! unless user_has_unsubscribed? self.mark_as_sent self.save self.class.deliver_channels(self.id) end end # Deliver a single notification across each channel. def self.deliver_channels(notification_id) notification = self.where(id: notification_id).first return unless notification self.channels.each do |channel_name, options| unless unsubscribed_from_channel?(notification.target, channel_name) channel = (channel_name.to_s + "_channel").camelize.constantize channel.deliver(notification, options) end end end # Deliver multiple notifications across each channel as an aggregate message. def self.deliver_channels_aggregated(notifications) self.channels.each do |channel_name, options| if options[:aggregate_per] != false && !unsubscribed_from_channel?(notifications.first.target, channel_name) channel = (channel_name.to_s + "_channel").camelize.constantize channel.deliver_aggregated(notifications, options) end end end #deliver to specific channel methods # Deliver a single notification to a specific channel. def self.deliver_notification_channel(notification_id, channel_name) notification = self.where(id: notification_id).first return unless notification channel_options = channels[channel_name.to_sym] channel = (channel_name.to_s + "_channel").camelize.constantize unless self.unsubscribed_from_channel?(notification.target, channel_name) channel.deliver(notification, channel_options) end end # Deliver a aggregated notifications to a specific channel. def self.deliver_notifications_channel(notifications, channel_name) channel_options = channels[channel_name.to_sym] channel = (channel_name.to_s + "_channel").camelize.constantize #check if user unsubsribed from channel type unless self.unsubscribed_from_channel?(notifications.first.target, channel_name) channel.deliver_aggregated(notifications, channel_options) end end #notifies a single channel for aggregation def self.notify_aggregated_channel(notification_id, channel_name) notification = self.find(notification_id) # Raise an exception if not found. # Find any pending notifications with the same type and target, which can all be sent in one message. notifications = self.pending_aggregation_with(notification) notifications.map(&:mark_as_sent) notifications.map(&:save) return if notifications.empty? if notifications.length == 1 # Despite waiting for more to aggregate, we only got one in the end. self.deliver_notification_channel(notifications.first.id, channel_name) else # We got several notifications while waiting, send them aggregated. self.deliver_notifications_channel(notifications, channel_name) end end def self.notify_aggregated(notification_id) notification = self.find(notification_id) # Raise an exception if not found. # Find any pending notifications with the same type and target, which can all be sent in one message. notifications = self.pending_aggregation_with(notification) notifications.map(&:mark_as_sent) notifications.map(&:save) return if notifications.empty? if notifications.length == 1 # Despite waiting for more to aggregate, we only got one in the end. self.deliver_channels(notifications.first.id) else # We got several notifications while waiting, send them aggregated. self.deliver_channels_aggregated(notifications) end end private def unsubscribed_validation errors.add(:target, (" has unsubscribed from this type")) if user_has_unsubscribed? end def user_has_unsubscribed? #return true if user has unsubscribed return true unless NotifyUser::Unsubscribe.has_unsubscribed_from(self.target, self.type).empty? return false end def self.unsubscribed_from_channel?(user, type) #return true if user has unsubscribed return true unless NotifyUser::Unsubscribe.has_unsubscribed_from(user, type).empty? return false end end end
require 'spree/tax/tax_helpers' module SolidusAvataxCertified class Line attr_reader :order, :lines include Spree::Tax::TaxHelpers def initialize(order, invoice_type, refund = nil) @order = order @invoice_type = invoice_type @lines = [] @refund = refund @refunds = [] build_lines end def build_lines if %w(ReturnInvoice ReturnOrder).include?(@invoice_type) refund_lines else item_lines_array shipment_lines_array end end def item_line(line_item) { number: "#{line_item.id}-LI", description: line_item.name[0..255], taxCode: line_item.tax_category.try(:tax_code) || '', itemCode: line_item.variant.sku, quantity: line_item.quantity, amount: line_item.amount.to_f, discounted: discounted?(line_item), taxIncluded: tax_included_in_price?(line_item), addresses: { shipFrom: get_stock_location(line_item), shipTo: ship_to } }.merge(base_line_hash) end def item_lines_array order.line_items.each do |line_item| lines << item_line(line_item) end end def shipment_lines_array order.shipments.each do |shipment| next unless shipment.tax_category lines << shipment_line(shipment) end end def shipment_line(shipment) { number: "#{shipment.id}-FR", itemCode: shipment.shipping_method.name, quantity: 1, amount: shipment.discounted_amount.to_f, description: 'Shipping Charge', taxCode: shipment.shipping_method_tax_code, discounted: !shipment.promo_total.zero?, taxIncluded: tax_included_in_price?(shipment), addresses: { shipFrom: shipment.stock_location.to_avatax_hash, shipTo: ship_to } }.merge(base_line_hash) end def refund_lines return lines << refund_line if @refund.reimbursement.nil? return_items = @refund.reimbursement.customer_return.return_items inventory_units = Spree::InventoryUnit.where(id: return_items.pluck(:inventory_unit_id)) inventory_units.group_by(&:line_item_id).each_value do |inv_unit| inv_unit_ids = inv_unit.map { |iu| iu.id } return_items = Spree::ReturnItem.where(inventory_unit_id: inv_unit_ids) quantity = inv_unit.uniq.count amount = if return_items.first.respond_to?(:amount) return_items.sum(:amount) else return_items.sum(:pre_tax_amount) end lines << return_item_line(inv_unit.first.line_item, quantity, amount) end end def refund_line { number: "#{@refund.id}-RA", itemCode: @refund.transaction_id || 'Refund', quantity: 1, amount: -@refund.amount.to_f, description: 'Refund', taxIncluded: true, addresses: { shipFrom: default_ship_from, shipTo: ship_to } }.merge(base_line_hash) end def return_item_line(line_item, quantity, amount) { number: "#{line_item.id}-LI", description: line_item.name[0..255], taxCode: line_item.tax_category.try(:tax_code) || '', itemCode: line_item.variant.sku, quantity: quantity, amount: -amount.to_f, addresses: { shipFrom: get_stock_location(line_item), shipTo: ship_to } }.merge(base_line_hash) end def get_stock_location(li) inventory_units = li.inventory_units return default_ship_from if inventory_units.blank? stock_loc = inventory_units.first.try(:shipment).try(:stock_location) stock_loc.nil? ? {} : stock_loc.to_avatax_hash end def ship_to order.ship_address.to_avatax_hash end def default_ship_from Spree::StockLocation.order_default.first.to_avatax_hash end private def base_line_hash @base_line_hash ||= { customerUsageType: order.customer_usage_type, businessIdentificationNo: business_id_no, exemptionCode: order.user.try(:exemption_number) } end def business_id_no order.user.try(:vat_id) end def discounted?(line_item) line_item.adjustments.promotion.eligible.any? || order.adjustments.promotion.eligible.any? end def tax_included_in_price?(item) !!rates_for_item(item).try(:first)&.included_in_price end end end Use total before tax require 'spree/tax/tax_helpers' module SolidusAvataxCertified class Line attr_reader :order, :lines include Spree::Tax::TaxHelpers def initialize(order, invoice_type, refund = nil) @order = order @invoice_type = invoice_type @lines = [] @refund = refund @refunds = [] build_lines end def build_lines if %w(ReturnInvoice ReturnOrder).include?(@invoice_type) refund_lines else item_lines_array shipment_lines_array end end def item_line(line_item) { number: "#{line_item.id}-LI", description: line_item.name[0..255], taxCode: line_item.tax_category.try(:tax_code) || '', itemCode: line_item.variant.sku, quantity: line_item.quantity, amount: line_item.amount.to_f, discounted: discounted?(line_item), taxIncluded: tax_included_in_price?(line_item), addresses: { shipFrom: get_stock_location(line_item), shipTo: ship_to } }.merge(base_line_hash) end def item_lines_array order.line_items.each do |line_item| lines << item_line(line_item) end end def shipment_lines_array order.shipments.each do |shipment| next unless shipment.tax_category lines << shipment_line(shipment) end end def shipment_line(shipment) { number: "#{shipment.id}-FR", itemCode: shipment.shipping_method.name, quantity: 1, amount: shipment.total_before_tax.to_f, description: 'Shipping Charge', taxCode: shipment.shipping_method_tax_code, discounted: !shipment.promo_total.zero?, taxIncluded: tax_included_in_price?(shipment), addresses: { shipFrom: shipment.stock_location.to_avatax_hash, shipTo: ship_to } }.merge(base_line_hash) end def refund_lines return lines << refund_line if @refund.reimbursement.nil? return_items = @refund.reimbursement.customer_return.return_items inventory_units = Spree::InventoryUnit.where(id: return_items.pluck(:inventory_unit_id)) inventory_units.group_by(&:line_item_id).each_value do |inv_unit| inv_unit_ids = inv_unit.map { |iu| iu.id } return_items = Spree::ReturnItem.where(inventory_unit_id: inv_unit_ids) quantity = inv_unit.uniq.count amount = if return_items.first.respond_to?(:amount) return_items.sum(:amount) else return_items.sum(:pre_tax_amount) end lines << return_item_line(inv_unit.first.line_item, quantity, amount) end end def refund_line { number: "#{@refund.id}-RA", itemCode: @refund.transaction_id || 'Refund', quantity: 1, amount: -@refund.amount.to_f, description: 'Refund', taxIncluded: true, addresses: { shipFrom: default_ship_from, shipTo: ship_to } }.merge(base_line_hash) end def return_item_line(line_item, quantity, amount) { number: "#{line_item.id}-LI", description: line_item.name[0..255], taxCode: line_item.tax_category.try(:tax_code) || '', itemCode: line_item.variant.sku, quantity: quantity, amount: -amount.to_f, addresses: { shipFrom: get_stock_location(line_item), shipTo: ship_to } }.merge(base_line_hash) end def get_stock_location(li) inventory_units = li.inventory_units return default_ship_from if inventory_units.blank? stock_loc = inventory_units.first.try(:shipment).try(:stock_location) stock_loc.nil? ? {} : stock_loc.to_avatax_hash end def ship_to order.ship_address.to_avatax_hash end def default_ship_from Spree::StockLocation.order_default.first.to_avatax_hash end private def base_line_hash @base_line_hash ||= { customerUsageType: order.customer_usage_type, businessIdentificationNo: business_id_no, exemptionCode: order.user.try(:exemption_number) } end def business_id_no order.user.try(:vat_id) end def discounted?(line_item) line_item.adjustments.promotion.eligible.any? || order.adjustments.promotion.eligible.any? end def tax_included_in_price?(item) !!rates_for_item(item).try(:first)&.included_in_price end end end
require 'paypal-sdk-merchant' module Spree class Gateway::PayPalExpress < Gateway preference :login, :string preference :password, :string preference :signature, :string preference :server, :string, default: 'sandbox' attr_accessible :preferred_login, :preferred_password, :preferred_signature def provider_class ::PayPal::SDK::Merchant::API.new end def provider ::PayPal::SDK.configure( :mode => preferred_server.present? ? preferred_server : "sandbox", :username => preferred_login, :password => preferred_password, :signature => preferred_signature) provider_class end def auto_capture? true end def method_type 'paypal' end def purchase(amount, express_checkout, gateway_options={}) pp_request = provider.build_do_express_checkout_payment({ :DoExpressCheckoutPaymentRequestDetails => { :PaymentAction => "Sale", :Token => express_checkout.token, :PayerID => express_checkout.payer_id, :PaymentDetails => [{ :OrderTotal => { :currencyID => Spree::Config[:currency], :value => ::Money.new(amount, Spree::Config[:currency]).to_s } }] } }) pp_response = provider.do_express_checkout_payment(pp_request) if pp_response.success? # We need to store the transaction id for the future. # This is mainly so we can use it later on to refund the payment if the user wishes. transaction_id = pp_response.do_express_checkout_payment_response_details.payment_info.first.transaction_id express_checkout.update_column(:transaction_id, transaction_id) # This is rather hackish, required for payment/processing handle_response code. Class.new do def success?; true; end def authorization; nil; end end.new else class << pp_response def to_s errors.map(&:long_message).join(" ") end end pp_response end end def refund(payment, amount) refund_type = payment.amount == amount.to_f ? "Full" : "Partial" refund_transaction = provider.build_refund_transaction({ :TransactionID => payment.source.transaction_id, :RefundType => refund_type, :Amount => { :currencyID => payment.currency, :value => amount }, :RefundSource => "any" }) refund_transaction_response = provider.refund_transaction(refund_transaction) if refund_transaction_response.success? payment.source.update_attributes({ :refunded_at => Time.now, :refund_transaction_id => refund_transaction_response.RefundTransactionID, :state => "refunded", :refund_type => refund_type }, :without_protection => true) end refund_transaction_response end end end # payment.state = 'completed' # current_order.state = 'complete' Don't instantiate provider in provider_class It was possible for payment_class to be called, which instantiated a new `PayPal::SDK::Merchant::API` object before paypal was configured by the code in .provider. This caused the error: No such file or directory - config/paypal.yml This changes provider_class to just return the class itself. It also overrides `.provides?` to be more explicit about the behaviour. Fixes #15 Fixes #26 Conflicts: app/models/spree/gateway/pay_pal_express.rb require 'paypal-sdk-merchant' module Spree class Gateway::PayPalExpress < Gateway preference :login, :string preference :password, :string preference :signature, :string preference :server, :string, default: 'sandbox' attr_accessible :preferred_login, :preferred_password, :preferred_signature def supports?(source) true end def provider_class ::PayPal::SDK::Merchant::API end def provider ::PayPal::SDK.configure( :mode => preferred_server.present? ? preferred_server : "sandbox", :username => preferred_login, :password => preferred_password, :signature => preferred_signature) provider_class.new end def auto_capture? true end def method_type 'paypal' end def purchase(amount, express_checkout, gateway_options={}) pp_request = provider.build_do_express_checkout_payment({ :DoExpressCheckoutPaymentRequestDetails => { :PaymentAction => "Sale", :Token => express_checkout.token, :PayerID => express_checkout.payer_id, :PaymentDetails => [{ :OrderTotal => { :currencyID => Spree::Config[:currency], :value => ::Money.new(amount, Spree::Config[:currency]).to_s } }] } }) pp_response = provider.do_express_checkout_payment(pp_request) if pp_response.success? # We need to store the transaction id for the future. # This is mainly so we can use it later on to refund the payment if the user wishes. transaction_id = pp_response.do_express_checkout_payment_response_details.payment_info.first.transaction_id express_checkout.update_column(:transaction_id, transaction_id) # This is rather hackish, required for payment/processing handle_response code. Class.new do def success?; true; end def authorization; nil; end end.new else class << pp_response def to_s errors.map(&:long_message).join(" ") end end pp_response end end def refund(payment, amount) refund_type = payment.amount == amount.to_f ? "Full" : "Partial" refund_transaction = provider.build_refund_transaction({ :TransactionID => payment.source.transaction_id, :RefundType => refund_type, :Amount => { :currencyID => payment.currency, :value => amount }, :RefundSource => "any" }) refund_transaction_response = provider.refund_transaction(refund_transaction) if refund_transaction_response.success? payment.source.update_attributes({ :refunded_at => Time.now, :refund_transaction_id => refund_transaction_response.RefundTransactionID, :state => "refunded", :refund_type => refund_type }, :without_protection => true) end refund_transaction_response end end end # payment.state = 'completed' # current_order.state = 'complete'
require 'fileutils' require 'md5' require 'fog' action :run do if new_resource.user.nil? user = node[:env][:geo_user] else user = new_resource.user end Chef::Log.debug("download_from_s3: artifact #{new_resource.artifact}") Chef::Log.debug("download_from_s3: user: #{user}") #TODO: refactor into library so untar_from_s3 and download_from_s3 can reuse code storage = Fog::Storage.new(get_creds().merge(:provider => 'AWS')) bucket = storage.directories.get(node.env.s3_bucket) # First, see if there is a new archive to download. artifacts = bucket.files.all( :prefix => [node.env.s3_folder, new_resource.artifact].join('/') ).to_a.select{ |k| not k.key.split('/')[-1].match(/.+-[^-]+\.t(ar\.)?(gz|bz2)/).nil? } raise "no artifacts found!" if artifacts.empty? artifact = artifacts[0] fileName = artifact.key.split('/')[-1] archivePath = node[:env][:archive_dir] + fileName #TODO: cleanup old and failed versions. #download block if ::File.exists?(archivePath) md5sum = MD5.hexdigest(::File.read(archivePath)) raise "version on filesystem doesn't match the one on s3!" unless md5sum == artifact.etag #TODO: delete bad file #TODO: do something smarter that just raise Chef::Log.debug("latest version of artifact #{new_resource.artifact} already on disk.") new_resource.updated_by_last_action(false) else Chef::Log.info("downloading new artifact to #{archivePath}") begin ::File.open(archivePath, 'w') {|local_file| local_file.write(artifact.body)} rescue Chef::Exceptions::Exec => e ::File.delete( archivePath ) raise e end FileUtils.touch archivePath FileUtils.chown(user, user, archivePath) new_resource.updated_by_last_action(true) end #TODO: check md5 of file we just downloaded to be sure it matches etag end compressed mysql dumps can be artifacts too require 'fileutils' require 'md5' require 'fog' action :run do if new_resource.user.nil? user = node[:env][:geo_user] else user = new_resource.user end Chef::Log.debug("download_from_s3: artifact #{new_resource.artifact}") Chef::Log.debug("download_from_s3: user: #{user}") #TODO: refactor into library so untar_from_s3 and download_from_s3 can reuse code storage = Fog::Storage.new(get_creds().merge(:provider => 'AWS')) bucket = storage.directories.get(node.env.s3_bucket) # First, see if there is a new archive to download. artifacts = bucket.files.all( :prefix => [node.env.s3_folder, new_resource.artifact].join('/') ).to_a.select{ |k| not k.key.split('/')[-1].match(/.+-[^-]+\.(t(ar\.)?)?(gz|bz2)/).nil? } raise "no artifacts found!" if artifacts.empty? artifact = artifacts[0] fileName = artifact.key.split('/')[-1] archivePath = node[:env][:archive_dir] + fileName #TODO: cleanup old and failed versions. #download block if ::File.exists?(archivePath) md5sum = MD5.hexdigest(::File.read(archivePath)) raise "version on filesystem doesn't match the one on s3!" unless md5sum == artifact.etag #TODO: delete bad file #TODO: do something smarter that just raise Chef::Log.debug("latest version of artifact #{new_resource.artifact} already on disk.") new_resource.updated_by_last_action(false) else Chef::Log.info("downloading new artifact to #{archivePath}") begin ::File.open(archivePath, 'w') {|local_file| local_file.write(artifact.body)} rescue Chef::Exceptions::Exec => e ::File.delete( archivePath ) raise e end FileUtils.touch archivePath FileUtils.chown(user, user, archivePath) new_resource.updated_by_last_action(true) end #TODO: check md5 of file we just downloaded to be sure it matches etag end
# Cookbook Name:: travis_build_environment # Recipe:: mysql # Copyright 2011-2015, Travis CI GmbH <contact+travis-cookbooks@travis-ci.org> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. package %w( mysql-client-5.5 mysql-client-core-5.5 mysql-common mysql-server-5.5 ) do action %i(remove purge) end %w( root_password root_password_again ).each do |selection| execute "echo 'mysql-server-5.6 mysql-server/#{selection} password ' " + '| debconf-set-selections' end package %w( libmysqlclient-dev libmysqlclient18 mysql-client-5.6 mysql-client-core-5.6 mysql-common-5.6 mysql-server-5.6 mysql-server-core-5.6 ) do action %i(install upgrade) end mysql_users_passwords_sql = ::File.join( Chef::Config[:file_cache_path], 'mysql_users_passwords.sql' ) file mysql_users_passwords_sql do content <<-EOF.gsub(/^\s+> /, '') > CREATE USER 'travis'@'%' IDENTIFIED WITH mysql_native_password; > SET old_passwords = 0; > SET PASSWORD FOR 'root'@'%' = PASSWORD(''); > SET PASSWORD FOR 'travis'@'%' = PASSWORD(''); EOF end bash 'setup mysql users and passwords' do code "mysql -u root <#{mysql_users_passwords_sql}" action :nothing end service 'mysql' do action %i(enable start) notifies :run, 'bash[setup mysql users and passwords]', :immediately end template "#{node['travis_build_environment']['home']}/.my.cnf" do source 'ci_user/dot_my.cnf.erb' user node['travis_build_environment']['user'] group node['travis_build_environment']['group'] mode 0o640 variables(socket: node['travis_build_environment']['mysql']['socket']) end file '/etc/profile.d/travis-mysql.sh' do content "export MYSQL_UNIX_PORT=#{node['travis_build_environment']['mysql']['socket']}\n" owner node['travis_build_environment']['user'] group node['travis_build_environment']['group'] mode 0o755 end Simplify mysql password dance a bit # Cookbook Name:: travis_build_environment # Recipe:: mysql # Copyright 2011-2015, Travis CI GmbH <contact+travis-cookbooks@travis-ci.org> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. package %w( mysql-client-5.5 mysql-client-core-5.5 mysql-common mysql-server-5.5 ) do action %i(remove purge) end %w( root_password root_password_again ).each do |selection| execute "echo 'mysql-server-5.6 mysql-server/#{selection} password ' " + '| debconf-set-selections' end package %w( libmysqlclient-dev libmysqlclient18 mysql-client-5.6 mysql-client-core-5.6 mysql-common-5.6 mysql-server-5.6 mysql-server-core-5.6 ) do action %i(install upgrade) end mysql_users_passwords_sql = ::File.join( Chef::Config[:file_cache_path], 'mysql_users_passwords.sql' ) file mysql_users_passwords_sql do content <<-EOF.gsub(/^\s+> /, '') > SET old_passwords = 0; > CREATE USER 'travis'@'%' IDENTIFIED BY ''; > SET PASSWORD FOR 'root'@'%' = PASSWORD(''); EOF end bash 'setup mysql users and passwords' do code "mysql -u root <#{mysql_users_passwords_sql}" action :nothing end service 'mysql' do action %i(enable start) notifies :run, 'bash[setup mysql users and passwords]', :immediately end template "#{node['travis_build_environment']['home']}/.my.cnf" do source 'ci_user/dot_my.cnf.erb' user node['travis_build_environment']['user'] group node['travis_build_environment']['group'] mode 0o640 variables(socket: node['travis_build_environment']['mysql']['socket']) end file '/etc/profile.d/travis-mysql.sh' do content "export MYSQL_UNIX_PORT=#{node['travis_build_environment']['mysql']['socket']}\n" owner node['travis_build_environment']['user'] group node['travis_build_environment']['group'] mode 0o755 end
# encoding: utf-8 # Copyright:: Copyright (c) 2012, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe 'postfix::_common' execute 'update-postfix-sender_dependent_relayhost_maps' do command "postmap #{node['postfix']['main']['sender_dependent_relayhost_file']}" environment PATH: "#{ENV['PATH']}:/opt/omni/bin:/opt/omni/sbin" if platform_family?('omnios') action :nothing end template node['postfix']['main']['sender_dependent_relayhost_file'] do source 'sender_dependent_relayhost_maps.erb' notifies :run, 'execute[update-postfix-sender_dependent_relayhost_maps]' end real last commit # encoding: utf-8 # Copyright:: Copyright (c) 2012, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe 'postfix::_common' execute 'update-postfix-sender_dependent_relayhost_maps' do command "postmap #{node['postfix']['main']['sender_dependent_relayhost_maps']}" environment PATH: "#{ENV['PATH']}:/opt/omni/bin:/opt/omni/sbin" if platform_family?('omnios') action :nothing end template node['postfix']['main']['sender_dependent_relayhost_maps'] do source 'sender_dependent_relayhost_maps.erb' notifies :run, 'execute[update-postfix-sender_dependent_relayhost_maps]' end
require 'spec_helper' feature 'Projects > Members > Anonymous user sees members', feature: true, js: true do include WaitForAjax let(:user) { create(:user) } let(:group) { create(:group, :public) } let(:project) { create(:empty_project, :public) } background do project.team << [user, :master] @group_link = create(:project_group_link, project: project, group: group) login_as(user) visit namespace_project_project_members_path(project.namespace, project) end it 'updates group access level' do select 'Guest', from: "member_access_level_#{group.id}" wait_for_ajax visit namespace_project_project_members_path(project.namespace, project) expect(page).to have_select("member_access_level_#{group.id}", selected: 'Guest') end it 'updates expiry date' do tomorrow = Date.today + 3 fill_in "member_expires_at_#{group.id}", with: tomorrow.strftime("%F") wait_for_ajax page.within(first('li.member')) do expect(page).to have_content('Expires in 3 days') end end end Expires in test update require 'spec_helper' feature 'Projects > Members > Anonymous user sees members', feature: true, js: true do include WaitForAjax let(:user) { create(:user) } let(:group) { create(:group, :public) } let(:project) { create(:empty_project, :public) } background do project.team << [user, :master] @group_link = create(:project_group_link, project: project, group: group) login_as(user) visit namespace_project_project_members_path(project.namespace, project) end it 'updates group access level' do select 'Guest', from: "member_access_level_#{group.id}" wait_for_ajax visit namespace_project_project_members_path(project.namespace, project) expect(page).to have_select("member_access_level_#{group.id}", selected: 'Guest') end it 'updates expiry date' do tomorrow = Date.today + 3 fill_in "member_expires_at_#{group.id}", with: tomorrow.strftime("%F") wait_for_ajax page.within(first('li.member')) do expect(page).to have_content('Expires in') end end end
require 'active_record/connection_adapters/abstract_adapter' require 'active_record/connection_adapters/postgresql_adapter' require 'discourse' class PostgreSQLFallbackHandler include Singleton def initialize @masters_down = {} @mutex = Mutex.new end def verify_master synchronize { return if @thread && @thread.alive? } @thread = Thread.new do while true do begin thread = Thread.new { initiate_fallback_to_master } thread.join break if synchronize { @masters_down.empty? } sleep 10 ensure thread.kill end end end end def master_down? synchronize { @masters_down[namespace] } end def master_down=(args) synchronize { @masters_down[namespace] = args } end def master_up(namespace) synchronize { @masters_down.delete(namespace) } end def running? synchronize { @thread.alive? } end def initiate_fallback_to_master @masters_down.keys.each do |key| RailsMultisite::ConnectionManagement.with_connection(key) do begin logger.warn "#{log_prefix}: Checking master server..." connection = ActiveRecord::Base.postgresql_connection(config) if connection.active? connection.disconnect! ActiveRecord::Base.clear_all_connections! logger.warn "#{log_prefix}: Master server is active. Reconnecting..." self.master_up(key) Discourse.disable_readonly_mode end rescue => e byebug logger.warn "#{log_prefix}: Connection to master PostgreSQL server failed with '#{e.message}'" end end end end # Use for testing def setup! @masters_down = {} end private def config ActiveRecord::Base.connection_config end def logger Rails.logger end def log_prefix "#{self.class} [#{namespace}]" end def namespace RailsMultisite::ConnectionManagement.current_db end def synchronize @mutex.synchronize { yield } end end module ActiveRecord module ConnectionHandling def postgresql_fallback_connection(config) fallback_handler = ::PostgreSQLFallbackHandler.instance config = config.symbolize_keys if fallback_handler.master_down? fallback_handler.verify_master connection = postgresql_connection(config.dup.merge({ host: config[:replica_host], port: config[:replica_port] })) verify_replica(connection) Discourse.enable_readonly_mode else begin connection = postgresql_connection(config) rescue PG::ConnectionBad => e fallback_handler.master_down = true fallback_handler.verify_master raise e end end connection end private def verify_replica(connection) value = connection.raw_connection.exec("SELECT pg_is_in_recovery()").values[0][0] raise "Replica database server is not in recovery mode." if value == 'f' end end end FIX: Remove unused code. require 'active_record/connection_adapters/abstract_adapter' require 'active_record/connection_adapters/postgresql_adapter' require 'discourse' class PostgreSQLFallbackHandler include Singleton def initialize @masters_down = {} @mutex = Mutex.new end def verify_master synchronize { return if @thread && @thread.alive? } @thread = Thread.new do while true do begin thread = Thread.new { initiate_fallback_to_master } thread.join break if synchronize { @masters_down.empty? } sleep 10 ensure thread.kill end end end end def master_down? synchronize { @masters_down[namespace] } end def master_down=(args) synchronize { @masters_down[namespace] = args } end def master_up(namespace) synchronize { @masters_down.delete(namespace) } end def initiate_fallback_to_master @masters_down.keys.each do |key| RailsMultisite::ConnectionManagement.with_connection(key) do begin logger.warn "#{log_prefix}: Checking master server..." connection = ActiveRecord::Base.postgresql_connection(config) if connection.active? connection.disconnect! ActiveRecord::Base.clear_all_connections! logger.warn "#{log_prefix}: Master server is active. Reconnecting..." self.master_up(key) Discourse.disable_readonly_mode end rescue => e logger.warn "#{log_prefix}: Connection to master PostgreSQL server failed with '#{e.message}'" end end end end # Use for testing def setup! @masters_down = {} end private def config ActiveRecord::Base.connection_config end def logger Rails.logger end def log_prefix "#{self.class} [#{namespace}]" end def namespace RailsMultisite::ConnectionManagement.current_db end def synchronize @mutex.synchronize { yield } end end module ActiveRecord module ConnectionHandling def postgresql_fallback_connection(config) fallback_handler = ::PostgreSQLFallbackHandler.instance config = config.symbolize_keys if fallback_handler.master_down? fallback_handler.verify_master connection = postgresql_connection(config.dup.merge({ host: config[:replica_host], port: config[:replica_port] })) verify_replica(connection) Discourse.enable_readonly_mode else begin connection = postgresql_connection(config) rescue PG::ConnectionBad => e fallback_handler.master_down = true fallback_handler.verify_master raise e end end connection end private def verify_replica(connection) value = connection.raw_connection.exec("SELECT pg_is_in_recovery()").values[0][0] raise "Replica database server is not in recovery mode." if value == 'f' end end end
class MembershipService def self.redeem_if_pending!(membership) redeem(membership: membership, actor: membership.user) if membership && membership.accepted_at.nil? end def self.redeem(membership:, actor:, notify: true) raise Membership::InvitationAlreadyUsed.new(membership) if membership.accepted_at expires_at = if membership.group.parent_or_self.saml_provider Time.current else nil end # so we want to accept all the pending invitations this person has been sent within this org # and we dont want any surprises if they already have some memberships. # they may be accepting memberships send to a different email (unverified_user) group_ids = membership.group.parent_or_self.id_and_subgroup_ids existing_group_ids = Membership.where(user_id: actor.id).pluck(:group_id) Membership.pending.where( user_id: membership.user_id, group_id: (group_ids - existing_group_ids)). update_all( user_id: actor.id, accepted_at: DateTime.now, saml_session_expires_at: expires_at) membership.reload Events::InvitationAccepted.publish!(membership) if notify && membership.accepted_at end def self.update(membership:, params:, actor:) actor.ability.authorize! :update, membership membership.assign_attributes(params.slice(:title)) return false unless membership.valid? membership.save! update_user_titles_and_broadcast(membership.id) EventBus.broadcast 'membership_update', membership, params, actor end def self.update_user_titles_and_broadcast(membership_id) membership = Membership.find(membership_id) user = membership.user group = membership.group return unless user && group titles = (user.experiences['titles'] || {}) titles[group.id] = membership.title user.experiences['titles'] = titles user.save! MessageChannelService.publish_models([user], serializer: AuthorSerializer, group_id: group.id) end def self.set_volume(membership:, params:, actor:) actor.ability.authorize! :update, membership val = Membership.volumes[params[:volume]] if params[:apply_to_all] group_ids = membership.group.parent_or_self.id_and_subgroup_ids actor.memberships.where(group_id: group_ids).update_all(volume: val) actor.discussion_readers.joins(:discussion). where('discussions.group_id': group_ids). update_all(volume: val) Stance.joins(:poll). where('polls.group_id': group_ids). where(participant_id: actor.id). update_all(volume: val) else membership.set_volume! params[:volume] membership.discussion_readers.update_all(volume: val) membership.stances.update_all(volume: val) end end def self.resend(membership:, actor:) actor.ability.authorize! :resend, membership EventBus.broadcast 'membership_resend', membership, actor Events::MembershipResent.publish!(membership, actor) end def self.make_admin(membership:, actor:) actor.ability.authorize! :make_admin, membership membership.update admin: true Events::NewCoordinator.publish!(membership, actor) end def self.remove_admin(membership:, actor:) actor.ability.authorize! :remove_admin, membership membership.update admin: false end def self.join_group(group:, actor:) actor.ability.authorize! :join, group membership = group.add_member!(actor) EventBus.broadcast('membership_join_group', group, actor) Events::UserJoinedGroup.publish!(membership) end def self.add_users_to_group(users:, group:, inviter:) inviter.ability.authorize!(:add_members, group) group.add_members!(users, inviter: inviter).tap do |memberships| Events::UserAddedToGroup.bulk_publish!(memberships, user: inviter) end end def self.destroy(membership:, actor:) actor.ability.authorize! :destroy, membership now = Time.zone.now DiscussionReader.joins(:discussion).where( 'discussions.group_id': membership.group.id_and_subgroup_ids, user_id: membership.user_id).update_all(revoked_at: now) Stance.joins(:poll).where( 'polls.group_id': membership.group.id_and_subgroup_ids, participant_id: membership.user_id, cast_at: nil ).update_all(revoked_at: now) Membership.where(user_id: membership.user_id, group_id: membership.group.id_and_subgroup_ids).destroy_all EventBus.broadcast('membership_destroy', membership, actor) end def self.save_experience(membership:, actor:, params:) actor.ability.authorize! :update, membership membership.experienced!(params[:experience]) EventBus.broadcast('membership_save_experience', membership, actor, params) end end ok i did it class MembershipService def self.redeem_if_pending!(membership) redeem(membership: membership, actor: membership.user) if membership && membership.accepted_at.nil? end def self.redeem(membership:, actor:, notify: true) raise Membership::InvitationAlreadyUsed.new(membership) if membership.accepted_at expires_at = if membership.group.parent_or_self.saml_provider Time.current else nil end # so we want to accept all the pending invitations this person has been sent within this org # and we dont want any surprises if they already have some memberships. # they may be accepting memberships send to a different email (unverified_user) group_ids = membership.group.parent_or_self.id_and_subgroup_ids # cant accept pending memberships to groups I already belong to existing_group_ids = Membership.pending.where(user_id: membership.user_id, group_id: actor.memberships.accepted.pluck(:group_id)).pluck(:group_id) Membership.pending.where( user_id: membership.user_id, group_id: (group_ids - existing_group_ids)). update_all( user_id: actor.id, accepted_at: DateTime.now, saml_session_expires_at: expires_at) membership.reload Events::InvitationAccepted.publish!(membership) if notify && membership.accepted_at end def self.update(membership:, params:, actor:) actor.ability.authorize! :update, membership membership.assign_attributes(params.slice(:title)) return false unless membership.valid? membership.save! update_user_titles_and_broadcast(membership.id) EventBus.broadcast 'membership_update', membership, params, actor end def self.update_user_titles_and_broadcast(membership_id) membership = Membership.find(membership_id) user = membership.user group = membership.group return unless user && group titles = (user.experiences['titles'] || {}) titles[group.id] = membership.title user.experiences['titles'] = titles user.save! MessageChannelService.publish_models([user], serializer: AuthorSerializer, group_id: group.id) end def self.set_volume(membership:, params:, actor:) actor.ability.authorize! :update, membership val = Membership.volumes[params[:volume]] if params[:apply_to_all] group_ids = membership.group.parent_or_self.id_and_subgroup_ids actor.memberships.where(group_id: group_ids).update_all(volume: val) actor.discussion_readers.joins(:discussion). where('discussions.group_id': group_ids). update_all(volume: val) Stance.joins(:poll). where('polls.group_id': group_ids). where(participant_id: actor.id). update_all(volume: val) else membership.set_volume! params[:volume] membership.discussion_readers.update_all(volume: val) membership.stances.update_all(volume: val) end end def self.resend(membership:, actor:) actor.ability.authorize! :resend, membership EventBus.broadcast 'membership_resend', membership, actor Events::MembershipResent.publish!(membership, actor) end def self.make_admin(membership:, actor:) actor.ability.authorize! :make_admin, membership membership.update admin: true Events::NewCoordinator.publish!(membership, actor) end def self.remove_admin(membership:, actor:) actor.ability.authorize! :remove_admin, membership membership.update admin: false end def self.join_group(group:, actor:) actor.ability.authorize! :join, group membership = group.add_member!(actor) EventBus.broadcast('membership_join_group', group, actor) Events::UserJoinedGroup.publish!(membership) end def self.add_users_to_group(users:, group:, inviter:) inviter.ability.authorize!(:add_members, group) group.add_members!(users, inviter: inviter).tap do |memberships| Events::UserAddedToGroup.bulk_publish!(memberships, user: inviter) end end def self.destroy(membership:, actor:) actor.ability.authorize! :destroy, membership now = Time.zone.now DiscussionReader.joins(:discussion).where( 'discussions.group_id': membership.group.id_and_subgroup_ids, user_id: membership.user_id).update_all(revoked_at: now) Stance.joins(:poll).where( 'polls.group_id': membership.group.id_and_subgroup_ids, participant_id: membership.user_id, cast_at: nil ).update_all(revoked_at: now) Membership.where(user_id: membership.user_id, group_id: membership.group.id_and_subgroup_ids).destroy_all EventBus.broadcast('membership_destroy', membership, actor) end def self.save_experience(membership:, actor:, params:) actor.ability.authorize! :update, membership membership.experienced!(params[:experience]) EventBus.broadcast('membership_save_experience', membership, actor, params) end end
require_relative 'spec_parsed_data' describe ManagerRefresh::SaveInventory do include SpecParsedData ###################################################################################################################### # # Testing SaveInventory for one DtoCollection with Vm data and various DtoCollection constructor attributes, to verify # that saving of one isolated DtoCollection works correctly for Full refresh, Targeted refresh, Skeletal refresh or # any other variations of refreshes that needs to save partial or complete collection with partial or complete data. # ###################################################################################################################### # Test all settings for ManagerRefresh::SaveInventory [{:dto_saving_strategy => nil}, {:dto_saving_strategy => :recursive}, ].each do |dto_settings| context "with settings #{dto_settings}" do before :each do @zone = FactoryGirl.create(:zone) @ems = FactoryGirl.create(:ems_cloud, :zone => @zone) allow(@ems.class).to receive(:ems_type).and_return(:mock) allow(Settings.ems_refresh).to receive(:mock).and_return(dto_settings) end context 'with no Vms in the DB' do it 'creates VMs' do # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data add_data_to_dto_collection(data[:vms], vm_data(1), vm_data(2)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert saved data assert_all_records_match_hashes( [Vm.all, @ems.vms], {:ems_ref => "vm_ems_ref_1", :name => "vm_name_1", :location => "vm_location_1"}, {:ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) end it 'creates and updates VMs' do # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data add_data_to_dto_collection(data[:vms], vm_data(1), vm_data(2)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the updated values, checking id to make sure the original records are updated assert_all_records_match_hashes( [Vm.all, @ems.vms], {:ems_ref => "vm_ems_ref_1", :name => "vm_name_1", :location => "vm_location_1"}, {:ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) # Fetch the created Vms from the DB vm1 = Vm.find_by(:ems_ref => "vm_ems_ref_1") vm2 = Vm.find_by(:ems_ref => "vm_ems_ref_2") # Second saving with the updated data # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data, that have a modified name add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(2).merge(:name => "vm_changed_name_2")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the updated values, checking id to make sure the original records are updated assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :location => "vm_location_2"}) end end context 'with existing Vms in the DB' do before :each do # Fill DB with test Vms @vm1 = FactoryGirl.create(:vm_cloud, vm_data(1).merge(:ext_management_system => @ems)) @vm2 = FactoryGirl.create(:vm_cloud, vm_data(2).merge(:ext_management_system => @ems)) end context 'with VM DtoCollection with default settings' do before :each do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) end it 'has correct records in the DB' do # Check we really have the expected Vms in the DB assert_all_records_match_hashes( [Vm.all, @ems.vms], {:ems_ref => "vm_ems_ref_1", :name => "vm_name_1", :location => "vm_location_1"}, {:ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) end it 'updates existing VMs' do # Fill the DtoCollections with data, that have a modified name add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(2).merge(:name => "vm_changed_name_2")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data have the updated values, checking id to make sure the original records are updated assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :location => "vm_location_2"}) end it 'creates new VMs' do # Fill the DtoCollections with data, that have a new VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(2).merge(:name => "vm_changed_name_2"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data contain the new VM assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end it 'deletes missing VMs' do # Fill the DtoCollections with data, that are missing one VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data do miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}) end it 'deletes missing and creates new VMs' do # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end end context 'with VM DtoCollection with :delete_method => :disconnect_inv' do before :each do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :delete_method => :disconnect_inv) end it 'disconnects a missing VM instead of deleting it' do # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that DB still contains the disconnected VMs assert_all_records_match_hashes( Vm.all, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) # Assert that ems do not have the disconnected VMs associated assert_all_records_match_hashes( @ems.vms, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end end context 'with VM DtoCollection blacklist or whitelist used' do let :changed_data do [ vm_data(1).merge(:name => "vm_changed_name_1", :location => "vm_changed_location_1", :uid_ems => "uid_ems_changed_1", :raw_power_state => "raw_power_state_changed_1"), vm_data(2).merge(:name => "vm_changed_name_2", :location => "vm_changed_location_2", :uid_ems => "uid_ems_changed_2", :raw_power_state => "raw_power_state_changed_2"), vm_data(3).merge(:name => "vm_changed_name_3", :location => "vm_changed_location_3", :uid_ems => "uid_ems_changed_3", :raw_power_state => "raw_power_state_changed_3") ] end # TODO(lsmola) fixed attributes should contain also other attributes, like inclusion validation of :vendor # column it 'recognizes correct presence validators' do dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_blacklist => [:ems_ref, :uid_ems, :name, :location]) # Check that :name and :location do have validate presence, those attributes will not be blacklisted presence_validators = dto_collection.model_class.validators .detect { |x| x.kind_of? ActiveRecord::Validations::PresenceValidator }.attributes expect(presence_validators).to include(:name) expect(presence_validators).to include(:location) end it 'does not blacklist fixed attributes with default manager_ref' do # Fixed attributes are attributes used for unique ID of the DTO or attributes with presence validation dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_blacklist => [:ems_ref, :uid_ems, :name, :location, :vendor, :raw_power_state]) expect(dto_collection.attributes_blacklist).to match_array([:vendor, :uid_ems, :raw_power_state]) end it 'has fixed and internal attributes amongst whitelisted_attributes with default manager_ref' do # Fixed attributes are attributes used for unique ID of the DTO or attributes with presence validation dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_whitelist => [:raw_power_state]) expect(dto_collection.attributes_whitelist).to match_array([:__feedback_edge_set_parent, :ems_ref, :name, :location, :raw_power_state]) end it 'does not blacklist fixed attributes when changing manager_ref' do dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :manager_ref => [:uid_ems], :parent => @ems, :association => :vms, :attributes_blacklist => [:ems_ref, :uid_ems, :name, :location, :vendor, :raw_power_state]) expect(dto_collection.attributes_blacklist).to match_array([:vendor, :ems_ref, :raw_power_state]) end it 'has fixed and internal attributes amongst whitelisted_attributes when changing manager_ref' do # Fixed attributes are attributes used for unique ID of the DTO or attributes with presence validation dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :manager_ref => [:uid_ems], :parent => @ems, :association => :vms, :attributes_whitelist => [:raw_power_state]) expect(dto_collection.attributes_whitelist).to match_array([:__feedback_edge_set_parent, :uid_ems, :name, :location, :raw_power_state]) end it 'saves all attributes with blacklist and whitelist disabled' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "raw_power_state_changed_1", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "raw_power_state_changed_2", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => "raw_power_state_changed_3", :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end it 'does not save blacklisted attributes (excluding fixed attributes)' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_blacklist => [:name, :location, :raw_power_state]) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => nil, :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end it 'saves only whilelisted attributes (including fixed attributes)' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, # TODO(lsmola) vendor is not getting caught by fixed attributes :attributes_whitelist => [:uid_ems, :vendor]) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => nil, :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end it 'saves correct set of attributes when both whilelist and blacklist are used' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, # TODO(lsmola) vendor is not getting caught by fixed attributes :attributes_whitelist => [:uid_ems, :raw_power_state, :vendor], :attributes_blacklist => [:name, :ems_ref, :raw_power_state]) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => nil, :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end end context 'with VM DtoCollection with :complete => false' do before :each do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :complete => false) end it 'only updates existing Vms and creates new VMs, does not delete or update missing VMs' do # Fill the DtoCollections with data, that have a new VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data contain the new VM, but no VM was deleted assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end end context 'with changed parent and association' do it 'with AvailabilityZone parent, deletes missing and creates new VMs' do availability_zone = FactoryGirl.create(:availability_zone, :ext_management_system => @ems) @vm1.update_attributes(:availability_zone => availability_zone) @vm2.update_attributes(:availability_zone => availability_zone) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => availability_zone, :association => :vms) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1", :ext_management_system => @ems), vm_data(3).merge(:name => "vm_changed_name_3", :ext_management_system => @ems)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms, availability_zone.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end it 'with CloudTenant parent, deletes missing and creates new VMs' do cloud_tenant = FactoryGirl.create(:cloud_tenant, :ext_management_system => @ems) @vm1.update_attributes(:cloud_tenant => cloud_tenant) @vm2.update_attributes(:cloud_tenant => cloud_tenant) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => cloud_tenant, :association => :vms) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1", :ext_management_system => @ems), vm_data(3).merge(:name => "vm_changed_name_3", :ext_management_system => @ems)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms, cloud_tenant.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end it 'with CloudTenant parent, not providing ems_relation, only relation to CloudTenant is affected' do cloud_tenant = FactoryGirl.create(:cloud_tenant, :ext_management_system => @ems) @vm1.update_attributes(:cloud_tenant => cloud_tenant) @vm2.update_attributes(:cloud_tenant => cloud_tenant) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => cloud_tenant, :association => :vms) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, cloud_tenant.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) # Assert that ems relation exists only for the updated VM assert_all_records_match_hashes( @ems.vms, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}) end it 'with CloudTenant parent, does not delete the missing VMs with :complete => false' do cloud_tenant = FactoryGirl.create(:cloud_tenant, :ext_management_system => @ems) @vm1.update_attributes(:cloud_tenant => cloud_tenant) @vm2.update_attributes(:cloud_tenant => cloud_tenant) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => cloud_tenant, :association => :vms, :complete => false) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, cloud_tenant.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) # Assert that ems relation exists only for the updated VM assert_all_records_match_hashes( @ems.vms, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) end end end end end def assert_all_records_match_hashes(model_classes, *expected_match) # Helper for matching attributes of the model's records to an Array of hashes model_classes = model_classes.kind_of?(Array) ? model_classes : [model_classes] attributes = expected_match.first.keys model_classes.each { |m| expect(m.to_a.map { |x| x.slice(*attributes) }).to(match_array(expected_match)) } end def add_data_to_dto_collection(dto_collection, *args) # Creates Dto object from each arg and adds it into the DtoCollection args.each { |data| dto_collection << dto_collection.new_dto(data) } end end Rephrase spec messages, to be consistent with the rest of the file Rephrase spec messages, to be consistent with the rest of the file require_relative 'spec_parsed_data' describe ManagerRefresh::SaveInventory do include SpecParsedData ###################################################################################################################### # # Testing SaveInventory for one DtoCollection with Vm data and various DtoCollection constructor attributes, to verify # that saving of one isolated DtoCollection works correctly for Full refresh, Targeted refresh, Skeletal refresh or # any other variations of refreshes that needs to save partial or complete collection with partial or complete data. # ###################################################################################################################### # Test all settings for ManagerRefresh::SaveInventory [{:dto_saving_strategy => nil}, {:dto_saving_strategy => :recursive}, ].each do |dto_settings| context "with settings #{dto_settings}" do before :each do @zone = FactoryGirl.create(:zone) @ems = FactoryGirl.create(:ems_cloud, :zone => @zone) allow(@ems.class).to receive(:ems_type).and_return(:mock) allow(Settings.ems_refresh).to receive(:mock).and_return(dto_settings) end context 'with no Vms in the DB' do it 'creates VMs' do # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data add_data_to_dto_collection(data[:vms], vm_data(1), vm_data(2)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert saved data assert_all_records_match_hashes( [Vm.all, @ems.vms], {:ems_ref => "vm_ems_ref_1", :name => "vm_name_1", :location => "vm_location_1"}, {:ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) end it 'creates and updates VMs' do # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data add_data_to_dto_collection(data[:vms], vm_data(1), vm_data(2)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the updated values, checking id to make sure the original records are updated assert_all_records_match_hashes( [Vm.all, @ems.vms], {:ems_ref => "vm_ems_ref_1", :name => "vm_name_1", :location => "vm_location_1"}, {:ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) # Fetch the created Vms from the DB vm1 = Vm.find_by(:ems_ref => "vm_ems_ref_1") vm2 = Vm.find_by(:ems_ref => "vm_ems_ref_2") # Second saving with the updated data # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data, that have a modified name add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(2).merge(:name => "vm_changed_name_2")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the updated values, checking id to make sure the original records are updated assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :location => "vm_location_2"}) end end context 'with existing Vms in the DB' do before :each do # Fill DB with test Vms @vm1 = FactoryGirl.create(:vm_cloud, vm_data(1).merge(:ext_management_system => @ems)) @vm2 = FactoryGirl.create(:vm_cloud, vm_data(2).merge(:ext_management_system => @ems)) end context 'with VM DtoCollection with default settings' do before :each do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) end it 'has correct records in the DB' do # Check we really have the expected Vms in the DB assert_all_records_match_hashes( [Vm.all, @ems.vms], {:ems_ref => "vm_ems_ref_1", :name => "vm_name_1", :location => "vm_location_1"}, {:ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) end it 'updates existing VMs' do # Fill the DtoCollections with data, that have a modified name add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(2).merge(:name => "vm_changed_name_2")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data have the updated values, checking id to make sure the original records are updated assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :location => "vm_location_2"}) end it 'creates new VMs' do # Fill the DtoCollections with data, that have a new VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(2).merge(:name => "vm_changed_name_2"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data contain the new VM assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end it 'deletes missing VMs' do # Fill the DtoCollections with data, that are missing one VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data do miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}) end it 'deletes missing and creates new VMs' do # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end end context 'with VM DtoCollection with :delete_method => :disconnect_inv' do before :each do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :delete_method => :disconnect_inv) end it 'disconnects a missing VM instead of deleting it' do # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that DB still contains the disconnected VMs assert_all_records_match_hashes( Vm.all, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) # Assert that ems do not have the disconnected VMs associated assert_all_records_match_hashes( @ems.vms, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end end context 'with VM DtoCollection blacklist or whitelist used' do let :changed_data do [ vm_data(1).merge(:name => "vm_changed_name_1", :location => "vm_changed_location_1", :uid_ems => "uid_ems_changed_1", :raw_power_state => "raw_power_state_changed_1"), vm_data(2).merge(:name => "vm_changed_name_2", :location => "vm_changed_location_2", :uid_ems => "uid_ems_changed_2", :raw_power_state => "raw_power_state_changed_2"), vm_data(3).merge(:name => "vm_changed_name_3", :location => "vm_changed_location_3", :uid_ems => "uid_ems_changed_3", :raw_power_state => "raw_power_state_changed_3") ] end # TODO(lsmola) fixed attributes should contain also other attributes, like inclusion validation of :vendor # column it 'recognizes correct presence validators' do dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_blacklist => [:ems_ref, :uid_ems, :name, :location]) # Check that :name and :location do have validate presence, those attributes will not be blacklisted presence_validators = dto_collection.model_class.validators .detect { |x| x.kind_of? ActiveRecord::Validations::PresenceValidator }.attributes expect(presence_validators).to include(:name) expect(presence_validators).to include(:location) end it 'does not blacklist fixed attributes with default manager_ref' do # Fixed attributes are attributes used for unique ID of the DTO or attributes with presence validation dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_blacklist => [:ems_ref, :uid_ems, :name, :location, :vendor, :raw_power_state]) expect(dto_collection.attributes_blacklist).to match_array([:vendor, :uid_ems, :raw_power_state]) end it 'has fixed and internal attributes amongst whitelisted_attributes with default manager_ref' do # Fixed attributes are attributes used for unique ID of the DTO or attributes with presence validation dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_whitelist => [:raw_power_state]) expect(dto_collection.attributes_whitelist).to match_array([:__feedback_edge_set_parent, :ems_ref, :name, :location, :raw_power_state]) end it 'does not blacklist fixed attributes when changing manager_ref' do dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :manager_ref => [:uid_ems], :parent => @ems, :association => :vms, :attributes_blacklist => [:ems_ref, :uid_ems, :name, :location, :vendor, :raw_power_state]) expect(dto_collection.attributes_blacklist).to match_array([:vendor, :ems_ref, :raw_power_state]) end it 'has fixed and internal attributes amongst whitelisted_attributes when changing manager_ref' do # Fixed attributes are attributes used for unique ID of the DTO or attributes with presence validation dto_collection = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :manager_ref => [:uid_ems], :parent => @ems, :association => :vms, :attributes_whitelist => [:raw_power_state]) expect(dto_collection.attributes_whitelist).to match_array([:__feedback_edge_set_parent, :uid_ems, :name, :location, :raw_power_state]) end it 'saves all attributes with blacklist and whitelist disabled' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "raw_power_state_changed_1", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "raw_power_state_changed_2", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => "raw_power_state_changed_3", :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end it 'does not save blacklisted attributes (excluding fixed attributes)' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :attributes_blacklist => [:name, :location, :raw_power_state]) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => nil, :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end it 'saves only whitelisted attributes (including fixed attributes)' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, # TODO(lsmola) vendor is not getting caught by fixed attributes :attributes_whitelist => [:uid_ems, :vendor]) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => nil, :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end it 'saves correct set of attributes when both whilelist and blacklist are used' do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, # TODO(lsmola) vendor is not getting caught by fixed attributes :attributes_whitelist => [:uid_ems, :raw_power_state, :vendor], :attributes_blacklist => [:name, :ems_ref, :raw_power_state]) # Fill the DtoCollections with data, that have a modified name, new VM and a missing VM add_data_to_dto_collection(@data[:vms], *changed_data) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data don;t have the blacklisted attributes updated nor filled assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_1", :location => "vm_changed_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_changed_name_2", :raw_power_state => "unknown", :uid_ems => "uid_ems_changed_2", :location => "vm_changed_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :raw_power_state => nil, :uid_ems => "uid_ems_changed_3", :location => "vm_changed_location_3"}) end end context 'with VM DtoCollection with :complete => false' do before :each do # Initialize the DtoCollections @data = {} @data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => @ems, :association => :vms, :complete => false) end it 'updates only existing VMs and creates new VMs, does not delete or update missing VMs' do # Fill the DtoCollections with data, that have a new VM add_data_to_dto_collection(@data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, @data) # Assert that saved data contain the new VM, but no VM was deleted assert_all_records_match_hashes( [Vm.all, @ems.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end end context 'with VM DtoCollection with changed parent and association' do it 'deletes missing and creates new VMs with AvailabilityZone parent, ' do availability_zone = FactoryGirl.create(:availability_zone, :ext_management_system => @ems) @vm1.update_attributes(:availability_zone => availability_zone) @vm2.update_attributes(:availability_zone => availability_zone) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => availability_zone, :association => :vms) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1", :ext_management_system => @ems), vm_data(3).merge(:name => "vm_changed_name_3", :ext_management_system => @ems)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms, availability_zone.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end it 'deletes missing and creates new VMs with CloudTenant parent' do cloud_tenant = FactoryGirl.create(:cloud_tenant, :ext_management_system => @ems) @vm1.update_attributes(:cloud_tenant => cloud_tenant) @vm2.update_attributes(:cloud_tenant => cloud_tenant) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => cloud_tenant, :association => :vms) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1", :ext_management_system => @ems), vm_data(3).merge(:name => "vm_changed_name_3", :ext_management_system => @ems)) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, @ems.vms, cloud_tenant.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) end it 'affects oly relation to CloudTenant when not providing EMS relation and with CloudTenant parent' do cloud_tenant = FactoryGirl.create(:cloud_tenant, :ext_management_system => @ems) @vm1.update_attributes(:cloud_tenant => cloud_tenant) @vm2.update_attributes(:cloud_tenant => cloud_tenant) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => cloud_tenant, :association => :vms) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, cloud_tenant.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) # Assert that ems relation exists only for the updated VM assert_all_records_match_hashes( @ems.vms, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}) end it 'does not delete the missing VMs with :complete => false and with CloudTenant parent' do cloud_tenant = FactoryGirl.create(:cloud_tenant, :ext_management_system => @ems) @vm1.update_attributes(:cloud_tenant => cloud_tenant) @vm2.update_attributes(:cloud_tenant => cloud_tenant) # Initialize the DtoCollections data = {} data[:vms] = ::ManagerRefresh::DtoCollection.new( ManageIQ::Providers::Amazon::CloudManager::Vm, :parent => cloud_tenant, :association => :vms, :complete => false) # Fill the DtoCollections with data, that have one new VM and are missing one VM add_data_to_dto_collection(data[:vms], vm_data(1).merge(:name => "vm_changed_name_1"), vm_data(3).merge(:name => "vm_changed_name_3")) # Invoke the DtoCollections saving ManagerRefresh::SaveInventory.save_inventory(@ems, data) # Assert that saved data have the new VM and miss the deleted VM assert_all_records_match_hashes( [Vm.all, cloud_tenant.vms], {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}, {:id => anything, :ems_ref => "vm_ems_ref_3", :name => "vm_changed_name_3", :location => "vm_location_3"}) # Assert that ems relation exists only for the updated VM assert_all_records_match_hashes( @ems.vms, {:id => @vm1.id, :ems_ref => "vm_ems_ref_1", :name => "vm_changed_name_1", :location => "vm_location_1"}, {:id => @vm2.id, :ems_ref => "vm_ems_ref_2", :name => "vm_name_2", :location => "vm_location_2"}) end end end end end def assert_all_records_match_hashes(model_classes, *expected_match) # Helper for matching attributes of the model's records to an Array of hashes model_classes = model_classes.kind_of?(Array) ? model_classes : [model_classes] attributes = expected_match.first.keys model_classes.each { |m| expect(m.to_a.map { |x| x.slice(*attributes) }).to(match_array(expected_match)) } end def add_data_to_dto_collection(dto_collection, *args) # Creates Dto object from each arg and adds it into the DtoCollection args.each { |data| dto_collection << dto_collection.new_dto(data) } end end
# # Copyright (c) 2015, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # Neither the name of Arista Networks nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # require 'spec_helper' include FixtureHelpers describe Puppet::Type.type(:eos_user).provider(:eos) do def load_default_settings @name = 'Username' @nopassword = :false @secret = 'dc647eb65e6711e155375218212b3964' @encryption = 'md5' @role = 'network-admin' @privilege = 1 @sshkey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKL1UtBALa4CvFUsHUipN' \ 'ymA04qCXuAtTwNcMj84bTUzUI+q7mdzRCTLkllXeVxKuBnaTm2PW7W67K5C' \ 'Vpl0EVCm6IY7FS7kc4nlnD/tFvTvShy/fzYQRAdM7ZfVtegW8sMSFJzBR/T' \ '/Y/sxI16Y/dQb8fC3la9T25XOrzsFrQiKRZmJGwg8d+0RLxpfMg0s/9ATwQ' \ 'Kp6tPoLE4f3dKlAgSk5eENyVLA3RsypWADHpenHPcB7sa8D38e1TS+n+EUy' \ 'Adb3Yov+5ESAbgLIJLd52Xv+FyYi0c2L49ByBjcRrupp4zfXn4DNRnEG4K6' \ 'GcmswHuMEGZv5vjJ9OYaaaaaaa' @other_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKL1UtBALa4CvFUsHUipN' \ 'ymA04qCXuAtTwNcMj84bTUzUI+q7mdzRCTLkllXeVxKuBnaTm2PW7W67K5C' \ 'Vpl0EVCm6IY7FS7kc4nlnD/tFvTvShy/fzYQRAdM7ZfVtegW8sMSFJzBR/T' \ '/Y/sxI16Y/dQb8fC3la9T25XOrzsFrQiKRZmJGwg8d+0RLxpfMg0s/9ATwQ' \ 'Kp6tPoLE4f3dKlAgSk5eENyVLA3RsypWADHpenHPcB7sa8D38e1TS+n+EUy' \ 'Adb3Yov+5ESAbgLIJLd52Xv+FyYi0c2L49ByBjcRrupp4zfXn4DNRnEG4K6' \ 'GcmswHuMEGZv5vjJ9OYaaaaaaa' @ensure = :present end # Puppet RAL memoized methods let(:resource) do load_default_settings resource_hash = { name: @name, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, ensure: :present, provider: described_class.name } Puppet::Type.type(:eos_user).new(resource_hash) end let(:provider) { resource.provider } let(:api) { double('users') } def users users = Fixtures[:users] return users if users fixture('users', dir: File.dirname(__FILE__)) end before :each do allow(described_class.node).to receive(:api).with('users').and_return(api) allow(provider.node).to receive(:api).with('users').and_return(api) load_default_settings end context 'class methods' do before { allow(api).to receive(:getall).and_return(users) } describe '.instances' do subject { described_class.instances } it { is_expected.to be_an Array } it 'has one entry' do expect(subject.size).to eq(1) end it 'has an instance Username' do instance = subject.find { |p| p.name == @name } expect(instance).to be_a described_class end context 'eos_user { Username }' do subject { described_class.instances.find { |p| p.name == @name } } end end describe '.prefetch' do let :resources do { 'Username' => Puppet::Type.type(:eos_user).new(name: @name), 'Username2' => Puppet::Type.type(:eos_user).new(name: 'Username2') } end subject { described_class.prefetch(resources) } it 'resource providers are absent prior to calling .prefetch' do resources.values.each do |rsrc| expect(rsrc.provider.nopassword).to eq(:absent) expect(rsrc.provider.secret).to eq(:absent) expect(rsrc.provider.encryption).to eq(:absent) expect(rsrc.provider.role).to eq(:absent) expect(rsrc.provider.privilege).to eq(:absent) expect(rsrc.provider.sshkey).to eq(:absent) end end it 'sets the provider instance of the managed resource 64600' do subject expect(resources['Username'].provider.name).to eq(@name) expect(resources['Username'].provider.nopassword).to eq(@nopassword) expect(resources['Username'].provider.secret).to eq(@secret) expect(resources['Username'].provider.encryption).to eq(@encryption) expect(resources['Username'].provider.role).to eq(@role) expect(resources['Username'].provider.privilege).to eq(@privilege) expect(resources['Username'].provider.sshkey).to eq(@sshkey) end it 'does not set the provider instance of the unmanaged resource' do subject expect(resources['Username2'].provider.nopassword).to eq(:absent) expect(resources['Username2'].provider.secret).to eq(:absent) expect(resources['Username2'].provider.encryption).to eq(:absent) expect(resources['Username2'].provider.role).to eq(:absent) expect(resources['Username2'].provider.privilege).to eq(:absent) expect(resources['Username2'].provider.sshkey).to eq(:absent) end end end context 'resource exists method' do describe '#exists?' do subject { provider.exists? } context 'when the resource does not exist on the system' do it { is_expected.to be_falsey } end context 'when the resource exists on the system' do let(:provider) do allow(api).to receive(:getall).and_return(users) described_class.instances.first end it { is_expected.to be_truthy } end end end context 'resource (instance) methods' do describe '#create' do it 'sets ensure on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: :false, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.provider = :eos provider.ensure = :present provider.nopassword = :false provider.secret = @secret provider.encryption = @encryption provider.role = @role provider.privilege = @privilege provider.sshkey = @sshkey provider.flush expect(provider.ensure).to eq(:present) expect(provider.nopassword).to eq(@nopassword) expect(provider.secret).to eq(@secret) expect(provider.encryption).to eq(@encryption) expect(provider.role).to eq(@role) expect(provider.privilege).to eq(@privilege) expect(provider.sshkey).to eq(@sshkey) end end describe '#nopassword=(value)' do it 'sets nopassword on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: :true, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.nopassword = :true provider.flush expect(provider.nopassword).to eq(:true) end end describe '#secret=(value)' do it 'sets secret on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: '%$dc647eb65e6711e', encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.secret = '%$dc647eb65e6711e' provider.flush expect(provider.secret).to eq('%$dc647eb65e6711e') end end describe '#encryption=(value)' do it 'sets encryption on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: 'sha512', role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.encryption = 'sha512' provider.flush expect(provider.encryption).to eq('sha512') end end describe '#role=(value)' do it 'sets role on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: 'network-master', privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.role = 'network-master' provider.flush expect(provider.role).to eq('network-master') end end describe '#privilege=(value)' do it 'sets privilege on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: @role, privilege: 2, sshkey: @sshkey, loglevel: :notice) provider.create provider.privilege = 2 provider.flush expect(provider.privilege).to eq(2) end end describe '#sshkey=(value)' do it 'sets sshkey on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @other_key, loglevel: :notice) provider.create provider.sshkey = @other_key provider.flush expect(provider.sshkey).to eq(@other_key) end end describe '#destroy' do it 'sets ensure to :absent' do resource[:ensure] = :absent expect(api).to receive(:delete) provider.destroy provider.flush expect(provider.ensure).to eq(:absent) end end end end Update test to appropriate name. # # Copyright (c) 2015, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # Neither the name of Arista Networks nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # require 'spec_helper' include FixtureHelpers describe Puppet::Type.type(:eos_user).provider(:eos) do def load_default_settings @name = 'Username' @nopassword = :false @secret = 'dc647eb65e6711e155375218212b3964' @encryption = 'md5' @role = 'network-admin' @privilege = 1 @sshkey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKL1UtBALa4CvFUsHUipN' \ 'ymA04qCXuAtTwNcMj84bTUzUI+q7mdzRCTLkllXeVxKuBnaTm2PW7W67K5C' \ 'Vpl0EVCm6IY7FS7kc4nlnD/tFvTvShy/fzYQRAdM7ZfVtegW8sMSFJzBR/T' \ '/Y/sxI16Y/dQb8fC3la9T25XOrzsFrQiKRZmJGwg8d+0RLxpfMg0s/9ATwQ' \ 'Kp6tPoLE4f3dKlAgSk5eENyVLA3RsypWADHpenHPcB7sa8D38e1TS+n+EUy' \ 'Adb3Yov+5ESAbgLIJLd52Xv+FyYi0c2L49ByBjcRrupp4zfXn4DNRnEG4K6' \ 'GcmswHuMEGZv5vjJ9OYaaaaaaa' @other_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKL1UtBALa4CvFUsHUipN' \ 'ymA04qCXuAtTwNcMj84bTUzUI+q7mdzRCTLkllXeVxKuBnaTm2PW7W67K5C' \ 'Vpl0EVCm6IY7FS7kc4nlnD/tFvTvShy/fzYQRAdM7ZfVtegW8sMSFJzBR/T' \ '/Y/sxI16Y/dQb8fC3la9T25XOrzsFrQiKRZmJGwg8d+0RLxpfMg0s/9ATwQ' \ 'Kp6tPoLE4f3dKlAgSk5eENyVLA3RsypWADHpenHPcB7sa8D38e1TS+n+EUy' \ 'Adb3Yov+5ESAbgLIJLd52Xv+FyYi0c2L49ByBjcRrupp4zfXn4DNRnEG4K6' \ 'GcmswHuMEGZv5vjJ9OYaaaaaaa' @ensure = :present end # Puppet RAL memoized methods let(:resource) do load_default_settings resource_hash = { name: @name, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, ensure: :present, provider: described_class.name } Puppet::Type.type(:eos_user).new(resource_hash) end let(:provider) { resource.provider } let(:api) { double('users') } def users users = Fixtures[:users] return users if users fixture('users', dir: File.dirname(__FILE__)) end before :each do allow(described_class.node).to receive(:api).with('users').and_return(api) allow(provider.node).to receive(:api).with('users').and_return(api) load_default_settings end context 'class methods' do before { allow(api).to receive(:getall).and_return(users) } describe '.instances' do subject { described_class.instances } it { is_expected.to be_an Array } it 'has one entry' do expect(subject.size).to eq(1) end it 'has an instance Username' do instance = subject.find { |p| p.name == @name } expect(instance).to be_a described_class end context 'eos_user { Username }' do subject { described_class.instances.find { |p| p.name == @name } } end end describe '.prefetch' do let :resources do { 'Username' => Puppet::Type.type(:eos_user).new(name: @name), 'Username2' => Puppet::Type.type(:eos_user).new(name: 'Username2') } end subject { described_class.prefetch(resources) } it 'resource providers are absent prior to calling .prefetch' do resources.values.each do |rsrc| expect(rsrc.provider.nopassword).to eq(:absent) expect(rsrc.provider.secret).to eq(:absent) expect(rsrc.provider.encryption).to eq(:absent) expect(rsrc.provider.role).to eq(:absent) expect(rsrc.provider.privilege).to eq(:absent) expect(rsrc.provider.sshkey).to eq(:absent) end end it 'sets the provider instance of the managed resource Username' do subject expect(resources['Username'].provider.name).to eq(@name) expect(resources['Username'].provider.nopassword).to eq(@nopassword) expect(resources['Username'].provider.secret).to eq(@secret) expect(resources['Username'].provider.encryption).to eq(@encryption) expect(resources['Username'].provider.role).to eq(@role) expect(resources['Username'].provider.privilege).to eq(@privilege) expect(resources['Username'].provider.sshkey).to eq(@sshkey) end it 'does not set the provider instance of the unmanaged resource' do subject expect(resources['Username2'].provider.nopassword).to eq(:absent) expect(resources['Username2'].provider.secret).to eq(:absent) expect(resources['Username2'].provider.encryption).to eq(:absent) expect(resources['Username2'].provider.role).to eq(:absent) expect(resources['Username2'].provider.privilege).to eq(:absent) expect(resources['Username2'].provider.sshkey).to eq(:absent) end end end context 'resource exists method' do describe '#exists?' do subject { provider.exists? } context 'when the resource does not exist on the system' do it { is_expected.to be_falsey } end context 'when the resource exists on the system' do let(:provider) do allow(api).to receive(:getall).and_return(users) described_class.instances.first end it { is_expected.to be_truthy } end end end context 'resource (instance) methods' do describe '#create' do it 'sets ensure on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: :false, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.provider = :eos provider.ensure = :present provider.nopassword = :false provider.secret = @secret provider.encryption = @encryption provider.role = @role provider.privilege = @privilege provider.sshkey = @sshkey provider.flush expect(provider.ensure).to eq(:present) expect(provider.nopassword).to eq(@nopassword) expect(provider.secret).to eq(@secret) expect(provider.encryption).to eq(@encryption) expect(provider.role).to eq(@role) expect(provider.privilege).to eq(@privilege) expect(provider.sshkey).to eq(@sshkey) end end describe '#nopassword=(value)' do it 'sets nopassword on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: :true, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.nopassword = :true provider.flush expect(provider.nopassword).to eq(:true) end end describe '#secret=(value)' do it 'sets secret on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: '%$dc647eb65e6711e', encryption: @encryption, role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.secret = '%$dc647eb65e6711e' provider.flush expect(provider.secret).to eq('%$dc647eb65e6711e') end end describe '#encryption=(value)' do it 'sets encryption on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: 'sha512', role: @role, privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.encryption = 'sha512' provider.flush expect(provider.encryption).to eq('sha512') end end describe '#role=(value)' do it 'sets role on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: 'network-master', privilege: @privilege, sshkey: @sshkey, loglevel: :notice) provider.create provider.role = 'network-master' provider.flush expect(provider.role).to eq('network-master') end end describe '#privilege=(value)' do it 'sets privilege on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: @role, privilege: 2, sshkey: @sshkey, loglevel: :notice) provider.create provider.privilege = 2 provider.flush expect(provider.privilege).to eq(2) end end describe '#sshkey=(value)' do it 'sets sshkey on the resource' do expect(api).to receive(:create).with(resource[:name], name: @name, provider: :eos, ensure: :present, nopassword: @nopassword, secret: @secret, encryption: @encryption, role: @role, privilege: @privilege, sshkey: @other_key, loglevel: :notice) provider.create provider.sshkey = @other_key provider.flush expect(provider.sshkey).to eq(@other_key) end end describe '#destroy' do it 'sets ensure to :absent' do resource[:ensure] = :absent expect(api).to receive(:delete) provider.destroy provider.flush expect(provider.ensure).to eq(:absent) end end end end
require 'fileutils' Puppet::Type.type(:db_directory_structure).provide(:db_directory_structure) do def configure name = resource[:name] oracle_base = resource[:oracle_base_dir] ora_inventory = resource[:ora_inventory_dir] download_folder = resource[:download_dir] user = resource[:os_user] group = resource[:os_group] Puppet.info "configure oracle folders for #{name}" Puppet.info "create the following directories: #{oracle_base}, #{ora_inventory}, #{download_folder}" make_directory oracle_base make_directory download_folder make_directory ora_inventory ownened_by_oracle ora_inventory, user, group ownened_by_oracle oracle_base, user, group allow_everybody download_folder end def make_directory(path) Puppet.info "creating directory #{path}" FileUtils.mkdir_p path end def ownened_by_oracle(path, user, group) Puppet.info "Setting oracle ownership for #{path} with 0775" FileUtils.chmod 0775, path FileUtils.chown_R user, group, path end def allow_everybody(path) Puppet.info "Setting public permissions 0777 for #{path}" FileUtils.chmod 0777, path end end Fixes #170 - Do not do worthless chown_R just to get download_folder require 'fileutils' Puppet::Type.type(:db_directory_structure).provide(:db_directory_structure) do def configure name = resource[:name] oracle_base = resource[:oracle_base_dir] ora_inventory = resource[:ora_inventory_dir] download_folder = resource[:download_dir] user = resource[:os_user] group = resource[:os_group] Puppet.info "configure oracle folders for #{name}" Puppet.info "create the following directories: #{oracle_base}, #{ora_inventory}, #{download_folder}" make_directory oracle_base make_directory download_folder make_directory ora_inventory owned_by_oracle oracle_base, user, group allow_everybody download_folder, user, group owned_by_oracle ora_inventory, user, group end def make_directory(path) Puppet.info "creating directory #{path}" FileUtils.mkdir_p path end def owned_by_oracle(path, user, group) Puppet.info "Setting oracle ownership for #{path} with 0775" FileUtils.chmod 0775, path FileUtils.chown user, group, path end def allow_everybody(path, user, group) Puppet.info "Setting public permissions 0777 for #{path}" FileUtils.chmod 0777, path FileUtils.chown user, group, path 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 = "packetthief" s.version = "0.3.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["William (B.J.) Snow Orvis"] s.date = "2012-10-09" s.description = "Framework for intercepting packets, redirecting them to a handler, and doing something with the \"stolen\" connection." s.email = "bjorvis@isecpartners.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "examples/certs/cacert.pem", "examples/certs/cakey.pem", "examples/certs/samplechain.pem", "examples/certs/samplekey.pem", "examples/em_ssl_test.rb", "examples/redirector.rb", "examples/setup_iptables.sh", "examples/ssl_client_simple.rb", "examples/ssl_server_simple.rb", "examples/ssl_smart_proxy.rb", "examples/ssl_transparent_proxy.rb", "examples/transparent_proxy.rb", "lib/packetthief.rb", "lib/packetthief/handlers.rb", "lib/packetthief/handlers/abstract_ssl_handler.rb", "lib/packetthief/handlers/proxy_redirector.rb", "lib/packetthief/handlers/ssl_client.rb", "lib/packetthief/handlers/ssl_server.rb", "lib/packetthief/handlers/ssl_smart_proxy.rb", "lib/packetthief/handlers/ssl_transparent_proxy.rb", "lib/packetthief/handlers/transparent_proxy.rb", "lib/packetthief/ipfw.rb", "lib/packetthief/netfilter.rb", "lib/packetthief/pf.rb", "lib/packetthief/redirect_rule.rb", "lib/packetthief/util.rb", "packetthief.gemspec", "spec/packetthief/ipfw_spec.rb", "spec/packetthief/netfilter_spec.rb", "spec/packetthief/pf_spec.rb", "spec/packetthief_spec.rb", "spec/spec_helper.rb" ] s.homepage = "https://github.com/iSECPartners/" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.23" s.summary = "Framework for intercepting packets on Mac OS X/BSD/Linux" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<eventmachine>, [">= 1.0.0.rc.4"]) s.add_development_dependency(%q<rspec>, ["~> 2.8.0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) else s.add_dependency(%q<eventmachine>, [">= 1.0.0.rc.4"]) s.add_dependency(%q<rspec>, ["~> 2.8.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) end else s.add_dependency(%q<eventmachine>, [">= 1.0.0.rc.4"]) s.add_dependency(%q<rspec>, ["~> 2.8.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) end end Regenerate gemspec for version 0.3.2 # 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 = "packetthief" s.version = "0.3.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["William (B.J.) Snow Orvis"] s.date = "2012-10-10" s.description = "Framework for intercepting packets, redirecting them to a handler, and doing something with the \"stolen\" connection." s.email = "bjorvis@isecpartners.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "examples/certs/cacert.pem", "examples/certs/cakey.pem", "examples/certs/samplechain.pem", "examples/certs/samplekey.pem", "examples/em_ssl_test.rb", "examples/redirector.rb", "examples/setup_iptables.sh", "examples/ssl_client_simple.rb", "examples/ssl_server_simple.rb", "examples/ssl_smart_proxy.rb", "examples/ssl_transparent_proxy.rb", "examples/transparent_proxy.rb", "lib/packetthief.rb", "lib/packetthief/handlers.rb", "lib/packetthief/handlers/abstract_ssl_handler.rb", "lib/packetthief/handlers/proxy_redirector.rb", "lib/packetthief/handlers/ssl_client.rb", "lib/packetthief/handlers/ssl_server.rb", "lib/packetthief/handlers/ssl_smart_proxy.rb", "lib/packetthief/handlers/ssl_transparent_proxy.rb", "lib/packetthief/handlers/transparent_proxy.rb", "lib/packetthief/ipfw.rb", "lib/packetthief/netfilter.rb", "lib/packetthief/pf.rb", "lib/packetthief/redirect_rule.rb", "lib/packetthief/util.rb", "packetthief.gemspec", "spec/packetthief/ipfw_spec.rb", "spec/packetthief/netfilter_spec.rb", "spec/packetthief/pf_spec.rb", "spec/packetthief_spec.rb", "spec/spec_helper.rb" ] s.homepage = "https://github.com/iSECPartners/" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.23" s.summary = "Framework for intercepting packets on Mac OS X/BSD/Linux" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<eventmachine>, [">= 1.0.0.rc.4"]) s.add_development_dependency(%q<rspec>, ["~> 2.8.0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) else s.add_dependency(%q<eventmachine>, [">= 1.0.0.rc.4"]) s.add_dependency(%q<rspec>, ["~> 2.8.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) end else s.add_dependency(%q<eventmachine>, [">= 1.0.0.rc.4"]) s.add_dependency(%q<rspec>, ["~> 2.8.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) end end
class Barbecue::PageSerializer < ActiveModel::Serializer attributes :id, :title_en, :url_en, :perex_en, :meta_title_en, :meta_description_en, :title_cs, :url_cs, :perex_cs, :meta_title_cs, :meta_description_cs, :year, :text_content_en, :text_content_cs, :subtitle_cs, :subtitle_en, :updated_at, :created_at, :published_at, :featured, :cover_type, :cover_columns, :media_placements_count, :links_count, :igram_list, :position, :thumbnail_url has_many :tags, embed: :ids, embed_in_root: true, serializer: Barbecue::TagSerializer has_many :links, embed: :ids, embed_in_root: true, serializer: Admin::LinkSerializer attributes :media_placement_ids, :media_item_ids # has_many :media_placements, embed: :ids, embed_in_root: false #, serializer: Barbecue::MediaPlacementSerializer # has_many :media_items, embed: :ids, embed_in_root: false def media_placements_count object.media_placements_count || 0 end def links_count object.links.count end def thumbnail_url object.cover_image.thumb('400x400#').url unless object.cover_image.nil? end end removing invalid serializer
module Cache class HeadingSerializer attr_reader :heading def initialize(heading) @heading = heading end def as_json if heading.declarable? {} else heading_attributes = { id: heading.id, goods_nomenclature_sid: heading.goods_nomenclature_sid, goods_nomenclature_item_id: heading.goods_nomenclature_item_id, producline_suffix: heading.producline_suffix, validity_start_date: heading.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: heading.validity_end_date, description: heading.description, formatted_description: heading.formatted_description, bti_url: heading.bti_url, number_indents: heading.number_indents, } if heading.chapter.present? heading_attributes[:chapter] = { id: heading.chapter.id, goods_nomenclature_sid: heading.chapter.goods_nomenclature_sid, goods_nomenclature_item_id: heading.chapter.goods_nomenclature_item_id, producline_suffix: heading.chapter.producline_suffix, validity_start_date: heading.chapter.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: heading.chapter.validity_end_date, description: heading.chapter.description, formatted_description: heading.chapter.formatted_description, chapter_note: heading.chapter.chapter_note&.content, guide_ids: heading.chapter.guides.map do |guide| guide.id end, guides: heading.chapter.guides.map do |guide| { id: guide.id, title: guide.title, url: guide.url } end } end heading_attributes[:section_id] = heading.section&.id if heading.section.present? heading_attributes[:section] = { id: heading.section.id, numeral: heading.section.numeral, title: heading.section.title, position: heading.section.position, section_note: heading.section.section_note&.content } end heading_attributes[:footnotes] = heading.footnotes.map do |footnote| { footnote_id: footnote.footnote_id, validity_start_date: footnote.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: footnote.validity_end_date, code: footnote.code, description: footnote.description, formatted_description: footnote.formatted_description } end heading_attributes[:commodities] = heading.commodities.map do |commodity| commodity_attributes = { id: commodity.id, goods_nomenclature_sid: commodity.goods_nomenclature_sid, goods_nomenclature_item_id: commodity.goods_nomenclature_item_id, validity_start_date: commodity.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: commodity.validity_end_date, } commodity_attributes[:goods_nomenclature_indents] = commodity.goods_nomenclature_indents.map do |goods_nomenclature_indent| { goods_nomenclature_indent_sid: goods_nomenclature_indent.goods_nomenclature_indent_sid, validity_start_date: goods_nomenclature_indent.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: goods_nomenclature_indent.validity_end_date, number_indents: goods_nomenclature_indent.number_indents, productline_suffix: goods_nomenclature_indent.productline_suffix, } end commodity_attributes[:goods_nomenclature_descriptions] = commodity.goods_nomenclature_descriptions.map do |goods_nomenclature_description| { goods_nomenclature_description_period_sid: goods_nomenclature_description.goods_nomenclature_description_period_sid, validity_start_date: goods_nomenclature_description.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: goods_nomenclature_description.validity_end_date, description: goods_nomenclature_description.description, formatted_description: DescriptionFormatter.format(value: goods_nomenclature_description.description), description_plain: DescriptionTrimFormatter.format(value: goods_nomenclature_description.description) } end commodity_attributes[:overview_measures] = commodity.overview_measures.map do |measure| { measure_sid: measure.measure_sid, effective_start_date: measure.effective_start_date&.strftime('%FT%T.%LZ'), effective_end_date: measure.effective_end_date&.strftime('%FT%T.%LZ'), goods_nomenclature_sid: measure.goods_nomenclature_sid, vat: measure.vat?, duty_expression_id: "#{measure.measure_sid}-duty_expression", duty_expression: { id: "#{measure.measure_sid}-duty_expression", base: measure.duty_expression_with_national_measurement_units_for(commodity), formatted_base: measure.formatted_duty_expression_with_national_measurement_units_for(commodity) }, measure_type_id: measure.measure_type.measure_type_id, measure_type: { measure_type_id: measure.measure_type.measure_type_id, description: measure.measure_type.description } } end commodity_attributes end heading_attributes end end end end added checks if goods nomenclature description is empty. module Cache class HeadingSerializer attr_reader :heading def initialize(heading) @heading = heading end def as_json if heading.declarable? {} else heading_attributes = { id: heading.id, goods_nomenclature_sid: heading.goods_nomenclature_sid, goods_nomenclature_item_id: heading.goods_nomenclature_item_id, producline_suffix: heading.producline_suffix, validity_start_date: heading.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: heading.validity_end_date, description: heading.description, formatted_description: heading.formatted_description, bti_url: heading.bti_url, number_indents: heading.number_indents, } if heading.chapter.present? heading_attributes[:chapter] = { id: heading.chapter.id, goods_nomenclature_sid: heading.chapter.goods_nomenclature_sid, goods_nomenclature_item_id: heading.chapter.goods_nomenclature_item_id, producline_suffix: heading.chapter.producline_suffix, validity_start_date: heading.chapter.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: heading.chapter.validity_end_date, description: heading.chapter.description, formatted_description: heading.chapter.formatted_description, chapter_note: heading.chapter.chapter_note&.content, guide_ids: heading.chapter.guides.map do |guide| guide.id end, guides: heading.chapter.guides.map do |guide| { id: guide.id, title: guide.title, url: guide.url } end } end heading_attributes[:section_id] = heading.section&.id if heading.section.present? heading_attributes[:section] = { id: heading.section.id, numeral: heading.section.numeral, title: heading.section.title, position: heading.section.position, section_note: heading.section.section_note&.content } end heading_attributes[:footnotes] = heading.footnotes.map do |footnote| { footnote_id: footnote.footnote_id, validity_start_date: footnote.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: footnote.validity_end_date, code: footnote.code, description: footnote.description, formatted_description: footnote.formatted_description } end heading_attributes[:commodities] = heading.commodities.map do |commodity| commodity_attributes = { id: commodity.id, goods_nomenclature_sid: commodity.goods_nomenclature_sid, goods_nomenclature_item_id: commodity.goods_nomenclature_item_id, validity_start_date: commodity.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: commodity.validity_end_date, } commodity_attributes[:goods_nomenclature_indents] = commodity.goods_nomenclature_indents.map do |goods_nomenclature_indent| { goods_nomenclature_indent_sid: goods_nomenclature_indent.goods_nomenclature_indent_sid, validity_start_date: goods_nomenclature_indent.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: goods_nomenclature_indent.validity_end_date, number_indents: goods_nomenclature_indent.number_indents, productline_suffix: goods_nomenclature_indent.productline_suffix, } end commodity_attributes[:goods_nomenclature_descriptions] = commodity.goods_nomenclature_descriptions.map do |goods_nomenclature_description| { goods_nomenclature_description_period_sid: goods_nomenclature_description.goods_nomenclature_description_period_sid, validity_start_date: goods_nomenclature_description.validity_start_date&.strftime('%FT%T.%LZ'), validity_end_date: goods_nomenclature_description.validity_end_date, description: goods_nomenclature_description.description, formatted_description: goods_nomenclature_description.description.present? ? DescriptionFormatter.format(value: goods_nomenclature_description.description) : '', description_plain: goods_nomenclature_description.description.present? ? DescriptionTrimFormatter.format(value: goods_nomenclature_description.description) : '', } end commodity_attributes[:overview_measures] = commodity.overview_measures.map do |measure| { measure_sid: measure.measure_sid, effective_start_date: measure.effective_start_date&.strftime('%FT%T.%LZ'), effective_end_date: measure.effective_end_date&.strftime('%FT%T.%LZ'), goods_nomenclature_sid: measure.goods_nomenclature_sid, vat: measure.vat?, duty_expression_id: "#{measure.measure_sid}-duty_expression", duty_expression: { id: "#{measure.measure_sid}-duty_expression", base: measure.duty_expression_with_national_measurement_units_for(commodity), formatted_base: measure.formatted_duty_expression_with_national_measurement_units_for(commodity) }, measure_type_id: measure.measure_type.measure_type_id, measure_type: { measure_type_id: measure.measure_type.measure_type_id, description: measure.measure_type.description } } end commodity_attributes end heading_attributes end end end end
class ContainerDashboardService CPU_USAGE_PRECISION = 2 # 2 decimal points def initialize(provider_id, controller) @provider_id = provider_id @ems = ManageIQ::Providers::ContainerManager.find(@provider_id) unless @provider_id.blank? @controller = controller end def all_data { :providers_link => get_url_to_entity(:ems_container), :status => status, :providers => providers, :heatmaps => heatmaps, :ems_utilization => ems_utilization, :hourly_network_metrics => hourly_network_metrics, :daily_network_metrics => daily_network_metrics }.compact end def status if @ems.present? && @ems.kind_of?(ManageIQ::Providers::Openshift::ContainerManager) routes_count = @ems.container_routes.count else routes_count = ContainerRoute.count end { :nodes => { :count => @ems.present? ? @ems.container_nodes.count : ContainerNode.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_node) }, :containers => { :count => @ems.present? ? @ems.containers.count : Container.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container) }, :registries => { :count => @ems.present? ? @ems.container_image_registries.count : ContainerImageRegistry.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_image_registry) }, :projects => { :count => @ems.present? ? @ems.container_projects.count : ContainerProject.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_project) }, :pods => { :count => @ems.present? ? @ems.container_groups.count : ContainerGroup.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_group) }, :services => { :count => @ems.present? ? @ems.container_services.count : ContainerService.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_service) }, :images => { :count => @ems.present? ? @ems.container_images.count : ContainerImage.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_image) }, :routes => { :count => routes_count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_route) } } end def providers provider_classes_to_ui_types = { "ManageIQ::Providers::Openshift::ContainerManager" => :openshift, "ManageIQ::Providers::OpenshiftEnterprise::ContainerManager" => :openshift, "ManageIQ::Providers::Kubernetes::ContainerManager" => :kubernetes, "ManageIQ::Providers::Atomic::ContainerManager" => :atomic, "ManageIQ::Providers::AtomicEnterprise::ContainerManager" => :atomic } providers = @ems.present? ? {@ems.type => 1} : ManageIQ::Providers::ContainerManager.group(:type).count result = {} providers.each do |type, count| ui_type = provider_classes_to_ui_types[type] (result[ui_type] ||= build_provider_status(ui_type))[:count] += count end result.values end def build_provider_status(ui_type) { :iconClass => "pficon pficon-#{ui_type}", :id => ui_type, :providerType => ui_type.capitalize, :count => 0 } end def get_url_to_entity(entity) if @ems.present? @controller.url_for(:action => 'show', :id => @provider_id, :display => entity.to_s.pluralize, :controller => :ems_container) else @controller.url_for(:action => 'show_list', :controller => entity) end end def heatmaps # Get latest hourly rollup for each node. node_ids = @ems.container_nodes if @ems.present? metrics = MetricRollup.latest_rollups(ContainerNode.name, node_ids) metrics = metrics.where('timestamp > ?', 1.day.ago.utc).includes(:resource) metrics = metrics.includes(:resource => [:ext_management_system]) unless @ems.present? node_cpu_usage = nil node_memory_usage = nil if metrics.any? node_cpu_usage = [] node_memory_usage = [] metrics.each do |m| next if m.resource.nil? # Metrics are purged asynchronously and might be missing their node node_cpu_usage << { :id => m.resource_id, :info => { :node => m.resource.name, :provider => @ems.present? ? @ems.ext_management_system.name : m.resource.ext_management_system.name, :total => m.derived_vm_numvcpus }, :value => (m.cpu_usage_rate_average / 100.0).round(CPU_USAGE_PRECISION) # pf accepts fractions 90% = 0.90 } node_memory_usage << { :id => m.resource_id, :info => { :node => m.resource.name, :provider => m.resource.ext_management_system.name, :total => m.derived_memory_available }, :value => (m.mem_usage_absolute_average / 100.0).round(CPU_USAGE_PRECISION) # pf accepts fractions 90% = 0.90 } end end { :nodeCpuUsage => node_cpu_usage, :nodeMemoryUsage => node_memory_usage } end def ems_utilization used_cpu = Hash.new(0) used_mem = Hash.new(0) total_cpu = Hash.new(0) total_mem = Hash.new(0) daily_provider_metrics.each do |metric| date = metric.timestamp.strftime("%Y-%m-%d") used_cpu[date] += metric.v_derived_cpu_total_cores_used used_mem[date] += metric.derived_memory_used total_cpu[date] += metric.derived_vm_numvcpus total_mem[date] += metric.derived_memory_available end if daily_provider_metrics.any? { :cpu => { :used => used_cpu.values.last.round, :total => total_cpu.values.last.round, :xData => ["date"] + used_cpu.keys, :yData => ["used"] + used_cpu.values.map(&:round) }, :mem => { :used => (used_mem.values.last / 1024.0).round, :total => (total_mem.values.last / 1024.0).round, :xData => ["date"] + used_mem.keys, :yData => ["used"] + used_mem.values.map { |m| (m / 1024.0).round } } } else { :cpu => nil, :mem => nil } end end def hourly_network_metrics resource_ids = @ems.present? ? [@ems.id] : ManageIQ::Providers::ContainerManager.select(:id) hourly_network_trend = Hash.new(0) hourly_metrics = MetricRollup.find_all_by_interval_and_time_range("hourly", 1.day.ago.beginning_of_hour.utc, Time.now.utc) hourly_metrics = hourly_metrics.where('resource_type = ? AND resource_id in (?)', 'ExtManagementSystem', resource_ids) hourly_metrics.each do |m| hour = m.timestamp.beginning_of_hour.utc hourly_network_trend[hour] += m.net_usage_rate_average end if hourly_metrics.any? { :xData => ["date"] + hourly_network_trend.keys, :yData => ["used"] + hourly_network_trend.values.map(&:round) } end end def daily_network_metrics daily_network_metrics = Hash.new(0) daily_provider_metrics.each do |m| day = m.timestamp.strftime("%Y-%m-%d") daily_network_metrics[day] += m.net_usage_rate_average end if daily_provider_metrics.any? { :xData => ["date"] + daily_network_metrics.keys, :yData => ["used"] + daily_network_metrics.values.map(&:round) } end end def daily_provider_metrics if @daily_metrics.blank? resource_ids = @ems.present? ? [@ems.id] : ManageIQ::Providers::ContainerManager.select(:id) @daily_metrics = VimPerformanceDaily.find_entries(:tz => @controller.current_user.get_timezone) @daily_metrics = @daily_metrics.where('resource_type = :type and resource_id in (:resource_ids) and timestamp > :min_time', :type => 'ExtManagementSystem', :resource_ids => resource_ids, :min_time => 30.days.ago) @daily_metrics = @daily_metrics.order("timestamp") end @daily_metrics end end simplify provider types in container dashboard service (transferred from ManageIQ/manageiq@57f6b971905273eb9b7dd984112fe5aa2cdf30ab) class ContainerDashboardService CPU_USAGE_PRECISION = 2 # 2 decimal points def initialize(provider_id, controller) @provider_id = provider_id @ems = ManageIQ::Providers::ContainerManager.find(@provider_id) unless @provider_id.blank? @controller = controller end def all_data { :providers_link => get_url_to_entity(:ems_container), :status => status, :providers => providers, :heatmaps => heatmaps, :ems_utilization => ems_utilization, :hourly_network_metrics => hourly_network_metrics, :daily_network_metrics => daily_network_metrics }.compact end def status if @ems.present? && @ems.kind_of?(ManageIQ::Providers::Openshift::ContainerManager) routes_count = @ems.container_routes.count else routes_count = ContainerRoute.count end { :nodes => { :count => @ems.present? ? @ems.container_nodes.count : ContainerNode.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_node) }, :containers => { :count => @ems.present? ? @ems.containers.count : Container.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container) }, :registries => { :count => @ems.present? ? @ems.container_image_registries.count : ContainerImageRegistry.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_image_registry) }, :projects => { :count => @ems.present? ? @ems.container_projects.count : ContainerProject.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_project) }, :pods => { :count => @ems.present? ? @ems.container_groups.count : ContainerGroup.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_group) }, :services => { :count => @ems.present? ? @ems.container_services.count : ContainerService.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_service) }, :images => { :count => @ems.present? ? @ems.container_images.count : ContainerImage.count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_image) }, :routes => { :count => routes_count, :errorCount => 0, :warningCount => 0, :href => get_url_to_entity(:container_route) } } end def providers provider_classes_to_ui_types = ManageIQ::Providers::ContainerManager.subclasses.each_with_object({}) { |subclass, h| name = subclass.name.split('::')[2] h[subclass.name] = name.underscore.downcase.to_sym } providers = @ems.present? ? {@ems.type => 1} : ManageIQ::Providers::ContainerManager.group(:type).count result = {} providers.each do |type, count| ui_type = provider_classes_to_ui_types[type] (result[ui_type] ||= build_provider_status(ui_type))[:count] += count end result.values end def build_provider_status(ui_type) { :iconClass => "pficon pficon-#{ui_type}", :id => ui_type, :providerType => ui_type.capitalize, :count => 0 } end def get_url_to_entity(entity) if @ems.present? @controller.url_for(:action => 'show', :id => @provider_id, :display => entity.to_s.pluralize, :controller => :ems_container) else @controller.url_for(:action => 'show_list', :controller => entity) end end def heatmaps # Get latest hourly rollup for each node. node_ids = @ems.container_nodes if @ems.present? metrics = MetricRollup.latest_rollups(ContainerNode.name, node_ids) metrics = metrics.where('timestamp > ?', 1.day.ago.utc).includes(:resource) metrics = metrics.includes(:resource => [:ext_management_system]) unless @ems.present? node_cpu_usage = nil node_memory_usage = nil if metrics.any? node_cpu_usage = [] node_memory_usage = [] metrics.each do |m| next if m.resource.nil? # Metrics are purged asynchronously and might be missing their node node_cpu_usage << { :id => m.resource_id, :info => { :node => m.resource.name, :provider => @ems.present? ? @ems.ext_management_system.name : m.resource.ext_management_system.name, :total => m.derived_vm_numvcpus }, :value => (m.cpu_usage_rate_average / 100.0).round(CPU_USAGE_PRECISION) # pf accepts fractions 90% = 0.90 } node_memory_usage << { :id => m.resource_id, :info => { :node => m.resource.name, :provider => m.resource.ext_management_system.name, :total => m.derived_memory_available }, :value => (m.mem_usage_absolute_average / 100.0).round(CPU_USAGE_PRECISION) # pf accepts fractions 90% = 0.90 } end end { :nodeCpuUsage => node_cpu_usage, :nodeMemoryUsage => node_memory_usage } end def ems_utilization used_cpu = Hash.new(0) used_mem = Hash.new(0) total_cpu = Hash.new(0) total_mem = Hash.new(0) daily_provider_metrics.each do |metric| date = metric.timestamp.strftime("%Y-%m-%d") used_cpu[date] += metric.v_derived_cpu_total_cores_used used_mem[date] += metric.derived_memory_used total_cpu[date] += metric.derived_vm_numvcpus total_mem[date] += metric.derived_memory_available end if daily_provider_metrics.any? { :cpu => { :used => used_cpu.values.last.round, :total => total_cpu.values.last.round, :xData => ["date"] + used_cpu.keys, :yData => ["used"] + used_cpu.values.map(&:round) }, :mem => { :used => (used_mem.values.last / 1024.0).round, :total => (total_mem.values.last / 1024.0).round, :xData => ["date"] + used_mem.keys, :yData => ["used"] + used_mem.values.map { |m| (m / 1024.0).round } } } else { :cpu => nil, :mem => nil } end end def hourly_network_metrics resource_ids = @ems.present? ? [@ems.id] : ManageIQ::Providers::ContainerManager.select(:id) hourly_network_trend = Hash.new(0) hourly_metrics = MetricRollup.find_all_by_interval_and_time_range("hourly", 1.day.ago.beginning_of_hour.utc, Time.now.utc) hourly_metrics = hourly_metrics.where('resource_type = ? AND resource_id in (?)', 'ExtManagementSystem', resource_ids) hourly_metrics.each do |m| hour = m.timestamp.beginning_of_hour.utc hourly_network_trend[hour] += m.net_usage_rate_average end if hourly_metrics.any? { :xData => ["date"] + hourly_network_trend.keys, :yData => ["used"] + hourly_network_trend.values.map(&:round) } end end def daily_network_metrics daily_network_metrics = Hash.new(0) daily_provider_metrics.each do |m| day = m.timestamp.strftime("%Y-%m-%d") daily_network_metrics[day] += m.net_usage_rate_average end if daily_provider_metrics.any? { :xData => ["date"] + daily_network_metrics.keys, :yData => ["used"] + daily_network_metrics.values.map(&:round) } end end def daily_provider_metrics if @daily_metrics.blank? resource_ids = @ems.present? ? [@ems.id] : ManageIQ::Providers::ContainerManager.select(:id) @daily_metrics = VimPerformanceDaily.find_entries(:tz => @controller.current_user.get_timezone) @daily_metrics = @daily_metrics.where('resource_type = :type and resource_id in (:resource_ids) and timestamp > :min_time', :type => 'ExtManagementSystem', :resource_ids => resource_ids, :min_time => 30.days.ago) @daily_metrics = @daily_metrics.order("timestamp") end @daily_metrics end end
# Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'rubaidh-google_analytics', :lib => 'rubaidh/google_analytics', :source => 'http://gems.github.com' # config.gem 'spreadsheet',:version=>"0.6.4.1" config.gem 'hpricot',:version=>"0.8.2" config.gem 'fastercsv', :version=>"1.5.1" config.gem 'libxml-ruby',:lib=>"libxml",:version=>"1.1.3" config.gem 'uuidtools',:lib=>"uuidtools",:version=>"2.1.1" config.gem 'RedCloth' config.gem 'simple-spreadsheet-extractor',:version=>"0.3.3" #config.gem 'rack-openid',:version=>"1.1.0" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) config.load_paths += %W(#{RAILS_ROOT}/app/sweepers ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :info begin RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log") rescue StandardError RAILS_DEFAULT_LOGGER = Logger.new(STDERR) RAILS_DEFAULT_LOGGER.level = Logger::WARN RAILS_DEFAULT_LOGGER.warn( "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." ) end # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_seek-hub_session', :secret => '1576ebcfe0d1c7477397d8fb6a7a4354ad24936cc12fd5d6ab6956ab0fc24fc7aa35da1cccc605a5abafc299ba8749694fc156dc84aa32bdf357c66537361f77' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector end removed rack-openid from gem config, as its causing problems # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'rubaidh-google_analytics', :lib => 'rubaidh/google_analytics', :source => 'http://gems.github.com' # config.gem 'spreadsheet',:version=>"0.6.4.1" config.gem 'hpricot',:version=>"0.8.2" #config.gem 'ruby-openid' #config.gem 'rack-openid',:version=>"1.0.1" config.gem 'fastercsv', :version=>"1.5.1" config.gem 'libxml-ruby',:lib=>"libxml",:version=>"1.1.3" config.gem 'uuidtools',:lib=>"uuidtools",:version=>"2.1.1" config.gem 'RedCloth' config.gem 'simple-spreadsheet-extractor',:version=>"0.3.3" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) config.load_paths += %W(#{RAILS_ROOT}/app/sweepers ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :info begin RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log") rescue StandardError RAILS_DEFAULT_LOGGER = Logger.new(STDERR) RAILS_DEFAULT_LOGGER.level = Logger::WARN RAILS_DEFAULT_LOGGER.warn( "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." ) end # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_seek-hub_session', :secret => '1576ebcfe0d1c7477397d8fb6a7a4354ad24936cc12fd5d6ab6956ab0fc24fc7aa35da1cccc605a5abafc299ba8749694fc156dc84aa32bdf357c66537361f77' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector end
class EmsCloudDashboardService < EmsDashboardService def recent_images_data recent_resources(MiqTemplate, _('Recent Images'), _('Images')) end def recent_instances_data recent_resources(ManageIQ::Providers::CloudManager::Vm, _('Recent Instances'), _('Instances')) end def aggregate_status_data { :aggStatus => aggregate_status }.compact end def aggregate_status { :status => status_data, :attrData => attributes_data, } end def attributes_data attributes = %i(flavors cloud_tenants miq_templates vms availability_zones security_groups cloud_networks cloud_volumes) attr_icon = { :flavors => "pficon pficon-flavor", :cloud_tenants => "pficon pficon-cloud-tenant", :miq_templates => "fa fa-database", :vms => "pficon pficon-virtual-machine", :availability_zones => "pficon pficon-zone", :security_groups => "pficon pficon-cloud-security", :cloud_networks => "pficon pficon-network", :cloud_volumes => "pficon pficon-volume" } attr_url = { :flavors => "flavors", :cloud_tenants => "cloud_tenants", :miq_templates => "miq_templates", :vms => "vms", :availability_zones => "availability_zones", :security_groups => "security_groups", :cloud_networks => "cloud_networks", :cloud_volumes => "cloud_volumes" } attr_hsh = { :flavors => "Flavors", :cloud_tenants => "Cloud Tenants", :miq_templates => "Images", :vms => "Instances", :availability_zones => "Availability Zones", :security_groups => "Security Groups", :cloud_networks => "Cloud Networks", :cloud_volumes => "Cloud Volumes" } format_data('ems_cloud', attributes, attr_icon, attr_url, attr_hsh) end end Fixed links for vm/templates to instances/images on cloud dashboard Fixes https://bugzilla.redhat.com/show_bug.cgi?id=1636160 class EmsCloudDashboardService < EmsDashboardService def recent_images_data recent_resources(MiqTemplate, _('Recent Images'), _('Images')) end def recent_instances_data recent_resources(ManageIQ::Providers::CloudManager::Vm, _('Recent Instances'), _('Instances')) end def aggregate_status_data { :aggStatus => aggregate_status }.compact end def aggregate_status { :status => status_data, :attrData => attributes_data, } end def attributes_data attributes = %i(flavors cloud_tenants miq_templates vms availability_zones security_groups cloud_networks cloud_volumes) attr_icon = { :flavors => "pficon pficon-flavor", :cloud_tenants => "pficon pficon-cloud-tenant", :miq_templates => "fa fa-database", :vms => "pficon pficon-virtual-machine", :availability_zones => "pficon pficon-zone", :security_groups => "pficon pficon-cloud-security", :cloud_networks => "pficon pficon-network", :cloud_volumes => "pficon pficon-volume" } attr_url = { :flavors => "flavors", :cloud_tenants => "cloud_tenants", :miq_templates => "images", :vms => "instances", :availability_zones => "availability_zones", :security_groups => "security_groups", :cloud_networks => "cloud_networks", :cloud_volumes => "cloud_volumes" } attr_hsh = { :flavors => "Flavors", :cloud_tenants => "Cloud Tenants", :miq_templates => "Images", :vms => "Instances", :availability_zones => "Availability Zones", :security_groups => "Security Groups", :cloud_networks => "Cloud Networks", :cloud_volumes => "Cloud Volumes" } format_data('ems_cloud', attributes, attr_icon, attr_url, attr_hsh) end end
# Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'rubaidh-google_analytics', :lib => 'rubaidh/google_analytics', :source => 'http://gems.github.com' # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) config.load_paths += %W(#{RAILS_ROOT}/app/sweepers ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug begin RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log") rescue StandardError RAILS_DEFAULT_LOGGER = Logger.new(STDERR) RAILS_DEFAULT_LOGGER.level = Logger::WARN RAILS_DEFAULT_LOGGER.warn( "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." ) end # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_seek-hub_session', :secret => '1576ebcfe0d1c7477397d8fb6a7a4354ad24936cc12fd5d6ab6956ab0fc24fc7aa35da1cccc605a5abafc299ba8749694fc156dc84aa32bdf357c66537361f77' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector # this will make the Authorization module available throughout the codebase require 'authorization' end load 'config/environment_local.rb' if FileTest.exist?('config/environment_local.rb') EMAIL_ENABLED=false unless Object.const_defined?("EMAIL_ENABLED") SOLR_ENABLED=false unless Object.const_defined?("SOLR_ENABLED") ACTIVATION_REQUIRED=false unless Object.const_defined?("ACTIVATION_REQUIRED") ENABLE_GOOGLE_ANALYTICS=false unless Object.const_defined?("ENABLE_GOOGLE_ANALYTICS") # Set Google Analytics code if ENABLE_GOOGLE_ANALYTICS Rubaidh::GoogleAnalytics.tracker_id = GOOGLE_ANALYTICS_TRACKER_ID else Rubaidh::GoogleAnalytics.tracker_id = nil end Added spreadsheet gem to gem dependencies # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'rubaidh-google_analytics', :lib => 'rubaidh/google_analytics', :source => 'http://gems.github.com' config.gem 'spreadsheet' # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) config.load_paths += %W(#{RAILS_ROOT}/app/sweepers ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug begin RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log") rescue StandardError RAILS_DEFAULT_LOGGER = Logger.new(STDERR) RAILS_DEFAULT_LOGGER.level = Logger::WARN RAILS_DEFAULT_LOGGER.warn( "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." ) end # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_seek-hub_session', :secret => '1576ebcfe0d1c7477397d8fb6a7a4354ad24936cc12fd5d6ab6956ab0fc24fc7aa35da1cccc605a5abafc299ba8749694fc156dc84aa32bdf357c66537361f77' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector # this will make the Authorization module available throughout the codebase require 'authorization' end load 'config/environment_local.rb' if FileTest.exist?('config/environment_local.rb') EMAIL_ENABLED=false unless Object.const_defined?("EMAIL_ENABLED") SOLR_ENABLED=false unless Object.const_defined?("SOLR_ENABLED") ACTIVATION_REQUIRED=false unless Object.const_defined?("ACTIVATION_REQUIRED") ENABLE_GOOGLE_ANALYTICS=false unless Object.const_defined?("ENABLE_GOOGLE_ANALYTICS") # Set Google Analytics code if ENABLE_GOOGLE_ANALYTICS Rubaidh::GoogleAnalytics.tracker_id = GOOGLE_ANALYTICS_TRACKER_ID else Rubaidh::GoogleAnalytics.tracker_id = nil end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'pact_broker/version' def gem_files if Dir.exist?(".git") `git ls-files`.split($/) else root_path = File.dirname(__FILE__) all_files = Dir.chdir(root_path) { Dir.glob("**/{*,.*}") } all_files.reject! { |file| [".", ".."].include?(File.basename(file)) || File.directory?(file)} gitignore_path = File.join(root_path, ".gitignore") gitignore = File.readlines(gitignore_path) gitignore.map! { |line| line.chomp.strip } gitignore.reject! { |line| line.empty? || line =~ /^(#|!)/ } all_files.reject do |file| gitignore.any? do |ignore| file.start_with?(ignore) || File.fnmatch(ignore, file, File::FNM_PATHNAME) || File.fnmatch(ignore, File.basename(file), File::FNM_PATHNAME) end end end end Gem::Specification.new do |gem| gem.name = "pact_broker" gem.version = PactBroker::VERSION gem.authors = ["Bethany Skurrie", "Sergei Matheson", "Warner Godfrey"] gem.email = ["bskurrie@dius.com.au", "serge.matheson@rea-group.com", "warner@warnergodfrey.com"] gem.description = %q{A server that stores and returns pact files generated by the pact gem. It enables head/prod cross testing of the consumer and provider projects.} gem.summary = %q{See description} gem.homepage = "https://github.com/pact-foundation/pact_broker" gem.required_ruby_version = '>= 2.2.0' gem.files = gem_files gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.license = 'MIT' #gem.add_runtime_dependency 'pact' gem.add_runtime_dependency 'httparty', '~> 0.14' gem.add_runtime_dependency 'json', '~> 2.3' gem.add_runtime_dependency 'roar', '~> 1.1' gem.add_runtime_dependency 'reform', '~> 2.3','>= 2.3.1' gem.add_runtime_dependency 'dry-validation', '~> 0.10.5' gem.add_runtime_dependency 'sequel', '~> 5.28' gem.add_runtime_dependency 'webmachine', '1.5.0' gem.add_runtime_dependency 'semver2', '~> 3.4.2' gem.add_runtime_dependency 'rack', '~> 2.2', '>= 2.2.3' gem.add_runtime_dependency 'redcarpet', '>=3.3.2', '~>3.3' gem.add_runtime_dependency 'pact-support', '~> 1.14', '>= 1.14.1' gem.add_runtime_dependency 'padrino-core', '>= 0.14.3', '~> 0.14' gem.add_runtime_dependency 'sinatra', '>= 2.0.8.1', '< 3.0' gem.add_runtime_dependency 'haml', '~>5.0' gem.add_runtime_dependency 'sucker_punch', '~>2.0' gem.add_runtime_dependency 'rack-protection', '>= 2.0.8.1', '< 3.0' gem.add_runtime_dependency 'dry-types', '~> 0.10.3' # https://travis-ci.org/pact-foundation/pact_broker/jobs/249448621 gem.add_runtime_dependency 'dry-logic', '0.4.2' # Later version cases ArgumentError: wrong number of arguments gem.add_runtime_dependency 'table_print', '~> 1.5' gem.add_runtime_dependency 'semantic_logger', '~> 4.3' gem.add_runtime_dependency 'sanitize', '>= 5.2.1', '~> 5.2' gem.add_development_dependency 'pact', '~>1.14' gem.add_development_dependency 'rspec-pact-matchers', '~>0.1' gem.add_development_dependency 'bundler-audit', '~>0.4' gem.add_development_dependency 'sqlite3', '~>1.3' gem.add_development_dependency 'pry-byebug' gem.add_development_dependency 'rake', '~>12.3.3' gem.add_development_dependency 'fakefs', '~>0.4' gem.add_development_dependency 'webmock', '~>2.3' gem.add_development_dependency 'rspec', '~>3.0' gem.add_development_dependency 'rspec-its', '~>1.2' gem.add_development_dependency 'database_cleaner', '~>1.8', '>= 1.8.1' gem.add_development_dependency 'pg', '~>1.2' gem.add_development_dependency 'conventional-changelog', '~>1.3' gem.add_development_dependency 'bump', '~> 0.5' gem.add_development_dependency 'timecop', '~> 0.9' gem.add_development_dependency 'sequel-annotate', '~>1.3' gem.add_development_dependency 'faraday', '~>0.15' gem.add_development_dependency 'docker-api', '~>1.34' end chore: see if swapping the order of the rack version selectors makes the false positive warning go away in Hakiri # -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'pact_broker/version' def gem_files if Dir.exist?(".git") `git ls-files`.split($/) else root_path = File.dirname(__FILE__) all_files = Dir.chdir(root_path) { Dir.glob("**/{*,.*}") } all_files.reject! { |file| [".", ".."].include?(File.basename(file)) || File.directory?(file)} gitignore_path = File.join(root_path, ".gitignore") gitignore = File.readlines(gitignore_path) gitignore.map! { |line| line.chomp.strip } gitignore.reject! { |line| line.empty? || line =~ /^(#|!)/ } all_files.reject do |file| gitignore.any? do |ignore| file.start_with?(ignore) || File.fnmatch(ignore, file, File::FNM_PATHNAME) || File.fnmatch(ignore, File.basename(file), File::FNM_PATHNAME) end end end end Gem::Specification.new do |gem| gem.name = "pact_broker" gem.version = PactBroker::VERSION gem.authors = ["Bethany Skurrie", "Sergei Matheson", "Warner Godfrey"] gem.email = ["bskurrie@dius.com.au", "serge.matheson@rea-group.com", "warner@warnergodfrey.com"] gem.description = %q{A server that stores and returns pact files generated by the pact gem. It enables head/prod cross testing of the consumer and provider projects.} gem.summary = %q{See description} gem.homepage = "https://github.com/pact-foundation/pact_broker" gem.required_ruby_version = '>= 2.2.0' gem.files = gem_files gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.license = 'MIT' #gem.add_runtime_dependency 'pact' gem.add_runtime_dependency 'httparty', '~> 0.14' gem.add_runtime_dependency 'json', '~> 2.3' gem.add_runtime_dependency 'roar', '~> 1.1' gem.add_runtime_dependency 'reform', '~> 2.3','>= 2.3.1' gem.add_runtime_dependency 'dry-validation', '~> 0.10.5' gem.add_runtime_dependency 'sequel', '~> 5.28' gem.add_runtime_dependency 'webmachine', '1.5.0' gem.add_runtime_dependency 'semver2', '~> 3.4.2' gem.add_runtime_dependency 'rack', '>= 2.2.3', '~> 2.2' gem.add_runtime_dependency 'redcarpet', '>=3.3.2', '~>3.3' gem.add_runtime_dependency 'pact-support', '~> 1.14', '>= 1.14.1' gem.add_runtime_dependency 'padrino-core', '>= 0.14.3', '~> 0.14' gem.add_runtime_dependency 'sinatra', '>= 2.0.8.1', '< 3.0' gem.add_runtime_dependency 'haml', '~>5.0' gem.add_runtime_dependency 'sucker_punch', '~>2.0' gem.add_runtime_dependency 'rack-protection', '>= 2.0.8.1', '< 3.0' gem.add_runtime_dependency 'dry-types', '~> 0.10.3' # https://travis-ci.org/pact-foundation/pact_broker/jobs/249448621 gem.add_runtime_dependency 'dry-logic', '0.4.2' # Later version cases ArgumentError: wrong number of arguments gem.add_runtime_dependency 'table_print', '~> 1.5' gem.add_runtime_dependency 'semantic_logger', '~> 4.3' gem.add_runtime_dependency 'sanitize', '>= 5.2.1', '~> 5.2' gem.add_development_dependency 'pact', '~>1.14' gem.add_development_dependency 'rspec-pact-matchers', '~>0.1' gem.add_development_dependency 'bundler-audit', '~>0.4' gem.add_development_dependency 'sqlite3', '~>1.3' gem.add_development_dependency 'pry-byebug' gem.add_development_dependency 'rake', '~>12.3.3' gem.add_development_dependency 'fakefs', '~>0.4' gem.add_development_dependency 'webmock', '~>2.3' gem.add_development_dependency 'rspec', '~>3.0' gem.add_development_dependency 'rspec-its', '~>1.2' gem.add_development_dependency 'database_cleaner', '~>1.8', '>= 1.8.1' gem.add_development_dependency 'pg', '~>1.2' gem.add_development_dependency 'conventional-changelog', '~>1.3' gem.add_development_dependency 'bump', '~> 0.5' gem.add_development_dependency 'timecop', '~> 0.9' gem.add_development_dependency 'sequel-annotate', '~>1.3' gem.add_development_dependency 'faraday', '~>0.15' gem.add_development_dependency 'docker-api', '~>1.34' end
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Huginn::Application.initialize! CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => "https://login-test.cc.nd.edu/cas/", :proxy_callback_url => "https://data-test.cc.nd.edu/cas_proxy_callback/receive_pgt" ) update CAS url removed cc part # Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Huginn::Application.initialize! CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => "https://login.nd.edu/cas/", :proxy_callback_url => "https://bitdata1-test.dc.nd.edu/cas_proxy_callback/receive_pgt" )
# Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION ENV['ADMIN_PASSWORD'] = "password" CENSORED = 0 NOTCENSORED = 1 # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'web-page-parser' config.gem "diff-lcs", :lib => "diff/lcs" config.gem "xapian-fu", :lib => 'xapian_fu' # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_newssniffer.git_session', :secret => '5209cf0818c56993ac6abaa917aa8d8d864ffd68e118dbecb80651752b6108abb78a470decef826b85b63467da9e8d287cbc178f249463b987a9d5b8be396dfd' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end require 'rubyrss' require 'diff_html' require 'http' require 'zlib' include HTTP require 'xapian_fu' Upgrade to Rails 2.3.5, add curb gem dependency # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION ENV['ADMIN_PASSWORD'] = "password" CENSORED = 0 NOTCENSORED = 1 # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem 'web-page-parser' config.gem "diff-lcs", :lib => "diff/lcs" config.gem "xapian-fu", :lib => 'xapian_fu' config.gem "curb" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_newssniffer.git_session', :secret => '5209cf0818c56993ac6abaa917aa8d8d864ffd68e118dbecb80651752b6108abb78a470decef826b85b63467da9e8d287cbc178f249463b987a9d5b8be396dfd' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end require 'rubyrss' require 'diff_html' require 'http' require 'zlib' include HTTP require 'xapian_fu'
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION #ENV['RAILS_ENV'] ||= 'production' # In production, using script/console does not properly # set a GEM_PATH, so gems aren't loaded correctly. if ENV['RAILS_ENV'] == 'production' ENV['GEM_PATH'] = File.expand_path(File.join(File.dirname(__FILE__),'..','gems')) end # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') # This constant is used in the ucb_ccls_engine#Document # and other places like Amazon buckets # for controlling the path to documents. RAILS_APP_NAME = 'odms' # great. now I have to require i18n here too??? Why? # didn't need it 10 minutes ago require 'i18n' Rails::Initializer.run do |config| if RUBY_PLATFORM =~ /java/ config.gem 'activerecord-jdbcsqlite3-adapter', :lib => 'active_record/connection_adapters/jdbcsqlite3_adapter' config.gem 'activerecord-jdbcmysql-adapter', :lib => 'active_record/connection_adapters/jdbcmysql_adapter' config.gem 'jdbc-mysql', :lib => 'jdbc/mysql' config.gem 'jdbc-sqlite3', :lib => 'jdbc/sqlite3' config.gem 'jruby-openssl', :lib => 'openssl' else config.gem 'mysql' config.gem "sqlite3" end # due to some enhancements, the db gems MUST come first # for use in the jruby environment. config.gem 'ccls-ccls_engine' # Without this, rake doesn't properly include that app/ paths config.gem 'jakewendt-simply_authorized' config.gem 'jakewendt-simply_pages' # config.gem 'jakewendt-simply_trackable' # require it, but don't load it config.gem 'jakewendt-rdoc_rails', :lib => false config.gem 'haml' # Needed for Surveyor # Keep chronic here config.gem "chronic" # http://chronic.rubyforge.org/ config.gem 'active_shipping' config.gem 'will_paginate' config.gem 'fastercsv' config.gem 'paperclip' # not using 'photos' or 'documents' so config.gem 'hpricot' config.frameworks -= [ :active_resource ] # 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. config.time_zone = 'UTC' end # don't use the default div wrappers as they muck up style # just adding a class to the tag is a little better require 'hpricot' ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| error_class = 'field_error' nodes = Hpricot(html_tag) nodes.each_child { |node| node[:class] = node.classes.push(error_class).join(' ') unless !node.elem? || node[:type] == 'hidden' || node.classes.include?(error_class) } nodes.to_html } Removed explicit i18n requirement. Added simply_helpful to config. # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION #ENV['RAILS_ENV'] ||= 'production' # In production, using script/console does not properly # set a GEM_PATH, so gems aren't loaded correctly. if ENV['RAILS_ENV'] == 'production' ENV['GEM_PATH'] = File.expand_path(File.join(File.dirname(__FILE__),'..','gems')) end # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') # This constant is used in the ucb_ccls_engine#Document # and other places like Amazon buckets # for controlling the path to documents. RAILS_APP_NAME = 'odms' Rails::Initializer.run do |config| if RUBY_PLATFORM =~ /java/ config.gem 'activerecord-jdbcsqlite3-adapter', :lib => 'active_record/connection_adapters/jdbcsqlite3_adapter' config.gem 'activerecord-jdbcmysql-adapter', :lib => 'active_record/connection_adapters/jdbcmysql_adapter' config.gem 'jdbc-mysql', :lib => 'jdbc/mysql' config.gem 'jdbc-sqlite3', :lib => 'jdbc/sqlite3' config.gem 'jruby-openssl', :lib => 'openssl' else config.gem 'mysql' config.gem "sqlite3" end # due to some enhancements, the db gems MUST come first # for use in the jruby environment. config.gem 'ccls-ccls_engine' # Without this, rake doesn't properly include that app/ paths config.gem 'jakewendt-simply_authorized' config.gem 'jakewendt-simply_pages' config.gem 'jakewendt-simply_helpful' # config.gem 'jakewendt-simply_trackable' # require it, but don't load it config.gem 'jakewendt-rdoc_rails', :lib => false config.gem 'haml' # Needed for Surveyor # Keep chronic here config.gem "chronic" # http://chronic.rubyforge.org/ config.gem 'active_shipping' config.gem 'will_paginate' config.gem 'fastercsv' config.gem 'paperclip' # not using 'photos' or 'documents' so config.gem 'hpricot' config.frameworks -= [ :active_resource ] # 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. config.time_zone = 'UTC' end # don't use the default div wrappers as they muck up style # just adding a class to the tag is a little better require 'hpricot' ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| error_class = 'field_error' nodes = Hpricot(html_tag) nodes.each_child { |node| node[:class] = node.classes.push(error_class).join(' ') unless !node.elem? || node[:type] == 'hidden' || node.classes.include?(error_class) } nodes.to_html }
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) config.gem 'authlogic', :version => '>= 2.1.1' config.gem "authlogic-oid", :lib => "authlogic_openid", :version => '>= 1.0.4' config.gem "ruby-openid", :lib => "openid", :version => '>= 2.1.7' config.gem 'nokogiri', :version => '>= 1.3.2' config.gem 'faker', :version => '>= 0.3.1' config.gem 'rdiscount', :version => '>= 1.3.5' config.gem 'feedzirra', :version => '>= 0.0.20' config.gem 'delayed_job', :version => '>= 1.8.4' config.gem 'luigi-httparty', :lib => 'httparty', :version => '>= 0.4.4' config.gem 'datacatalog', :version => '>= 0.4.5' config.gem "rspec", :lib => false, :version => ">= 1.2.0" config.gem "rspec-rails", :lib => false, :version => ">= 1.2.0" config.gem 'thoughtbot-shoulda', :lib => 'shoulda', :version => ">= 2.10.0", :source => 'http://gems.github.com' config.gem 'rr', :version => '>= 0.10.0' config.gem 'notahat-machinist', :lib => 'machinist', :version => ">= 1.0.3", :source => 'http://gems.github.com' config.gem 'webrat', :version => '>= 0.4.5' config.gem 'cucumber', :version => '>= 0.3.94', :source => 'http://gems.github.com' config.gem 'bmabey-database_cleaner', :lib => 'database_cleaner', :version => '>= 0.2.2', :source => 'http://gems.github.com' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. config.frameworks -= [ :active_resource ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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. config.time_zone = 'UTC' config.action_controller.session = { :session_key => 'natdatcat', :secret => 'f3f57b71ef9345ffccd0c4e841d8e74bb2e7d2ef692a506aa6c2a3c29d584a55dd18426ffc04610be49956a51af' } config.after_initialize do CACHE = Cache.new end end httparty is not a direct dependency (The datacatalog gem will handle the httparty dependency as needed.) # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) config.gem 'authlogic', :version => '>= 2.1.1' config.gem "authlogic-oid", :lib => "authlogic_openid", :version => '>= 1.0.4' config.gem "ruby-openid", :lib => "openid", :version => '>= 2.1.7' config.gem 'nokogiri', :version => '>= 1.3.2' config.gem 'faker', :version => '>= 0.3.1' config.gem 'rdiscount', :version => '>= 1.3.5' config.gem 'feedzirra', :version => '>= 0.0.20' config.gem 'delayed_job', :version => '>= 1.8.4' config.gem 'datacatalog', :version => '>= 0.4.5' config.gem "rspec", :lib => false, :version => ">= 1.2.0" config.gem "rspec-rails", :lib => false, :version => ">= 1.2.0" config.gem 'thoughtbot-shoulda', :lib => 'shoulda', :version => ">= 2.10.0", :source => 'http://gems.github.com' config.gem 'rr', :version => '>= 0.10.0' config.gem 'notahat-machinist', :lib => 'machinist', :version => ">= 1.0.3", :source => 'http://gems.github.com' config.gem 'webrat', :version => '>= 0.4.5' config.gem 'cucumber', :version => '>= 0.3.94', :source => 'http://gems.github.com' config.gem 'bmabey-database_cleaner', :lib => 'database_cleaner', :version => '>= 0.2.2', :source => 'http://gems.github.com' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. config.frameworks -= [ :active_resource ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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. config.time_zone = 'UTC' config.action_controller.session = { :session_key => 'natdatcat', :secret => 'f3f57b71ef9345ffccd0c4e841d8e74bb2e7d2ef692a506aa6c2a3c29d584a55dd18426ffc04610be49956a51af' } config.after_initialize do CACHE = Cache.new end end
RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| config.time_zone = 'UTC' end Fix cucumber tests Update to Rails 2.3.8 broke cucumber tests. This is fix from agibralter from https://gist.github.com/431811 RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION require File.join(File.dirname(__FILE__), 'boot') class RackRailsCookieHeaderHack def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) if headers['Set-Cookie'] && headers['Set-Cookie'].respond_to?(:collect!) headers['Set-Cookie'].collect! { |h| h.strip } end [status, headers, body] end end Rails::Initializer.run do |config| config.time_zone = 'UTC' config.after_initialize do ActionController::Dispatcher.middleware.insert_before(ActionController::Base.session_store, RackRailsCookieHeaderHack) end end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "resque-multi-job-forks" s.version = "0.3.5" s.authors = ["Mick Staugaard", "Luke Antins", 'Sergio Tulentsev'] s.email = ["mick@zendesk.com", "luke@lividpenguin.com", 'sergei.tulentsev@gmail.com'] s.homepage = "http://github.com/staugaard/resque-multi-job-forks" s.summary = "Have your resque workers process more that one job" s.description = "When your resque jobs are frequent and fast, the overhead of forking and running your after_fork might get too big." s.add_runtime_dependency("resque", "= 1.23") s.add_runtime_dependency("json") s.add_development_dependency("rake") s.add_development_dependency("bundler") s.files = Dir["lib/**/*"] s.test_files = Dir["test/**/*"] s.require_paths = ["lib"] end Bumped version # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "resque-multi-job-forks" s.version = "0.4.0" s.authors = ["Mick Staugaard", "Luke Antins", 'Sergio Tulentsev'] s.email = ["mick@zendesk.com", "luke@lividpenguin.com", 'sergei.tulentsev@gmail.com'] s.homepage = "http://github.com/staugaard/resque-multi-job-forks" s.summary = "Have your resque workers process more that one job" s.description = "When your resque jobs are frequent and fast, the overhead of forking and running your after_fork might get too big." s.add_runtime_dependency("resque", "~> 1.24") s.add_runtime_dependency("json") s.add_development_dependency("rake") s.add_development_dependency("bundler") s.files = Dir["lib/**/*"] s.test_files = Dir["test/**/*"] s.require_paths = ["lib"] end
# Be sure to restart your web server when you modify this file. # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') require File.join(File.dirname(__FILE__), '../lib/localization.rb') Localization.load Rails::Initializer.run do |config| # 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. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Use the database for sessions instead of the file system # (create the session table with 'rake create_sessions_table') config.action_controller.session_store = :active_record_store # Enable page/fragment caching by setting a file-based store # (remember to create the caching directory and make it readable to the application) config.action_controller.cache_store = :file_store, "#{RAILS_ROOT}/tmp/cache" # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector # 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. config.time_zone = 'UTC' # 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}')] # config.i18n.default_locale = :de # See Rails::Configuration for more options config.logger = Logger.new("#{RAILS_ROOT}/log/#{ENV['RAILS_ENV']}.log", 5) config.gem 'splattael-activerecord_base_without_table', :lib => 'activerecord_base_without_table', :source => 'http://gems.github.com' config.gem 'rails', :version => '2.3.2' config.gem 'actionpack', :version => '2.3.2' config.gem 'actionmailer', :version => '2.3.2' config.gem 'activerecord', :version => '2.3.2' config.gem 'activeresource', :version => '2.3.2' config.gem 'activesupport', :version => '2.3.2' config.gem 'mysql', :version => '2.7' config.gem 'daemons', :version => '1.0.10' config.gem 'eventmachine', :version => '0.12.6' config.gem 'json', :version => '1.1.4' config.gem 'mislav-will_paginate', :version => '2.3.8', :lib => 'will_paginate', :source => 'http://gems.github.com' config.gem 'ferret', :version => '0.11.6' config.gem 'acts_as_ferret', :version => '0.4.3' config.gem 'fastercsv', :version => '1.4.0' config.gem 'icalendar', :version => '1.1.0' config.gem 'tzinfo', :version => '0.3.12' config.gem 'RedCloth', :version => '4.1.9' config.gem 'rmagick', :version => '2.9.1' config.gem 'ZenTest', :version => '4.0.0' #config.gem 'hoe', :version => '1.12.1' config.gem 'gchartrb', :version => '0.8', :lib => 'google_chart' config.gem 'test-spec', :version => '0.10.0', :lib => 'test/spec' #config.gem 'echoe', :version => '3.1.1' # Juggernaut is installed as a plugin and heavily customised, therefore it cannot be listed here. # Required for development only config.gem 'allison', :version => '2.0.3' config.gem 'markaby', :version => '0.5' end ActionController::Base.session_options[:session_expires]= Time.local(2015,"jan") # # Add new inflection rules using the following format # (all these examples are active by default): # Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end require File.join(File.dirname(__FILE__), '../lib/rails_extensions') load File.join(File.dirname(__FILE__), 'environment.local.rb') require File.join(File.dirname(__FILE__), '../lib/misc.rb') require_dependency 'tzinfo' include TZInfo Clean up environment file. Nothing significant. # Be sure to restart your web server when you modify this file. # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') require File.join(File.dirname(__FILE__), '../lib/localization.rb') Localization.load Rails::Initializer.run do |config| # 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. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Use the database for sessions instead of the file system # (create the session table with 'rake create_sessions_table') config.action_controller.session_store = :active_record_store # Enable page/fragment caching by setting a file-based store # (remember to create the caching directory and make it readable to the application) config.action_controller.cache_store = :file_store, "#{RAILS_ROOT}/tmp/cache" # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector # 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. config.time_zone = 'UTC' # 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}')] # config.i18n.default_locale = :de # See Rails::Configuration for more options config.logger = Logger.new("#{RAILS_ROOT}/log/#{ENV['RAILS_ENV']}.log", 5) config.gem 'rails', :version => '2.3.2' config.gem 'actionpack', :version => '2.3.2' config.gem 'actionmailer', :version => '2.3.2' config.gem 'activerecord', :version => '2.3.2' config.gem 'activeresource', :version => '2.3.2' config.gem 'activesupport', :version => '2.3.2' config.gem 'splattael-activerecord_base_without_table', :lib => 'activerecord_base_without_table', :source => 'http://gems.github.com' config.gem 'mysql', :version => '2.7' config.gem 'daemons', :version => '1.0.10' config.gem 'eventmachine', :version => '0.12.6' config.gem 'json', :version => '1.1.4' config.gem 'mislav-will_paginate', :version => '2.3.8', :lib => 'will_paginate', :source => 'http://gems.github.com' config.gem 'ferret', :version => '0.11.6' config.gem 'acts_as_ferret', :version => '0.4.3' config.gem 'fastercsv', :version => '1.4.0' config.gem 'icalendar', :version => '1.1.0' config.gem 'tzinfo', :version => '0.3.12' config.gem 'RedCloth', :version => '4.1.9' config.gem 'rmagick', :version => '2.9.1' config.gem 'ZenTest', :version => '4.0.0' #config.gem 'hoe', :version => '1.12.1' config.gem 'gchartrb', :version => '0.8', :lib => 'google_chart' config.gem 'test-spec', :version => '0.10.0', :lib => 'test/spec' #config.gem 'echoe', :version => '3.1.1' # Juggernaut is installed as a plugin and heavily customised, therefore it cannot be listed here. # Required for development only config.gem 'allison', :version => '2.0.3' config.gem 'markaby', :version => '0.5' end ActionController::Base.session_options[:session_expires]= Time.local(2015,"jan") # # Add new inflection rules using the following format # (all these examples are active by default): # Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end require File.join(File.dirname(__FILE__), '../lib/rails_extensions') load File.join(File.dirname(__FILE__), 'environment.local.rb') require File.join(File.dirname(__FILE__), '../lib/misc.rb') require_dependency 'tzinfo' include TZInfo
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') # This constant is used in the ucb_ccls_engine#Document # and other places like Amazon buckets # for controlling the path to documents. RAILS_APP_NAME = 'ccls' Rails::Initializer.run do |config| config.frameworks -= [:active_resource] config.routes_configuration_file = File.expand_path( File.join(File.dirname(__FILE__),'..','test/config/routes.rb')) if RUBY_PLATFORM =~ /java/ config.gem 'activerecord-jdbcsqlite3-adapter', :lib => 'active_record/connection_adapters/jdbcsqlite3_adapter' config.gem 'activerecord-jdbcmysql-adapter', :lib => 'active_record/connection_adapters/jdbcmysql_adapter' config.gem 'jdbc-mysql', :lib => 'jdbc/mysql' config.gem 'jdbc-sqlite3', :lib => 'jdbc/sqlite3' config.gem 'jruby-openssl', :lib => 'openssl' else config.gem 'mysql' config.gem "sqlite3" end config.gem "jakewendt-use_db" config.gem 'jakewendt-simply_trackable' config.gem 'jakewendt-simply_authorized' config.gem 'jakewendt-simply_pages' config.gem 'jakewendt-simply_helpful' # require it, but don't load it config.gem 'jakewendt-rdoc_rails', :lib => false config.gem 'haml' # Needed for Surveyor # Keep chronic here config.gem "chronic" # http://chronic.rubyforge.org/ config.gem 'active_shipping' config.gem 'will_paginate' config.gem 'fastercsv' config.gem 'paperclip' config.after_initialize do load File.expand_path(File.join(File.dirname(__FILE__),'../lib','ccls_engine.rb')) end end Updated to rails 2.3.12 # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.12' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') # This constant is used in the ucb_ccls_engine#Document # and other places like Amazon buckets # for controlling the path to documents. RAILS_APP_NAME = 'ccls' Rails::Initializer.run do |config| config.frameworks -= [:active_resource] config.routes_configuration_file = File.expand_path( File.join(File.dirname(__FILE__),'..','test/config/routes.rb')) if RUBY_PLATFORM =~ /java/ config.gem 'activerecord-jdbcsqlite3-adapter', :lib => 'active_record/connection_adapters/jdbcsqlite3_adapter' config.gem 'activerecord-jdbcmysql-adapter', :lib => 'active_record/connection_adapters/jdbcmysql_adapter' config.gem 'jdbc-mysql', :lib => 'jdbc/mysql' config.gem 'jdbc-sqlite3', :lib => 'jdbc/sqlite3' config.gem 'jruby-openssl', :lib => 'openssl' else config.gem 'mysql' config.gem "sqlite3" end config.gem "jakewendt-use_db" config.gem 'jakewendt-simply_trackable' config.gem 'jakewendt-simply_authorized' config.gem 'jakewendt-simply_pages' config.gem 'jakewendt-simply_helpful' # require it, but don't load it config.gem 'jakewendt-rdoc_rails', :lib => false config.gem 'haml' # Needed for Surveyor # Keep chronic here config.gem "chronic" # http://chronic.rubyforge.org/ config.gem 'active_shipping' config.gem 'will_paginate' config.gem 'fastercsv' config.gem 'paperclip' config.after_initialize do load File.expand_path(File.join(File.dirname(__FILE__),'../lib','ccls_engine.rb')) end end
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize! removing environment so as to not accidentally check it in
# Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" config.gem "andand" config.gem "whenever", :lib => false, :source => 'http://gemcutter.org/' # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs config.load_paths += %W( #{RAILS_ROOT}/app/sweepers ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector # Environment variable part for Common Services begins here DB_STRING_MAX_LENGTH = 255 PURSE_LIMIT = -10 SERVER_DOMAIN = "http://localhost:3000" RESSI_URL = "http://localhost:9000" RESSI_TIMEOUT = 5 RESSI_UPLOAD_HOUR = 3 CAS_BASE_URL = "http://cos.alpha.sizl.org:8180/cas" #CAS_BASE_URL = "https://zeus.cs.hut.fi/cs/shib/cos" CAS_VALIDATE_URL = "https://zeus.cs.hut.fi/cs/shib/9997/proxyValidate" LOG_TO_RESSI = false #If following is true, created users must validate their emails before they can log in. VALIDATE_EMAILS = false REQUIRE_SSL_LOGIN = false end require 'render_extend' require 'filtered_pagination' require 'casclient' require 'casclient/frameworks/rails/filter' require 'casclient/frameworks/rails/cas_proxy_callback_controller' require 'whenever' require 'actionpack_extend' # enable detailed CAS logging for easier troubleshooting cas_logger = CASClient::Logger.new(RAILS_ROOT+'/log/cas.log') cas_logger.level = Logger::DEBUG CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => CAS_BASE_URL, :logger => cas_logger, :validate_url => "https://zeus.cs.hut.fi/cs/shib/9997/proxyValidate" #:proxy_retrieval_url => "https://kassi:3444/cas_proxy_callback/retrieve_pgt", #:proxy_callback_url => "https://kassi:3444/cas_proxy_callback/receive_pgt" ) # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. secret_file = File.join(RAILS_ROOT, "config/session_secret") if File.exist?(secret_file) secret = File.read(secret_file) else secret = ActiveSupport::SecureRandom.hex(64) File.open(secret_file, 'w') { |f| f.write(secret) } end config.action_controller.session = { :session_key => '_trunk_session', :secret => secret } Updated secret key generation script # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') #Generating secret key if it does not exist secret_file = File.join(RAILS_ROOT, "config/session_secret") if File.exist?(secret_file) secret = File.read(secret_file) else secret = ActiveSupport::SecureRandom.hex(64) File.open(secret_file, 'w') { |f| f.write(secret) } end Rails::Initializer.run do |config| # 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. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" config.gem "andand" config.gem "whenever", :lib => false, :source => 'http://gemcutter.org/' # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs config.load_paths += %W( #{RAILS_ROOT}/app/sweepers ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_trunk_session', :secret => secret } # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector # Environment variable part for Common Services begins here DB_STRING_MAX_LENGTH = 255 PURSE_LIMIT = -10 SERVER_DOMAIN = "http://localhost:3000" RESSI_URL = "http://localhost:9000" RESSI_TIMEOUT = 5 RESSI_UPLOAD_HOUR = 3 CAS_BASE_URL = "http://cos.alpha.sizl.org:8180/cas" #CAS_BASE_URL = "https://zeus.cs.hut.fi/cs/shib/cos" CAS_VALIDATE_URL = "https://zeus.cs.hut.fi/cs/shib/9997/proxyValidate" LOG_TO_RESSI = false #If following is true, created users must validate their emails before they can log in. VALIDATE_EMAILS = false REQUIRE_SSL_LOGIN = false end require 'render_extend' require 'filtered_pagination' require 'casclient' require 'casclient/frameworks/rails/filter' require 'casclient/frameworks/rails/cas_proxy_callback_controller' require 'whenever' require 'actionpack_extend' # enable detailed CAS logging for easier troubleshooting cas_logger = CASClient::Logger.new(RAILS_ROOT+'/log/cas.log') cas_logger.level = Logger::DEBUG CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => CAS_BASE_URL, :logger => cas_logger, :validate_url => "https://zeus.cs.hut.fi/cs/shib/9997/proxyValidate" #:proxy_retrieval_url => "https://kassi:3444/cas_proxy_callback/retrieve_pgt", #:proxy_callback_url => "https://kassi:3444/cas_proxy_callback/receive_pgt" )
# 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{automaze} s.version = "0.0.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Toshiyuki Hirooka"] s.date = %q{2010-10-31} s.description = %q{automaze is a maze generator library for ruby.} s.email = %q{toshi.hirooka@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ "LICENSE", "README.rdoc", "Rakefile", "VERSION", "automaze.gemspec", "lib/algorithms/boutaoshi.rb", "lib/algorithms/dug_tunnels.rb", "lib/automaze.rb", "lib/panel.rb", "sample.rb", "spec/automaze_spec.rb", "spec/panel_spec.rb" ] s.homepage = %q{http://github.com/tosik/automazerb} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{maze generator} s.test_files = [ "spec/automaze_spec.rb", "spec/panel_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_runtime_dependency(%q<activesupport>, [">= 3.0.1"]) else s.add_dependency(%q<activesupport>, [">= 3.0.1"]) end else s.add_dependency(%q<activesupport>, [">= 3.0.1"]) end end Regenerated gemspec for version 0.0.4 # 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{automaze} s.version = "0.0.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Toshiyuki Hirooka"] s.date = %q{2010-10-31} s.description = %q{automaze is a maze generator library for ruby.} s.email = %q{toshi.hirooka@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ "LICENSE", "README.rdoc", "Rakefile", "VERSION", "automaze.gemspec", "lib/algorithms/boutaoshi.rb", "lib/algorithms/dug_tunnels.rb", "lib/automaze.rb", "lib/panel.rb", "sample.rb", "spec/automaze_spec.rb", "spec/panel_spec.rb" ] s.homepage = %q{http://github.com/tosik/automazerb} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{maze generator} s.test_files = [ "spec/automaze_spec.rb", "spec/panel_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_runtime_dependency(%q<activesupport>, [">= 3.0.1"]) else s.add_dependency(%q<activesupport>, [">= 3.0.1"]) end else s.add_dependency(%q<activesupport>, [">= 3.0.1"]) end end
require 'mxx_ru/cpp' MxxRu::Cpp::composite_target( Mxx_ru::BUILD_ROOT ) { toolset.force_cpp0x_std global_include_path "." required_prj( "test/prj.rb" ) required_prj( "samples/prj.rb" ) } Fixed MxxRu project. require 'mxx_ru/cpp' MxxRu::Cpp::composite_target( Mxx_ru::BUILD_ROOT ) { toolset.force_cpp0x_std global_include_path "." required_prj( "tests/prj.rb" ) required_prj( "samples/prj.rb" ) }
#!/usr/bin/env ruby require "fileutils" require "optparse" require "ostruct" def log(*args) puts args end def trim_leading(string) p = string[/\A(\s*)/, 1] string.gsub(/^#{p}/, "") end module Tor module_function DIR_BASE = File.expand_path("..", __FILE__) DIR_CHROOT = "chroot" class AJoin < String def initialize(path) super(path) end def join(*paths) File.join(self, *paths) end end def chroot @@chroot ||= AJoin.new(File.join(DIR_BASE, DIR_CHROOT)) end end @opts, opts = OpenStruct.new, OptionParser.new do |op| op.banner = "usage: build.rb <option>" op.separator "" op.on("-h", "--help", "show this message") { @opts.help = true } op.on("-c", "--create", "create new jail") { @opts.create = true } op.on("-u", "--update", "update existing jail") { @opts.update = true } end opts.parse! ARGV if @opts.help || !(@opts.create || @opts.update) || (@opts.create && @opts.update) puts opts.banner, opts.summarize exit end if @opts.create log "Creating a new jail..." abort "#{Tor.chroot} exists" if File.exist?(Tor.chroot) FileUtils.mkdir_p Tor.chroot.join("dev") end if @opts.update log "Updating an existing jail..." abort "#{Tor.chroot} does not exist" unless File.exist?(Tor.chroot) end Dir.glob("test/*_test.rb").each do |file| output = %x(ruby #{file}) abort(output) unless $? == 0 end @copy_files = Dir.glob(%w( /etc/host.conf /etc/hosts /etc/localtime /etc/nsswitch.conf /etc/resolv.conf /lib/ld-linux.so.2 /lib/libnsl* /lib/libnss* /lib/libresolv* /usr/lib/libgcc_s.so.* /usr/lib/libnss*.so )) [%x(pacman -Qlq tor), %x(ldd /usr/bin/tor)].each do |files| @copy_files += files.split.reject do |file| File.directory?(file) || !File.exist?(file) end end @copy_files = @copy_files.uniq.sort if @opts.update @copy_files.reject! { |file| file =~ /\A\/(dev|etc|var)/ } end @copy_files.each do |file| FileUtils.mkdir_p Tor.chroot.join(File.dirname(file)) %x(cp -fp #{file} #{Tor.chroot.join(file)}) end if @opts.create %x(grep ^tor: /etc/passwd > #{ Tor.chroot.join 'etc/passwd' }) %x(grep ^tor: /etc/group > #{ Tor.chroot.join 'etc/group' }) %w(lib log run).each do |dir| FileUtils.mkdir_p Tor.chroot.join("var", dir, "tor") FileUtils.chmod 0700, Tor.chroot.join("var", dir, "tor") end open(Tor.chroot.join("etc/tor/torrc"), "w") do |torrc| torrc.write trim_leading <<-__EOF__ ClientOnly 1 DataDirectory /var/lib/tor Log notice stderr PidFile /var/run/tor/tor.pid RunAsDaemon 0 SafeSocks 1 User tor __EOF__ end puts trim_leading <<-__EOF__ Almost done. Perform the following commands as root to complete the installation: chown tor:tor #{ Tor.chroot.join "var", "{lib,log,run}", "tor" } mknod -m 644 #{ Tor.chroot.join "dev/random" } c 1 8 mknod -m 644 #{ Tor.chroot.join "dev/urandom" } c 1 9 mknod -m 666 #{ Tor.chroot.join "dev/null" } c 1 3 __EOF__ end if @opts.update log "Done." end use log #!/usr/bin/env ruby require "fileutils" require "optparse" require "ostruct" def log(*args) puts args end def trim_leading(string) p = string[/\A(\s*)/, 1] string.gsub(/^#{p}/, "") end module Tor module_function DIR_BASE = File.expand_path("..", __FILE__) DIR_CHROOT = "chroot" class AJoin < String def initialize(path) super(path) end def join(*paths) File.join(self, *paths) end end def chroot @@chroot ||= AJoin.new(File.join(DIR_BASE, DIR_CHROOT)) end end @opts, opts = OpenStruct.new, OptionParser.new do |op| op.banner = "usage: build.rb <option>" op.separator "" op.on("-h", "--help", "show this message") { @opts.help = true } op.on("-c", "--create", "create new jail") { @opts.create = true } op.on("-u", "--update", "update existing jail") { @opts.update = true } end opts.parse! ARGV if @opts.help || !(@opts.create || @opts.update) || (@opts.create && @opts.update) log opts.banner, opts.summarize exit end if @opts.create log "Creating a new jail..." abort "#{Tor.chroot} exists" if File.exist?(Tor.chroot) FileUtils.mkdir_p Tor.chroot.join("dev") end if @opts.update log "Updating an existing jail..." abort "#{Tor.chroot} does not exist" unless File.exist?(Tor.chroot) end Dir.glob("test/*_test.rb").each do |file| output = %x(ruby #{file}) abort(output) unless $? == 0 end @copy_files = Dir.glob(%w( /etc/host.conf /etc/hosts /etc/localtime /etc/nsswitch.conf /etc/resolv.conf /lib/ld-linux.so.2 /lib/libnsl* /lib/libnss* /lib/libresolv* /usr/lib/libgcc_s.so.* /usr/lib/libnss*.so )) [%x(pacman -Qlq tor), %x(ldd /usr/bin/tor)].each do |files| @copy_files += files.split.reject do |file| File.directory?(file) || !File.exist?(file) end end @copy_files = @copy_files.uniq.sort if @opts.update @copy_files.reject! { |file| file =~ /\A\/(dev|etc|var)/ } end @copy_files.each do |file| FileUtils.mkdir_p Tor.chroot.join(File.dirname(file)) %x(cp -fp #{file} #{Tor.chroot.join(file)}) end if @opts.create %x(grep ^tor: /etc/passwd > #{ Tor.chroot.join 'etc/passwd' }) %x(grep ^tor: /etc/group > #{ Tor.chroot.join 'etc/group' }) %w(lib log run).each do |dir| FileUtils.mkdir_p Tor.chroot.join("var", dir, "tor") FileUtils.chmod 0700, Tor.chroot.join("var", dir, "tor") end open(Tor.chroot.join("etc/tor/torrc"), "w") do |torrc| torrc.write trim_leading <<-__EOF__ ClientOnly 1 DataDirectory /var/lib/tor Log notice stderr PidFile /var/run/tor/tor.pid RunAsDaemon 0 SafeSocks 1 User tor __EOF__ end log trim_leading <<-__EOF__ Almost done. Perform the following commands as root to complete the installation: chown tor:tor #{ Tor.chroot.join "var", "{lib,log,run}", "tor" } mknod -m 644 #{ Tor.chroot.join "dev/random" } c 1 8 mknod -m 644 #{ Tor.chroot.join "dev/urandom" } c 1 9 mknod -m 666 #{ Tor.chroot.join "dev/null" } c 1 3 __EOF__ end if @opts.update log "Done." end
adding build.rb to make compile the jcom.test.sample~ compile using the global build script #!/usr/bin/env ruby -wKU # encoding: utf-8 glibdir = "." Dir.chdir glibdir glibdir = Dir.pwd projectNameParts = glibdir.split('/') projectName = projectNameParts.last; projectName.gsub!(/Jamoma/, "") ENV['JAMOMAPROJECT'] = projectName Dir.chdir "#{glibdir}/../Support" load "build.rb"
#!/usr/bin/env ruby -wKU glibdir = "." Dir.chdir glibdir glibdir = Dir.pwd Dir.chdir "#{glibdir}/supports" load "build.rb" if win32? else `cp -r "../../../Builds/MaxMSP/jcom.fxlib≈.mxo" "/Applications/Max5/Cycling '74/extensions/jcom.fxlib≈.mxo"` end removing jcom.fxlib≈ stuff #!/usr/bin/env ruby -wKU glibdir = "." Dir.chdir glibdir glibdir = Dir.pwd Dir.chdir "#{glibdir}/supports" load "build.rb"
require "formula" class Caffe < Formula homepage "http://caffe.berkeleyvision.org/" url "https://github.com/BVLC/caffe.git" version "1.0" def install system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/cmake" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/boost" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/snappy" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/leveldb" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/protobuf" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/gflags" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/glog" system "brew", "install", "--build-from-source", "--fresh", "-vd", "mitmul/caffe/opencv" system "sed", "-e", "\"/^PYTHON_INCLUDES/ s/\/usr\/include/~\/anaconda\/include/g\"", "-e", "\"/numpy/ s/\/usr\/local/~\/anaconda/g", "-e", "\"/CXX/ s/\/usr\/bin\/g++/\/usr\/bin\/clang++/g\"", "-e", "\"/CXXFLAGS/ s/#CXXFLAGS/CXXFLAGS/\"", "Makefile.config.example", "Makefile.config" system "make" system "make pycaffe" end end fix description for dependencies require "formula" class Caffe < Formula homepage "http://caffe.berkeleyvision.org/" url "https://github.com/BVLC/caffe.git" version "1.0" depends_on 'mitmul/caffe/cmake' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/boost' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/snappy' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/leveldb' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/protobuf' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/gflags' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/glog' => %w{build-from-source fresh vd} depends_on 'mitmul/caffe/opencv' => %w{build-from-source fresh vd} def install system "sed", "-e", "\"/^PYTHON_INCLUDES/ s/\/usr\/include/~\/anaconda\/include/g\"", "-e", "\"/numpy/ s/\/usr\/local/~\/anaconda/g", "-e", "\"/CXX/ s/\/usr\/bin\/g++/\/usr\/bin\/clang++/g\"", "-e", "\"/CXXFLAGS/ s/#CXXFLAGS/CXXFLAGS/\"", "Makefile.config.example", "Makefile.config" system "make" system "make pycaffe" end end
{ collection: collection.decorate.as_json, total_pages: collection.total_pages, current_page: collection.current_page }.to_json Update base index json view { collection: collection.decorate.as_json, total_pages: collection.total_pages, current_page: collection.current_page, total_entries: collection.total_count }.to_json
$:.unshift File.join(File.dirname(__FILE__), 'lib') require 'clockwork' require 'monytr/core' # Scheduler is only required in 'clockwork' context, so is included here # explicitly require 'monytr/core/scheduler' module Clockwork handler do |job, time| puts "Running #{job} at #{time}" end #every(5.minutes, 'checks.enqueue') { Monytr::Core::Scheduler.enqueue_checks } every(20.seconds, 'checks.enqueue') { Monytr::Core::Scheduler.enqueue_checks } end Checks should run every 5 minutes, not 20 seconds Oops. Comment out development mode thing. This should really be a config variable. $:.unshift File.join(File.dirname(__FILE__), 'lib') require 'clockwork' require 'monytr/core' # Scheduler is only required in 'clockwork' context, so is included here # explicitly require 'monytr/core/scheduler' module Clockwork handler do |job, time| puts "Running #{job} at #{time}" end every(5.minutes, 'checks.enqueue') { Monytr::Core::Scheduler.enqueue_checks } #every(20.seconds, 'checks.enqueue') { Monytr::Core::Scheduler.enqueue_checks } end
require 'rspec' require 'pry' require 'pp' require File.expand_path('../../../../pakyow-support/lib/pakyow-support', __FILE__) require File.expand_path('../../../../pakyow-core/lib/pakyow-core', __FILE__) require File.expand_path('../../../lib/pakyow-presenter', __FILE__) Dir[File.join(File.dirname(__FILE__), 'helpers', '*.rb')].each {|file| require file } Dir[File.join(File.dirname(__FILE__), 'mixins', '*.rb')].each {|file| require file } require_relative 'test_app' include ViewBindingHelpers def str_to_doc(str) if str.match(/<html.*>/) Nokogiri::HTML::Document.parse(str) else Nokogiri::HTML.fragment(str) end end def reset_index_contents file = 'spec/support/views/index.html' contents = File.read(file) File.open(file, 'w') { |file| file.write('index') } unless contents == 'index' end $views = {} $views[:many] = create_view_from_string(<<-D) <div class="contact" data-scope="contact"> <span data-prop="full_name">John Doe</span> <a data-prop="email">john@example.com</a> </div> <div class="contact" data-scope="contact"> <span data-prop="full_name">John Doe</span> <a data-prop="email">john@example.com</a> </div> <div class="contact" data-scope="contact"> <span data-prop="full_name">John Doe</span> <a data-prop="email">john@example.com</a> </div> D $views[:single] = create_view_from_string(<<-D) <div class="contact" data-scope="contact"> <span data-prop="full_name">John Doe</span> <a data-prop="email">john@example.com</a> </div> D $views[:unscoped] = create_view_from_string(<<-D) <span class="foo" data-prop="foo"></span> D Remove unneeded file
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "weari" s.version = "0.0.2" s.platform = Gem::Platform::RUBY s.authors = ["Erik Hetzner"] s.email = ["erik.hetzner@ucop.edu"] s.homepage = "" s.summary = %q{WEb ARchive Indexer} s.add_dependency "rsolr", ">=1.0.6" s.rubyforge_project = "weari" s.files = `hg locate "ruby/**"`.split("\n") s.test_files = `hg locate "ruby/**" --include '{spec,features}'`.split("\n") s.executables = `hg locate "ruby/**" --include bin`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end bump ruby gem version # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "weari" s.version = "0.0.3" s.platform = Gem::Platform::RUBY s.authors = ["Erik Hetzner"] s.email = ["erik.hetzner@ucop.edu"] s.homepage = "" s.summary = %q{WEb ARchive Indexer} s.add_dependency "rsolr", ">=1.0.6" s.rubyforge_project = "weari" s.files = `hg locate "ruby/**"`.split("\n") s.test_files = `hg locate "ruby/**" --include '{spec,features}'`.split("\n") s.executables = `hg locate "ruby/**" --include bin`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'paper_trail/version_number' Gem::Specification.new do |s| s.name = 'paper_trail' s.version = PaperTrail::VERSION s.summary = "Track changes to your models' data. Good for auditing or versioning." s.description = s.summary s.homepage = 'http://github.com/airblade/paper_trail' s.authors = ['Andy Stewart'] s.email = 'boss@airbladesoftware.com' 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'] s.add_dependency 'railties', '~> 3.0' s.add_dependency 'activerecord', '~> 3.0' s.add_development_dependency 'rake' s.add_development_dependency 'shoulda', '2.10.3' s.add_development_dependency 'sqlite3-ruby', '~> 1.2' s.add_development_dependency 'capybara', '~> 1.0.0' end sqlite3-ruby is now just sqlite3 $LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'paper_trail/version_number' Gem::Specification.new do |s| s.name = 'paper_trail' s.version = PaperTrail::VERSION s.summary = "Track changes to your models' data. Good for auditing or versioning." s.description = s.summary s.homepage = 'http://github.com/airblade/paper_trail' s.authors = ['Andy Stewart'] s.email = 'boss@airbladesoftware.com' 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'] s.add_dependency 'railties', '~> 3.0' s.add_dependency 'activerecord', '~> 3.0' s.add_development_dependency 'rake' s.add_development_dependency 'shoulda', '2.10.3' s.add_development_dependency 'sqlite3', '~> 1.2' s.add_development_dependency 'capybara', '~> 1.0.0' end
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'paper_trail/version_number' Gem::Specification.new do |s| s.name = 'paper_trail' s.version = PaperTrail::VERSION s.summary = "Track changes to your models' data. Good for auditing or versioning." s.description = s.summary s.homepage = 'http://github.com/airblade/paper_trail' s.authors = ['Andy Stewart'] s.email = 'boss@airbladesoftware.com' 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'] s.add_dependency 'railties', '~> 3.0' s.add_dependency 'activerecord', '~> 3.0' s.add_development_dependency 'rake' s.add_development_dependency 'shoulda', '~> 3.0.1' s.add_development_dependency 'sqlite3', '~> 1.2' s.add_development_dependency 'capybara', '~> 1.0.0' end Updated capybara gem to latest $LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'paper_trail/version_number' Gem::Specification.new do |s| s.name = 'paper_trail' s.version = PaperTrail::VERSION s.summary = "Track changes to your models' data. Good for auditing or versioning." s.description = s.summary s.homepage = 'http://github.com/airblade/paper_trail' s.authors = ['Andy Stewart'] s.email = 'boss@airbladesoftware.com' 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'] s.add_dependency 'railties', '~> 3.0' s.add_dependency 'activerecord', '~> 3.0' s.add_development_dependency 'rake' s.add_development_dependency 'shoulda', '~> 3.0.1' s.add_development_dependency 'sqlite3', '~> 1.2' s.add_development_dependency 'capybara', '~> 1.1.2' end
atom_feed do |feed| feed.title(Settings.name) feed.updated(@posts.first.published_at) if @posts.first @posts.each do |post| feed.entry(post) do |entry| entry.title(post.title) entry.published(post.published_at) entry.content(post.body, format: 'html') entry.author do |author| author.name(post.user.to_s) end end end end Sanitize post body in atom feed atom_feed do |feed| feed.title(Settings.name) feed.updated(@posts.first.published_at) if @posts.first @posts.each do |post| feed.entry(post) do |entry| entry.title(post.title) entry.published(post.published_at) entry.content(sanitize post.body, format: 'html') entry.author do |author| author.name(post.user.to_s) end end end end
class RcCustomView < UIView VIEW_WIDTH = 200 VIEW_HEIGHT = 44 LABEL_HEIGHT = 20 MARGIN_SIZE = 10 def self.view_width return VIEW_WIDTH end def self.view_height return VIEW_HEIGHT end def initWithTitle(title, image: image) initWithFrame([[0.0, 0.0], [VIEW_WIDTH, VIEW_HEIGHT]]) yCoord = (self.bounds.size.height - LABEL_HEIGHT) / 2 @titleLabel = UILabel.alloc.initWithFrame([[MARGIN_SIZE + image.size.width + MARGIN_SIZE, yCoord], [CGRectGetWidth(self.frame) - MARGIN_SIZE + image.size.width + MARGIN_SIZE, LABEL_HEIGHT]]) @titleLabel.text = title @titleLabel.backgroundColor = UIColor.clearColor self.addSubview @titleLabel yCoord = (self.bounds.size.height - image.size.height) / 2 imageView = UIImageView.alloc.initWithFrame([[MARGIN_SIZE, yCoord], [image.size.width, image.size.height]]) imageView.image = image self.addSubview imageView self end # Enable accessibility for this view. def isAccessibilityElement return true end # Return a string that describes this view. def accessibilityLabel return @titleLabel.text end end renamed variables to match snake_case convention class RcCustomView < UIView VIEW_WIDTH = 200 VIEW_HEIGHT = 44 LABEL_HEIGHT = 20 MARGIN_SIZE = 10 def self.view_width return VIEW_WIDTH end def self.view_height return VIEW_HEIGHT end def initWithTitle(title, image: image) initWithFrame([[0.0, 0.0], [VIEW_WIDTH, VIEW_HEIGHT]]) y_coord = (self.bounds.size.height - LABEL_HEIGHT) / 2 @title_label = UILabel.alloc.initWithFrame([[MARGIN_SIZE + image.size.width + MARGIN_SIZE, y_coord], [CGRectGetWidth(self.frame) - MARGIN_SIZE + image.size.width + MARGIN_SIZE, LABEL_HEIGHT]]) @title_label.text = title @title_label.backgroundColor = UIColor.clearColor self.addSubview @title_label y_coord = (self.bounds.size.height - image.size.height) / 2 image_view = UIImageView.alloc.initWithFrame([[MARGIN_SIZE, y_coord], [image.size.width, image.size.height]]) image_view.image = image self.addSubview image_view self end # Enable accessibility for this view. def isAccessibilityElement return true end # Return a string that describes this view. def accessibilityLabel return @title_label.text end end
class RoundCorneredButton < UIButton def setHighlighted(highlighted) if highlighted self.layer.borderColor = UIColor.lightGrayColor.CGColor else if self.isEnabled self.layer.borderColor = UIColor.blueColor.CGColor else self.layer.borderColor = UIColor.darkGrayColor.CGColor end end end end def RoundCorneredButton.systemButton button = RoundCorneredButton.buttonWithType(UIButtonTypeSystem) button.layer.cornerRadius = 15 button.layer.borderWidth = 2 button.layer.borderColor = UIColor.blueColor.CGColor button end Make enabled corners smarter class RoundCorneredButton < UIButton def setHighlighted(highlighted) if highlighted self.layer.borderColor = UIColor.lightGrayColor.CGColor else if self.isEnabled self.layer.borderColor = UIColor.blueColor.CGColor else self.layer.borderColor = UIColor.darkGrayColor.CGColor end end end def drawRect(rect) if self.isEnabled self.layer.borderColor = UIColor.blueColor.CGColor else self.layer.borderColor = UIColor.darkGrayColor.CGColor end super end end def RoundCorneredButton.systemButton button = RoundCorneredButton.buttonWithType(UIButtonTypeSystem) button.layer.cornerRadius = 15 button.layer.borderWidth = 2 button.layer.borderColor = UIColor.blueColor.CGColor button end
# Samuel Vasko 2013 # Cmder build script # Like really a beta # # This script downloads dependencies form google code. Each software is extracted # in a folder with same name as the project on google code. So Conemu becomes # conemu-maximus5. Correct files are beeing picked by using labels. # I will move the script for getting files by labels from php to here as soon I feel like it require 'fileutils' require 'open-uri' require 'uri' def get_file project, query urlToFile = URI.escape('http://samuelvasko.tk/gcode/?project='+project+'&query='+query) open(urlToFile) do |resp| urlToFile = URI.escape(resp.read.split(/\r?\n/).first) end extension = urlToFile.split('.').last filename = project+'.'+extension puts "\n ------ Downloading #{project} from #{urlToFile} ------- \n \n" begin open(urlToFile, 'rb') do |infile| open(filename, 'wb') do |outfile| outfile.write(infile.read) end end rescue IOError => error puts error FileUtils.rm(filename) if File.exists?(filename) exit(1) end system("7z x -o\"#{project}\" #{filename}") File.unlink(project+"."+extension); # When the folder contains another folder # that is not what we want if Dir.glob("#{project}/*").length == 1 temp_name = "#{project}_temp" FileUtils.mv(project, temp_name) FileUtils.mv(Dir.glob("#{temp_name}/*")[0], project) FileUtils.rm_r(temp_name) end end def find_on_path exe path = ENV['PATH'].split(File::PATH_SEPARATOR) for dir in path if File.exists?(File.join(dir, exe)) return true end end return false end puts ' ______ _ _ _ _ _ | ___ \ (_) | | (_) | | | |_/ /_ _ _| | __| |_ _ __ __ _ ___ _ __ ___ __| | ___ _ __ | ___ \ | | | | |/ _` | | \'_ \ / _` | / __| \'_ ` _ \ / _` |/ _ \ \'__| | |_/ / |_| | | | (_| | | | | | (_| | | (__| | | | | | (_| | __/ | \____/ \__,_|_|_|\__,_|_|_| |_|\__, | \___|_| |_| |_|\__,_|\___|_| __/ | |___/ ' unless find_on_path('7z.exe') puts '7z.exe not found. Ensure 7-zip is installed and on the PATH.' exit(1) end build_exe = true unless find_on_path('msbuild.exe') puts 'msbuild.exe not found. We need that to build the executable.' puts 'Do you want to continue? [Y/n]' build_exe = false exit(1) unless gets.chomp.downcase == 'y' end puts 'Cleanup' if Dir.exists?('vendor') Dir.glob('vendor/*') { |file| FileUtils.rm_rf(file) if File.directory?(file) } end Dir.chdir('vendor') puts 'Getting files' get_file('clink', 'label:Type-Archive label:Featured') get_file('conemu-maximus5', 'label:Type-Archive label:Preview label:Featured') get_file('msysgit', 'label:Type-Archive label:Featured') puts 'Creating executable' if build_exe Dir.chdir('../launcher') status = system('msbuild /p:Configuration=Release') unless status puts 'Looks like the build failied' exit(1) end end puts 'Done, bye' Initial git cleanup creation # Samuel Vasko 2013 # Cmder build script # Like really a beta # # This script downloads dependencies form google code. Each software is extracted # in a folder with same name as the project on google code. So Conemu becomes # conemu-maximus5. Correct files are beeing picked by using labels. # I will move the script for getting files by labels from php to here as soon I feel like it require 'fileutils' require 'open-uri' require 'uri' def get_file project, query urlToFile = URI.escape('http://samuelvasko.tk/gcode/?project='+project+'&query='+query) open(urlToFile) do |resp| urlToFile = URI.escape(resp.read.split(/\r?\n/).first) end extension = urlToFile.split('.').last filename = project+'.'+extension puts "\n ------ Downloading #{project} from #{urlToFile} ------- \n \n" begin open(urlToFile, 'rb') do |infile| open(filename, 'wb') do |outfile| outfile.write(infile.read) end end rescue IOError => error puts error FileUtils.rm(filename) if File.exists?(filename) exit(1) end system("7z x -o\"#{project}\" #{filename}") File.unlink(project+"."+extension); # When the folder contains another folder # that is not what we want if Dir.glob("#{project}/*").length == 1 temp_name = "#{project}_temp" FileUtils.mv(project, temp_name) FileUtils.mv(Dir.glob("#{temp_name}/*")[0], project) FileUtils.rm_r(temp_name) end end def find_on_path exe path = ENV['PATH'].split(File::PATH_SEPARATOR) for dir in path if File.exists?(File.join(dir, exe)) return true end end return false end def git_cleanup gexe if gexe.gsub(/.*?(?=git), "").contains("-") # recreate file to bat # put @ECHO OFF/n # git stuff end end puts ' ______ _ _ _ _ _ | ___ \ (_) | | (_) | | | |_/ /_ _ _| | __| |_ _ __ __ _ ___ _ __ ___ __| | ___ _ __ | ___ \ | | | | |/ _` | | \'_ \ / _` | / __| \'_ ` _ \ / _` |/ _ \ \'__| | |_/ / |_| | | | (_| | | | | | (_| | | (__| | | | | | (_| | __/ | \____/ \__,_|_|_|\__,_|_|_| |_|\__, | \___|_| |_| |_|\__,_|\___|_| __/ | |___/ ' unless find_on_path('7z.exe') puts '7z.exe not found. Ensure 7-zip is installed and on the PATH.' exit(1) end build_exe = true unless find_on_path('msbuild.exe') puts 'msbuild.exe not found. We need that to build the executable.' puts 'Do you want to continue? [Y/n]' build_exe = false exit(1) unless gets.chomp.downcase == 'y' end puts 'Cleanup' if Dir.exists?('vendor') Dir.glob('vendor/*') { |file| FileUtils.rm_rf(file) if File.directory?(file) } end Dir.chdir('vendor') puts 'Getting files' get_file('clink', 'label:Type-Archive label:Featured') get_file('conemu-maximus5', 'label:Type-Archive label:Preview label:Featured') get_file('msysgit', 'label:Type-Archive label:Featured') puts 'Creating executable' if build_exe Dir.chdir('../launcher') status = system('msbuild /p:Configuration=Release') unless status puts 'Looks like the build failied' exit(1) end end puts 'Done, bye'
#!/usr/bin/env ruby # Copyright (c) 2013 Matt Hodges (http://matthodges.com) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'rubygems' require 'date' require 'active_support/all' class Post def initialize(title, slug, filename, publish_date) @title = title @slug = slug @filename = filename @publish_date = publish_date end end class BlogBuilder class << self attr_reader :posts, :json_string def set_post_metadata @posts = [] Dir.foreach('./content/posts/') do |item| next if item == '.' or item == '..' title = File.open("./content/posts/#{item}", &:readline) title = title.gsub("\n", "") title[0] = '' slug = item[0...-3] publish_date = `git log --format='format:%ci' --diff-filter=A ./content/posts/"#{item}"` @posts.push(Post.new(title, slug, item, publish_date)) end end def jsonify_posts posts = @posts.sort_by { |post| DateTime.parse(post.instance_variable_get(:@publish_date)) } @json_string = posts.reverse.to_json end def create_posts_from_json File.open('./content/posts.json', 'w') { |f| f.write(json_string) } end def commit `git add .` puts `git commit -m "Empress built - #{Time.now}"` end def build! set_post_metadata jsonify_posts create_posts_from_json commit end end end BlogBuilder.build! remove trailing / leading white space from title #!/usr/bin/env ruby # Copyright (c) 2013 Matt Hodges (http://matthodges.com) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'rubygems' require 'date' require 'active_support/all' class Post def initialize(title, slug, filename, publish_date) @title = title @slug = slug @filename = filename @publish_date = publish_date end end class BlogBuilder class << self attr_reader :posts, :json_string def set_post_metadata @posts = [] Dir.foreach('./content/posts/') do |item| next if item == '.' or item == '..' title = File.open("./content/posts/#{item}", &:readline) title = title.gsub("\n", "") title[0] = '' title = title.strip slug = item[0...-3] publish_date = `git log --format='format:%ci' --diff-filter=A ./content/posts/"#{item}"` @posts.push(Post.new(title, slug, item, publish_date)) end end def jsonify_posts posts = @posts.sort_by { |post| DateTime.parse(post.instance_variable_get(:@publish_date)) } @json_string = posts.reverse.to_json end def create_posts_from_json File.open('./content/posts.json', 'w') { |f| f.write(json_string) } end def commit `git add .` puts `git commit -m "Empress built - #{Time.now}"` end def build! set_post_metadata jsonify_posts create_posts_from_json commit end end end BlogBuilder.build!
#!/usr/bin/ruby # # -couch <type> couchdb1.6, couchdb2.0, cloudantSAAS, cloudantlocal - default is couchdb1.6 # -platform <platfrom> java | android default is Java # -D* gets passed into build. # # params = { :d_options => Array.new } arg_is_value = false prev_arg = nil ARGV.each do |arg| if arg.start_with?("-D") params[:d_options].push(arg) next end #process arguments into a hash unless arg_is_value params[arg[1,arg.length] ] = nil $prev_arg = arg[1,arg.length] arg_is_value = true else params[$prev_arg] = arg arg_is_value = false end end #apply defaults params["platform"] = "java" unless params["platform"] params["couch"] = "couchdb1.6" unless params["couch"] #kill any docker container that may be running on the machine. #we don't want to effected by another failing build system("docker rm --force couchdb") #launch docker puts "Starting docker container #{$couch}" #cloudant local current runs in a Vagrant box, rather than docker, this box is *always* running on cloudantsync001 #so we skip the docker set up commands and change the options to enable connection to cloudant local if params["couch"] == "cloudantlocal" #remove options that will clash with cloudant local options_to_remove = Array.new params[:d_options].each do |d_option| if d_option.start_with?("-Dtest.couch.username") || d_option.start_with?("-Dtest.couch.password") || d_option.start_with?("-Dtest.couch.host") || d_option.start_with?("-Dtest.couch.port") options_to_remove.push d_option end end options_to_remove.each do |option| params[:d_options].delete option end #add some -d opts to point tests at local instead params[:d_options].push "-Dtest.couch.username=admin" params[:d_options].push "-Dtest.couch.password=pass" params[:d_options].push "-Dtest.couch.host=127.0.0.1" params[:d_options].push "-Dtest.couch.port=8081" #jenkins runs on 8080 this needs to be 8081 params[:d_options].push "-Dtest.couch.ignore.auth.headers=true" params[:d_options].push "-Dtest.couch.ignore.compaction=true" else docker_port = 5984 #special case for couchdb2.0 it runs on port 15984 in the docker container rather than 5984 docker_port = 15984 if params["couch"] == "couchdb2.0" unless system("docker run -p 5984:#{docker_port} -d -h db1.dockertest --name 'couchdb' #{params["couch"]}") #we need to stop, we failed to run the docker container, just in case we will delete system("docker rm --force couchdb") exit 1 end end puts "Performing build" #make gradlew executable system("chmod a+x ./gradlew ") #exit #handle the differences in the platform if params["platform"] == "java" system("./gradlew #{params[:d_options].join(" ")} clean check integrationTest") elsif params["platform"] == "android" system("./gradlew -b AndroidTest/build.gradle #{params[:d_options].join(" ")} clean uploadFixtures connectedCheck") end #get the build exit code, will exit with this after tearing down the docker container exitcode = $? unless params["couch"] == "cloudantlocal" puts "Tearing down docker container" system("docker stop couchdb") system("docker rm couchdb") end exit exitcode.to_i Correct CloudantLocal Parameters Correct parameters passed to the android test suite for cloudant local. #!/usr/bin/ruby # # -couch <type> couchdb1.6, couchdb2.0, cloudantSAAS, cloudantlocal - default is couchdb1.6 # -platform <platfrom> java | android default is Java # -D* gets passed into build. # # params = { :d_options => Array.new } arg_is_value = false prev_arg = nil ARGV.each do |arg| if arg.start_with?("-D") params[:d_options].push(arg) next end #process arguments into a hash unless arg_is_value params[arg[1,arg.length] ] = nil $prev_arg = arg[1,arg.length] arg_is_value = true else params[$prev_arg] = arg arg_is_value = false end end #apply defaults params["platform"] = "java" unless params["platform"] params["couch"] = "couchdb1.6" unless params["couch"] #kill any docker container that may be running on the machine. #we don't want to effected by another failing build system("docker rm --force couchdb") #launch docker puts "Starting docker container #{$couch}" #cloudant local current runs in a Vagrant box, rather than docker, this box is *always* running on cloudantsync001 #so we skip the docker set up commands and change the options to enable connection to cloudant local if params["couch"] == "cloudantlocal" #remove options that will clash with cloudant local options_to_remove = Array.new params[:d_options].each do |d_option| if d_option.start_with?("-Dtest.couch.username") || d_option.start_with?("-Dtest.couch.password") || d_option.start_with?("-Dtest.couch.host") || d_option.start_with?("-Dtest.couch.port") options_to_remove.push d_option end end options_to_remove.each do |option| params[:d_options].delete option end #add some -d opts to point tests at local instead params[:d_options].push "-Dtest.couch.username=admin" params[:d_options].push "-Dtest.couch.password=pass" #cloudant local needs a different port on Android to Java #android needs to use a special address which maps to #local loopback interface for the machine it is running on if params["platform"] == "java" params[:d_options].push "-Dtest.couch.host=127.0.0.1" else params[:d_options].push "-Dtest.couch.host=10.0.2.2" end params[:d_options].push "-Dtest.couch.port=8081" #jenkins runs on 8080 this needs to be 8081 params[:d_options].push "-Dtest.couch.ignore.auth.headers=true" params[:d_options].push "-Dtest.couch.ignore.compaction=true" else docker_port = 5984 #special case for couchdb2.0 it runs on port 15984 in the docker container rather than 5984 docker_port = 15984 if params["couch"] == "couchdb2.0" unless system("docker run -p 5984:#{docker_port} -d -h db1.dockertest --name 'couchdb' #{params["couch"]}") #we need to stop, we failed to run the docker container, just in case we will delete system("docker rm --force couchdb") exit 1 end end puts "Performing build" #make gradlew executable system("chmod a+x ./gradlew ") #exit #handle the differences in the platform if params["platform"] == "java" system("./gradlew #{params[:d_options].join(" ")} clean check integrationTest") elsif params["platform"] == "android" system("./gradlew -b AndroidTest/build.gradle #{params[:d_options].join(" ")} clean uploadFixtures connectedCheck") end #get the build exit code, will exit with this after tearing down the docker container exitcode = $? unless params["couch"] == "cloudantlocal" puts "Tearing down docker container" system("docker stop couchdb") system("docker rm couchdb") end exit exitcode.to_i
#!/bin/ruby require 'find' require 'json' require 'octokit' require 'fileutils' require 'erb' require 'yaml' require 'digest' $public_html = "public_html" $markdown_src = "src/markdown" $template_src = "src/templates" $cache_file = "cache/pages.yaml" ## Page class stores data for each markdown file. class Page attr_reader :title, :source, :target, :content, :date, :section @@instance_collector = [] ## Initialize the class def initialize(in_file) @source = in_file @title = source2title in_file @tags = source2tags in_file @section = source2section in_file @content = md2html in_file @date = source2date in_file, @section @target = source2target in_file, @section @@instance_collector << self end def source2title(in_file) title = File.basename in_file title = title.sub /.md$/, '' # Remove the extension title = title.sub /#.*/, '' # Remove the tags title.gsub /_/, ' ' # Convert underscore to spaces end def source2tags(in_file) tags = File.basename in_file tags = tags.sub /.md$/, '' # Remove the extension tags = tags.split '#' # Separate the tags tags.drop 1 # Drop the title end def source2target(in_file, section) out_file = File.basename(in_file).sub /.md$/, ".html" "#{$public_html}/#{section}/#{out_file}" end def source2section(in_file) section = File.dirname(in_file).sub /^#{$markdown_src}/, '' section.split('/')[1] end def source2date(in_file, section) if section and File.dirname(in_file) != "#{$markdown_src}/#{section}" date = File.dirname(in_file).sub /^#{$markdown_src}\/#{section}\//, '' date = date.split('/') Time.new date[0], date[1], date[2] else File.mtime in_file end end def md2html(in_file) ## Only regenerate if what is in cache doesn't match md5_in = Digest::MD5.hexdigest File.read(in_file) if $cache[in_file] != nil md5_cache = $cache[in_file]["md5sum"] return $cache[in_file]["content"] if md5_in == md5_cache end ## If there is an access token in the environment, we can use that to auth token = ENV['TOKEN'] if token != nil client = Octokit::Client.new :access_token => token content = client.markdown File.read(in_file), :mode => "gfm" else content = Octokit.markdown File.read(in_file), :mode => "gfm" end ## Update the cache $cache[in_file] = { "md5sum" => md5_in, "content" => content } ## We are done return content end def refresh_content @content = md2html @source end ## Check if this page is an index def is_index? @source =~ /\/index.md$/ end ## Return a link to the page. def link if @title == "index" File.dirname(@target).sub(/^#{$public_html}/, '') + "/" else @target.sub /^#{$public_html}/, '' end end def to_s @title end ## Write the full html page def render b = binding ## Load the templates pre_template = ERB.new(File.read("#{$template_src}/pre.html.erb"), 0, '-') main_template = ERB.new(File.read("#{$template_src}/main.html.erb"), 0, '-') post_template = ERB.new(File.read("#{$template_src}/post.html.erb"), 0, '-') ## Generate the html page pre = pre_template.result b post = post_template.result b main = main_template.result b File.open(@target, "w") { |f| f.write pre + main + post } end ## Return array of each page def self.all_pages @@instance_collector end ## Return all sections as array def self.all_sections sections = {} @@instance_collector.each do |page| sections[page.section] = true end array = [] sections.each_key { |k| array << k if k } array end ## Return all the pages that are part of a section def self.section(section) p = [] @@instance_collector.each do |x| next if x.is_index? p << x if x.section == section end return p end ## Find the page with the matching title def self.with_title(title) @@instance_collector.each do |x| return x if x.title == title end return nil end end def render_site ## Clear the existing public_html directory FileUtils::rm_rf $public_html FileUtils::mkdir_p $public_html ## Symlink the needful FileUtils::symlink "../assets", $public_html FileUtils::symlink "../bower_components", $public_html ## Load/initialize the cache if File.exists? $cache_file $cache = YAML::load_file $cache_file else FileUtils::mkdir_p File.dirname($cache_file) $cache = {} end ## Load the data for the pages Find.find("src/markdown") do |in_file| ## Only operate on files next unless File.file? in_file ## Only operate on markdown next unless in_file =~ /.md$/ Page.new in_file end ## Make the sub directories Find.find($markdown_src) do |src_dir| ## We only care about directories next unless File.directory? src_dir # Convert the path name target_dir = src_dir.sub /^#{$markdown_src}/, $public_html # Create the directory FileUtils::mkdir_p target_dir end ## Generare each page Page.all_pages.each { |page| page.render } ## Save the cache file File.open($cache_file, "w") { |f| f.write YAML::dump($cache) } end render_site Fixed links in navbar #!/bin/ruby require 'find' require 'json' require 'octokit' require 'fileutils' require 'erb' require 'yaml' require 'digest' $public_html = "public_html" $markdown_src = "src/markdown" $template_src = "src/templates" $cache_file = "cache/pages.yaml" ## Page class stores data for each markdown file. class Page attr_reader :title, :source, :target, :content, :date, :section @@instance_collector = [] ## Initialize the class def initialize(in_file) @source = in_file @title = source2title in_file @tags = source2tags in_file @section = source2section in_file @content = md2html in_file @date = source2date in_file, @section @target = source2target in_file, @section @@instance_collector << self end def source2title(in_file) title = File.basename in_file title = title.sub /.md$/, '' # Remove the extension title = title.sub /#.*/, '' # Remove the tags title.gsub /_/, ' ' # Convert underscore to spaces end def source2tags(in_file) tags = File.basename in_file tags = tags.sub /.md$/, '' # Remove the extension tags = tags.split '#' # Separate the tags tags.drop 1 # Drop the title end def source2target(in_file, section) out_file = File.basename(in_file).sub /.md$/, ".html" if section != nil "#{$public_html}/#{section}/#{out_file}" else "#{$public_html}/#{out_file}" end end def source2section(in_file) section = File.dirname(in_file).sub /^#{$markdown_src}/, '' section.split('/')[1] end def source2date(in_file, section) if section and File.dirname(in_file) != "#{$markdown_src}/#{section}" date = File.dirname(in_file).sub /^#{$markdown_src}\/#{section}\//, '' date = date.split('/') Time.new date[0], date[1], date[2] else File.mtime in_file end end def md2html(in_file) ## Only regenerate if what is in cache doesn't match md5_in = Digest::MD5.hexdigest File.read(in_file) if $cache[in_file] != nil md5_cache = $cache[in_file]["md5sum"] return $cache[in_file]["content"] if md5_in == md5_cache end ## If there is an access token in the environment, we can use that to auth token = ENV['TOKEN'] if token != nil client = Octokit::Client.new :access_token => token content = client.markdown File.read(in_file), :mode => "gfm" else content = Octokit.markdown File.read(in_file), :mode => "gfm" end ## Update the cache $cache[in_file] = { "md5sum" => md5_in, "content" => content } ## We are done return content end def refresh_content @content = md2html @source end ## Check if this page is an index def is_index? @source =~ /\/index.md$/ end ## Return a link to the page. def link if @title == "index" File.dirname(@target).sub(/^#{$public_html}/, '') + "/" else @target.sub /^#{$public_html}/, '' end end def to_s @title end ## Write the full html page def render b = binding ## Load the templates pre_template = ERB.new(File.read("#{$template_src}/pre.html.erb"), 0, '-') main_template = ERB.new(File.read("#{$template_src}/main.html.erb"), 0, '-') post_template = ERB.new(File.read("#{$template_src}/post.html.erb"), 0, '-') ## Generate the html page pre = pre_template.result b post = post_template.result b main = main_template.result b File.open(@target, "w") { |f| f.write pre + main + post } end ## Return array of each page def self.all_pages @@instance_collector end ## Return all sections as array def self.all_sections sections = {} @@instance_collector.each do |page| sections[page.section] = true end array = [] sections.each_key { |k| array << k if k } array end ## Return all the pages that are part of a section def self.section(section) p = [] @@instance_collector.each do |x| next if x.is_index? p << x if x.section == section end return p end ## Find the page with the matching title def self.with_title(title) @@instance_collector.each do |x| return x if x.title == title end return nil end end def render_site ## Clear the existing public_html directory FileUtils::rm_rf $public_html FileUtils::mkdir_p $public_html ## Symlink the needful FileUtils::symlink "../assets", $public_html FileUtils::symlink "../bower_components", $public_html ## Load/initialize the cache if File.exists? $cache_file $cache = YAML::load_file $cache_file else FileUtils::mkdir_p File.dirname($cache_file) $cache = {} end ## Load the data for the pages Find.find("src/markdown") do |in_file| ## Only operate on files next unless File.file? in_file ## Only operate on markdown next unless in_file =~ /.md$/ Page.new in_file end ## Make the sub directories Find.find($markdown_src) do |src_dir| ## We only care about directories next unless File.directory? src_dir # Convert the path name target_dir = src_dir.sub /^#{$markdown_src}/, $public_html # Create the directory FileUtils::mkdir_p target_dir end ## Generare each page Page.all_pages.each { |page| page.render } ## Save the cache file File.open($cache_file, "w") { |f| f.write YAML::dump($cache) } end render_site
# encoding: utf-8 class RecoverTaskWorker include Sidekiq::Worker # only try 2x to recover, which should be enough. sidekiq_options :retry => 2 def perform(task_id) ActiveRecord::Base.connection_pool.with_connection do task = Task.find_by_id(task_id) begin task.recover! if task rescue StateMachine::InvalidTransition => err logger.warn "RecoverTaskWorker: StateMachine::InvalidTransition: task: #{task_id}, err: #{err.message}" end true end end end call task.owner.check_tasks so that recovery followed by new task(s) if necessary # encoding: utf-8 class RecoverTaskWorker include Sidekiq::Worker # only try 2x to recover, which should be enough. sidekiq_options :retry => 2 def perform(task_id) ActiveRecord::Base.connection_pool.with_connection do task = Task.find_by_id(task_id) begin if task task.recover! task.owner.check_tasks end rescue StateMachine::InvalidTransition => err logger.warn "RecoverTaskWorker: StateMachine::InvalidTransition: task: #{task_id}, err: #{err.message}" end true end end end
module DivisionsHelper # Rather than using url_for which would be the sensible thing, we're constructing the paths # by hand to match the order in the php app def divisions_path(q = {}) p = "" p += "&rdisplay=#{q[:rdisplay]}" if q[:rdisplay] p += "&rdisplay2=#{q[:rdisplay2]}" if q[:rdisplay2] p += "&house=#{q[:house]}" if q[:house] p += "&sort=#{q[:sort]}" if q[:sort] r = "/divisions.php" r += "?" + p[1..-1] if p != "" r end def division_path(q, display_active_policy = true, member = false) p = "" p += "&date=#{q[:date]}" if q[:date] p += "&number=#{q[:number]}" if q[:number] p += "&mpn=#{member.url_name}" if member p += "&mpc=#{member.electorate}" if member p += "&dmp=#{q[:dmp]}" if q[:dmp] && !(display_active_policy && user_signed_in?) p += "&house=#{q[:house]}" if q[:house] p += "&display=#{q[:display]}" if q[:display] p += "&sort=#{q[:sort]}" if q[:sort] p += "&dmp=#{q[:dmp] || current_user.active_policy_id}" if display_active_policy && user_signed_in? r = "division.php" r += "?" + p[1..-1] if p != "" r end def division_path2(q, display_active_policy = true, member = false) p = "" p += "&date=#{q[:date]}" if q[:date] p += "&number=#{q[:number]}" if q[:number] p += "&mpn=#{member.url_name}" if member p += "&mpc=#{member.electorate}" if member p += "&house=#{q[:house]}" if q[:house] p += "&display=#{q[:display]}" if q[:display] p += "&sort=#{q[:sort]}" if q[:sort] if q[:dmp] p += "&dmp=#{q[:dmp]}" elsif display_active_policy && user_signed_in? p += "&dmp=#{current_user.active_policy_id}" end r = "division.php" r += "?" + p[1..-1] if p != "" r end def sort_link_divisions(sort, sort_name, name, current_sort) if current_sort == sort content_tag(:b, name) else link_to name, divisions_path(params.merge(sort: sort)), alt: "Sort by #{sort_name}" end end def majority_vote_class(whip) if whip.majority_votes == 0 "normal" # Special case for free votes elsif whip.whip_guess_majority == "majority" || whip.free? "whip" else "rebel" end end def minority_vote_class(whip) if whip.minority_votes == 0 "normal" elsif whip.whip_guess_majority == "minority" || whip.free? "whip" else "rebel" end end def no_vote_total_class(division) division.no_votes >= division.aye_votes ? "whip" : "normal" end def aye_vote_total_class(division) division.aye_votes >= division.no_votes ? "whip" : "normal" end def majority_vote_total_class(division) if division.noes_in_majority? division.no_votes >= division.aye_votes ? "whip" : "normal" else division.aye_votes >= division.no_votes ? "whip" : "normal" end end def minority_vote_total_class(division) division.noes_in_majority? ? aye_vote_total_class(division) : no_vote_total_class(division) end def division_nav_link(display, name, title, current_display) if current_display == display content_tag(:li, name, class: "on") else params.delete(:house) if params[:house] == 'representatives' content_tag(:li, class: "off") do link_to name, division_path2(params.merge(display: display)), title: title, class: "off" end end end def vote_display_in_table(vote, aye_majority) display = if (aye_majority >= 0 && (vote == 'aye' || vote == 'aye3')) || (aye_majority <= 0 && (vote == 'no' || vote == 'no3')) 'Majority' elsif vote == 'absent' vote else content_tag(:i, 'minority') end vote == 'aye3' || vote == 'no3' ? "#{display} (strong)".html_safe : display end # TODO: Refactor this - it looks suspiciously like the above def simple_vote_display(vote) vote == 'aye3' || vote == 'no3' ? "#{vote[0...-1]} (strong)" : vote end # Accessing @member inside this helper. Eek! # TODO: Fix this! def member_voted_with(member, division) # We're using a different member for the link to try to make things the same as the php # TODO get rid of this silliness as soon as we can member2 = Member.where(person: @member.person).first sentence = link_to @member.full_name, member_path(member2) sentence += " " if @member.vote_on_division_without_tell(@division) == "absent" sentence += "did not vote." end if !division.action_text.empty? && division.action_text[@member.vote_on_division_without_tell(@division)] sentence += "voted ".html_safe + content_tag(:em, division.action_text[@member.vote_on_division_without_tell(@division)]) else # TODO Should be using whip for this calculation. Only doing it this way to match php # calculation # AND THIS IS WRONG FURTHER BECAUSE THE MAJORITY CALCULATION DOESN"T TAKE INTO ACCOUNT THE TELLS ayenodiff = (@division.votes.group(:vote).count["aye"] || 0) - (@division.votes.group(:vote).count["no"] || 0) if ayenodiff == 0 if @member.vote_on_division_with_tell(@division) == "tellaye" sentence += "was a Teller for the Ayes." elsif @member.vote_on_division_with_tell(@division) == "tellno" sentence += "was a Teller for the Noes." elsif @member.vote_on_division_with_tell(@division) != "absent" sentence += "voted #{@member.vote_on_division_with_tell(@division).capitalize}." end elsif @member.vote_on_division_without_tell(@division) == "aye" && ayenodiff >= 0 || @member.vote_on_division_without_tell(@division) == "no" && ayenodiff < 0 sentence += "voted ".html_safe + content_tag(:em, "with the majority") elsif @member.vote_on_division_without_tell(@division) != "absent" sentence += "voted ".html_safe + content_tag(:em, "in the minority") end if @member.vote_on_division_without_tell(@division) != "absent" && ayenodiff != 0 if @member.vote_on_division_with_tell(@division) == "tellaye" sentence += " (Teller for the Ayes)." elsif @member.vote_on_division_with_tell(@division) == "tellno" sentence += " (Teller for the Noes)." else sentence += " (#{@member.vote_on_division_with_tell(@division).capitalize})." end end sentence end end # Format according to Public Whip's unique-enough-to-be-annoying markup language. # It's *similar* to MediaWiki but not quite. It would be so nice to switch to Markdown. def formatted_motion_text(division) text = division.motion # Remove any preceeding spaces so wikiparser doesn't format with monospaced font text.gsub! /^ */, '' # Remove comment lines (those starting with '@') text = text.lines.reject { |l| l =~ /(^@.*)/ }.join # Italics text.gsub!(/''(.*?)''/) { "<em>#{$1}</em>" } # Parse as MediaWiki text = Marker.parse(text).to_html(nofootnotes: true) # Footnote links. The MediaWiki parser would mess these up so we do them after parsing text.gsub!(/(?<![<li>\s])(\[(\d+)\])/) { %(<sup class="sup-#{$2}"><a class="sup" href='#footnote-#{$2}' onclick="ClickSup(#{$2}); return false;">#{$1}</a></sup>) } # Footnotes text.gsub!(/<li>\[(\d+)\]/) { %(<li class="footnote" id="footnote-#{$1}">[#{$1}]) } text.html_safe end def relative_time(time) time < 1.month.ago ? formatted_date(time) : "#{time_ago_in_words(time)} ago" end end Hopefully finally fixed this pesky link module DivisionsHelper # Rather than using url_for which would be the sensible thing, we're constructing the paths # by hand to match the order in the php app def divisions_path(q = {}) p = "" p += "&rdisplay=#{q[:rdisplay]}" if q[:rdisplay] p += "&rdisplay2=#{q[:rdisplay2]}" if q[:rdisplay2] p += "&house=#{q[:house]}" if q[:house] p += "&sort=#{q[:sort]}" if q[:sort] r = "/divisions.php" r += "?" + p[1..-1] if p != "" r end def division_path(q, display_active_policy = true, member = false) p = "" p += "&date=#{q[:date]}" if q[:date] p += "&number=#{q[:number]}" if q[:number] p += "&mpn=#{member.url_name}" if member p += "&mpc=#{member.electorate}" if member p += "&dmp=#{q[:dmp]}" if q[:dmp] && !(display_active_policy && user_signed_in?) p += "&house=#{q[:house]}" if q[:house] p += "&display=#{q[:display]}" if q[:display] p += "&sort=#{q[:sort]}" if q[:sort] p += "&dmp=#{q[:dmp] || current_user.active_policy_id}" if display_active_policy && user_signed_in? r = "division.php" r += "?" + p[1..-1] if p != "" r end def division_path2(q, display_active_policy = true, member = false) p = "" p += "&date=#{q[:date]}" if q[:date] p += "&number=#{q[:number]}" if q[:number] p += "&mpn=#{member.url_name}" if member p += "&mpc=#{member.electorate}" if member p += "&house=#{q[:house]}" if q[:house] p += "&display=#{q[:display]}" if q[:display] p += "&sort=#{q[:sort]}" if q[:sort] if q[:dmp] p += "&dmp=#{q[:dmp]}" elsif display_active_policy && user_signed_in? p += "&dmp=#{current_user.active_policy_id}" end r = "division.php" r += "?" + p[1..-1] if p != "" r end def sort_link_divisions(sort, sort_name, name, current_sort) if current_sort == sort content_tag(:b, name) else link_to name, divisions_path(params.merge(sort: sort)), alt: "Sort by #{sort_name}" end end def majority_vote_class(whip) if whip.majority_votes == 0 "normal" # Special case for free votes elsif whip.whip_guess_majority == "majority" || whip.free? "whip" else "rebel" end end def minority_vote_class(whip) if whip.minority_votes == 0 "normal" elsif whip.whip_guess_majority == "minority" || whip.free? "whip" else "rebel" end end def no_vote_total_class(division) division.no_votes >= division.aye_votes ? "whip" : "normal" end def aye_vote_total_class(division) division.aye_votes >= division.no_votes ? "whip" : "normal" end def majority_vote_total_class(division) if division.noes_in_majority? division.no_votes >= division.aye_votes ? "whip" : "normal" else division.aye_votes >= division.no_votes ? "whip" : "normal" end end def minority_vote_total_class(division) division.noes_in_majority? ? aye_vote_total_class(division) : no_vote_total_class(division) end def division_nav_link(display, name, title, current_display) if current_display == display content_tag(:li, name, class: "on") else params.delete(:house) if params[:house] == 'representatives' content_tag(:li, class: "off") do link_to name, division_path2(params.merge(display: display)), title: title, class: "off" end end end def vote_display_in_table(vote, aye_majority) display = if (aye_majority >= 0 && (vote == 'aye' || vote == 'aye3')) || (aye_majority <= 0 && (vote == 'no' || vote == 'no3')) 'Majority' elsif vote == 'absent' vote else content_tag(:i, 'minority') end vote == 'aye3' || vote == 'no3' ? "#{display} (strong)".html_safe : display end # TODO: Refactor this - it looks suspiciously like the above def simple_vote_display(vote) vote == 'aye3' || vote == 'no3' ? "#{vote[0...-1]} (strong)" : vote end # Accessing @member inside this helper. Eek! # TODO: Fix this! def member_voted_with(member, division) # We're using a different member for the link to try to make things the same as the php # TODO get rid of this silliness as soon as we can member2 = Member.where(person: @member.person, house: division.house).first sentence = link_to @member.full_name, member_path(member2) sentence += " " if @member.vote_on_division_without_tell(@division) == "absent" sentence += "did not vote." end if !division.action_text.empty? && division.action_text[@member.vote_on_division_without_tell(@division)] sentence += "voted ".html_safe + content_tag(:em, division.action_text[@member.vote_on_division_without_tell(@division)]) else # TODO Should be using whip for this calculation. Only doing it this way to match php # calculation # AND THIS IS WRONG FURTHER BECAUSE THE MAJORITY CALCULATION DOESN"T TAKE INTO ACCOUNT THE TELLS ayenodiff = (@division.votes.group(:vote).count["aye"] || 0) - (@division.votes.group(:vote).count["no"] || 0) if ayenodiff == 0 if @member.vote_on_division_with_tell(@division) == "tellaye" sentence += "was a Teller for the Ayes." elsif @member.vote_on_division_with_tell(@division) == "tellno" sentence += "was a Teller for the Noes." elsif @member.vote_on_division_with_tell(@division) != "absent" sentence += "voted #{@member.vote_on_division_with_tell(@division).capitalize}." end elsif @member.vote_on_division_without_tell(@division) == "aye" && ayenodiff >= 0 || @member.vote_on_division_without_tell(@division) == "no" && ayenodiff < 0 sentence += "voted ".html_safe + content_tag(:em, "with the majority") elsif @member.vote_on_division_without_tell(@division) != "absent" sentence += "voted ".html_safe + content_tag(:em, "in the minority") end if @member.vote_on_division_without_tell(@division) != "absent" && ayenodiff != 0 if @member.vote_on_division_with_tell(@division) == "tellaye" sentence += " (Teller for the Ayes)." elsif @member.vote_on_division_with_tell(@division) == "tellno" sentence += " (Teller for the Noes)." else sentence += " (#{@member.vote_on_division_with_tell(@division).capitalize})." end end sentence end end # Format according to Public Whip's unique-enough-to-be-annoying markup language. # It's *similar* to MediaWiki but not quite. It would be so nice to switch to Markdown. def formatted_motion_text(division) text = division.motion # Remove any preceeding spaces so wikiparser doesn't format with monospaced font text.gsub! /^ */, '' # Remove comment lines (those starting with '@') text = text.lines.reject { |l| l =~ /(^@.*)/ }.join # Italics text.gsub!(/''(.*?)''/) { "<em>#{$1}</em>" } # Parse as MediaWiki text = Marker.parse(text).to_html(nofootnotes: true) # Footnote links. The MediaWiki parser would mess these up so we do them after parsing text.gsub!(/(?<![<li>\s])(\[(\d+)\])/) { %(<sup class="sup-#{$2}"><a class="sup" href='#footnote-#{$2}' onclick="ClickSup(#{$2}); return false;">#{$1}</a></sup>) } # Footnotes text.gsub!(/<li>\[(\d+)\]/) { %(<li class="footnote" id="footnote-#{$1}">[#{$1}]) } text.html_safe end def relative_time(time) time < 1.month.ago ? formatted_date(time) : "#{time_ago_in_words(time)} ago" end end
require 'rails/code_statistics_calculator' class CodeStatistics #:nodoc: TEST_TYPES = ['Controller tests', 'Helper tests', 'Model tests', 'Mailer tests', 'Job tests', 'Integration tests'] def initialize(*pairs) @pairs = pairs @statistics = calculate_statistics @total = calculate_total if pairs.length > 1 end def to_s print_header @pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) } print_splitter if @total print_line("Total", @total) print_splitter end print_code_test_stats end private def calculate_statistics Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}] end def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coffee|rake)$/) stats = CodeStatisticsCalculator.new Dir.foreach(directory) do |file_name| path = "#{directory}/#{file_name}" if File.directory?(path) && (/^\./ !~ file_name) stats.add(calculate_directory_statistics(path, pattern)) elsif file_name =~ pattern stats.add_by_file_path(path) end end stats end def calculate_total @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, total| total.add(pair.last) end end def calculate_code code_loc = 0 @statistics.each { |k, v| code_loc += v.code_lines unless TEST_TYPES.include? k } code_loc end def calculate_tests test_loc = 0 @statistics.each { |k, v| test_loc += v.code_lines if TEST_TYPES.include? k } test_loc end def print_header print_splitter puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |" print_splitter end def print_splitter puts "+----------------------+--------+--------+---------+---------+-----+-------+" end def print_line(name, statistics) m_over_c = (statistics.methods / statistics.classes) rescue m_over_c = 0 loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0 puts "| #{name.ljust(20)} " \ "| #{statistics.lines.to_s.rjust(6)} " \ "| #{statistics.code_lines.to_s.rjust(6)} " \ "| #{statistics.classes.to_s.rjust(7)} " \ "| #{statistics.methods.to_s.rjust(7)} " \ "| #{m_over_c.to_s.rjust(3)} " \ "| #{loc_over_m.to_s.rjust(5)} |" end def print_code_test_stats code = calculate_code tests = calculate_tests puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f/code)}" puts "" end end Revert "Lines of code can be 100,000+ in a Rails app" This reverts commit 293bd95c3e77275193130bc14c986348aae8b0e2. This broke the header :< require 'rails/code_statistics_calculator' class CodeStatistics #:nodoc: TEST_TYPES = ['Controller tests', 'Helper tests', 'Model tests', 'Mailer tests', 'Job tests', 'Integration tests'] def initialize(*pairs) @pairs = pairs @statistics = calculate_statistics @total = calculate_total if pairs.length > 1 end def to_s print_header @pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) } print_splitter if @total print_line("Total", @total) print_splitter end print_code_test_stats end private def calculate_statistics Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}] end def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coffee|rake)$/) stats = CodeStatisticsCalculator.new Dir.foreach(directory) do |file_name| path = "#{directory}/#{file_name}" if File.directory?(path) && (/^\./ !~ file_name) stats.add(calculate_directory_statistics(path, pattern)) elsif file_name =~ pattern stats.add_by_file_path(path) end end stats end def calculate_total @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, total| total.add(pair.last) end end def calculate_code code_loc = 0 @statistics.each { |k, v| code_loc += v.code_lines unless TEST_TYPES.include? k } code_loc end def calculate_tests test_loc = 0 @statistics.each { |k, v| test_loc += v.code_lines if TEST_TYPES.include? k } test_loc end def print_header print_splitter puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |" print_splitter end def print_splitter puts "+----------------------+-------+-------+---------+---------+-----+-------+" end def print_line(name, statistics) m_over_c = (statistics.methods / statistics.classes) rescue m_over_c = 0 loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0 puts "| #{name.ljust(20)} " \ "| #{statistics.lines.to_s.rjust(5)} " \ "| #{statistics.code_lines.to_s.rjust(5)} " \ "| #{statistics.classes.to_s.rjust(7)} " \ "| #{statistics.methods.to_s.rjust(7)} " \ "| #{m_over_c.to_s.rjust(3)} " \ "| #{loc_over_m.to_s.rjust(5)} |" end def print_code_test_stats code = calculate_code tests = calculate_tests puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f/code)}" puts "" end end
require 'fileutils' require 'optparse' require 'action_dispatch' require 'rails' module Rails class Server < ::Rack::Server class Options def parse!(args) args, options = args.dup, {} option_parser(options).parse! args options[:log_stdout] = options[:daemonize].blank? && (options[:environment] || Rails.env) == "development" options[:server] = args.shift options end private def option_parser(options) OptionParser.new do |opts| opts.banner = "Usage: rails server [mongrel, thin etc] [options]" opts.on("-p", "--port=port", Integer, "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } opts.on("-b", "--binding=IP", String, "Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v } opts.on("-c", "--config=file", String, "Uses a custom rackup configuration.") { |v| options[:config] = v } opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true } opts.on("-e", "--environment=name", String, "Specifies the environment to run this server under (test/development/production).", "Default: development") { |v| options[:environment] = v } opts.on("-P", "--pid=pid", String, "Specifies the PID file.", "Default: tmp/pids/server.pid") { |v| options[:pid] = v } opts.on("-C", "--[no-]dev-caching", "Specifies whether to perform caching in development.", "true or false") { |v| options[:caching] = v } opts.separator "" opts.on("-h", "--help", "Shows this help message.") { puts opts; exit } end end end def initialize(*) super set_environment end # TODO: this is no longer required but we keep it for the moment to support older config.ru files. def app @app ||= begin app = super app.respond_to?(:to_app) ? app.to_app : app end end def opt_parser Options.new end def set_environment ENV["RAILS_ENV"] ||= options[:environment] end def start print_boot_information trap(:INT) { exit } create_tmp_directories setup_dev_caching log_to_stdout if options[:log_stdout] super ensure # The '-h' option calls exit before @options is set. # If we call 'options' with it unset, we get double help banners. puts 'Exiting' unless @options && options[:daemonize] end def middleware Hash.new([]) end def default_options super.merge({ Port: 3000, DoNotReverseLookup: true, environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, daemonize: false, caching: false, pid: File.expand_path("tmp/pids/server.pid") }) end private def setup_dev_caching return unless options[:environment] == "development" if options[:caching] == false delete_cache_file elsif options[:caching] create_cache_file end end def print_boot_information url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}" puts "=> Run `rails server -h` for more startup options" puts "=> Ctrl-C to shutdown server" unless options[:daemonize] end def create_cache_file FileUtils.touch("tmp/caching-dev.txt") end def delete_cache_file FileUtils.rm("tmp/caching-dev.txt") if File.exists?("tmp/caching-dev.txt") end def create_tmp_directories %w(cache pids sockets).each do |dir_to_make| FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make)) end end def log_to_stdout wrapped_app # touch the app so the logger is set up console = ActiveSupport::Logger.new($stdout) console.formatter = Rails.logger.formatter console.level = Rails.logger.level Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) end end end Use exist? instead of deprecated exists? require 'fileutils' require 'optparse' require 'action_dispatch' require 'rails' module Rails class Server < ::Rack::Server class Options def parse!(args) args, options = args.dup, {} option_parser(options).parse! args options[:log_stdout] = options[:daemonize].blank? && (options[:environment] || Rails.env) == "development" options[:server] = args.shift options end private def option_parser(options) OptionParser.new do |opts| opts.banner = "Usage: rails server [mongrel, thin etc] [options]" opts.on("-p", "--port=port", Integer, "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } opts.on("-b", "--binding=IP", String, "Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v } opts.on("-c", "--config=file", String, "Uses a custom rackup configuration.") { |v| options[:config] = v } opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true } opts.on("-e", "--environment=name", String, "Specifies the environment to run this server under (test/development/production).", "Default: development") { |v| options[:environment] = v } opts.on("-P", "--pid=pid", String, "Specifies the PID file.", "Default: tmp/pids/server.pid") { |v| options[:pid] = v } opts.on("-C", "--[no-]dev-caching", "Specifies whether to perform caching in development.", "true or false") { |v| options[:caching] = v } opts.separator "" opts.on("-h", "--help", "Shows this help message.") { puts opts; exit } end end end def initialize(*) super set_environment end # TODO: this is no longer required but we keep it for the moment to support older config.ru files. def app @app ||= begin app = super app.respond_to?(:to_app) ? app.to_app : app end end def opt_parser Options.new end def set_environment ENV["RAILS_ENV"] ||= options[:environment] end def start print_boot_information trap(:INT) { exit } create_tmp_directories setup_dev_caching log_to_stdout if options[:log_stdout] super ensure # The '-h' option calls exit before @options is set. # If we call 'options' with it unset, we get double help banners. puts 'Exiting' unless @options && options[:daemonize] end def middleware Hash.new([]) end def default_options super.merge({ Port: 3000, DoNotReverseLookup: true, environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, daemonize: false, caching: false, pid: File.expand_path("tmp/pids/server.pid") }) end private def setup_dev_caching return unless options[:environment] == "development" if options[:caching] == false delete_cache_file elsif options[:caching] create_cache_file end end def print_boot_information url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}" puts "=> Run `rails server -h` for more startup options" puts "=> Ctrl-C to shutdown server" unless options[:daemonize] end def create_cache_file FileUtils.touch("tmp/caching-dev.txt") end def delete_cache_file FileUtils.rm("tmp/caching-dev.txt") if File.exist?("tmp/caching-dev.txt") end def create_tmp_directories %w(cache pids sockets).each do |dir_to_make| FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make)) end end def log_to_stdout wrapped_app # touch the app so the logger is set up console = ActiveSupport::Logger.new($stdout) console.formatter = Rails.logger.formatter console.level = Rails.logger.level Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) end end end
class RubyMappings def add_all(fun) fun.add_mapping "ruby_library", RubyLibrary.new fun.add_mapping "ruby_test", CheckTestArgs.new fun.add_mapping "ruby_test", AddTestDefaults.new fun.add_mapping "ruby_test", JRubyTest.new fun.add_mapping "ruby_test", MRITest.new fun.add_mapping "ruby_test", AddTestDependencies.new fun.add_mapping "rubydocs", RubyDocs.new fun.add_mapping "rubygem", RubyGem.new end class RubyLibrary < Tasks def handle(fun, dir, args) desc "Build #{args[:name]} in build/#{dir}" task_name = task_name(dir, args[:name]) t = task task_name do puts "Preparing: #{task_name} in #{build_dir}/#{dir}" copy_sources dir, args[:srcs] copy_resources dir, args[:resources], build_dir if args[:resources] remove_svn_dirs end add_dependencies t, dir, args[:deps] add_dependencies t, dir, args[:resources] end def copy_sources(dir, globs) globs.each do |glob| Dir[File.join(dir, glob)].each do |file| destination = destination_for(file) mkdir_p File.dirname(destination) cp file, destination end end end def remove_svn_dirs Dir["#{build_dir}/rb/**/.svn"].each { |file| rm_rf file } end def destination_for(file) File.join build_dir, file end def build_dir "build" end end class CheckTestArgs def handle(fun, dir, args) raise "no :srcs specified for #{dir}" unless args.has_key? :srcs raise "no :name specified for #{dir}" unless args.has_key? :name end end class AddTestDefaults def handle(fun, dir, args) args[:include] = Array(args[:include]) args[:include] << "#{dir}/spec" args[:command] = args[:command] || "spec" args[:require] = Array(args[:require]) # move? args[:srcs] = args[:srcs].map { |str| Dir[File.join(dir, str)] }.flatten end end class AddTestDependencies < Tasks def handle(fun, dir, args) jruby_task = Rake::Task[task_name(dir, "#{args[:name]}-test:jruby")] mri_task = Rake::Task[task_name(dir, "#{args[:name]}-test:mri")] # TODO: # Specifying a dependency here isn't ideal, but it's the easiest way to # avoid a lot of duplication in the build files, since this dep only applies to this task. # Maybe add a jruby_dep argument? add_dependencies jruby_task, dir, ["//common:test"] if args.has_key?(:deps) add_dependencies jruby_task, dir, args[:deps] add_dependencies mri_task, dir, args[:deps] end end end class JRubyTest < Tasks def handle(fun, dir, args) requires = args[:require] + %w[ json-jruby.jar rubyzip.jar childprocess.jar ci_reporter.jar rack.jar ].map { |jar| File.join("third_party/jruby", jar) } desc "Run ruby tests for #{args[:name]} (jruby)" t = task task_name(dir, "#{args[:name]}-test:jruby") do puts "Running: #{args[:name]} ruby tests (jruby)" ENV['WD_SPEC_DRIVER'] = args[:name] jruby :include => args[:include], :require => requires, :command => args[:command], :args => %w[--format CI::Reporter::RSpec], :debug => !!ENV['DEBUG'], :files => args[:srcs] end end end class MRITest < Tasks def handle(fun, dir, args) deps = [] desc "Run ruby tests for #{args[:name]} (mri)" task task_name(dir, "#{args[:name]}-test:mri") => deps do puts "Running: #{args[:name]} ruby tests (mri)" ENV['WD_SPEC_DRIVER'] = args[:name] ruby :require => args[:require], :include => args[:include], :command => args[:command], :args => %w[--format CI::Reporter::RSpec], :debug => !!ENV['DEBUG'], :files => args[:srcs] end end end class RubyDocs def handle(fun, dir, args) if have_yard? define_task(dir, args) else define_noop(dir) end end def define_task(dir, args) files = args[:files] || raise("no :files specified for rubydocs") output_dir = args[:output_dir] || raise("no :output_dir specified for rubydocs") files = Array(files).map { |glob| Dir[glob] }.flatten YARD::Rake::YardocTask.new("//#{dir}:docs") do |t| t.files = args[:files] t.options << "--verbose" t.options << "--readme" << args[:readme] if args.has_key?(:readme) t.options << "--output-dir" << output_dir end end def have_yard? require 'yard' true rescue LoadError false end def define_noop(dir) task "//#{dir}:docs" do abort "YARD is not available." end end end # RubyDocs class RubyGem GEMSPEC_HEADER = "# Automatically generated by the build system. Edits may be lost.\n" def handle(fun, dir, args) raise "no :dir for rubygem" unless args[:dir] raise "no :version for rubygem" unless args[:version] if has_gem_task? define_spec_task dir, args define_clean_task dir, args define_build_task dir, args define_release_task dir, args end define_gem_install_task dir, args end def has_gem_task? require "rubygems" require "rake/gempackagetask" true rescue LoadError false end def define_spec_task(dir, args) gemspec = File.join(args[:dir], "#{args[:name]}.gemspec") file gemspec do mkdir_p args[:dir] Dir.chdir(args[:dir]) { File.open("#{args[:name]}.gemspec", "w") { |file| file << GEMSPEC_HEADER file << gemspec(args).to_ruby } } end task("clean_#{gemspec}") { rm_rf gemspec } end def define_build_task(dir, args) gemfile = File.join("build", "#{args[:name]}-#{args[:version]}.gem") gemspec = File.join(args[:dir], "#{args[:name]}.gemspec") deps = (args[:deps] || []) deps << "clean_#{gemspec}" << gemspec file gemfile => deps do require 'rubygems/builder' spec = eval(File.read(gemspec)) file = Dir.chdir(args[:dir]) { Gem::Builder.new(spec).build } mv File.join(args[:dir], file), gemfile end desc "Build #{gemfile}" task "//#{dir}:gem:build" => gemfile end def define_clean_task(dir, args) desc 'Clean rubygem artifacts' task "//#{dir}:gem:clean" do rm_rf args[:dir] rm_rf "build/*.gem" end end def define_release_task(dir, args) desc 'Build and release the ruby gem to Gemcutter' task "//#{dir}:gem:release" => %W[//#{dir}:gem:clean //#{dir}:gem:build] do sh "gem push build/#{args[:name]}-#{args[:version]}.gem" end end def define_gem_install_task(dir, args) desc 'Install gem dependencies for the current Ruby' task "//#{dir}:install-gems" do dependencies = Array(args[:gemdeps]) + Array(args[:devdeps]) dependencies.each do |dep| name, version = dep.shift ruby :command => "gem", :args => ["install", name, "--version", version, "--no-rdoc", "--no-ri"] end end end def gemspec(args) Gem::Specification.new do |s| s.name = args[:name] s.version = args[:version] s.summary = args[:summary] s.description = args[:description] s.authors = args[:author] s.email = args[:email] s.homepage = args[:homepage] s.files = Dir[*args[:files]] args[:gemdeps].each { |dep| s.add_dependency(*dep.shift) } args[:devdeps].each { |dep| s.add_development_dependency(*dep.shift) } end end end # RubyGem end # RubyMappings class RubyRunner JRUBY_JAR = "third_party/jruby/jruby-complete.jar" def self.run(impl, opts) cmd = ["ruby"] if impl.to_sym == :jruby JRuby.runtime.instance_config.run_ruby_in_process = true cmd << "-J-Djava.awt.headless=true" if opts[:headless] else JRuby.runtime.instance_config.run_ruby_in_process = false end if opts[:debug] cmd << "-d" end if opts.has_key? :include cmd << "-I" cmd << Array(opts[:include]).join(File::PATH_SEPARATOR) end Array(opts[:require]).each do |f| cmd << "-r#{f}" end cmd << "-S" << opts[:command] if opts.has_key? :command cmd += Array(opts[:args]) if opts.has_key? :args cmd += Array(opts[:files]) if opts.has_key? :files puts cmd.join(' ') sh(*cmd) end end def jruby(opts) RubyRunner.run :jruby, opts end def ruby(opts) RubyRunner.run :ruby, opts end JariBakken: Work around jruby-complete/Windows bug, introduced in r9916. r10245 class RubyMappings def add_all(fun) fun.add_mapping "ruby_library", RubyLibrary.new fun.add_mapping "ruby_test", CheckTestArgs.new fun.add_mapping "ruby_test", AddTestDefaults.new fun.add_mapping "ruby_test", JRubyTest.new fun.add_mapping "ruby_test", MRITest.new fun.add_mapping "ruby_test", AddTestDependencies.new fun.add_mapping "rubydocs", RubyDocs.new fun.add_mapping "rubygem", RubyGem.new end class RubyLibrary < Tasks def handle(fun, dir, args) desc "Build #{args[:name]} in build/#{dir}" task_name = task_name(dir, args[:name]) t = task task_name do puts "Preparing: #{task_name} in #{build_dir}/#{dir}" copy_sources dir, args[:srcs] copy_resources dir, args[:resources], build_dir if args[:resources] remove_svn_dirs end add_dependencies t, dir, args[:deps] add_dependencies t, dir, args[:resources] end def copy_sources(dir, globs) globs.each do |glob| Dir[File.join(dir, glob)].each do |file| destination = destination_for(file) mkdir_p File.dirname(destination) cp file, destination end end end def remove_svn_dirs Dir["#{build_dir}/rb/**/.svn"].each { |file| rm_rf file } end def destination_for(file) File.join build_dir, file end def build_dir "build" end end class CheckTestArgs def handle(fun, dir, args) raise "no :srcs specified for #{dir}" unless args.has_key? :srcs raise "no :name specified for #{dir}" unless args.has_key? :name end end class AddTestDefaults def handle(fun, dir, args) args[:include] = Array(args[:include]) args[:include] << "#{dir}/spec" args[:command] = args[:command] || "spec" args[:require] = Array(args[:require]) # move? args[:srcs] = args[:srcs].map { |str| Dir[File.join(dir, str)] }.flatten end end class AddTestDependencies < Tasks def handle(fun, dir, args) jruby_task = Rake::Task[task_name(dir, "#{args[:name]}-test:jruby")] mri_task = Rake::Task[task_name(dir, "#{args[:name]}-test:mri")] # TODO: # Specifying a dependency here isn't ideal, but it's the easiest way to # avoid a lot of duplication in the build files, since this dep only applies to this task. # Maybe add a jruby_dep argument? add_dependencies jruby_task, dir, ["//common:test"] if args.has_key?(:deps) add_dependencies jruby_task, dir, args[:deps] add_dependencies mri_task, dir, args[:deps] end end end class JRubyTest < Tasks def handle(fun, dir, args) requires = args[:require] + %w[ json-jruby.jar rubyzip.jar childprocess.jar ci_reporter.jar rack.jar ].map { |jar| File.join("third_party/jruby", jar) } desc "Run ruby tests for #{args[:name]} (jruby)" t = task task_name(dir, "#{args[:name]}-test:jruby") do puts "Running: #{args[:name]} ruby tests (jruby)" ENV['WD_SPEC_DRIVER'] = args[:name] jruby :include => args[:include], :require => requires, :command => args[:command], :args => %w[--format CI::Reporter::RSpec], :debug => !!ENV['DEBUG'], :files => args[:srcs] end end end class MRITest < Tasks def handle(fun, dir, args) deps = [] desc "Run ruby tests for #{args[:name]} (mri)" task task_name(dir, "#{args[:name]}-test:mri") => deps do puts "Running: #{args[:name]} ruby tests (mri)" ENV['WD_SPEC_DRIVER'] = args[:name] ruby :require => args[:require], :include => args[:include], :command => args[:command], :args => %w[--format CI::Reporter::RSpec], :debug => !!ENV['DEBUG'], :files => args[:srcs] end end end class RubyDocs def handle(fun, dir, args) if have_yard? define_task(dir, args) else define_noop(dir) end end def define_task(dir, args) files = args[:files] || raise("no :files specified for rubydocs") output_dir = args[:output_dir] || raise("no :output_dir specified for rubydocs") files = Array(files).map { |glob| Dir[glob] }.flatten YARD::Rake::YardocTask.new("//#{dir}:docs") do |t| t.files = args[:files] t.options << "--verbose" t.options << "--readme" << args[:readme] if args.has_key?(:readme) t.options << "--output-dir" << output_dir end end def have_yard? require 'yard' true rescue LoadError false end def define_noop(dir) task "//#{dir}:docs" do abort "YARD is not available." end end end # RubyDocs class RubyGem GEMSPEC_HEADER = "# Automatically generated by the build system. Edits may be lost.\n" def handle(fun, dir, args) raise "no :dir for rubygem" unless args[:dir] raise "no :version for rubygem" unless args[:version] if has_gem_task? define_spec_task dir, args define_clean_task dir, args define_build_task dir, args define_release_task dir, args end define_gem_install_task dir, args end def has_gem_task? require "rubygems" require "rake/gempackagetask" true rescue LoadError false end def define_spec_task(dir, args) gemspec = File.join(args[:dir], "#{args[:name]}.gemspec") file gemspec do mkdir_p args[:dir] Dir.chdir(args[:dir]) { File.open("#{args[:name]}.gemspec", "w") { |file| file << GEMSPEC_HEADER file << gemspec(args).to_ruby } } end task("clean_#{gemspec}") { rm_rf gemspec } end def define_build_task(dir, args) gemfile = File.join("build", "#{args[:name]}-#{args[:version]}.gem") gemspec = File.join(args[:dir], "#{args[:name]}.gemspec") deps = (args[:deps] || []) deps << "clean_#{gemspec}" << gemspec file gemfile => deps do require 'rubygems/builder' spec = eval(File.read(gemspec)) file = Dir.chdir(args[:dir]) { Gem::Builder.new(spec).build } mv File.join(args[:dir], file), gemfile end desc "Build #{gemfile}" task "//#{dir}:gem:build" => gemfile end def define_clean_task(dir, args) desc 'Clean rubygem artifacts' task "//#{dir}:gem:clean" do rm_rf args[:dir] rm_rf "build/*.gem" end end def define_release_task(dir, args) desc 'Build and release the ruby gem to Gemcutter' task "//#{dir}:gem:release" => %W[//#{dir}:gem:clean //#{dir}:gem:build] do sh "gem push build/#{args[:name]}-#{args[:version]}.gem" end end def define_gem_install_task(dir, args) desc 'Install gem dependencies for the current Ruby' task "//#{dir}:install-gems" do dependencies = Array(args[:gemdeps]) + Array(args[:devdeps]) dependencies.each do |dep| name, version = dep.shift ruby :command => "gem", :args => ["install", name, "--version", version, "--no-rdoc", "--no-ri"] end end end def gemspec(args) Gem::Specification.new do |s| s.name = args[:name] s.version = args[:version] s.summary = args[:summary] s.description = args[:description] s.authors = args[:author] s.email = args[:email] s.homepage = args[:homepage] s.files = Dir[*args[:files]] args[:gemdeps].each { |dep| s.add_dependency(*dep.shift) } args[:devdeps].each { |dep| s.add_development_dependency(*dep.shift) } end end end # RubyGem end # RubyMappings class RubyRunner JRUBY_JAR = "third_party/jruby/jruby-complete.jar" def self.run(impl, opts) if impl.to_sym == :jruby JRuby.runtime.instance_config.run_ruby_in_process = true cmd = ["ruby"] cmd << "-J-Djava.awt.headless=true" if opts[:headless] else cmd = [find_ruby] JRuby.runtime.instance_config.run_ruby_in_process = false end if opts[:debug] cmd << "-d" end if opts.has_key? :include cmd << "-I" cmd << Array(opts[:include]).join(File::PATH_SEPARATOR) end Array(opts[:require]).each do |f| cmd << "-r#{f}" end cmd << "-S" << opts[:command] if opts.has_key? :command cmd += Array(opts[:args]) if opts.has_key? :args cmd += Array(opts[:files]) if opts.has_key? :files puts cmd.join(' ') sh(*cmd) end def self.find_ruby return "ruby" unless windows? # work around windows/jruby bug by searching the PATH ourselves paths = ENV['PATH'].split(File::PATH_SEPARATOR) paths.each do |path| exe = File.join(path, "ruby.exe") return exe if File.executable?(exe) end raise "could not find ruby.exe" end end def jruby(opts) RubyRunner.run :jruby, opts end def ruby(opts) RubyRunner.run :ruby, opts end
garp deploy script # s t a g e s set :stages, %w(integration staging production) require 'capistrano/ext/multistage' set :stage, nil set :default_stage, "integration" # v e r s i o n c o n t r o l set :scm, :git # r e m o t e s e r v e r set :deploy_via, :remote_cache ssh_options[:forward_agent] = true set :git_enable_submodules, 1 set :use_sudo, false set :keep_releases, 3 # f l o w after "deploy:update_code", "deploy:cleanup" namespace :deploy do task :update do transaction do update_code set_permissions spawn symlink end end task :finalize_update do transaction do run "chmod -R g+w #{releases_path}/#{release_name}" end end task :symlink do transaction do run "ln -nfs #{current_release} #{deploy_to}/#{current_dir}" run "ln -nfs #{deploy_to}/#{current_dir} #{document_root}" end end task :set_permissions do transaction do run "echo '<?php' > #{current_release}/application/data/cache/pluginLoaderCache.php" end end task :spawn do transaction do run "php #{current_release}/garp/scripts/garp.php Spawn --e=#{garp_env}" end end task :migrate do # nothing end task :restart do # nothing end end # p r o d u c t i o n w a r n i n g task :ask_production_confirmation do set(:confirmed) do puts <<-WARN ======================================================================== WARNING: You're about to deploy to a live, public server. Please confirm that your work is ready for that. ======================================================================== WARN answer = Capistrano::CLI.ui.ask " Are you sure? (Y) " if answer == 'Y' then true else false end end unless fetch(:confirmed) puts "\nDeploy cancelled!" exit end end before 'production', :ask_production_confirmation
class AddCustomSlugToRefineryPages < ActiveRecord::Migration[4.2] def up if page_column_names.exclude?('custom_slug') add_column :refinery_pages, :custom_slug, :string end end def down if page_column_names.include?('custom_slug') remove_column :refinery_pages, :custom_slug end end private def page_column_names return [] unless defined?(::Refinery::Page) Refinery::Page.column_names.map(&:to_s) end end Fix checking :custom_slug existence to use column_exists? class AddCustomSlugToRefineryPages < ActiveRecord::Migration[4.2] def up add_column :refinery_pages, :custom_slug, :string unless custom_slug_exists? end def down remove_column :refinery_pages, :custom_slug if custom_slug_exists? end private def custom_slug_exists? column_exists?(:refinery_pages, :custom_slug) end end
# -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.authors = ["Katrina Owen"] gem.email = ["katrina.owen@gmail.com"] gem.description = %q{Provide pebble-compliant paths for ActiveRecord models.} gem.summary = %q{Provides searchable, parseable pebble-compliant UID paths, e.g. (such as a.b.*) for Active Record models.} gem.homepage = "" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "pebble_path" gem.require_paths = ["lib"] gem.version = "0.0.2" gem.add_development_dependency 'rspec' gem.add_dependency 'pebblebed', '>=0.0.15' end Bump version # -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.authors = ["Katrina Owen"] gem.email = ["katrina.owen@gmail.com"] gem.description = %q{Provide pebble-compliant paths for ActiveRecord models.} gem.summary = %q{Provides searchable, parseable pebble-compliant UID paths, e.g. (such as a.b.*) for Active Record models.} gem.homepage = "" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "pebble_path" gem.require_paths = ["lib"] gem.version = "0.0.3" gem.add_development_dependency 'rspec' gem.add_dependency 'pebblebed', '>=0.0.15' end
require 'json' module Spider; module Master class ScoutController < Spider::PageController route /([\w\d]{8}-[\w\d]{4}-[\w\d]{4}-[\w\d]{4}-[\w\d]{12})/, self, :do => lambda{ |uuid| @servant = Servant.load(:uuid => uuid) @uuid = uuid raise NotFound.new("Servant #{uuid}") unless @servant } __.json def plan last_modified = (@servant.scout_plan_changed || @servant.obj_modified).to_local_time @servant.scout_plugins.each do |instance| stat = File.lstat(instance.plugin.rb_path) mtime = stat.mtime last_modified = mtime if mtime > last_modified end if @request.env['HTTP_IF_MODIFIED_SINCE'] if_modified = nil begin if_modified = Time.httpdate(@request.env['HTTP_IF_MODIFIED_SINCE']) rescue ArgumentError if_modified = 0 end raise HTTPStatus.new(Spider::HTTP::NOT_MODIFIED) if last_modified <= if_modified end @response.headers['Last-Modified'] = last_modified.httpdate $out << @servant.scout_plan.to_json end __.json def checkin res = Zlib::GzipReader.new(@request.body).read #Spider.logger.debug("RECEIVED REPORT FOR #{@uuid}:") #Spider.logger.debug(res) res = JSON.parse(res) statuses = {} reports = {} res["reports"].each do |rep| statuses[rep["plugin_id"]] = :ok reports[rep["plugin_id"]] ||= ScoutReport.create( :plugin_instance => rep["plugin_id"], :created_at => DateTime.parse(rep["created_at"]) ) report = reports[rep["plugin_id"]] rep["fields"].each do |name, val| field = ScoutReportField.create(:name => name, :value => val, :report => report) end end res["alerts"].each do |alert| subject = alert["fields"]["subject"] body = alert["fields"]["body"] last = ScoutAlert.where( :plugin_instance => alert["plugin_id"], :active => true ).order_by(:obj_created, :desc) statuses[alert["plugin_id"]] = :alert had_previous = false last.each do |l| if l && l.subject == subject && l.body == body last.repeated += 1 last.save had_previous = true break end end next if had_previous subject = alert["fields"]["subject"] instance = ScoutPluginInstance.new(alert["plugin_id"]) subject = "#{instance.servant} - #{subject}" alert = ScoutAlert.create( :plugin_instance => alert["plugin_id"], :subject => alert["fields"]["subject"], :body => alert["fields"]["body"] ) end res["errors"].each do |err| subject = err["fields"]["subject"] body = err["fields"]["body"] last = ScoutError.where(:plugin_instance => err["plugin_id"]).order_by(:obj_created, :desc) last.limit = 1 statuses[err["plugin_id"]] = :error if last[0] && last[0].subject == subject && last[0].body == body last.repeated += 1 last.save next end subject = err["fields"]["subject"] instance = ScoutPluginInstance.new(err["plugin_id"]) subject = "#{instance.servant} - #{subject}" error = ScoutError.create( :plugin_instance => err["plugin_id"], :subject => err["fields"]["subject"], :body => err["fields"]["body"] ) end today = Date.today statuses.each do |id, val| i = ScoutPluginInstance.new(id) averages = i.averages_computed_at i.obj_modified = DateTime.now i.status = val i.compute_averages if averages && averages < today i.check_triggers i.save end end end end; end Fixes in ScoutController require 'json' module Spider; module Master class ScoutController < Spider::PageController route /([\w\d]{8}-[\w\d]{4}-[\w\d]{4}-[\w\d]{4}-[\w\d]{12})/, self, :do => lambda{ |uuid| @servant = Servant.load(:uuid => uuid) @uuid = uuid raise NotFound.new("Servant #{uuid}") unless @servant } __.json def plan last_modified = (@servant.scout_plan_changed || @servant.obj_modified).to_local_time @servant.scout_plugins.each do |instance| stat = File.lstat(instance.plugin.rb_path) mtime = stat.mtime last_modified = mtime if mtime > last_modified end if @request.env['HTTP_IF_MODIFIED_SINCE'] if_modified = nil begin if_modified = Time.httpdate(@request.env['HTTP_IF_MODIFIED_SINCE']) rescue ArgumentError if_modified = 0 end raise HTTPStatus.new(Spider::HTTP::NOT_MODIFIED) if last_modified <= if_modified end @response.headers['Last-Modified'] = last_modified.httpdate $out << @servant.scout_plan.to_json end __.json def checkin res = Zlib::GzipReader.new(@request.body).read #Spider.logger.debug("RECEIVED REPORT FOR #{@uuid}:") #Spider.logger.debug(res) res = JSON.parse(res) statuses = {} reports = {} res["reports"].each do |rep| statuses[rep["plugin_id"]] = :ok reports[rep["plugin_id"]] ||= ScoutReport.create( :plugin_instance => rep["plugin_id"], :created_at => DateTime.parse(rep["created_at"]) ) report = reports[rep["plugin_id"]] rep["fields"].each do |name, val| field = ScoutReportField.create(:name => name, :value => val, :report => report) end end res["alerts"].each do |alert| subject = alert["fields"]["subject"] body = alert["fields"]["body"] last = ScoutAlert.where( :plugin_instance => alert["plugin_id"], :active => true ).order_by(:obj_created, :desc) statuses[alert["plugin_id"]] = :alert had_previous = false last.each do |l| if l && l.subject == subject && l.body == body l.repeated += 1 l.save had_previous = true break end end next if had_previous subject = alert["fields"]["subject"] instance = ScoutPluginInstance.new(alert["plugin_id"]) subject = "#{instance.servant} - #{subject}" alert = ScoutAlert.create( :plugin_instance => alert["plugin_id"], :subject => alert["fields"]["subject"], :body => alert["fields"]["body"] ) end res["errors"].each do |err| subject = err["fields"]["subject"] body = err["fields"]["body"] last = ScoutError.where(:plugin_instance => err["plugin_id"]).order_by(:obj_created, :desc) last.limit = 1 statuses[err["plugin_id"]] = :error if last[0] && last[0].subject == subject && last[0].body == body last[0].repeated += 1 last[0].save next end subject = err["fields"]["subject"] instance = ScoutPluginInstance.new(err["plugin_id"]) subject = "#{instance.servant} - #{subject}" error = ScoutError.create( :plugin_instance => err["plugin_id"], :subject => err["fields"]["subject"], :body => err["fields"]["body"] ) end today = Date.today statuses.each do |id, val| i = ScoutPluginInstance.new(id) averages = i.averages_computed_at i.obj_modified = DateTime.now i.status = val i.compute_averages if averages && averages < today i.check_triggers i.save end end end end; end
$LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'publify_core/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'publify_core' s.version = PublifyCore::VERSION s.authors = ['Matijs van Zuijlen', 'Yannick François', 'Thomas Lecavellier', 'Frédéric de Villamil'] s.email = ['matijs@matijs.net'] s.homepage = 'https://publify.co' s.summary = 'Core engine for the Publify blogging system.' s.description = 'Core engine for the Publify blogging system, formerly known as Typo.' s.license = 'MIT' s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc'] s.required_ruby_version = '>= 2.1.0' s.add_dependency 'rails', '~> 4.2.6' s.add_dependency 'RedCloth', '~> 4.3.1' s.add_dependency 'actionpack-page_caching', '~> 1.0.2' # removed from Rails-core as Rails 4.0 s.add_dependency 'activerecord-session_store', '~> 1.0.0' s.add_dependency 'akismet', '~> 2.0' s.add_dependency 'bluecloth', '~> 2.1' s.add_dependency 'bootstrap-sass', '~> 3.3.6' s.add_dependency 'cancancan', '~> 1.14' s.add_dependency 'carrierwave', '~> 0.11.2' s.add_dependency 'devise', '~> 4.2.0' s.add_dependency 'devise-i18n', '~> 1.1.0' s.add_dependency 'dynamic_form', '~> 1.1.4' s.add_dependency 'feedjira', '~> 2.0.0' s.add_dependency 'fog-aws', '~> 0.12.0' s.add_dependency 'jquery-rails', '~> 4.1.0' s.add_dependency 'jquery-ui-rails', '~> 5.0.2' s.add_dependency 'kaminari', '~> 0.17.0' s.add_dependency 'mini_magick', '~> 4.2' s.add_dependency 'rails-observers', '~> 0.1.2' s.add_dependency 'rails-timeago', '~> 2.0' s.add_dependency 'rails_autolink', '~> 1.1.0' s.add_dependency 'recaptcha', '~> 3.2' s.add_dependency 'rubypants', '~> 0.2.0' s.add_dependency 'sass-rails', '~> 5.0' s.add_dependency 'twitter', '~> 5.16.0' s.add_dependency 'uuidtools', '~> 2.1.1' s.add_development_dependency 'sqlite3' s.add_development_dependency 'rspec-rails', '~> 3.5.2' s.add_development_dependency 'capybara', '~> 2.7' s.add_development_dependency 'factory_girl_rails', '~> 4.6' s.add_development_dependency 'rubocop', '~> 0.45.0' s.add_development_dependency 'i18n-tasks', '~> 0.9.1' end Update jquery-rails to 4.2.1 $LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'publify_core/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'publify_core' s.version = PublifyCore::VERSION s.authors = ['Matijs van Zuijlen', 'Yannick François', 'Thomas Lecavellier', 'Frédéric de Villamil'] s.email = ['matijs@matijs.net'] s.homepage = 'https://publify.co' s.summary = 'Core engine for the Publify blogging system.' s.description = 'Core engine for the Publify blogging system, formerly known as Typo.' s.license = 'MIT' s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc'] s.required_ruby_version = '>= 2.1.0' s.add_dependency 'rails', '~> 4.2.6' s.add_dependency 'RedCloth', '~> 4.3.1' s.add_dependency 'actionpack-page_caching', '~> 1.0.2' # removed from Rails-core as Rails 4.0 s.add_dependency 'activerecord-session_store', '~> 1.0.0' s.add_dependency 'akismet', '~> 2.0' s.add_dependency 'bluecloth', '~> 2.1' s.add_dependency 'bootstrap-sass', '~> 3.3.6' s.add_dependency 'cancancan', '~> 1.14' s.add_dependency 'carrierwave', '~> 0.11.2' s.add_dependency 'devise', '~> 4.2.0' s.add_dependency 'devise-i18n', '~> 1.1.0' s.add_dependency 'dynamic_form', '~> 1.1.4' s.add_dependency 'feedjira', '~> 2.0.0' s.add_dependency 'fog-aws', '~> 0.12.0' s.add_dependency 'jquery-rails', '~> 4.2.1' s.add_dependency 'jquery-ui-rails', '~> 5.0.2' s.add_dependency 'kaminari', '~> 0.17.0' s.add_dependency 'mini_magick', '~> 4.2' s.add_dependency 'rails-observers', '~> 0.1.2' s.add_dependency 'rails-timeago', '~> 2.0' s.add_dependency 'rails_autolink', '~> 1.1.0' s.add_dependency 'recaptcha', '~> 3.2' s.add_dependency 'rubypants', '~> 0.2.0' s.add_dependency 'sass-rails', '~> 5.0' s.add_dependency 'twitter', '~> 5.16.0' s.add_dependency 'uuidtools', '~> 2.1.1' s.add_development_dependency 'sqlite3' s.add_development_dependency 'rspec-rails', '~> 3.5.2' s.add_development_dependency 'capybara', '~> 2.7' s.add_development_dependency 'factory_girl_rails', '~> 4.6' s.add_development_dependency 'rubocop', '~> 0.45.0' s.add_development_dependency 'i18n-tasks', '~> 0.9.1' end
module OpenNebula begin require 'nokogiri' NOKOGIRI=true rescue LoadError NOKOGIRI=false end # Require crack library if present, otherwise don't bother # This is just for OCCI use begin require 'crack' rescue LoadError end ########################################################################### # The XMLUtilsElement module provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pool Elements ########################################################################### module XMLUtilsElement # Initialize a XML document for the element # xml:: _String_ the XML document of the object # root_element:: _String_ Base xml element # [return] _XML_ object for the underlying XML engine def self.initialize_xml(xml, root_element) if NOKOGIRI Nokogiri::XML(xml).xpath("/#{root_element}") else REXML::Document.new(xml).root end end # Extract an element from the XML description of the PoolElement. # key::_String_ The name of the element # [return] _String_ the value of the element # Examples: # ['VID'] # gets VM id # ['HISTORY/HOSTNAME'] # get the hostname from the history def [](key) if NOKOGIRI element=@xml.xpath(key.to_s.upcase) else element=@xml.elements[key.to_s.upcase] end if element element.text end end def template_str(indent=true) template_like_str('TEMPLATE', indent) end def template_like_str(root_element, indent=true) if NOKOGIRI xml_template=@xml.xpath(root_element).to_s rexml=REXML::Document.new(xml_template).root else rexml=@xml.elements[root_element] end if indent ind_enter="\n" ind_tab=' ' else ind_enter='' ind_tab=' ' end str=rexml.collect {|n| if n.class==REXML::Element str_line="" if n.has_elements? str_line << n.name << "=[" << ind_enter str_line << n.collect {|n2| if n2 && n2.class==REXML::Element str = ind_tab + n2.name + "=" str += n2.text if n2.text str end }.compact.join(","+ind_enter) str_line<<" ]" else str_line<<n.name << "=" << n.text.to_s end str_line end }.compact.join("\n") str end def to_hash if !@hash @hash=Crack::XML.parse(to_xml) end return @hash end def to_xml if NOKOGIRI @xml.to_xml else str = "" REXML::Formatters::Pretty.new(1).write(@xml,str) str end end end ########################################################################### # The XMLUtilsPool module provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pools ########################################################################### module XMLUtilsPool #Initialize a XML document for the element #xml:: _String_ the XML document of the object #[return] _XML_ object for the underlying XML engine def initialize_xml(xml) if NOKOGIRI Nokogiri::XML(xml).xpath("/#{@pool_name}") else xml=REXML::Document.new(xml).root end end #Executes the given block for each element of the Pool #block:: _Block_ def each_element(block) if NOKOGIRI @xml.xpath( "#{@element_name}").each {|pelem| block.call self.factory(pelem) } else @xml.elements.each( "#{@element_name}") {|pelem| block.call self.factory(pelem) } end end def to_xml if NOKOGIRI @xml.to_xml else str = "" REXML::Formatters::Pretty.new(1).write(@xml,str) str end end def to_hash if !@hash @hash=Crack::XML.parse(to_xml) end return @hash end end end feature #192 Fixed error on to_xml method when no @xml, now it returns nil module OpenNebula begin require 'nokogiri' NOKOGIRI=true rescue LoadError NOKOGIRI=false end # Require crack library if present, otherwise don't bother # This is just for OCCI use begin require 'crack' rescue LoadError end ########################################################################### # The XMLUtilsElement module provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pool Elements ########################################################################### module XMLUtilsElement # Initialize a XML document for the element # xml:: _String_ the XML document of the object # root_element:: _String_ Base xml element # [return] _XML_ object for the underlying XML engine def self.initialize_xml(xml, root_element) if NOKOGIRI Nokogiri::XML(xml).xpath("/#{root_element}") else REXML::Document.new(xml).root end end # Extract an element from the XML description of the PoolElement. # key::_String_ The name of the element # [return] _String_ the value of the element # Examples: # ['VID'] # gets VM id # ['HISTORY/HOSTNAME'] # get the hostname from the history def [](key) if NOKOGIRI element=@xml.xpath(key.to_s.upcase) else element=@xml.elements[key.to_s.upcase] end if element element.text end end def template_str(indent=true) template_like_str('TEMPLATE', indent) end def template_like_str(root_element, indent=true) if NOKOGIRI xml_template=@xml.xpath(root_element).to_s rexml=REXML::Document.new(xml_template).root else rexml=@xml.elements[root_element] end if indent ind_enter="\n" ind_tab=' ' else ind_enter='' ind_tab=' ' end str=rexml.collect {|n| if n.class==REXML::Element str_line="" if n.has_elements? str_line << n.name << "=[" << ind_enter str_line << n.collect {|n2| if n2 && n2.class==REXML::Element str = ind_tab + n2.name + "=" str += n2.text if n2.text str end }.compact.join(","+ind_enter) str_line<<" ]" else str_line<<n.name << "=" << n.text.to_s end str_line end }.compact.join("\n") str end def to_hash if !@hash && @xml @hash=Crack::XML.parse(to_xml) end return @hash end def to_xml if NOKOGIRI @xml.to_xml else str = "" REXML::Formatters::Pretty.new(1).write(@xml,str) str end end end ########################################################################### # The XMLUtilsPool module provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pools ########################################################################### module XMLUtilsPool #Initialize a XML document for the element #xml:: _String_ the XML document of the object #[return] _XML_ object for the underlying XML engine def initialize_xml(xml) if NOKOGIRI Nokogiri::XML(xml).xpath("/#{@pool_name}") else xml=REXML::Document.new(xml).root end end #Executes the given block for each element of the Pool #block:: _Block_ def each_element(block) if NOKOGIRI @xml.xpath( "#{@element_name}").each {|pelem| block.call self.factory(pelem) } else @xml.elements.each( "#{@element_name}") {|pelem| block.call self.factory(pelem) } end end def to_xml if NOKOGIRI @xml.to_xml else str = "" REXML::Formatters::Pretty.new(1).write(@xml,str) str end end def to_hash if !@hash && @xml @hash=Crack::XML.parse(to_xml) end return @hash end end end
module OpenNebula begin require 'nokogiri' NOKOGIRI=true rescue LoadError NOKOGIRI=false end begin require 'rexml/formatters/default' REXML_FORMATTERS=true rescue LoadError REXML_FORMATTERS=false end ########################################################################### # The XMLElement class provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pool and # PoolElement classes ########################################################################### class XMLElement # xml:: _opaque xml object_ an xml object as returned by build_xml def initialize(xml=nil) @xml = xml end # Initialize a XML document for the element # xml:: _String_ the XML document of the object # root_element:: _String_ Base xml element def initialize_xml(xml, root_element) if NOKOGIRI @xml = Nokogiri::XML(xml).xpath("/#{root_element}") if @xml.size == 0 @xml = nil end else @xml = REXML::Document.new(xml).root if @xml.name != root_element @xml = nil end end end # Builds a XML document # xml:: _String_ the XML document of the object # root_element:: _String_ Base xml element # [return] _XML_ object for the underlying XML engine def self.build_xml(xml, root_element) if NOKOGIRI doc = Nokogiri::XML(xml).xpath("/#{root_element}") else doc = REXML::Document.new(xml).root end return doc end # Extract an element from the XML description of the PoolElement. # key::_String_ The name of the element # [return] _String_ the value of the element # Examples: # ['VID'] # gets VM id # ['HISTORY/HOSTNAME'] # get the hostname from the history def [](key) if NOKOGIRI element=@xml.xpath(key.to_s) if element.size == 0 return nil end else element=@xml.elements[key.to_s] end if element element.text end end # Gets an attribute from an elemenT # key:: _String_ xpath for the element # name:: _String_ name of the attribute def attr(key,name) value = nil if NOKOGIRI element=@xml.xpath(key.to_s.upcase) if element.size == 0 return nil end value = element[name] if element != nil else element=@xml.elements[key.to_s.upcase] value = element.attributes[name] if element != nil end return value end # Iterates over every Element in the XPath and calls the block with a # a XMLElement # block:: _Block_ def each(xpath_str,&block) if NOKOGIRI @xml.xpath(xpath_str).each { |pelem| block.call XMLElement.new(pelem) } else @xml.elements.each(xpath_str) { |pelem| block.call XMLElement.new(pelem) } end end def name @xml.name end def text if NOKOGIRI @xml.content else @xml.text end end def has_elements?(xpath_str) if NOKOGIRI element = @xml.xpath(xpath_str.to_s.upcase) return element != nil && element.children.size > 0 else element = @xml.elements[xpath_str.to_s] return element != nil && element.has_elements? end end def template_str(indent=true) template_like_str('TEMPLATE', indent) end def template_like_str(root_element, indent=true) if NOKOGIRI xml_template=@xml.xpath(root_element).to_s rexml=REXML::Document.new(xml_template).root else rexml=@xml.elements[root_element] end if indent ind_enter="\n" ind_tab=' ' else ind_enter='' ind_tab=' ' end str=rexml.collect {|n| if n.class==REXML::Element str_line="" if n.has_elements? str_line << n.name << "=[" << ind_enter str_line << n.collect {|n2| if n2 && n2.class==REXML::Element str = ind_tab + n2.name + "=" str += n2.text if n2.text str end }.compact.join(","+ind_enter) str_line<<" ]" else str_line<<n.name << "=" << n.text.to_s end str_line end }.compact.join("\n") str end def to_xml(pretty=false) if NOKOGIRI && pretty str = @xml.to_xml elsif REXML_FORMATTERS && pretty str = String.new formatter = REXML::Formatters::Pretty.new formatter.compact = true str = formatter.write(@xml,str) else str = @xml.to_s end return str end end ########################################################################### # The XMLUtilsPool module provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pools ########################################################################### class XMLPool < XMLElement def initialize(xml=nil) super(xml) end #Executes the given block for each element of the Pool #block:: _Block_ def each_element(block) if NOKOGIRI @xml.xpath( "#{@element_name}").each {|pelem| block.call self.factory(pelem) } else @xml.elements.each( "#{@element_name}") {|pelem| block.call self.factory(pelem) } end end end end bug #381: require pretty formatter module OpenNebula begin require 'nokogiri' NOKOGIRI=true rescue LoadError NOKOGIRI=false end begin require 'rexml/formatters/pretty' REXML_FORMATTERS=true rescue LoadError REXML_FORMATTERS=false end ########################################################################### # The XMLElement class provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pool and # PoolElement classes ########################################################################### class XMLElement # xml:: _opaque xml object_ an xml object as returned by build_xml def initialize(xml=nil) @xml = xml end # Initialize a XML document for the element # xml:: _String_ the XML document of the object # root_element:: _String_ Base xml element def initialize_xml(xml, root_element) if NOKOGIRI @xml = Nokogiri::XML(xml).xpath("/#{root_element}") if @xml.size == 0 @xml = nil end else @xml = REXML::Document.new(xml).root if @xml.name != root_element @xml = nil end end end # Builds a XML document # xml:: _String_ the XML document of the object # root_element:: _String_ Base xml element # [return] _XML_ object for the underlying XML engine def self.build_xml(xml, root_element) if NOKOGIRI doc = Nokogiri::XML(xml).xpath("/#{root_element}") else doc = REXML::Document.new(xml).root end return doc end # Extract an element from the XML description of the PoolElement. # key::_String_ The name of the element # [return] _String_ the value of the element # Examples: # ['VID'] # gets VM id # ['HISTORY/HOSTNAME'] # get the hostname from the history def [](key) if NOKOGIRI element=@xml.xpath(key.to_s) if element.size == 0 return nil end else element=@xml.elements[key.to_s] end if element element.text end end # Gets an attribute from an elemenT # key:: _String_ xpath for the element # name:: _String_ name of the attribute def attr(key,name) value = nil if NOKOGIRI element=@xml.xpath(key.to_s.upcase) if element.size == 0 return nil end value = element[name] if element != nil else element=@xml.elements[key.to_s.upcase] value = element.attributes[name] if element != nil end return value end # Iterates over every Element in the XPath and calls the block with a # a XMLElement # block:: _Block_ def each(xpath_str,&block) if NOKOGIRI @xml.xpath(xpath_str).each { |pelem| block.call XMLElement.new(pelem) } else @xml.elements.each(xpath_str) { |pelem| block.call XMLElement.new(pelem) } end end def name @xml.name end def text if NOKOGIRI @xml.content else @xml.text end end def has_elements?(xpath_str) if NOKOGIRI element = @xml.xpath(xpath_str.to_s.upcase) return element != nil && element.children.size > 0 else element = @xml.elements[xpath_str.to_s] return element != nil && element.has_elements? end end def template_str(indent=true) template_like_str('TEMPLATE', indent) end def template_like_str(root_element, indent=true) if NOKOGIRI xml_template=@xml.xpath(root_element).to_s rexml=REXML::Document.new(xml_template).root else rexml=@xml.elements[root_element] end if indent ind_enter="\n" ind_tab=' ' else ind_enter='' ind_tab=' ' end str=rexml.collect {|n| if n.class==REXML::Element str_line="" if n.has_elements? str_line << n.name << "=[" << ind_enter str_line << n.collect {|n2| if n2 && n2.class==REXML::Element str = ind_tab + n2.name + "=" str += n2.text if n2.text str end }.compact.join(","+ind_enter) str_line<<" ]" else str_line<<n.name << "=" << n.text.to_s end str_line end }.compact.join("\n") str end def to_xml(pretty=false) if NOKOGIRI && pretty str = @xml.to_xml elsif REXML_FORMATTERS && pretty str = String.new formatter = REXML::Formatters::Pretty.new formatter.compact = true formatter.write(@xml,str) else str = @xml.to_s end return str end end ########################################################################### # The XMLUtilsPool module provides an abstraction of the underlying # XML parser engine. It provides XML-related methods for the Pools ########################################################################### class XMLPool < XMLElement def initialize(xml=nil) super(xml) end #Executes the given block for each element of the Pool #block:: _Block_ def each_element(block) if NOKOGIRI @xml.xpath( "#{@element_name}").each {|pelem| block.call self.factory(pelem) } else @xml.elements.each( "#{@element_name}") {|pelem| block.call self.factory(pelem) } end end end end
# -------------------------------------------------------------------------- # # Copyright 2002-2016, OpenNebula Project, OpenNebula Systems # # # # 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 'set' require 'base64' require 'zlib' require 'pathname' require 'opennebula' $: << File.dirname(__FILE__) require 'db_schema' include OpenNebula module Migrator def db_version "5.3.80" end def one_version "OpenNebula 5.3.80" end def up init_log_time() feature_4901() feature_5005() log_time() return true end private def xpath(doc, sxpath) element = doc.root.at_xpath(sxpath) if !element.nil? element.text else "" end end ############################################################################ # Feature 4921. Adds TOTAL_CPU and TOTAL_MEM to HOST/HOST_SHARE to compute # MAX_CPU and MAX_MEM when RESERVED_CPU/MEM is updated ############################################################################ def feature_4901 @db.run "ALTER TABLE host_pool RENAME TO old_host_pool;" @db.run host_pool_schema() @db.transaction do @db.fetch("SELECT * FROM old_host_pool") do |row| doc = Nokogiri::XML(row[:body], nil, NOKOGIRI_ENCODING) { |c| c.default_xml.noblanks } rcpu = xpath(doc, "TEMPLATE/RESERVED_CPU").to_i rmem = xpath(doc, "TEMPLATE/RESERVED_MEM").to_i total_cpu = xpath(doc, "HOST_SHARE/MAX_CPU").to_i + rcpu total_mem = xpath(doc, "HOST_SHARE/MAX_MEM").to_i + rmem total_cpu_e = doc.create_element "TOTAL_CPU", total_cpu total_mem_e = doc.create_element "TOTAL_MEM", total_mem host_share = doc.root.at_xpath("HOST_SHARE") host_share.add_child(total_cpu_e) host_share.add_child(total_mem_e) row[:body] = doc.root.to_s @db[:host_pool].insert(row) end end @db.run "DROP TABLE old_host_pool;" end ############################################################################ # Feature 5005. # Adds UID, GID and REQUEST_ID to history records ############################################################################ def feature_5005 @db.run "ALTER TABLE vm_pool RENAME TO old_vm_pool;" @db.run vm_pool_schema() @db.transaction do @db.fetch("SELECT * FROM old_vm_pool") do |row| doc = Nokogiri::XML(row[:body], nil, NOKOGIRI_ENCODING) { |c| c.default_xml.noblanks } doc.root.xpath("HISTORY_RECORDS/HISTORY").each do |h| reason = h.xpath("REASON") reason.unlink if !reason.nil? uid = doc.create_element "UID", -1 gid = doc.create_element "GID", -1 rid = doc.create_element "REQUEST_ID", -1 h.add_child(uid) h.add_child(gid) h.add_child(rid) end row[:body] = doc.root.to_s @db[:vm_pool].insert(row) end end @db.run "DROP TABLE old_vm_pool;" end end F #5005: Added comment for missing migration # -------------------------------------------------------------------------- # # Copyright 2002-2016, OpenNebula Project, OpenNebula Systems # # # # 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 'set' require 'base64' require 'zlib' require 'pathname' require 'opennebula' $: << File.dirname(__FILE__) require 'db_schema' include OpenNebula module Migrator def db_version "5.3.80" end def one_version "OpenNebula 5.3.80" end def up init_log_time() feature_4901() feature_5005() log_time() return true end private def xpath(doc, sxpath) element = doc.root.at_xpath(sxpath) if !element.nil? element.text else "" end end ############################################################################ # Feature 4921. Adds TOTAL_CPU and TOTAL_MEM to HOST/HOST_SHARE to compute # MAX_CPU and MAX_MEM when RESERVED_CPU/MEM is updated ############################################################################ def feature_4901 @db.run "ALTER TABLE host_pool RENAME TO old_host_pool;" @db.run host_pool_schema() @db.transaction do @db.fetch("SELECT * FROM old_host_pool") do |row| doc = Nokogiri::XML(row[:body], nil, NOKOGIRI_ENCODING) { |c| c.default_xml.noblanks } rcpu = xpath(doc, "TEMPLATE/RESERVED_CPU").to_i rmem = xpath(doc, "TEMPLATE/RESERVED_MEM").to_i total_cpu = xpath(doc, "HOST_SHARE/MAX_CPU").to_i + rcpu total_mem = xpath(doc, "HOST_SHARE/MAX_MEM").to_i + rmem total_cpu_e = doc.create_element "TOTAL_CPU", total_cpu total_mem_e = doc.create_element "TOTAL_MEM", total_mem host_share = doc.root.at_xpath("HOST_SHARE") host_share.add_child(total_cpu_e) host_share.add_child(total_mem_e) row[:body] = doc.root.to_s @db[:host_pool].insert(row) end end @db.run "DROP TABLE old_host_pool;" end ############################################################################ # Feature 5005. # Adds UID, GID and REQUEST_ID to history records ############################################################################ def feature_5005 #TODO ADD VALUES TO HISTORY POOL TABLE @db.run "ALTER TABLE vm_pool RENAME TO old_vm_pool;" @db.run vm_pool_schema() @db.transaction do @db.fetch("SELECT * FROM old_vm_pool") do |row| doc = Nokogiri::XML(row[:body], nil, NOKOGIRI_ENCODING) { |c| c.default_xml.noblanks } doc.root.xpath("HISTORY_RECORDS/HISTORY").each do |h| reason = h.xpath("REASON") reason.unlink if !reason.nil? uid = doc.create_element "UID", -1 gid = doc.create_element "GID", -1 rid = doc.create_element "REQUEST_ID", -1 h.add_child(uid) h.add_child(gid) h.add_child(rid) end row[:body] = doc.root.to_s @db[:vm_pool].insert(row) end end @db.run "DROP TABLE old_vm_pool;" end end
require 'set' # @start = "12345678900" # @fin = "02345678911" @start = "1234500" @fin = "0234510" @ptn = Set.new def p_pillar placement p "*"*30 p placement[0..(@p_len / 2 - 1)] p placement[3..(@p_len)] end def p_placements placements placements.each do |placement| p_pillar placement end end def p_placements2 placements placements.each do |placement| p placement[0..9] end end def solve start, fin before_placements_from_s = [] before_placements_from_f = [] found = false count = 0 @p_len = start[0].length - 1 @mid_u = (@p_len / 2) / 2 @mid_b = @mid_u + @p_len / 2 @half = @p_len / 2 p 'before' p_placements start # p_placements fin before_placements_from_s = start before_placements_from_f = fin while !found do next_placements_from_s = [] next_placements_from_f = [] before_placements_from_s.each do |placement| next_placements_from_s.concat (move_all placement) end next_placements_from_s.each do |placement| found = before_placements_from_f.any? do |p| # p "#{placement[0..@p_len -1]} #{p[0..@p_len -1]}" if count == 9 placement[0..(@p_len -1)] == p[0..(@p_len -1)] end end break if found before_placements_from_f.each do |placement| next_placements_from_f.concat (move_all placement) end count += 1 before_placements_from_s = next_placements_from_s before_placements_from_f = next_placements_from_f p "#{count}times after" p_placements next_placements_from_s # p_placements next_placements_from_f # target_s = before_placements_from_s.select{|plc| plc[@mid_u] == "0" || plc[@mid_b] == "0"} # target_f = before_placements_from_f.select{|plc| plc[@mid_u] == "0" || plc[@mid_b] == "0"} target_s = before_placements_from_s target_f = before_placements_from_f # p_placements target_s # p_placements target_f target_s.each do |placement| found = target_f.any? do |p| # p "s #{placement[0..9]}" # p "f #{p[0..9]}" # placement[0..9] == p[0..9] placement[0..(@p_len -1)] == p[0..(@p_len -1)] end end # p count # found = true if count == 3 # p_placements next_placements_from_s if count == 1 # p_placements @ptn if count == 1 # p "#{@ptn.length}" end return found ? count : -1*before_placements_from_s.length end def move placement, before, after p_dup = placement.dup tmp = p_dup[after] p_dup[after], p_dup[before] = p_dup[before], tmp p_dup[@p_len] = before.to_s p_dup end def move_all placement placements = [] now = placement.index("0") before = placement[@p_len].to_i # p "#{now}, #{@half}, #{before}" # p "#{now - @half - 1}" if now < @half if before != now + @half tmp = move placement, now, now + @half placements << tmp if @ptn.add? tmp end if before != now + @half + 1 && now < @half - 1 tmp = move placement, now, now + @half + 1 placements << tmp if @ptn.add? tmp end if before != now + @half - 1 && now > 0 tmp = move placement, now, now + @half - 1 placements << tmp if @ptn.add? tmp end else if before != now - @half tmp = move placement, now, now - @half placements << tmp if @ptn.add? tmp end if before != now - @half - 1 && now > @half tmp = move placement, now, now - @half - 1 placements << tmp if @ptn.add? tmp end if before != now - @half + 1 && now < @p_len -1 tmp = move placement, now, now - @half + 1 placements << tmp if @ptn.add? tmp end end placements end # in = STDIN.gets # if in.nil? # puts "Warning input not be nil" # exit 0 # end answer = solve [@start], [@fin] puts answer fix logic if true #5 require 'set' # @start = "12345678900" # @fin = "02345678910" @start = "1234500" @fin = "0234510" @ptn = Set.new def p_pillar placement p "*"*30 p placement[0..(@p_len / 2 - 1)] p placement[3..(@p_len)] end def p_placements placements placements.each do |placement| p_pillar placement end end def p_placements2 placements placements.each do |placement| p placement[0..9] end end def solve start, fin before_placements_from_s = [] before_placements_from_f = [] found = false count = 0 @p_len = start[0].length - 1 @mid_u = (@p_len / 2) / 2 @mid_b = @mid_u + @p_len / 2 @half = @p_len / 2 # p 'before' # p_placements start # p_placements fin before_placements_from_s = start before_placements_from_f = fin while !found do next_placements_from_s = [] next_placements_from_f = [] before_placements_from_s.each do |placement| next_placements_from_s.concat (move_all placement) end target_s = next_placements_from_s.select{|plc| plc[@mid_u] == "0" || plc[@mid_b] == "0"} target_s.each do |placement1| found = found || before_placements_from_f.any? do |placement2| # p "#{placement[0..@p_len -1]} #{p[0..@p_len -1]}" if count == 9 p_pillar "#{placement1}" if placement1[0..(@p_len -1)] == placement2[0..(@p_len -1)] p_pillar "#{placement2}" if placement1[0..(@p_len -1)] == placement2[0..(@p_len -1)] placement1[0..(@p_len -1)] == placement2[0..(@p_len -1)] end end break if found before_placements_from_f.each do |placement| next_placements_from_f.concat (move_all placement) end count += 1 before_placements_from_s = next_placements_from_s before_placements_from_f = next_placements_from_f # p "#{count}times after" # p_placements next_placements_from_s # p_placements next_placements_from_f target_s = before_placements_from_s.select{|plc| plc[@mid_u] == "0" || plc[@mid_b] == "0"} target_f = before_placements_from_f.select{|plc| plc[@mid_u] == "0" || plc[@mid_b] == "0"} target_s = before_placements_from_s target_f = before_placements_from_f # p_placements target_s # p_placements target_f target_s.each do |placement1| found = found || target_f.any? do |placement2| # p "s #{placement[0..9]}" # p "f #{p[0..9]}" # placement[0..9] == p[0..9] placement1[0..(@p_len -1)] == placement2[0..(@p_len -1)] end end p count # found = true if count == 3 # p_placements next_placements_from_s if count == 1 # p_placements @ptn if count == 1 # p "#{@ptn.length}" end return found ? count : -1*before_placements_from_s.length end def move placement, before, after p_dup = placement.dup tmp = p_dup[after] p_dup[after], p_dup[before] = p_dup[before], tmp p_dup[@p_len] = before.to_s p_dup end def move_all placement placements = [] now = placement.index("0") before = placement[@p_len].to_i # p "#{now}, #{@half}, #{before}" # p "#{now - @half - 1}" if now < @half if before != now + @half tmp = move placement, now, now + @half placements << tmp if @ptn.add? tmp end if before != now + @half + 1 && now < @half - 1 tmp = move placement, now, now + @half + 1 placements << tmp if @ptn.add? tmp end if before != now + @half - 1 && now > 0 tmp = move placement, now, now + @half - 1 placements << tmp if @ptn.add? tmp end else if before != now - @half tmp = move placement, now, now - @half placements << tmp if @ptn.add? tmp end if before != now - @half - 1 && now > @half tmp = move placement, now, now - @half - 1 placements << tmp if @ptn.add? tmp end if before != now - @half + 1 && now < @p_len -1 tmp = move placement, now, now - @half + 1 placements << tmp if @ptn.add? tmp end end placements end # in = STDIN.gets # if in.nil? # puts "Warning input not be nil" # exit 0 # end answer = solve [@start], [@fin] puts answer
register 'Store and output Cassyisms.' command 'cassy', 'Look up Cassy\'s definitions of terms. Syntax: RANDOM|ADD word definition|DELETE word' do argc! 1 p = @params.first first_word, second_word, remainder = p.split(/\s/, 3) if remainder.nil? first_word.upcase! if first_word == 'RANDOM' word = get_all_data.keys.sample fact = get_data word reply "\02#{word}\02 is: #{fact}" next end unless second_word.nil? second_word.upcase! if first_word == 'DELETE' unless get_data second_word raise 'No such Cassy fact.' end delete_data second_word reply "Definition for #{second_word} has been deleted." next end end else first_word.upcase! second_word.upcase! if first_word == 'ADD' if get_data second_word raise "Definition for #{second_word} already exists." end store_data second_word, remainder reply "Definition for #{second_word} has been stored." next end end fact = get_data p.upcase if fact.nil? reply 'No such Cassy fact.' next end reply fact end cassy: add list and stats command, change keys to lower-case (requires manual database change) register 'Store and output Cassyisms.' command 'cassy', 'Look up Cassy\'s definitions of terms. Syntax: word|RANDOM|ADD word definition|DELETE word|STATS|LIST' do argc! 1 p = @params.first first_word, second_word, remainder = p.split(/\s/, 3) if remainder.nil? first_word.upcase! if first_word == 'RANDOM' word = get_all_data.keys.sample fact = get_data word reply "\02#{word}\02 is: #{fact}" next elsif first_word == 'STATS' reply "There are \002#{get_all_data.length}\002 definitions in the databsae." next elsif first_word == 'LIST' reply get_all_data.keys.join ', ' next end unless second_word.nil? second_word.downcase! if first_word == 'DELETE' unless get_data second_word raise 'No such Cassy fact.' end delete_data second_word reply "Definition for #{second_word} has been deleted." next end end else first_word.upcase! second_word.downcase! if first_word == 'ADD' if get_data second_word raise "Definition for #{second_word} already exists." end store_data second_word, remainder reply "Definition for #{second_word} has been stored." next end end fact = get_data p.downcase if fact.nil? reply 'No such Cassy fact.' next end reply fact end
#!/usr/bin/env ruby # ----------------------------------------------------------------------------- # # File: cetus.rb # Description: Fast file navigation, a tiny version of zfm # Author: rkumar http://github.com/rkumar/cetus/ # Date: 2013-02-17 - 17:48 # License: GPL # Last update: 2013-02-27 15:49 # ----------------------------------------------------------------------------- # # cetus.rb Copyright (C) 2012-2013 rahul kumar # TODO - refresh should requery lines and cols and set pagesize # let user decide how many cols he wants to see require 'readline' require 'io/wait' # http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html require 'shellwords' # -- requires 1.9.3 for io/wait # -- cannot do with Highline since we need a timeout on wait, not sure if HL can do that ## INSTALLATION # copy into PATH # alias y=~/bin/cetus.rb # y VERSION="0.0.9-alpha" O_CONFIG=true CONFIG_FILE="~/.lyrainfo" $bindings = {} $bindings = { "`" => "main_menu", "=" => "toggle_menu", "!" => "command_mode", "@" => "selection_mode_toggle", "M-a" => "select_all", "M-A" => "unselect_all", "," => "goto_parent_dir", "+" => "goto_dir", "." => "pop_dir", ":" => "subcommand", "'" => "goto_bookmark", "/" => "enter_regex", "M-p" => "prev_page", "M-n" => "next_page", "SPACE" => "next_page", "M-f" => "select_visited_files", "M-d" => "select_used_dirs", "M-b" => "select_bookmarks", "M-m" => "create_bookmark", "M-M" => "show_marks", "C-c" => "escape", "ESCAPE" => "escape", "TAB" => "views", "C-i" => "views", "?" => "child_dirs", "ENTER" => "select_first", "D" => "delete_file", "Q" => "quit_command", "RIGHT" => "column_next", "LEFT" => "column_next 1", "M-?" => "print_help", "F1" => "print_help", "F2" => "child_dirs" } ## clean this up a bit, copied from shell program and macro'd $kh=Hash.new $kh["OP"]="F1" $kh[""]="UP" $kh["[5~"]="PGUP" $kh['']="ESCAPE" KEY_PGDN="[6~" KEY_PGUP="[5~" ## I needed to replace the O with a [ for this to work # in Vim Home comes as ^[OH whereas on the command line it is correct as ^[[H KEY_HOME='' KEY_END="" KEY_F1="OP" KEY_UP="" KEY_DOWN="" $kh[KEY_PGDN]="PgDn" $kh[KEY_PGUP]="PgUp" $kh[KEY_HOME]="Home" $kh[KEY_END]="End" $kh[KEY_F1]="F1" $kh[KEY_UP]="UP" $kh[KEY_DOWN]="DOWN" KEY_LEFT='' KEY_RIGHT='' $kh["OQ"]="F2" $kh["OR"]="F3" $kh["OS"]="F4" $kh[KEY_LEFT] = "LEFT" $kh[KEY_RIGHT]= "RIGHT" KEY_F5='[15~' KEY_F6='[17~' KEY_F7='[18~' KEY_F8='[19~' KEY_F9='[20~' KEY_F10='[21~' $kh[KEY_F5]="F5" $kh[KEY_F6]="F6" $kh[KEY_F7]="F7" $kh[KEY_F8]="F8" $kh[KEY_F9]="F9" $kh[KEY_F10]="F10" ## get a character from user and return as a string # Adapted from: #http://stackoverflow.com/questions/174933/how-to-get-a-single-character-without-pressing-enter/8274275#8274275 # Need to take complex keys and matc against a hash. def get_char begin system("stty raw -echo 2>/dev/null") # turn raw input on c = nil #if $stdin.ready? c = $stdin.getc cn=c.ord return "ENTER" if cn == 10 || cn == 13 return "BACKSPACE" if cn == 127 return "C-SPACE" if cn == 0 return "SPACE" if cn == 32 # next does not seem to work, you need to bind C-i return "TAB" if cn == 8 if cn >= 0 && cn < 27 x= cn + 96 return "C-#{x.chr}" end if c == '' buff=c.chr while true k = nil if $stdin.ready? k = $stdin.getc #puts "got #{k}" buff += k.chr else x=$kh[buff] return x if x #puts "returning with #{buff}" if buff.size == 2 ## possibly a meta/alt char k = buff[-1] return "M-#{k.chr}" end return buff end end end #end return c.chr if c ensure #system "stty -raw echo" # turn raw input off system("stty -raw echo 2>/dev/null") # turn raw input on end end #$IDX="123456789abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" #$IDX="abcdefghijklmnopqrstuvwxy" $IDX=('a'..'y').to_a $IDX.concat ('za'..'zz').to_a $IDX.concat ('Za'..'Zz').to_a $IDX.concat ('ZA'..'ZZ').to_a $selected_files = Array.new $bookmarks = {} $mode = nil $glines=%x(tput lines).to_i $gcols=%x(tput cols).to_i $grows = $glines - 3 $pagesize = 60 $gviscols = 3 $pagesize = $grows * $gviscols $stact = 0 GMARK='*' CLEAR = "\e[0m" BOLD = "\e[1m" BOLD_OFF = "\e[22m" RED = "\e[31m" GREEN = "\e[32m" YELLOW = "\e[33m" BLUE = "\e[34m" REVERSE = "\e[7m" $patt=nil $ignorecase = true $quitting = false $modified = $writing = false $visited_files = [] ## dir stack for popping $visited_dirs = [] ## dirs where some work has been done, for saving and restoring $used_dirs = [] $sorto = nil $viewctr = 0 $history = [] #$help = "#{BOLD}1-9a-zA-Z#{BOLD_OFF} Select #{BOLD}/#{BOLD_OFF} Grep #{BOLD}'#{BOLD_OFF} First char #{BOLD}M-n/p#{BOLD_OFF} Paging #{BOLD}!#{BOLD_OFF} Command Mode #{BOLD}@#{BOLD_OFF} Selection Mode #{BOLD}q#{BOLD_OFF} Quit" $help = "#{BOLD}M-?#{BOLD_OFF} Help #{BOLD}`#{BOLD_OFF} Menu #{BOLD}!#{BOLD_OFF} Command #{BOLD}=#{BOLD_OFF} Toggle #{BOLD}@#{BOLD_OFF} Selection Mode #{BOLD}Q#{BOLD_OFF} Quit " ## main loop which calls all other programs def run() ctr=0 config_read $files = `zsh -c 'print -rl -- *(#{$hidden}M)'`.split("\n") fl=$files.size selectedix = nil $patt="" $sta=0 while true i = 0 if $patt if $ignorecase $view = $files.grep(/#{$patt}/i) else $view = $files.grep(/#{$patt}/) end else $view = $files end fl=$view.size $sta = 0 if $sta >= fl || $sta < 0 $viewport = $view[$sta, $pagesize] fin = $sta + $viewport.size $title ||= Dir.pwd system("clear") # title print "#{GREEN}#{$help} #{BLUE}cetus #{VERSION}#{CLEAR}\n" print "#{BOLD}#{$title} #{$sta + 1} to #{fin} of #{fl} #{$sorto}#{CLEAR}\n" $title = nil # split into 2 procedures so columnate can e clean and reused. buff = format $viewport buff = columnate buff, $grows # needed the next line to see how much extra we were going in padding #buff.each {|line| print "#{REVERSE}#{line}#{CLEAR}\n" } buff.each {|line| print line, "\n" } print # prompt #print "#{$files.size}, #{view.size} sta=#{sta} (#{patt}): " _mm = "" _mm = "[#{$mode}] " if $mode print "\r#{_mm}#{$patt} >" ch = get_char #puts #break if ch == "q" #elsif ch =~ /^[1-9a-zA-Z]$/ if ch =~ /^[a-zZ]$/ # hint mode select_hint $viewport, ch ctr = 0 elsif ch == "BACKSPACE" $patt = $patt[0..-2] ctr = 0 else #binding = $bindings[ch] x = $bindings[ch] x = x.split if x if x binding = x.shift args = x send(binding, *args) if binding else #perror "No binding for #{ch}" end #p ch end break if $quitting end puts "bye" config_write if $writing end ## code related to long listing of files GIGA_SIZE = 1073741824.0 MEGA_SIZE = 1048576.0 KILO_SIZE = 1024.0 # Return the file size with a readable style. def readable_file_size(size, precision) case #when size == 1 : "1 B" when size < KILO_SIZE then "%d B" % size when size < MEGA_SIZE then "%.#{precision}f K" % (size / KILO_SIZE) when size < GIGA_SIZE then "%.#{precision}f M" % (size / MEGA_SIZE) else "%.#{precision}f G" % (size / GIGA_SIZE) end end ## format date for file given stat def date_format t t.strftime "%Y/%m/%d" end ## # # print in columns # ary - array of data # sz - lines in one column # def columnate ary, sz buff=Array.new return buff if ary.nil? || ary.size == 0 # determine width based on number of files to show # if less than sz then 1 col and full width # wid = 30 ars = ary.size ars = [$pagesize, ary.size].min d = 0 if ars <= sz wid = $gcols - d else tmp = (ars * 1.000/ sz).ceil wid = $gcols / tmp - d end #elsif ars < sz * 2 #wid = $gcols/2 - d #elsif ars < sz * 3 #wid = $gcols/3 - d #else #wid = $gcols/$gviscols - d #end # ix refers to the index in the complete file list, wherease we only show 60 at a time ix=0 while true ## ctr refers to the index in the column ctr=0 while ctr < sz f = ary[ix] if f.size > wid f = f[0, wid-2]+"$ " else f = f.ljust(wid) end if buff[ctr] buff[ctr] += f else buff[ctr] = f end ctr+=1 ix+=1 break if ix >= ary.size end break if ix >= ary.size end return buff end ## formats the data with number, mark and details def format ary #buff = Array.new buff = Array.new(ary.size) return buff if ary.nil? || ary.size == 0 # determine width based on number of files to show # if less than sz then 1 col and full width # # ix refers to the index in the complete file list, wherease we only show 60 at a time ix=0 ctr=0 ary.each do |f| ## ctr refers to the index in the column ind = get_shortcut(ix) mark=" " mark="#{GMARK} " if $selected_files.index(ary[ix]) if $long_listing begin unless File.exist? f last = f[-1] if last == " " || last == "@" || last == '*' stat = File.stat(f.chop) end else stat = File.stat(f) end f = "%10s %s %s" % [readable_file_size(stat.size,1), date_format(stat.mtime), f] rescue Exception => e f = "%10s %s %s" % ["?", "??????????", f] end end s = "#{ind}#{mark}#{f}" buff[ctr] = s ctr+=1 ix+=1 end return buff end ## select file based on key pressed def select_hint view, ch # a to y is direct # if x or z take a key IF there are those many # ix = get_index(ch, view.size) if ix f = view[ix] return unless f if $mode == 'SEL' toggle_select f elsif $mode == 'COM' run_command f else open_file f end #selectedix=ix end end ## toggle selection state of file def toggle_select f if $selected_files.index f $selected_files.delete f else $selected_files.push f end end ## open file or directory def open_file f return unless f unless File.exist? f # this happens if we use (T) in place of (M) # it places a space after normal files and @ and * which borks commands last = f[-1] if last == " " || last == "@" || last == '*' f = f.chop end end if File.directory? f change_dir f elsif File.readable? f system("$EDITOR #{Shellwords.escape(f)}") f = Dir.pwd + "/" + f if f[0] != '/' $visited_files.insert(0, f) push_used_dirs Dir.pwd else perror "open_file: (#{f}) not found" # could check home dir or CDPATH env variable DO end end ## run command on given file/s # Accepts command from user # After putting readline in place of gets, pressing a C-c has a delayed effect. It goes intot # exception bloack after executing other commands and still does not do the return ! def run_command f files=nil case f when Array # escape the contents and create a string files = Shellwords.join(f) when String files = Shellwords.escape(f) end print "Run a command on #{files}: " begin #Readline::HISTORY.push(*values) command = Readline::readline('>', true) #command = gets().chomp return if command.size == 0 print "Second part of command: " #command2 = gets().chomp command2 = Readline::readline('>', true) puts "#{command} #{files} #{command2}" system "#{command} #{files} #{command2}" rescue Exception => ex perror "Canceled command, press a key" return end begin rescue Exception => ex end refresh puts "Press a key ..." push_used_dirs Dir.pwd get_char end def change_dir f $visited_dirs.insert(0, Dir.pwd) f = File.expand_path(f) Dir.chdir f $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") $sta = 0 $patt=nil screen_settings end ## clear sort order and refresh listing, used typically if you are in some view # such as visited dirs or files def escape $sorto = nil $viewctr = 0 refresh end ## refresh listing after some change like option change, or toggle def refresh # get tput cols and lines and recalc ROWS and pagesize TODO $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") $patt=nil end # ## unselect all files def unselect_all $selected_files = [] end ## select all files def select_all $selected_files = $view.dup end ## accept dir to goto and change to that ( can be a file too) def goto_dir print "Enter path: " begin path = gets.chomp #rescue => ex rescue Exception => ex perror "Cancelled cd, press a key" return end f = File.expand_path(path) unless File.directory? f ## check for env variable tmp = ENV[path] if tmp.nil? || !File.directory?( tmp ) ## check for dir in home tmp = File.expand_path("~/#{path}") if File.directory? tmp f = tmp end else f = tmp end end open_file f end ## toggle mode to selection or not # In selection, pressed hotkey selects a file without opening, one can keep selecting # (or deselecting). # def selection_mode_toggle if $mode == 'SEL' # we seem to be coming out of select mode with some files if $selected_files.size > 0 run_command $selected_files end $mode = nil else #$selection_mode = !$selection_mode $mode = 'SEL' end end ## toggle command mode def command_mode if $mode == 'COM' $mode = nil return end $mode = 'COM' end def goto_parent_dir change_dir ".." end def goto_entry_starting_with fc=nil unless fc print "Entries starting with: " fc = get_char end return if fc.size != 1 $patt = "^#{fc}" ctr = 0 end def goto_bookmark ch=nil unless ch print "Enter bookmark char: " ch = get_char end if ch =~ /^[A-Z]$/ d = $bookmarks[ch] # this is if we use zfm's bookmarks which have a position # this way we leave the position as is, so it gets written back if d if d.index(":") ix = d.index(":") d = d[0,ix] end change_dir d else perror "#{ch} not a bookmark" end else goto_entry_starting_with ch end end ## take regex from user, to run on files on screen, user can filter file names def enter_regex print "Enter pattern: " $patt = gets $patt.chomp! ctr = 0 end def next_page $sta += $pagesize end def prev_page $sta -= $pagesize end def print_help system("clear") puts "HELP" puts puts "To open a file or dir press 1-9 a-z A-Z " puts "Command Mode: Will prompt for a command to run on a file, after selecting using hotkey" puts "Selection Mode: Each selection adds to selection list (toggles)" puts " Upon exiting mode, user is prompted for a command to run on selected files" puts ary = [] $bindings.each_pair { |k, v| ary.push "#{k.ljust(7)} => #{v}" } ary = columnate ary, $grows - 7 ary.each {|line| print line, "\n" } get_char end def show_marks puts puts "Bookmarks: " $bookmarks.each_pair { |k, v| puts "#{k.ljust(7)} => #{v}" } puts print "Enter bookmark to goto: " ch = get_char goto_bookmark(ch) if ch =~ /^[A-Z]$/ end def main_menu h = { "s" => "sort_menu", "f" => "filter_menu", "c" => "command_menu" , "x" => "extras"} menu "Main Menu", h end def toggle_menu h = { "h" => "toggle_hidden", "c" => "toggle_case", "l" => "toggle_long_list" , "1" => "toggle_columns"} menu "Toggle Menu", h end def menu title, h return unless h pbold "#{title}" h.each_pair { |k, v| puts "#{k}: #{v}" } ch = get_char binding = h[ch] if binding if respond_to?(binding, true) send(binding) end end return ch, binding end def toggle_menu h = { "h" => "toggle_hidden", "c" => "toggle_case", "l" => "toggle_long_list" , "1" => "toggle_columns"} ch, menu_text = menu "Toggle Menu", h case menu_text when "toggle_hidden" $hidden = $hidden ? nil : "D" refresh when "toggle_case" #$ignorecase = $ignorecase ? "" : "i" $ignorecase = !$ignorecase refresh when "toggle_columns" $gviscols = 3 if $gviscols == 1 #$long_listing = false if $gviscols > 1 x = $grows * $gviscols $pagesize = $pagesize==x ? $grows : x when "toggle_long_list" $long_listing = !$long_listing if $long_listing $gviscols = 1 $pagesize = $grows else x = $grows * $gviscols $pagesize = $pagesize==x ? $grows : x end refresh end end def sort_menu lo = nil h = { "n" => "newest", "a" => "accessed", "o" => "oldest", "l" => "largest", "s" => "smallest" , "m" => "name" , "r" => "rname", "d" => "dirs", "c" => "clear" } ch, menu_text = menu "Sort Menu", h case menu_text when "newest" lo="om" when "accessed" lo="oa" when "oldest" lo="Om" when "largest" lo="OL" when "smallest" lo="oL" when "name" lo="on" when "rname" lo="On" when "dirs" lo="/" when "clear" lo="" end $sorto = lo ## This needs to persist and be a part of all listings, put in change_dir. $files = `zsh -c 'print -rl -- *(#{lo}#{$hidden}M)'`.split("\n") if lo #$files =$(eval "print -rl -- ${pattern}(${MFM_LISTORDER}$filterstr)") end def command_menu ## # since these involve full paths, we need more space, like only one column # ## in these cases, getting back to the earlier dir, back to earlier listing # since we've basically overlaid the old listing # # should be able to sort THIS listing and not rerun command. But for that I'd need to use # xargs ls -t etc rather than the zsh sort order. But we can run a filter using |. # h = { "a" => "ack", "f" => "ffind", "l" => "locate", "t" => "today" } ch, menu_text = menu "Command Menu", h case menu_text when "ack" print "Enter a pattern to search: " pattern = gets.chomp $files = `ack -l #{pattern}`.split("\n") when "ffind" print "Enter a pattern to find: " pattern = gets.chomp $files = `find . -name #{pattern}`.split("\n") when "locate" print "Enter a pattern to locate: " pattern = gets.chomp $files = `locate #{pattern}`.split("\n") when "today" $files = `zsh -c 'print -rl -- *(#{$hidden}Mm0)'`.split("\n") end end def extras h = { "1" => "one_column", "2" => "multi_column", "c" => "columns", "r" => "config_read" , "w" => "config_write"} ch, menu_text = menu "Extras Menu", h case menu_text when "one_column" $pagesize = $grows when "multi_column" $pagesize = 60 $pagesize = $grows * $gviscols when "columns" print "How many columns would you like: 1-6 ?" ch = get_char ch = ch.to_i if ch > 0 && ch < 7 $gviscols = ch.to_i $pagesize = $grows * $gviscols end end end def filter_menu h = { "d" => "dirs", "f" => "files", "e" => "empty dirs" , "0" => "empty files"} ch, menu_text = menu "Filter Menu", h case menu_text when "dirs" $files = `zsh -c 'print -rl -- *(#{$sorto}/M)'`.split("\n") when "files" $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}.)'`.split("\n") when "empty dirs" $files = `zsh -c 'print -rl -- *(#{$sorto}/D^F)'`.split("\n") when "empty files" $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}.L0)'`.split("\n") end end def select_used_dirs $title = "Used Directories" $files = $used_dirs.uniq end def select_visited_files # not yet a unique list, needs to be unique and have latest pushed to top $title = "Visited Files" $files = $visited_files.uniq end def select_bookmarks $title = "Bookmarks" $files = $bookmarks.values end ## part copied and changed from change_dir since we don't dir going back on top # or we'll be stuck in a cycle def pop_dir # the first time we pop, we need to put the current on stack if !$visited_dirs.index(Dir.pwd) $visited_dirs.push Dir.pwd end ## XXX make sure thre is something to pop d = $visited_dirs.delete_at 0 ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise $visited_dirs.push d Dir.chdir d $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") $patt=nil end # ## read dirs and files and bookmarks from file def config_read #f = File.expand_path("~/.zfminfo") f = File.expand_path(CONFIG_FILE) if File.readable? f load f # maybe we should check for these existing else crash will happen. $used_dirs.push(*(DIRS.split ":")) $visited_files.push(*(FILES.split ":")) #$bookmarks.push(*bookmarks) if bookmarks chars = ('A'..'Z') chars.each do |ch| if Kernel.const_defined? "BM_#{ch}" $bookmarks[ch] = Kernel.const_get "BM_#{ch}" end end end end ## save dirs and files and bookmarks to a file def config_write # Putting it in a format that zfm can also read and write #f1 = File.expand_path("~/.zfminfo") f1 = File.expand_path(CONFIG_FILE) d = $used_dirs.join ":" f = $visited_files.join ":" File.open(f1, 'w+') do |f2| # use "\n" for two lines of text f2.puts "DIRS=\"#{d}\"" f2.puts "FILES=\"#{f}\"" $bookmarks.each_pair { |k, val| f2.puts "BM_#{k}=\"#{val}\"" #f2.puts "BOOKMARKS[\"#{k}\"]=\"#{val}\"" } end $writing = $modified = false end ## accept a character to save this dir as a bookmark def create_bookmark print "Enter (upper case) char for bookmark: " ch = get_char if ch =~ /^[A-Z]$/ $bookmarks[ch] = Dir.pwd $modified = true else perror "Bookmark must be upper-case character" end end def subcommand print "Enter command: " begin command = gets().chomp rescue Exception => ex return end if command == "q" if $modified print "Do you want to save bookmarks? (y/n): " ch = get_char if ch == "y" $writing = true $quitting = true elsif ch == "n" $quitting = true print "Quitting without saving bookmarks" else perror "No action taken." end else $quitting = true end elsif command == "wq" $quitting = true $writing = true elsif command == "x" $quitting = true $writing = true if $modified elsif command == "p" system "echo $PWD | pbcopy" puts "Stored PWD in clipboard (using pbcopy)" end end def quit_command if $modified puts "Press w to save bookmarks before quitting " if $modified print "Press another q to quit " ch = get_char else $quitting = true end $quitting = true if ch == "q" $quitting = $writing = true if ch == "w" end def views views=%w[/ om oa Om OL oL On on] viewlabels=%w[Dirs Newest Accessed Oldest Largest Smallest Reverse Name] $sorto = views[$viewctr] $viewctr += 1 $viewctr = 0 if $viewctr > views.size $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") end def child_dirs $files = `zsh -c 'print -rl -- *(/#{$sorto}#{$hidden}M)'`.split("\n") end def select_first ## vp is local there, so i can do $vp[0] open_file $view[$sta] if $view[$sta] end ## create a list of dirs in which some action has happened, for saving def push_used_dirs d=Dir.pwd $used_dirs.index(d) || $used_dirs.push(d) end def pbold text puts "#{BOLD}#{text}#{BOLD_OFF}" end def perror text puts "#{RED}#{text}#{CLEAR}" get_char end ## return shortcut for an index (offset in file array) # use 2 more arrays to make this faster # TODO key needs to convert back to actual index # if z or x take another key if there are those many in view # Also, display ROWS * COLS so now we are not limited to 60. def get_shortcut ix return "<" if ix < $stact ix -= $stact i = $IDX[ix] return i if i #sz = $IDX.size #dif = ix - sz #if dif < 26 #dif += 97 #return "z#{dif.chr}" #elsif dif < 52 #dif += 97 - 26 #return "Z#{dif.chr}" #elsif dif < 78 #dif += 65 - 52 #return "Z#{dif.chr}" #end return "->" end ## returns the integer offset in view (file array based on a-y za-zz and Za - Zz # Called when user types a key # should we even ask for a second key if there are not enough rows # What if we want to also trap z with numbers for other purposes def get_index key, vsz=999 i = $IDX.index(key) return i+$stact if i #sz = $IDX.size zch = nil if vsz > 25 if key == "z" || key == "Z" print key zch = get_char print zch i = $IDX.index("#{key}#{zch}") return i+$stact if i end end return nil if vsz > sz if key == "z" print "z" zch = get_char if zch =~ /^[a-z]$/ ko = sz + (zch.ord - 97) return ko + $stact #key = "#{key}#{zch}" end end end if vsz > sz + 26 if key == "Z" print "Z" zch = get_char if zch =~ /^[a-z]$/ ko = sz + 26 + (zch.ord - 97) return ko + $stact elsif zch =~ /^[A-Z]$/ ko = sz + 52 + (zch.ord - "A".ord) return ko + $stact end end end return nil end def delete_file print "DELETE :: Enter file shortcut: " file = ask_hint perror "Cancelled" unless file return unless file if File.exists? file pbold "rmtrash #{file}" system "rmtrash #{file}" refresh end end def ask_hint ch = get_char ix = get_index(ch, $viewport.size) f = $viewport[ix] return f end def screen_settings $glines=%x(tput lines).to_i $gcols=%x(tput cols).to_i $grows = $glines - 3 $pagesize = 60 #$gviscols = 3 $pagesize = $grows * $gviscols $stact = 0 end ## moves column offset so we can reach unindexed columns or entries def column_next dir=0 if dir == 0 $stact += $grows $stact = 0 if $stact >= $viewport.size else $stact -= $grows $stact = 0 if $stact < 0 end end run if __FILE__ == $PROGRAM_NAME various enhancements #!/usr/bin/env ruby # ----------------------------------------------------------------------------- # # File: cetus.rb # Description: Fast file navigation, a tiny version of zfm # Author: rkumar http://github.com/rkumar/cetus/ # Date: 2013-02-17 - 17:48 # License: GPL # Last update: 2013-02-28 01:49 # ----------------------------------------------------------------------------- # # cetus.rb Copyright (C) 2012-2013 rahul kumar # TODO - refresh should requery lines and cols and set pagesize # let user decide how many cols he wants to see require 'readline' require 'io/wait' # http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html require 'shellwords' require 'fileutils' # -- requires 1.9.3 for io/wait # -- cannot do with Highline since we need a timeout on wait, not sure if HL can do that ## INSTALLATION # copy into PATH # alias y=~/bin/cetus.rb # y VERSION="0.0.9-alpha" O_CONFIG=true CONFIG_FILE="~/.lyrainfo" $bindings = {} $bindings = { "`" => "main_menu", "=" => "toggle_menu", "!" => "command_mode", "@" => "selection_mode_toggle", "M-a" => "select_all", "M-A" => "unselect_all", "," => "goto_parent_dir", "+" => "goto_dir", "." => "pop_dir", ":" => "subcommand", "'" => "goto_bookmark", "/" => "enter_regex", "M-p" => "prev_page", "M-n" => "next_page", "SPACE" => "next_page", "M-f" => "select_visited_files", "M-d" => "select_used_dirs", "M-b" => "select_bookmarks", "M-m" => "create_bookmark", "M-M" => "show_marks", "C-c" => "escape", "ESCAPE" => "escape", "TAB" => "views", "C-i" => "views", "?" => "child_dirs", "ENTER" => "select_first", "D" => "delete_file", "Q" => "quit_command", "RIGHT" => "column_next", "LEFT" => "column_next 1", "C-x" => "file_actions", "M--" => "columns_incdec -1", "M-+" => "columns_incdec 1", "S" => "command_file list y ls -lh", "L" => "command_file Page n less", "M-?" => "print_help", "F1" => "print_help", "F2" => "child_dirs" } ## clean this up a bit, copied from shell program and macro'd $kh=Hash.new $kh["OP"]="F1" $kh[""]="UP" $kh["[5~"]="PGUP" $kh['']="ESCAPE" KEY_PGDN="[6~" KEY_PGUP="[5~" ## I needed to replace the O with a [ for this to work # in Vim Home comes as ^[OH whereas on the command line it is correct as ^[[H KEY_HOME='' KEY_END="" KEY_F1="OP" KEY_UP="" KEY_DOWN="" $kh[KEY_PGDN]="PgDn" $kh[KEY_PGUP]="PgUp" $kh[KEY_HOME]="Home" $kh[KEY_END]="End" $kh[KEY_F1]="F1" $kh[KEY_UP]="UP" $kh[KEY_DOWN]="DOWN" KEY_LEFT='' KEY_RIGHT='' $kh["OQ"]="F2" $kh["OR"]="F3" $kh["OS"]="F4" $kh[KEY_LEFT] = "LEFT" $kh[KEY_RIGHT]= "RIGHT" KEY_F5='[15~' KEY_F6='[17~' KEY_F7='[18~' KEY_F8='[19~' KEY_F9='[20~' KEY_F10='[21~' $kh[KEY_F5]="F5" $kh[KEY_F6]="F6" $kh[KEY_F7]="F7" $kh[KEY_F8]="F8" $kh[KEY_F9]="F9" $kh[KEY_F10]="F10" ## get a character from user and return as a string # Adapted from: #http://stackoverflow.com/questions/174933/how-to-get-a-single-character-without-pressing-enter/8274275#8274275 # Need to take complex keys and matc against a hash. def get_char begin system("stty raw -echo 2>/dev/null") # turn raw input on c = nil #if $stdin.ready? c = $stdin.getc cn=c.ord return "ENTER" if cn == 10 || cn == 13 return "BACKSPACE" if cn == 127 return "C-SPACE" if cn == 0 return "SPACE" if cn == 32 # next does not seem to work, you need to bind C-i return "TAB" if cn == 8 if cn >= 0 && cn < 27 x= cn + 96 return "C-#{x.chr}" end if c == '' buff=c.chr while true k = nil if $stdin.ready? k = $stdin.getc #puts "got #{k}" buff += k.chr else x=$kh[buff] return x if x #puts "returning with #{buff}" if buff.size == 2 ## possibly a meta/alt char k = buff[-1] return "M-#{k.chr}" end return buff end end end #end return c.chr if c ensure #system "stty -raw echo" # turn raw input off system("stty -raw echo 2>/dev/null") # turn raw input on end end #$IDX="123456789abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" #$IDX="abcdefghijklmnopqrstuvwxy" $IDX=('a'..'y').to_a $IDX.concat ('za'..'zz').to_a $IDX.concat ('Za'..'Zz').to_a $IDX.concat ('ZA'..'ZZ').to_a $selected_files = Array.new $bookmarks = {} $mode = nil $glines=%x(tput lines).to_i $gcols=%x(tput cols).to_i $grows = $glines - 3 $pagesize = 60 $gviscols = 3 $pagesize = $grows * $gviscols $stact = 0 GMARK='*' CLEAR = "\e[0m" BOLD = "\e[1m" BOLD_OFF = "\e[22m" RED = "\e[31m" GREEN = "\e[32m" YELLOW = "\e[33m" BLUE = "\e[34m" REVERSE = "\e[7m" $patt=nil $ignorecase = true $quitting = false $modified = $writing = false $visited_files = [] ## dir stack for popping $visited_dirs = [] ## dirs where some work has been done, for saving and restoring $used_dirs = [] $sorto = nil $viewctr = 0 $history = [] #$help = "#{BOLD}1-9a-zA-Z#{BOLD_OFF} Select #{BOLD}/#{BOLD_OFF} Grep #{BOLD}'#{BOLD_OFF} First char #{BOLD}M-n/p#{BOLD_OFF} Paging #{BOLD}!#{BOLD_OFF} Command Mode #{BOLD}@#{BOLD_OFF} Selection Mode #{BOLD}q#{BOLD_OFF} Quit" $help = "#{BOLD}M-?#{BOLD_OFF} Help #{BOLD}`#{BOLD_OFF} Menu #{BOLD}!#{BOLD_OFF} Command #{BOLD}=#{BOLD_OFF} Toggle #{BOLD}@#{BOLD_OFF} Selection Mode #{BOLD}Q#{BOLD_OFF} Quit " ## main loop which calls all other programs def run() ctr=0 config_read $files = `zsh -c 'print -rl -- *(#{$hidden}M)'`.split("\n") fl=$files.size selectedix = nil $patt="" $sta=0 while true i = 0 if $patt if $ignorecase $view = $files.grep(/#{$patt}/i) else $view = $files.grep(/#{$patt}/) end else $view = $files end fl=$view.size $sta = 0 if $sta >= fl || $sta < 0 $viewport = $view[$sta, $pagesize] fin = $sta + $viewport.size $title ||= Dir.pwd system("clear") # title print "#{GREEN}#{$help} #{BLUE}cetus #{VERSION}#{CLEAR}\n" print "#{BOLD}#{$title} #{$sta + 1} to #{fin} of #{fl} #{$sorto}#{CLEAR}\n" $title = nil # split into 2 procedures so columnate can e clean and reused. buff = format $viewport buff = columnate buff, $grows # needed the next line to see how much extra we were going in padding #buff.each {|line| print "#{REVERSE}#{line}#{CLEAR}\n" } buff.each {|line| print line, "\n" } print # prompt #print "#{$files.size}, #{view.size} sta=#{sta} (#{patt}): " _mm = "" _mm = "[#{$mode}] " if $mode print "\r#{_mm}#{$patt} >" ch = get_char #puts #break if ch == "q" #elsif ch =~ /^[1-9a-zA-Z]$/ if ch =~ /^[a-zZ]$/ # hint mode select_hint $viewport, ch ctr = 0 elsif ch == "BACKSPACE" $patt = $patt[0..-2] ctr = 0 else #binding = $bindings[ch] x = $bindings[ch] x = x.split if x if x binding = x.shift args = x send(binding, *args) if binding else #perror "No binding for #{ch}" end #p ch end break if $quitting end puts "bye" config_write if $writing end ## code related to long listing of files GIGA_SIZE = 1073741824.0 MEGA_SIZE = 1048576.0 KILO_SIZE = 1024.0 # Return the file size with a readable style. def readable_file_size(size, precision) case #when size == 1 : "1 B" when size < KILO_SIZE then "%d B" % size when size < MEGA_SIZE then "%.#{precision}f K" % (size / KILO_SIZE) when size < GIGA_SIZE then "%.#{precision}f M" % (size / MEGA_SIZE) else "%.#{precision}f G" % (size / GIGA_SIZE) end end ## format date for file given stat def date_format t t.strftime "%Y/%m/%d" end ## # # print in columns # ary - array of data # sz - lines in one column # def columnate ary, sz buff=Array.new return buff if ary.nil? || ary.size == 0 # determine width based on number of files to show # if less than sz then 1 col and full width # wid = 30 ars = ary.size ars = [$pagesize, ary.size].min d = 0 if ars <= sz wid = $gcols - d else tmp = (ars * 1.000/ sz).ceil wid = $gcols / tmp - d end #elsif ars < sz * 2 #wid = $gcols/2 - d #elsif ars < sz * 3 #wid = $gcols/3 - d #else #wid = $gcols/$gviscols - d #end # ix refers to the index in the complete file list, wherease we only show 60 at a time ix=0 while true ## ctr refers to the index in the column ctr=0 while ctr < sz f = ary[ix] if f.size > wid f = f[0, wid-2]+"$ " else f = f.ljust(wid) end if buff[ctr] buff[ctr] += f else buff[ctr] = f end ctr+=1 ix+=1 break if ix >= ary.size end break if ix >= ary.size end return buff end ## formats the data with number, mark and details def format ary #buff = Array.new buff = Array.new(ary.size) return buff if ary.nil? || ary.size == 0 # determine width based on number of files to show # if less than sz then 1 col and full width # # ix refers to the index in the complete file list, wherease we only show 60 at a time ix=0 ctr=0 ary.each do |f| ## ctr refers to the index in the column ind = get_shortcut(ix) mark=" " mark="#{GMARK} " if $selected_files.index(ary[ix]) if $long_listing begin unless File.exist? f last = f[-1] if last == " " || last == "@" || last == '*' stat = File.stat(f.chop) end else stat = File.stat(f) end f = "%10s %s %s" % [readable_file_size(stat.size,1), date_format(stat.mtime), f] rescue Exception => e f = "%10s %s %s" % ["?", "??????????", f] end end s = "#{ind}#{mark}#{f}" buff[ctr] = s ctr+=1 ix+=1 end return buff end ## select file based on key pressed def select_hint view, ch # a to y is direct # if x or z take a key IF there are those many # ix = get_index(ch, view.size) if ix f = view[ix] return unless f if $mode == 'SEL' toggle_select f elsif $mode == 'COM' run_command f else open_file f end #selectedix=ix end end ## toggle selection state of file def toggle_select f if $selected_files.index f $selected_files.delete f else $selected_files.push f end end ## open file or directory def open_file f return unless f unless File.exist? f # this happens if we use (T) in place of (M) # it places a space after normal files and @ and * which borks commands last = f[-1] if last == " " || last == "@" || last == '*' f = f.chop end end if File.directory? f change_dir f elsif File.readable? f $default_command ||= "$EDITOR" system("#{$default_command} #{Shellwords.escape(f)} #{$default_command2}") f = Dir.pwd + "/" + f if f[0] != '/' $visited_files.insert(0, f) push_used_dirs Dir.pwd else perror "open_file: (#{f}) not found" # could check home dir or CDPATH env variable DO end end ## run command on given file/s # Accepts command from user # After putting readline in place of gets, pressing a C-c has a delayed effect. It goes intot # exception bloack after executing other commands and still does not do the return ! def run_command f files=nil case f when Array # escape the contents and create a string files = Shellwords.join(f) when String files = Shellwords.escape(f) end print "Run a command on #{files}: " begin #Readline::HISTORY.push(*values) command = Readline::readline('>', true) #command = gets().chomp return if command.size == 0 print "Second part of command: " #command2 = gets().chomp command2 = Readline::readline('>', true) puts "#{command} #{files} #{command2}" system "#{command} #{files} #{command2}" rescue Exception => ex perror "Canceled command, press a key" return end begin rescue Exception => ex end refresh puts "Press a key ..." push_used_dirs Dir.pwd get_char end def change_dir f $visited_dirs.insert(0, Dir.pwd) f = File.expand_path(f) Dir.chdir f $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") $sta = 0 $patt=nil screen_settings end ## clear sort order and refresh listing, used typically if you are in some view # such as visited dirs or files def escape $sorto = nil $viewctr = 0 refresh end ## refresh listing after some change like option change, or toggle def refresh # get tput cols and lines and recalc ROWS and pagesize TODO $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") $patt=nil end # ## unselect all files def unselect_all $selected_files = [] end ## select all files def select_all $selected_files = $view.dup end ## accept dir to goto and change to that ( can be a file too) def goto_dir print "Enter path: " begin path = gets.chomp #rescue => ex rescue Exception => ex perror "Cancelled cd, press a key" return end f = File.expand_path(path) unless File.directory? f ## check for env variable tmp = ENV[path] if tmp.nil? || !File.directory?( tmp ) ## check for dir in home tmp = File.expand_path("~/#{path}") if File.directory? tmp f = tmp end else f = tmp end end open_file f end ## toggle mode to selection or not # In selection, pressed hotkey selects a file without opening, one can keep selecting # (or deselecting). # def selection_mode_toggle if $mode == 'SEL' # we seem to be coming out of select mode with some files if $selected_files.size > 0 run_command $selected_files end $mode = nil else #$selection_mode = !$selection_mode $mode = 'SEL' end end ## toggle command mode def command_mode if $mode == 'COM' $mode = nil return end $mode = 'COM' end def goto_parent_dir change_dir ".." end def goto_entry_starting_with fc=nil unless fc print "Entries starting with: " fc = get_char end return if fc.size != 1 $patt = "^#{fc}" ctr = 0 end def goto_bookmark ch=nil unless ch print "Enter bookmark char: " ch = get_char end if ch =~ /^[A-Z]$/ d = $bookmarks[ch] # this is if we use zfm's bookmarks which have a position # this way we leave the position as is, so it gets written back if d if d.index(":") ix = d.index(":") d = d[0,ix] end change_dir d else perror "#{ch} not a bookmark" end else goto_entry_starting_with ch end end ## take regex from user, to run on files on screen, user can filter file names def enter_regex print "Enter pattern: " $patt = gets $patt.chomp! ctr = 0 end def next_page $sta += $pagesize end def prev_page $sta -= $pagesize end def print_help system("clear") puts "HELP" puts puts "To open a file or dir press 1-9 a-z A-Z " puts "Command Mode: Will prompt for a command to run on a file, after selecting using hotkey" puts "Selection Mode: Each selection adds to selection list (toggles)" puts " Upon exiting mode, user is prompted for a command to run on selected files" puts ary = [] $bindings.each_pair { |k, v| ary.push "#{k.ljust(7)} => #{v}" } ary = columnate ary, $grows - 7 ary.each {|line| print line, "\n" } get_char end def show_marks puts puts "Bookmarks: " $bookmarks.each_pair { |k, v| puts "#{k.ljust(7)} => #{v}" } puts print "Enter bookmark to goto: " ch = get_char goto_bookmark(ch) if ch =~ /^[A-Z]$/ end # MENU MAIN def main_menu h = { "s" => "sort_menu", "f" => "filter_menu", "c" => "command_menu" , "B" => "bindkey", "x" => "extras"} menu "Main Menu", h end def toggle_menu h = { "h" => "toggle_hidden", "c" => "toggle_case", "l" => "toggle_long_list" , "1" => "toggle_columns"} menu "Toggle Menu", h end def menu title, h return unless h pbold "#{title}" h.each_pair { |k, v| puts "#{k}: #{v}" } ch = get_char binding = h[ch] if binding if respond_to?(binding, true) send(binding) end end return ch, binding end def toggle_menu h = { "h" => "toggle_hidden", "c" => "toggle_case", "l" => "toggle_long_list" , "1" => "toggle_columns"} ch, menu_text = menu "Toggle Menu", h case menu_text when "toggle_hidden" $hidden = $hidden ? nil : "D" refresh when "toggle_case" #$ignorecase = $ignorecase ? "" : "i" $ignorecase = !$ignorecase refresh when "toggle_columns" $gviscols = 3 if $gviscols == 1 #$long_listing = false if $gviscols > 1 x = $grows * $gviscols $pagesize = $pagesize==x ? $grows : x when "toggle_long_list" $long_listing = !$long_listing if $long_listing $gviscols = 1 $pagesize = $grows else x = $grows * $gviscols $pagesize = $pagesize==x ? $grows : x end refresh end end def sort_menu lo = nil h = { "n" => "newest", "a" => "accessed", "o" => "oldest", "l" => "largest", "s" => "smallest" , "m" => "name" , "r" => "rname", "d" => "dirs", "c" => "clear" } ch, menu_text = menu "Sort Menu", h case menu_text when "newest" lo="om" when "accessed" lo="oa" when "oldest" lo="Om" when "largest" lo="OL" when "smallest" lo="oL" when "name" lo="on" when "rname" lo="On" when "dirs" lo="/" when "clear" lo="" end $sorto = lo ## This needs to persist and be a part of all listings, put in change_dir. $files = `zsh -c 'print -rl -- *(#{lo}#{$hidden}M)'`.split("\n") if lo #$files =$(eval "print -rl -- ${pattern}(${MFM_LISTORDER}$filterstr)") end def command_menu ## # since these involve full paths, we need more space, like only one column # ## in these cases, getting back to the earlier dir, back to earlier listing # since we've basically overlaid the old listing # # should be able to sort THIS listing and not rerun command. But for that I'd need to use # xargs ls -t etc rather than the zsh sort order. But we can run a filter using |. # h = { "a" => "ack", "f" => "ffind", "l" => "locate", "t" => "today", "D" => "default_command" } ## TODO use readline for these ch, menu_text = menu "Command Menu", h case menu_text when "ack" print "Enter a pattern to search: " pattern = gets.chomp $files = `ack -l #{pattern}`.split("\n") when "ffind" print "Enter a pattern to find: " pattern = gets.chomp $files = `find . -name #{pattern}`.split("\n") when "locate" print "Enter a pattern to locate: " pattern = gets.chomp $files = `locate #{pattern}`.split("\n") when "today" $files = `zsh -c 'print -rl -- *(#{$hidden}Mm0)'`.split("\n") when "default_command" print "Selecting a file usually invokes $EDITOR, what command do you want to use repeatedly on selected files: " $default_command = gets().chomp if $default_command != "" print "Second part of command (maybe blank): " $default_command2 = gets().chomp else print "Cleared default command, will default to $EDITOR" $default_command2 = nil $default_command = nil end end end def extras h = { "1" => "one_column", "2" => "multi_column", "c" => "columns", "r" => "config_read" , "w" => "config_write"} ch, menu_text = menu "Extras Menu", h case menu_text when "one_column" $pagesize = $grows when "multi_column" #$pagesize = 60 $pagesize = $grows * $gviscols when "columns" print "How many columns to show: 1-6 [current #{$gviscols}]? " ch = get_char ch = ch.to_i if ch > 0 && ch < 7 $gviscols = ch.to_i $pagesize = $grows * $gviscols end end end def filter_menu h = { "d" => "dirs", "f" => "files", "e" => "empty dirs" , "0" => "empty files"} ch, menu_text = menu "Filter Menu", h case menu_text when "dirs" $files = `zsh -c 'print -rl -- *(#{$sorto}/M)'`.split("\n") when "files" $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}.)'`.split("\n") when "empty dirs" $files = `zsh -c 'print -rl -- *(#{$sorto}/D^F)'`.split("\n") when "empty files" $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}.L0)'`.split("\n") end end def select_used_dirs $title = "Used Directories" $files = $used_dirs.uniq end def select_visited_files # not yet a unique list, needs to be unique and have latest pushed to top $title = "Visited Files" $files = $visited_files.uniq end def select_bookmarks $title = "Bookmarks" $files = $bookmarks.values end ## part copied and changed from change_dir since we don't dir going back on top # or we'll be stuck in a cycle def pop_dir # the first time we pop, we need to put the current on stack if !$visited_dirs.index(Dir.pwd) $visited_dirs.push Dir.pwd end ## XXX make sure thre is something to pop d = $visited_dirs.delete_at 0 ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise $visited_dirs.push d Dir.chdir d $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") $patt=nil end # ## read dirs and files and bookmarks from file def config_read #f = File.expand_path("~/.zfminfo") f = File.expand_path(CONFIG_FILE) if File.readable? f load f # maybe we should check for these existing else crash will happen. $used_dirs.push(*(DIRS.split ":")) $visited_files.push(*(FILES.split ":")) #$bookmarks.push(*bookmarks) if bookmarks chars = ('A'..'Z') chars.each do |ch| if Kernel.const_defined? "BM_#{ch}" $bookmarks[ch] = Kernel.const_get "BM_#{ch}" end end end end ## save dirs and files and bookmarks to a file def config_write # Putting it in a format that zfm can also read and write #f1 = File.expand_path("~/.zfminfo") f1 = File.expand_path(CONFIG_FILE) d = $used_dirs.join ":" f = $visited_files.join ":" File.open(f1, 'w+') do |f2| # use "\n" for two lines of text f2.puts "DIRS=\"#{d}\"" f2.puts "FILES=\"#{f}\"" $bookmarks.each_pair { |k, val| f2.puts "BM_#{k}=\"#{val}\"" #f2.puts "BOOKMARKS[\"#{k}\"]=\"#{val}\"" } end $writing = $modified = false end ## accept a character to save this dir as a bookmark def create_bookmark print "Enter (upper case) char for bookmark: " ch = get_char if ch =~ /^[A-Z]$/ $bookmarks[ch] = Dir.pwd $modified = true else perror "Bookmark must be upper-case character" end end def subcommand print "Enter command: " begin command = gets().chomp rescue Exception => ex return end if command == "q" if $modified print "Do you want to save bookmarks? (y/n): " ch = get_char if ch == "y" $writing = true $quitting = true elsif ch == "n" $quitting = true print "Quitting without saving bookmarks" else perror "No action taken." end else $quitting = true end elsif command == "wq" $quitting = true $writing = true elsif command == "x" $quitting = true $writing = true if $modified elsif command == "p" system "echo $PWD | pbcopy" puts "Stored PWD in clipboard (using pbcopy)" end end def quit_command if $modified puts "Press w to save bookmarks before quitting " if $modified print "Press another q to quit " ch = get_char else $quitting = true end $quitting = true if ch == "q" $quitting = $writing = true if ch == "w" end def views views=%w[/ om oa Om OL oL On on] viewlabels=%w[Dirs Newest Accessed Oldest Largest Smallest Reverse Name] $sorto = views[$viewctr] $viewctr += 1 $viewctr = 0 if $viewctr > views.size $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split("\n") end def child_dirs $files = `zsh -c 'print -rl -- *(/#{$sorto}#{$hidden}M)'`.split("\n") end def select_first ## vp is local there, so i can do $vp[0] open_file $view[$sta] if $view[$sta] end ## create a list of dirs in which some action has happened, for saving def push_used_dirs d=Dir.pwd $used_dirs.index(d) || $used_dirs.push(d) end def pbold text puts "#{BOLD}#{text}#{BOLD_OFF}" end def perror text puts "#{RED}#{text}#{CLEAR}" get_char end def pause text=" Press a key ..." print text get_char end ## return shortcut for an index (offset in file array) # use 2 more arrays to make this faster # TODO key needs to convert back to actual index # if z or x take another key if there are those many in view # Also, display ROWS * COLS so now we are not limited to 60. def get_shortcut ix return "<" if ix < $stact ix -= $stact i = $IDX[ix] return i if i #sz = $IDX.size #dif = ix - sz #if dif < 26 #dif += 97 #return "z#{dif.chr}" #elsif dif < 52 #dif += 97 - 26 #return "Z#{dif.chr}" #elsif dif < 78 #dif += 65 - 52 #return "Z#{dif.chr}" #end return "->" end ## returns the integer offset in view (file array based on a-y za-zz and Za - Zz # Called when user types a key # should we even ask for a second key if there are not enough rows # What if we want to also trap z with numbers for other purposes def get_index key, vsz=999 i = $IDX.index(key) return i+$stact if i #sz = $IDX.size zch = nil if vsz > 25 if key == "z" || key == "Z" print key zch = get_char print zch i = $IDX.index("#{key}#{zch}") return i+$stact if i end end return nil if vsz > sz if key == "z" print "z" zch = get_char if zch =~ /^[a-z]$/ ko = sz + (zch.ord - 97) return ko + $stact #key = "#{key}#{zch}" end end end if vsz > sz + 26 if key == "Z" print "Z" zch = get_char if zch =~ /^[a-z]$/ ko = sz + 26 + (zch.ord - 97) return ko + $stact elsif zch =~ /^[A-Z]$/ ko = sz + 52 + (zch.ord - "A".ord) return ko + $stact end end end return nil end def delete_file print "DELETE :: Enter file shortcut: " file = ask_hint perror "Cancelled" unless file return unless file if File.exists? file pbold "rmtrash #{file}" system "rmtrash #{file}" refresh end end def command_file prompt, *command pauseyn = command.shift command = command.join " " print "#{prompt} :: Enter file shortcut: " file = ask_hint perror "Command Cancelled" unless file return unless file if File.exists? file file = Shellwords.escape(file) pbold "#{command} #{file} (#{pauseyn})" system "#{command} #{file}" pause if pauseyn == "y" refresh end end def ask_hint f = nil ch = get_char ix = get_index(ch, $viewport.size) f = $viewport[ix] if ix return f end def screen_settings $glines=%x(tput lines).to_i $gcols=%x(tput cols).to_i $grows = $glines - 3 $pagesize = 60 #$gviscols = 3 $pagesize = $grows * $gviscols $stact = 0 end ## moves column offset so we can reach unindexed columns or entries def column_next dir=0 if dir == 0 $stact += $grows $stact = 0 if $stact >= $viewport.size else $stact -= $grows $stact = 0 if $stact < 0 end end def file_actions sct = $selected_files.size file = nil if sct > 0 text = "#{sct} files" file = $selected_files else print "Choose a file: " file = ask_hint return unless file text = file end case file when Array # escape the contents and create a string files = Shellwords.join(file) when String files = Shellwords.escape(file) end h = { "d" => "delete", "m" => "move", "r" => "rename", "v" => ENV["EDITOR"] || "vim", "l" => "less", "s" => "most" , "f" => "file" , "o" => "open", "x" => "dtrx", "z" => "zip" } ch, menu_text = menu "File Menu for #{text}", h case ch when "q" when "d" print "rmtrash #{files}" ch = get_char return if ch == "n" system "rmtrash #{files}" refresh when "m" print "move #{text} to : " target = gets().chomp if target FileUtils.mv text, target refresh else perror "Cancelled move" end when "z" print "Archive name: " target = gets().chomp # don't want a blank space or something screwing up if target && target.size > 3 if File.exists? target perror "Target (#{target}) exists" else system "tar zcvf #{target} #{files}" refresh end end else return unless menu_text print "#{menu_text} #{files}" pause print system "#{menu_text} #{files}" refresh pause end end def columns_incdec howmany $gviscols += howmany.to_i $gviscols = 1 if $gviscols < 1 $gviscols = 6 if $gviscols > 6 $pagesize = $grows * $gviscols end def bindkey print pbold "Bind a capital letter to a external command" print "Enter a capital letter to bind: " ch = get_char return if ch == "Q" if ch =~ /^[A-Z]$/ print "Enter an external command to bind to #{ch}: " com = gets().chomp if com != "" print "Enter prompt for command (blank if same as command): " pro = gets().chomp pro = com if pro == "" end print "Pause after output [y/n]: " yn = get_char $bindings[ch] = "command_file #{pro} #{yn} #{com}" end end run if __FILE__ == $PROGRAM_NAME
#!/usr/bin/env ruby require "httpclient" require "json" require_relative "config" require_relative "myfunc" require_relative "mylogger" #################################### # blockchain # # TODO write a class/function to communicate with rpc server def chain_post (data:{}) $LOG.debug (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if data.nil? or data.empty? return end client = HTTPClient.new client.connect_timeout=5 client.receive_timeout=5 myconfig = my_chain_config uri = myconfig["uri"] user = myconfig["user"] pass = myconfig["pass"] client.set_auth uri, user, pass begin response = client.post uri, data.to_json, nil #$LOG.debug (method(__method__).name) { response } response_content = response.content $LOG.debug (method(__method__).name) { {"response_content" => response_content} } response_json = JSON.parse response_content if not response_json["error"].nil? #$LOG.debug (method(__method__).name) { response_json["error"] } #response_content = response.body end return response_json rescue Exception => e print "chain_post error: " puts e end end # params is an array def chain_command (command:nil, params:nil) $LOG.debug (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if command.nil? or params.nil? return end #request_data= '{"jsonrpc": "2.0", "method": "blockchain_get_asset", "params":["'+quote.upcase+'"], "id":1}' data = { "jsonrpc" => "2.0", "method" => command, "params" => params, "id" => 0 } return chain_post data:data end def fetch_chain (quote="bts", base="cny", max_orders=5) chain_fetch quote:quote, base:base, max_orders:max_orders end def chain_fetch (quote:"bts", base:"cny", max_orders:5) response_json = chain_command command:"blockchain_get_asset", params:[quote.upcase] quote_precision = response_json["result"]["precision"] response_json = chain_command command:"blockchain_get_asset", params:[base.upcase] base_precision = response_json["result"]["precision"] response_json = chain_command command:"blockchain_median_feed_price", params:[base.upcase] feed_price = response_json["result"] response_json = chain_command command:"blockchain_market_order_book", params:[base.upcase, quote.upcase] ob = response_json["result"] #puts JSON.pretty_generate ob["result"] #ask orders and cover orders are in same array. filter invalid short orders here. TODO maybe wrong logic here asks = ob[1].delete_if {|e| e["type"] == "cover_order" #and #feed_price > e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision }.sort_by {|e| e["market_index"]["order_price"]["ratio"].to_f}.first(max_orders) bids = ob[0].sort_by {|e| e["market_index"]["order_price"]["ratio"].to_f}.reverse.first(max_orders) #asks_new=Hash[*asks.map["price","volume"]] asks_new=[] bids_new=[] asks.each do |e| item = { "price"=>e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision, "volume"=>e["state"]["balance"].to_f/quote_precision } #item["volume"] /= item["price"] asks_new.push item end bids.each do |e| item = { "price"=>e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision, "volume"=>e["state"]["balance"].to_f/base_precision } item["volume"] /= item["price"] bids_new.push item end # if there are orders can be matched, wait until they matched. if not asks_new[0].nil? and not bids_new[0].nil? and asks_new[0]["price"] <= bids_new[0]["price"] asks_new=[] bids_new=[] end #return ret={ "source"=>"chain", "base"=>base, "quote"=>quote, "asks"=>asks_new, "bids"=>bids_new } end def chain_balance account = my_chain_config["account"] response_json = chain_command command:"wallet_account_balance", params:[account] balances = response_json["result"] #puts balances =begin "result":[ [ "account1", [ [asset_id, balance], ..., [asset_id, balance] ] ], ... [ "account2" ... ] ] =end my_balance = Hash.new balances.each { |e| account_info = Hash.new account_name = e[0] assets = e[1] assets.each { |a| asset_id = a[0] asset_balance = a[1] asset_response_json = chain_command command:"blockchain_get_asset", params:[asset_id] asset_precision = asset_response_json["result"]["precision"] asset_symbol = asset_response_json["result"]["symbol"].downcase account_info.store asset_symbol, asset_balance.to_f / asset_precision } my_balance.store account_name, account_info } return my_balance[account] end def chain_orders (quote:"bts", base:"cny", type:"all") ret = { "source"=>"chain", "base"=>base, "quote"=>quote, "asks"=>[], "bids"=>[] } #account = my_chain_config["account"] response_json = chain_command command:"wallet_market_order_list", params:[base.upcase, quote.upcase] orders = response_json["result"] #puts orders if orders.empty? return ret end response_json = chain_command command:"blockchain_get_asset", params:[quote.upcase] quote_precision = response_json["result"]["precision"] response_json = chain_command command:"blockchain_get_asset", params:[base.upcase] base_precision = response_json["result"]["precision"] need_ask = ("all" == type or "ask" == type) need_bid = ("all" == type or "bid" == type) asks_new=[] bids_new=[] =begin [ "9c8d305ffe11c880b85b66928979b1e251e108fb", { "type": "ask_order", "market_index": { "order_price": { "ratio": "998877.0000345", "quote_asset_id": 14, "base_asset_id": 0 }, "owner": "BTS2TgDZ3nNwn9u6yfqaQ2o63bif15U8Y4En" }, "state": { "balance": 314159, "limit_price": null, "last_update": "2015-01-06T02:01:40" }, "collateral": null, "interest_rate": null, "expiration": null } ], =end orders.each do |e| order_id = e[0] order_type = e[1]["type"] order_price = e[1]["market_index"]["order_price"]["ratio"].to_f * quote_precision / base_precision if "bid_order" == order_type and need_bid order_volume = e[1]["state"]["balance"].to_f / base_precision / order_price item = {"id"=>e[0], "price"=>order_price, "volume"=>order_volume} bids_new.push item elsif "ask_order" == order_type and need_ask order_volume = e[1]["state"]["balance"].to_f / quote_precision item = {"id"=>e[0], "price"=>order_price, "volume"=>order_volume} asks_new.push item end end asks_new.sort_by! {|e| e["price"].to_f} bids_new.sort_by! {|e| e["price"].to_f}.reverse! ret["asks"]=asks_new ret["bids"]=bids_new return ret end # parameter base is to be compatible with btc38 def chain_cancel_order (id:nil, base:"cny") #$LOG.debug (self.class.name.to_s+'.'+method(__method__).name) { method(__method__).parameters.map } #$LOG.debug (method(__method__).name) { method(__method__).parameters.map { |arg| "#{arg} = #{eval arg}" }.join(', ')} $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if id.nil? return end # the API wallet_market_cancel_order is deprecated, so call another method chain_cancel_orders ids:[id], base:base #response_json = chain_command command:"wallet_market_cancel_order", params:[id] #result = response_json["result"] end # parameter base is to be compatible with btc38 def chain_cancel_orders (ids:[], base:"cny") $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if ids.nil? or ids.empty? return end response_json = chain_command command:"wallet_market_cancel_orders", params:[ids] #result = response_json["result"] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } end #return result end def chain_cancel_orders_by_type (quote:"bts", base:"cny", type:"all") orders = chain_orders quote:quote, base:base, type:type ids = orders["bids"].concat(orders["asks"]).collect { |e| e["id"] } puts ids.to_s chain_cancel_orders ids:ids end def chain_cancel_all_orders (quote:"bts", base:"cny") chain_cancel_orders_by_type quote:quote, base:base, type:"all" end def chain_new_order (quote:"bts", base:"cny", type:nil, price:nil, volume:nil, cancel_order_id:nil) $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if "bid" == type chain_bid quote:quote, base:base, price:price, volume:volume elsif "ask" == type chain_ask quote:quote, base:base, price:price, volume:volume elsif "cancel" == type chain_cancel_order id:cancel_order_id end end def chain_submit_orders (orders:[],quote:"bts",base:"cny") $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if orders.nil? or orders.empty? return nil end cancel_order_ids = [] new_orders = [] account = my_chain_config["account"] orders.each { |e| case e["type"] when "cancel" cancel_order_ids.push e["id"] when "ask" new_orders.push ["ask_order", [account, e["volume"], (e["quote"] or quote).upcase, e["price"], (e["base"] or base).upcase]] when "bid" new_orders.push ["bid_order", [account, e["volume"], (e["quote"] or quote).upcase, e["price"], (e["base"] or base).upcase]] end } #wallet_market_batch_update <cancel_order_ids> <new_orders> <sign> #param2 example: [['bid_order', ['myname', quantity, 'BTS', price, 'USD']], ['bid_order', ['myname', 124, 'BTS', 224, 'CNY']], ['ask_order', ['myname', 524, 'BTS', 624, 'CNY']], ['ask_order', ['myname', 534, 'BTS', 634, 'CNY']]] #wallet_market_submit_bid <from_account_name> <quantity> <quantity_symbol> <base_price> <base_symbol> [allow_stupid_bid] response_json = chain_command command:"wallet_market_batch_update", params:[cancel_order_ids, new_orders, true] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } return response_json["error"] else return response_json["result"] end end def chain_bid (quote:"bts", base:"cny", price:nil, volume:nil) $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if price.nil? or volume.nil? return nil end account = my_chain_config["account"] #wallet_market_submit_bid <from_account_name> <quantity> <quantity_symbol> <base_price> <base_symbol> [allow_stupid_bid] response_json = chain_command command:"wallet_market_submit_bid", params:[account, volume, quote.upcase, price, base.upcase] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } return response_json["error"] else return response_json["result"] end end def chain_ask (quote:"bts", base:"cny", price:nil, volume:nil) $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if price.nil? or volume.nil? return nil end account = my_chain_config["account"] #wallet_market_submit_ask <from_account_name> <sell_quantity> <sell_quantity_symbol> <ask_price> <ask_price_symbol> [allow_stupid_ask] response_json = chain_command command:"wallet_market_submit_ask", params:[account, volume, quote.upcase, price, base.upcase] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } return response_json["error"] else return response_json["result"] end end #main if __FILE__ == $0 =begin if ARGV[0] ob = fetch_chain ARGV[0], ARGV[1] else ob = fetch_chain end print_order_book ob =end if ARGV[0] if ARGV[1] args = ARGV.clone args.shift puts "command=" + ARGV[0] puts "args=" + args.to_s parsed_args = [] args.each {|e| begin obj = JSON.parse e parsed_args.push obj rescue JSON::ParserError parsed_args.push e end } puts "parsed_args=" + parsed_args.to_s result = chain_command command:ARGV[0], params:parsed_args else result = chain_command command:ARGV[0], params:[] end begin puts JSON.pretty_generate result rescue puts result end else ob = fetch_chain print_order_book ob puts puts JSON.pretty_generate chain_balance puts puts chain_orders end end chain_orders list orders of specified account only #!/usr/bin/env ruby require "httpclient" require "json" require_relative "config" require_relative "myfunc" require_relative "mylogger" #################################### # blockchain # # TODO write a class/function to communicate with rpc server def chain_post (data:{}) $LOG.debug (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if data.nil? or data.empty? return end client = HTTPClient.new client.connect_timeout=5 client.receive_timeout=5 myconfig = my_chain_config uri = myconfig["uri"] user = myconfig["user"] pass = myconfig["pass"] client.set_auth uri, user, pass begin response = client.post uri, data.to_json, nil #$LOG.debug (method(__method__).name) { response } response_content = response.content $LOG.debug (method(__method__).name) { {"response_content" => response_content} } response_json = JSON.parse response_content if not response_json["error"].nil? #$LOG.debug (method(__method__).name) { response_json["error"] } #response_content = response.body end return response_json rescue Exception => e print "chain_post error: " puts e end end # params is an array def chain_command (command:nil, params:nil) $LOG.debug (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if command.nil? or params.nil? return end #request_data= '{"jsonrpc": "2.0", "method": "blockchain_get_asset", "params":["'+quote.upcase+'"], "id":1}' data = { "jsonrpc" => "2.0", "method" => command, "params" => params, "id" => 0 } return chain_post data:data end def fetch_chain (quote="bts", base="cny", max_orders=5) chain_fetch quote:quote, base:base, max_orders:max_orders end def chain_fetch (quote:"bts", base:"cny", max_orders:5) response_json = chain_command command:"blockchain_get_asset", params:[quote.upcase] quote_precision = response_json["result"]["precision"] response_json = chain_command command:"blockchain_get_asset", params:[base.upcase] base_precision = response_json["result"]["precision"] response_json = chain_command command:"blockchain_median_feed_price", params:[base.upcase] feed_price = response_json["result"] response_json = chain_command command:"blockchain_market_order_book", params:[base.upcase, quote.upcase] ob = response_json["result"] #puts JSON.pretty_generate ob["result"] #ask orders and cover orders are in same array. filter invalid short orders here. TODO maybe wrong logic here asks = ob[1].delete_if {|e| e["type"] == "cover_order" #and #feed_price > e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision }.sort_by {|e| e["market_index"]["order_price"]["ratio"].to_f}.first(max_orders) bids = ob[0].sort_by {|e| e["market_index"]["order_price"]["ratio"].to_f}.reverse.first(max_orders) #asks_new=Hash[*asks.map["price","volume"]] asks_new=[] bids_new=[] asks.each do |e| item = { "price"=>e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision, "volume"=>e["state"]["balance"].to_f/quote_precision } #item["volume"] /= item["price"] asks_new.push item end bids.each do |e| item = { "price"=>e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision, "volume"=>e["state"]["balance"].to_f/base_precision } item["volume"] /= item["price"] bids_new.push item end # if there are orders can be matched, wait until they matched. if not asks_new[0].nil? and not bids_new[0].nil? and asks_new[0]["price"] <= bids_new[0]["price"] asks_new=[] bids_new=[] end #return ret={ "source"=>"chain", "base"=>base, "quote"=>quote, "asks"=>asks_new, "bids"=>bids_new } end def chain_balance account = my_chain_config["account"] response_json = chain_command command:"wallet_account_balance", params:[account] balances = response_json["result"] #puts balances =begin "result":[ [ "account1", [ [asset_id, balance], ..., [asset_id, balance] ] ], ... [ "account2" ... ] ] =end my_balance = Hash.new balances.each { |e| account_info = Hash.new account_name = e[0] assets = e[1] assets.each { |a| asset_id = a[0] asset_balance = a[1] asset_response_json = chain_command command:"blockchain_get_asset", params:[asset_id] asset_precision = asset_response_json["result"]["precision"] asset_symbol = asset_response_json["result"]["symbol"].downcase account_info.store asset_symbol, asset_balance.to_f / asset_precision } my_balance.store account_name, account_info } return my_balance[account] end def chain_orders (quote:"bts", base:"cny", type:"all") ret = { "source"=>"chain", "base"=>base, "quote"=>quote, "asks"=>[], "bids"=>[] } account = my_chain_config["account"] response_json = chain_command command:"wallet_market_order_list", params:[base.upcase, quote.upcase, -1, account] orders = response_json["result"] #puts orders if orders.empty? return ret end response_json = chain_command command:"blockchain_get_asset", params:[quote.upcase] quote_precision = response_json["result"]["precision"] response_json = chain_command command:"blockchain_get_asset", params:[base.upcase] base_precision = response_json["result"]["precision"] need_ask = ("all" == type or "ask" == type) need_bid = ("all" == type or "bid" == type) asks_new=[] bids_new=[] =begin [ "9c8d305ffe11c880b85b66928979b1e251e108fb", { "type": "ask_order", "market_index": { "order_price": { "ratio": "998877.0000345", "quote_asset_id": 14, "base_asset_id": 0 }, "owner": "BTS2TgDZ3nNwn9u6yfqaQ2o63bif15U8Y4En" }, "state": { "balance": 314159, "limit_price": null, "last_update": "2015-01-06T02:01:40" }, "collateral": null, "interest_rate": null, "expiration": null } ], =end orders.each do |e| order_id = e[0] order_type = e[1]["type"] order_price = e[1]["market_index"]["order_price"]["ratio"].to_f * quote_precision / base_precision if "bid_order" == order_type and need_bid order_volume = e[1]["state"]["balance"].to_f / base_precision / order_price item = {"id"=>e[0], "price"=>order_price, "volume"=>order_volume} bids_new.push item elsif "ask_order" == order_type and need_ask order_volume = e[1]["state"]["balance"].to_f / quote_precision item = {"id"=>e[0], "price"=>order_price, "volume"=>order_volume} asks_new.push item end end asks_new.sort_by! {|e| e["price"].to_f} bids_new.sort_by! {|e| e["price"].to_f}.reverse! ret["asks"]=asks_new ret["bids"]=bids_new return ret end # parameter base is to be compatible with btc38 def chain_cancel_order (id:nil, base:"cny") #$LOG.debug (self.class.name.to_s+'.'+method(__method__).name) { method(__method__).parameters.map } #$LOG.debug (method(__method__).name) { method(__method__).parameters.map { |arg| "#{arg} = #{eval arg}" }.join(', ')} $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if id.nil? return end # the API wallet_market_cancel_order is deprecated, so call another method chain_cancel_orders ids:[id], base:base #response_json = chain_command command:"wallet_market_cancel_order", params:[id] #result = response_json["result"] end # parameter base is to be compatible with btc38 def chain_cancel_orders (ids:[], base:"cny") $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if ids.nil? or ids.empty? return end response_json = chain_command command:"wallet_market_cancel_orders", params:[ids] #result = response_json["result"] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } end #return result end def chain_cancel_orders_by_type (quote:"bts", base:"cny", type:"all") orders = chain_orders quote:quote, base:base, type:type ids = orders["bids"].concat(orders["asks"]).collect { |e| e["id"] } puts ids.to_s chain_cancel_orders ids:ids end def chain_cancel_all_orders (quote:"bts", base:"cny") chain_cancel_orders_by_type quote:quote, base:base, type:"all" end def chain_new_order (quote:"bts", base:"cny", type:nil, price:nil, volume:nil, cancel_order_id:nil) $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if "bid" == type chain_bid quote:quote, base:base, price:price, volume:volume elsif "ask" == type chain_ask quote:quote, base:base, price:price, volume:volume elsif "cancel" == type chain_cancel_order id:cancel_order_id end end def chain_submit_orders (orders:[],quote:"bts",base:"cny") $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if orders.nil? or orders.empty? return nil end cancel_order_ids = [] new_orders = [] account = my_chain_config["account"] orders.each { |e| case e["type"] when "cancel" cancel_order_ids.push e["id"] when "ask" new_orders.push ["ask_order", [account, e["volume"], (e["quote"] or quote).upcase, e["price"], (e["base"] or base).upcase]] when "bid" new_orders.push ["bid_order", [account, e["volume"], (e["quote"] or quote).upcase, e["price"], (e["base"] or base).upcase]] end } #wallet_market_batch_update <cancel_order_ids> <new_orders> <sign> #param2 example: [['bid_order', ['myname', quantity, 'BTS', price, 'USD']], ['bid_order', ['myname', 124, 'BTS', 224, 'CNY']], ['ask_order', ['myname', 524, 'BTS', 624, 'CNY']], ['ask_order', ['myname', 534, 'BTS', 634, 'CNY']]] #wallet_market_submit_bid <from_account_name> <quantity> <quantity_symbol> <base_price> <base_symbol> [allow_stupid_bid] response_json = chain_command command:"wallet_market_batch_update", params:[cancel_order_ids, new_orders, true] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } return response_json["error"] else return response_json["result"] end end def chain_bid (quote:"bts", base:"cny", price:nil, volume:nil) $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if price.nil? or volume.nil? return nil end account = my_chain_config["account"] #wallet_market_submit_bid <from_account_name> <quantity> <quantity_symbol> <base_price> <base_symbol> [allow_stupid_bid] response_json = chain_command command:"wallet_market_submit_bid", params:[account, volume, quote.upcase, price, base.upcase] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } return response_json["error"] else return response_json["result"] end end def chain_ask (quote:"bts", base:"cny", price:nil, volume:nil) $LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } } if price.nil? or volume.nil? return nil end account = my_chain_config["account"] #wallet_market_submit_ask <from_account_name> <sell_quantity> <sell_quantity_symbol> <ask_price> <ask_price_symbol> [allow_stupid_ask] response_json = chain_command command:"wallet_market_submit_ask", params:[account, volume, quote.upcase, price, base.upcase] if not response_json["error"].nil? $LOG.error (method(__method__).name) { JSON.pretty_generate response_json["error"] } return response_json["error"] else return response_json["result"] end end #main if __FILE__ == $0 =begin if ARGV[0] ob = fetch_chain ARGV[0], ARGV[1] else ob = fetch_chain end print_order_book ob =end if ARGV[0] if ARGV[1] args = ARGV.clone args.shift puts "command=" + ARGV[0] puts "args=" + args.to_s parsed_args = [] args.each {|e| begin obj = JSON.parse e parsed_args.push obj rescue JSON::ParserError parsed_args.push e end } puts "parsed_args=" + parsed_args.to_s result = chain_command command:ARGV[0], params:parsed_args else result = chain_command command:ARGV[0], params:[] end begin puts JSON.pretty_generate result rescue puts result end else ob = fetch_chain print_order_book ob puts puts JSON.pretty_generate chain_balance puts puts chain_orders end end
minor require 'rubygems' include RubyCards hand=Hand.new deck=Deck.new deck.shuffle! hand.Draw(deck,5) puts hand
done 08 class Book def title=(title) little_words = ["and", "in", "the", "of", "a", "an"] words = title.split.map do |word| little_words.include?(word) ? word : word.capitalize end words[0].capitalize! @title = words.join(" ") end def title @title end end
# = Руководство Cigui # В данном руководстве описана работа модуля CIGUI, # а также методы для управления его работой.<br> # Рекомендуется к прочтению пользователям, имеющим навыки программирования # (написания скриптов) на Ruby.<br> # Для получения помощи по командам, обрабатываемым Cigui, # перейдите по адресу: <https://github.com/deadelf79/CIGUI/wiki> # --- # Author:: Sergey 'DeadElf79' Anikin (mailto:deadelf79@gmail.com) # License:: Public Domain (see <http://unlicense.org> for more information) # Модуль, содержащий данные обо всех возможных ошибках, которые # может выдать CIGUI при некорректной работе.<br> # Включает в себя: # * CIGUIERR::CantStart # * CIGUIERR::CantReadNumber # * CIGUIERR::CantReadString # * CIGUIERR::CantInterpretCommand # * CIGUIERR::CannotCreateWindow # * CIGUIERR::WrongWindowIndex # module CIGUIERR # Ошибка, которая появляется при неудачной попытке запуска интерпретатора Cigui # class CantStart < StandardError private def message 'Could not initialize module' end end # Ошибка, которая появляется, если в строке не было обнаружено числовое значение.<br> # Правила оформления строки указаны для каждого типа значений отдельно: # * целые числа - CIGUI.decimal # * дробные числа - CIGUI.fraction # class CantReadNumber < StandardError private def message 'Could not find numerical value in this string' end end # Ошибка, которая появляется, если в строке не было обнаружено строчное значение.<br> # Правила оформления строки и примеры использования указаны в описании # к этому методу: CIGUI.string # class CantReadString < StandardError private def message 'Could not find substring' end end # Ошибка, которая появляется при попытке работать с Cigui после # вызова команды <i>cigui finish</i>. # class CantInterpretCommand < StandardError private def message 'Unable to process the command after CIGUI was finished' end end # Ошибка создания окна. # class CannotCreateWindow < StandardError private def message 'Unable to create window' end end # Ошибка, которая появляется при попытке обращения # к несуществующему индексу в массиве <i>windows</i><br> # Вызывается при некорректном вводе пользователя # class WrongWindowIndex < StandardError private def message 'Index must be included in range of 0 to internal windows array size' end end end # Инициирует классы, если версия Ruby выше 1.9.0 # if RUBY_VERSION.to_f>=1.9 begin # Класс окна с реализацией всех возможностей, доступных при помощи Cigui.<br> # Реализация выполнена для RGSS3. # class Win3 < Window_Selectable # Скорость перемещения attr_accessor :speed # Прозрачность окна. Может принимать значения от 0 до 255 attr_accessor :opacity # Прозрачность фона окна. Может принимать значения от 0 до 255 attr_accessor :back_opacity # Метка окна. Строка, по которой происходит поиск экземпляра # в массиве CIGUI.windows при выборе окна по метке (select by label) attr_reader :label # Создает окно. По умолчанию задается размер 192х64 и # помещается в координаты 0, 0 # def initialize(x=0,y=0,w=192,h=64) super 0,0,192,64 @label=nil @items=[] @texts=[] @speed=1 end # Обновляет окно. Влияет только на положение курсора (параметр cursor_rect), # прозрачность и цветовой тон окна. def update;end # Обновляет окно. В отличие от #update, влияет только # на содержимое окна (производит повторную отрисовку). def refresh self.contents.clear end # Задает метку окну, проверяя ее на правильность перед этим: # * удаляет круглые и квадратгые скобки # * удаляет кавычки # * заменяет пробелы и табуляцию на символы подчеркивания # * заменяет символы "больше" и "меньше" на символы подчеркивания def label=(string) # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end # Этот метод позволяет добавить текст в окно.<br> # Принимает в качестве параметра значение класса Text def add_text(text) end # Этот метод добавляет команду во внутренний массив <i>items</i>. # Команды используются для отображения кнопок.<br> # * command - отображаемый текст кнопки # * procname - название вызываемого метода # По умолчанию значение enable равно true, что значит, # что кнопка включена и может быть нажата. # def add_item(command,procname,enabled=true) @items+=[ { :command=>command, :procname=>procname, :enabled=>enabled, :x=>:auto, :y=>:auto } ] end # Включает кнопку.<br> # В параметр commandORindex помещается либо строковое значение, # являющееся названием кнопки, либо целое число - индекс кнопки во внутреннем массиве <i>items</i>. # enable_item(0) # => @items[0].enabled set 'true' # enable_item('New game') # => @items[0].enabled set 'true' # def enable_item(commandORindex) case commandORindex.class when Integer, Float @items[commandORindex.to_i][:enabled]=true if (0...@items.size).include? commandORindex.to_i when String @items.times{|index|@items[index][:enabled]=true if @items[index][:command]==commandORindex} else raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{string}" end end # С помощью этого метода производится полная отрисовка всех # элементов из массива <i>items</i>.<br> # Параметр ignore_disabled отвечает за отображение выключенных # команд из массива <i>items</i>. Если его значение равно true, # то отрисовка выключенных команд производиться не будет. # def draw_items(ignore_disabled=false) end # Устанавливает новые размеры окна дополнительно изменяя # также и размеры содержимого (contents).<br> # Все части содержимого, которые не помещаются в новые размер, # удаляются безвозратно. # def resize(new_width, new_height) temp=Sprite.new temp.bitmap=self.contents self.contents.dispose src_rect(0,0,temp.width,temp.height) self.contents=Bitmap.new( width - padding * 2, height - padding * 2 ) self.contents.bit(0,0,temp.bitmap,src_rect,255) temp.bitmap.dispose temp.dispose width=new_width height=new_height end # Удаляет окно и все связанные с ним ресурсы # def dispose super end # Возврашает полную информацию обо всех параметрах # в формате строки # def inspect "<#{self.class}:"+ " @back_opacity=#{back_opacity},"+ " @contents_opacity=#{contents_opacity}"+ " @height=#{height},"+ " @opacity=#{opacity},"+ " @speed=#{@speed},"+ " @width=#{width},"+ " @x=#{x},"+ " @y=#{y}>" end end # Если классы инициировать не удалось (ошибка в отсутствии родительских классов), # то в память загружаются исключительно консольные версии (console-only) классов # необходимые для работы с командной строкой. rescue # Класс абстрактного (невизуального) прямоугольника. # Хранит значения о положении и размере прямоугольника class Rect # Координата X attr_accessor :x # Координата Y attr_accessor :y # Ширина прямоугольника attr_accessor :width # Высота прямоугольника attr_accessor :height # Создание прямоугольника # * x, y - назначает положение прямоуголника в пространстве # * width, height - устанавливает ширину и высоту прямоугольника def initialize(x,y,width,height) @x,@y,@width,@height = x,y,width,height end # Задает все параметры единовременно # Может принимать значения: # * Rect - другой экземпляр класса Rect, все значения копируются из него # * x, y, width, height - позиция и размер прямоугольника # # Оба варианта работают аналогично: # set(Rect.new(0,0,192,64)) # set(0,0,192,64) def set(*args) if args.size==1 @x,@y,@width,@height = args[0].x, args[0].y, args[0].width, args[0].height elsif args.size==4 @x,@y,@width,@height = args[0], args[1], args[2], args[3] elsif args.size.between?(2,3) # throw error, but i don't remember which error O_o end end # Устанавливает все параметры прямоугольника равными нулю. def empty @x,@y,@width,@height = 0, 0, 0, 0 end end # Класс, хранящий данные о цвете в формате RGBA # (красный, зеленый, синий и прозрачность). Каждое значение # является рациональным числом (число с плавающей точкой) и # имеет значение от 0.0 до 255.0. Все значения, выходящие # за указанный интервал, корректируются автоматически. # class Color # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * a - задает прозрачность, по умолчанию имеет значение 255.0 (полностью непрозрачный цвет) def initialize(r,g,b,a=255.0) @r,@g,@b,@a = r.to_f,g.to_f,b.to_f,a.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @r end # Возвращает значение синего цвета def blue @r end # Возвращает значение прозрачности def alpha @r end # Задает новые значения цвета и прозрачности.<br> # <b>Варианты параметров:</b> # * set(Color) - в качестве параметра задан другой экземпляр класса Color # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, alpha) - задает новые значения цвета и прозрачности. def set(*args) if args.size==1 @r,@g,@b,@a = args[0].red,args[0].green,args[0].blue,args[0].alpha elsif args.size==4 @r,@g,@b,@a = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@a = args[0],args[1],args[2],255.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=0 if @r<0 @r=255 if @r>255 @g=0 if @g<0 @g=255 if @g>255 @b=0 if @b<0 @b=255 if @b>255 @a=0 if @a<0 @a=255 if @a>255 end end # Класс, хранящий данные о тонировании в ввиде четырех значений: # красный, зеленый, синий и насыщенность. Последнее значение влияет # на цветовую насыщенность, чем ниже его значение, тем сильнее # цветовые оттенки заменяются на оттенки серого. # Каждое значение, кроме последнего, является рациональным числом # (число с плавающей точкой) и имеет значение от -255.0 до 255.0. # Значение насыщенности лежит в пределах от 0 до 255. # Все значения, выходящие за указанные интервалы, # корректируются автоматически. # class Tone # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * gs - задает насыщенность, по умолчанию имеет значение 0 def initialize(r,g,b,gs=0.0) @r,@g,@b,@gs = r.to_f,g.to_f,b.to_f,gs.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @r end # Возвращает значение синего цвета def blue @r end # Возвращает значение насыщенности def gray @gs end # Задает новые значения цвета и насыщенности.<br> # <b>Варианты параметров:</b> # * set(Tone) - в качестве параметра задан другой экземпляр класса Tone # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, greyscale) - задает новые значения цвета и насыщенности. def set(*args) if args.size==1 @r,@g,@b,@gs = args[0].red,args[0].green,args[0].blue,args[0].gray elsif args.size==4 @r,@g,@b,@gs = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@gs = args[0],args[1],args[2],0.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=-255 if @r<-255 @r=255 if @r>255 @g=-255 if @g<-255 @g=255 if @g>255 @b=-255 if @b<-255 @b=255 if @b>255 @gs=0 if @gs<0 @gs=255 if @gs>255 end end # Console-only version of this class class Win3#:nodoc: # X Coordinate of Window attr_accessor :x # Y Coordinate of Window attr_accessor :y # X Coordinate of contens attr_accessor :ox # Y Coordinate of contents attr_accessor :oy # Width of Window attr_accessor :width # Height of Window attr_accessor :height # Speed movement attr_accessor :speed # Opacity of window. May be in range of 0 to 255 attr_accessor :opacity # Back opacity of window. May be in range of 0 to 255 attr_accessor :back_opacity # Label of window attr_reader :label # If window is active then it updates attr_accessor :active # Openness of window attr_accessor :openness # Window skin - what window looks like attr_accessor :windowskin # Tone of the window attr_accessor :tone # # Create window def initialize @x,@y,@width,@height = 0, 0, 192, 64 @ox,@oy,@speed=0,0,:auto @opacity, @back_opacity, @contents_opacity = 255, 255, 255 @z, @tone, @openness = 100, Tone.new(0,0,0,0), 255 @active, @label = true, nil @windowskin='window' @items=[] end # Resize (simple) def resize(new_width, new_height) @width=new_width @height=new_height end # Update window (do nothing now) def update;end # Close window def close @openness=0 end # Open window def open @openness=255 end # Dispose window def dispose;end def label=(string) return if string.nil? # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end end # Класс спрайта со всеми параметрами, доступными в RGSS3. Пока пустой, ожидается обновление во время работы над спрайтами # (ветка work-with-sprites в github). # class Spr3 # Создает новый спрайт def initialize;end # Производит обновление спрайта def update;end # Производит повторную отрисовку содержимого спрайта def refresh;end # Удаляет спрайт def dispose;end end end end # Класс, хранящий данные о тексте в окне. Создается для каждого окна отдельно, # имеет индивидуальные настройки. class Text # Название файла изображения, из которого загружаются данные для отрисовки окон.<br> # По умолчанию задан путь 'Graphics\System\Window.png'. attr_accessor :windowskin # Массив цветов для отрисовки текста, по умолчанию содержит 32 цвета attr_accessor :colorset # Переменная класса Color, содержит цвет обводки текста. attr_accessor :out_color # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку обводки текста. По умолчанию, # обводка включена (outline=true) attr_accessor :outline # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку тени от текста. По умолчанию, # тень выключена (shadow=false) attr_accessor :shadow # Устанавливает жирность шрифта для <b>всего</b> текста.<br> # Игнорирует тег < b > в тексте attr_accessor :bold # Устанавливает наклон шрифта (курсив) для <b>всего</b> текста.<br> # Игнорирует тег < i > в тексте attr_accessor :italic # Устанавливает подчеркивание шрифта для <b>всего</b> текста.<br> # Игнорирует тег < u > в тексте attr_accessor :underline # Гарнитура (название) шрифта. По умолчанию - Tahoma attr_accessor :font # Размер шрифта. По умолчанию - 20 attr_accessor :size # Строка текста, которая будет отображена при использовании # экземпляра класса. attr_accessor :string # Создает экземпляр класса.<br> # <b>Параметры:</b> # * string - строка текста # * font_family - массив названий (гарнитур) шрифта, по умолчанию # имеет только "Tahoma". # При выборе гарнитуры шрифта, убедитесь в том, что символы, используемые # в тексте, корректно отображаются при использовании данного шрифта. # * font_size - размер шрифта, по умолчанию равен 20 пунктам # * bold - <b>жирный шрифт</b> (по умолчанию - false) # * italic - <i>курсив</i> (по умолчанию - false) # * underline - <u>подчеркнутый шрифт</u> (по умолчанию - false) def initialize(string, font_family=['Tahoma'], font_size=20, bold=false, italic=false, underline=false) @string=string @font=font_family @size=font_size @bold, @italic, @underline = bold, italic, underline @colorset=[] @out_color=Color.new(0,0,0,128) @shadow, @outline = false, true @windowskin='Graphics\\System\\Window.png' default_colorset end # Восстанавливает первоначальные значения цвета. По возможности, эти данные загружаются # из файла def default_colorset @colorset.clear if FileTest.exist?(@windowskin) bitmap=Bitmap.new(@windowskin) for y in 0..3 for x in 0..7 @colorset<<bitmap.get_pixel(x*8+64,y*8+96) end end bitmap.dispose else # Colors for this set was taken from <RTP path>/Graphics/Window.png file, # not just from the sky @colorset = [ # First row Color.new(255,255,255), # 1 Color.new(32, 160,214), # 2 Color.new(255,120, 76), # 3 Color.new(102,204, 64), # 4 Color.new(153,204,255), # 5 Color.new(204,192,255), # 6 Color.new(255,255,160), # 7 Color.new(128,128,128), # 8 # Second row Color.new(192,192,192), # 1 Color.new(32, 128,204), # 2 Color.new(255, 56, 16), # 3 Color.new( 0,160, 16), # 4 Color.new( 62,154,222), # 5 Color.new(160,152,255), # 6 Color.new(255,204, 32), # 7 Color.new( 0, 0, 0), # 8 # Third row Color.new(132,170,255), # 1 Color.new(255,255, 64), # 2 Color.new(255,120, 76), # 3 Color.new( 32, 32, 64), # 4 Color.new(224,128, 64), # 5 Color.new(240,192, 64), # 6 Color.new( 64,128,192), # 7 Color.new( 64,192,240), # 8 # Fourth row Color.new(128,255,128), # 1 Color.new(192,128,128), # 2 Color.new(128,128,255), # 3 Color.new(255,128,255), # 4 Color.new( 0,160, 64), # 5 Color.new( 0,224, 96), # 6 Color.new(160, 96,224), # 7 Color.new(192,128,255) # 8 ] end end # Сбрасывает все данные, кроме colorset, на значения по умолчанию def empty @string='' @font=['Tahoma'] @size=20 @bold, @italic, @underline = false, false, false @out_color=Color.new(0,0,0,128) @shadow, @outline = false, false @windowskin='Graphics\\System\\Window.png' end end # Основной модуль, обеспечивающий работу Cigui.<br> # Для передачи команд используйте массив $do, например: # * $do<<"команда" # * $do.push("команда") # Оба варианта имеют один и тот же результат.<br> # Перед запуском модуля вызовите метод CIGUI.setup.<br> # Для исполнения команд вызовите метод CIGUI.update.<br> # module CIGUI # Специальный словарь, содержащий все используемые команды Cigui. # Предоставляет возможности не только внесения новых слов, но и добавление # локализации (перевода) имеющихся (см. #update_by_user).<br> # Для удобства поиска разбит по категориям: # * common - общие команды, не имеющие категории; # * cigui - управление интерпретатором; # * event - событиями на карте; # * map - параметрами карты; # * picture - изображениями, используемыми через команды событий; # * sprite - самостоятельными изображениями; # * text - текстом и шрифтами # * window - окнами. # Русификацию этого словаря Вы можете найти в файле localize.rb # по адресу: <https://github.com/deadelf79/CIGUI/>, если этот файл # не приложен к демонстрационной версии проекта, который у Вас есть. # VOCAB={ #--COMMON unbranch :please=>'please', :last=>'last|this', :select=>'select', # by index or label :true=>'true|1', # for active||visible :false=>'false|0', :equal=>'[\s]*[\=]?[\s]*', #--CIGUI branch :cigui=>{ :main=>'cigui', :start=>'start', :finish=>'finish', :flush=>'flush', :restart=>'restart|resetup', }, #--EVENT branch :event=>{ :main=>'event|char(?:acter)?', :create=>'create|созда(?:[йть]|ва[йть])', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :load=>'load', # TAB #1 #~MESSAGE group :show=>'show', :message=>'message|text', :choices=>'choices', :scroll=>'scro[l]*(?:ing|er|ed)?', :input=>'input', :key=>'key|bu[t]*on', :number=>'number', :item=>'item', #to use as - select key item || condition branch item #~GAME PROGRESSION group :set=>'set|cotrol', # other word - see at :condition #~FLOW CONTROL group :condition=>'condition|if|case', :branch=>'bran[ch]|when', :switch=>'swit[ch]', :variable=>'var(?:iable)?', :self=>'self', # to use as - self switch :timer=>'timer', :min=>'min(?:ute[s]?)?', :sec=>'sec(?:[ou]nds)?', :ORmore=>'or[\s]*more', :ORless=>'or[\s]*less', :actor=>'actor', :in_party=>'in[\s]*party', :name=>'name', :applied=>'a[p]*lied', :class=>'cla[s]*', :skill=>'ski[l]*', :weapon=>'wea(?:p(?:on)?)?|wip(?:on)?', :armor=>'armo[u]?r', :state=>'stat(?:e|us)?', :enemy=>'enemy', :appeared=>'a[p]*eared', :inflicted=>'inflicted', # to use as - state inflicted :facing=>'facing', # to use as - event facing :up=>'up', :down=>'down', :left=>'left', :right=>'right', :vehicle=>'vehicle', :gold=>'gold|money', :script=>'script|code', :loop=>'loop', :break=>'break', :exit=>'exit', # to use as - exit event processing :call=>'call', :common=>'common', :label=>'label|link', :jump=>'jump(?:[\s]*to)?', :comment=>'comment', #~PARTY group :change=>'change', :party=>'party', :member=>'member', #~ACTOR group :hp=>'hp', :sp=>'[ms]p', :recover=>'recover', # may be used for one member :all=>'a[l]*', :exp=>'exp(?:irience)?', :level=>'l[e]?v[e]?l', :params=>'param(?:et[e]?r)s', :nickname=>'nick(?:name)?', # TAB#2 #~MOVEMENT group :transfer=>'transfer|teleport(?:ate|ion)', :player=>'player', :map=>'map', # to use as - scroll map || event map x :x=>'x', :y=>'y', :screen=>'scr[e]*n', # to use as - event screen x :route=>'rout(?:e|ing)?', :move=>'move|go', :forward=>'forward|в[\s]*пер[её][дт]', :backward=>'backward|н[ао][\s]*за[дт]', :lower=>'lower', :upper=>'upper', :random=>'rand(?:om[ed]*)?', :toward=>'toward', :away=>'away([\s]*from)?', :step=>'step', :get=>'get', :on=>'on', :off=>'off', # to use as - get on/off vehicle :turn=>'turn', :clockwise=>'clockwise', # по часовой :counterclockwise=>'counter[\s]clockwise', # против часовой :emulate=>'emulate', :click=>'click|tap', :touch=>'touch|enter', :by_event=>'by[\s]*event', :autorun=>'auto[\s]*run', :parallel=>'para[ll]*el', :wait=>'wait', :frames=>'frame[s]?', }, #--MAP branch :map=>{ :main=>'map', :name=>'name', :width=>'width', :height=>'height', }, #--PICTURE branch :picture=>{ :maybe=>'in future versions' }, #--SPRITE branch :sprite=>{ :main=>'sprite|спрайт', :create=>'create|созда(?:[йть]|ва[йть])', :dispose=>'dispose|delete', :move=>'move', :resize=>'resize', :set=>'set', :x=>'x|х|икс', :y=>'y|у|игрек', :width=>'width', :height=>'height', }, #--TEXT branch :text=>{ :main=>'text', :make=>'make', :bigger=>'bigger', :smaller=>'smaller', :set=>'set', :font=>'font', :size=>'size', }, #--WINDOW branch :window=>{ :main=>'window', :create=>'create', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :move=>'move', :to=>'to', :speed=>'speed', :auto=>'auto', :resize=>'resize', :set=>'set', :x=>'x', :y=>'y', :z=>'z', :ox=>'ox', :oy=>'oy', :tone=>'tone', :width=>'width', :height=>'height', :link=>'link', # to use as - set button[DEC] link to switch[DEC] #dunnolol :label=>'label', :index=>'index', :indexed=>'indexed', :labeled=>'labeled', :as=>'as', :opacity=>'opacity', :back=>'back', # to use as - set back opacity :contents=>'contents', # to use as - set contents opacity :open=>'open', :openness=>'openness', :close=>'close', :active=>'active', :activate=>'activate', :deactivate=>'deactivate', :windowskin=>'skin|window[\s_]*skin', :cursor=>'cursor', :rect=>'rect', } } # Хэш-таблица всех возможных сочетаний слов из VOCAB и их положения относительно друг друга в тексте.<br> # Именно по этим сочетаниям производится поиск команд Cigui в тексте. Редактировать без понимания правил # составления регулярных выражений не рекомендуется. CMB={ #~COMMON unbranch # selection window :select_window=>"(?:(?:#{VOCAB[:select]})+[\s]*(?:#{VOCAB[:window][:main]})+)|"+ "(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:select]})+)", :select_by_index=>"(?:(?:#{VOCAB[:window][:index]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:indexed]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?)", :select_by_label=>"(?:(?:#{VOCAB[:window][:label]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:labeled]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?)", #~CIGUI branch # commands only :cigui_start=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:start]})+)+", :cigui_finish=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:finish]})+)+", :cigui_flush=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:flush]})+)+", :cigui_restart=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:restart]})+)+", #~WINDOW branch # expressions :window_x_equal=>"(?:#{VOCAB[:window][:x]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_y_equal=>"(?:#{VOCAB[:window][:y]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ox_equal=>"(?:#{VOCAB[:window][:ox]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_oy_equal=>"(?:#{VOCAB[:window][:oy]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_w_equal=>"(?:#{VOCAB[:window][:width]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_h_equal=>"(?:#{VOCAB[:window][:height]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_s_equal=>"(?:#{VOCAB[:window][:speed]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_a_equal=>"(?:#{VOCAB[:window][:opacity]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ba_equal=>"(?:(?:#{VOCAB[:window][:back]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_ca_equal=>"(?:(?:#{VOCAB[:window][:contents]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_active_equal=>"(?:#{VOCAB[:window][:active]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_skin_equal=>"(?:#{VOCAB[:window][:windowskin]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_openness_equal=>"(?:#{VOCAB[:window][:openness]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_tone_equal=>"(?:#{VOCAB[:window][:tone]})+(?:#{VOCAB[:equal]}|[\s]*)+", # commands :window_create=>"(((?:#{VOCAB[:window][:create]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:create]})+)", :window_create_atORwith=>"((?:#{VOCAB[:window][:at]})+[\s]*(#{VOCAB[:window][:x]}|#{VOCAB[:window][:y]})+)|"+ "((?:#{VOCAB[:window][:with]})+[\s]*(?:#{VOCAB[:window][:width]}|#{VOCAB[:window][:height]}))", :window_dispose=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_dispose_this=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_move=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:move]}))|"+ "(?:(?:#{VOCAB[:window][:move]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_resize=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:resize]}))|"+ "(?:(?:#{VOCAB[:window][:resize]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_set=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:set]})+)|"+ "(?:(?:#{VOCAB[:window][:set]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_activate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:activate]})+)|"+ "(?:(?:#{VOCAB[:window][:activate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_deactivate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:deactivate]})+)|"+ "(?:(?:#{VOCAB[:window][:deactivate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_open=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:open]}))|"+ "(?:(?:#{VOCAB[:window][:open]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", :window_close=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:close]}))|"+ "(?:(?:#{VOCAB[:window][:close]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", } # class <<self # Внутренний массив для вывода информации обо всех созданных окнах.<br> # Открыт только для чтения. # attr_reader :windows # Внутренний массив для вывода информации обо всех созданных спрайтах.<br> # Открыт только для чтения. # attr_reader :sprites # Требуется выполнить этот метод перед началом работы с CIGUI.<br> # Инициализирует массив $do, если он еще не был создан. В этот массив пользователь подает # команды для исполнения при следующем запуске метода #update.<br> # Если даже массив $do был инициализирован ранее, # то исполняет команду <i>cigui start</i> прежде всего.<br> # <b>Пример:</b> # begin # CIGUI.setup # #~~~ some code fragment ~~~ # CIGUI.update # #~~~ some other code fragment ~~~ # end # def setup $do||=[] $do.insert 0,'cigui start' _setup end # Вызывает все методы обработки команд, содержащиеся в массиве $do.<br> # Вызовет исключение CIGUIERR::CantInterpretCommand в том случае, # если после выполнения <i>cigui finish</i> в массиве $do будут находится # новые команды для обработки.<br> # По умолчанию очищает массив $do после обработки всех команд. Если clear_after_update # поставить значение false, то все команды из массива $do будут выполнены повторно # при следующем запуске этого метода.<br> # Помимо приватных методов обработки вызывает также метод #update_by_user, который может быть # модифицирован пользователем (подробнее смотри в описании метода).<br> # def update(clear_after_update=true) $do.each do |line| _restart? line _common? line _cigui? line _window? line #_ update_internal_objects update_by_user(line) end $do.clear if clear_after_update end # Вызывает обновление всех объектов из внутренних массивов ::windows и ::sprites.<br> # Вызывается автоматически по окончании обработки команд из массива $do в методе #update. def update_internal_objects @windows.each{ |win| win.update if win.is_a? Win3 } @sprites.each{ |spr| spr.update if spr.is_a? Spr3 } end # Метод обработки текста, созданный для пользовательских модификаций, не влияющих на работу # встроенных обработчиков.<br> # Используйте <i>alias</i> этого метода при добавлении обработки собственных команд.<br> # <b>Пример:</b> # alias my_update update_by_user # def update_by_user # # add new word # VOCAB[:window][:throw]='throw' # # add 'window throw' combination # CMB[:window_throw]="(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:throw]})+)" # # call method # window_throw? line # end # def update_by_user(string) end # Данный метод возвращает первое попавшееся целое число, найденное в строке source_string.<br> # Производит поиск только в том случае, если число записано: # * в скобки, например (10); # * в квадратные скобки, например [23]; # * в кавычки(апострофы), например '45'; # * в двойные кавычки, например "8765". # Также, вернет всю целую часть числа записанную: # * до точки, так здесь [1.35] вернет 1; # * до запятой, так здесь (103,81) вернет 103; # * до первого пробела (при стандартной конвертации в целое число), так здесь "816 586,64" вернет только 816; # * через символ подчеркивания, так здесь '1_000_0_0_0,143' вернет ровно один миллион (1000000). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # decimal('[10,25]') # => 10 # decimal('[1 0 2]',false) # => 102 # decimal('[1_234_5678 89]',false) # => 123456789 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def decimal(source_string, std_conversion=true) fraction(source_string, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #decimal, но возвращает рациональное число # (число с плавающей запятой или точкой).<br> # Имеется пара замечаний к правилам использования в дополнение к упомянутым в #decimal: # * Все цифры после запятой или точки считаются дробной частью и также могут содержать помимо цифр символ подчёркивания; # * При наличии между цифрами в дробной части пробела вернет ноль (в стандартной конвертации в целое или дробное число). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # fraction('(109,86)') # => 109.86 # fraction('(1 0 9 , 8 6)',false) # => 109.86 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def fraction(source_string, std_conversion=true) match='(?:[\[|"\(\'])[\s]*([\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)(?:[\]|"\)\'])' return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск подстроки, используемой в качестве параметра.<br> # Строка должна быть заключена в одинарные или двойные кавычки или же в круглые # или квадратные скобки. # substring('[Hello cruel world!]') # => Hello cruel world! # substring("set window label='SomeSome' and no more else") # => SomeSome # def substring(source_string) match='(?:[\[\(\"\'])[\s]*([\w\s _\!\#\$\%\^\&\*]*)[\s]*(?:[\]|"\)\'])' return source_string.match(match)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск булевого значения (true или false) в строке и возвращает его. # Если булевое значение в строке не обнаружено, по умолчанию возвращает false. def boolean(source_string) match="((?:#{VOCAB[:true]}|#{VOCAB[:false]}))" if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает массив из четырех значений для передачи в качестве параметра # в объекты класса Rect. Массив в строке должен быть помещен в квадратные скобки, # а значения в нем должны разделяться <b>точкой с запятой.</b><br> # <b>Пример:</b> # rect('[1;2,0;3.5;4.0_5]') # => [ 1, 2.0, 3.5, 4.05 ] # def rect(source_string) read='' start=false arr=[] for index in 0...source_string.size char=source_string[index] if char=='[' start=true next end if start if char!=';' if char!=']' read+=char else arr<<read break end else arr<<read read='' end end end if arr.size<4 for index in 1..4-arr.size arr<<0 end elsif arr.size>4 arr.slice!(4,arr.size) end for index in 0...arr.size arr[index]=dec(arr[index]) if arr[index].is_a? String arr[index]=0 if arr[index].is_a? NilClass end return arr end # Данный метод работает по аналогии с #decimal, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # dec('x=1cm','x=','cm') # => 1 # dec('y=120 m','[xy]=','[\s]*(?:cm|m|km)') # => 120 # В отличие от #frac, возвращает целое число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def dec(source_string, prefix='', postfix='', std_conversion=true) frac(source_string, prefix, postfix, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #fraction, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # frac('x=31.2mm','x=','mm') # => 31.2 # frac('y=987,67 m','[xy]=','[\s]*(?:cm|m|km)') # => 987.67 # В отличие от #dec, возвращает рациональное число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def frac(source_string, prefix='', postfix='', std_conversion=true) match=prefix+'([\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)'+postfix return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #substring, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг подстроки.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # puts 'Who can make me strong?' # someone = substring("Make me invincible",'Make','invincible') # puts 'Only'+someone # => 'Only me' # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def substr(source_string, prefix='', postfix='') match=prefix+'([\w\s _\!\#\$\%\^\&\*]*)'+postfix return source_string.match(match)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Возвращает сообщение о последнем произведенном действии # или классе последнего использованного объекта, используя метод # Kernel.inspect.<br> # <b>Пример:</b> # CIGUI.setup # puts CIGUI.last # => 'CIGUI started' # def last @last_action.is_a?(String) ? @last_action : @last_action.inspect end private # SETUP CIGUI / CLEAR FOR RESTART def _setup @last_action = nil @finished = false @windows = [] @sprites = [] @selection = { :type => nil, # may be window or sprite :index => 0, # index in internal array :label => nil # string in class to find index } @global_text.is_a?(NilClass) ? @global_text=Text.new('') : @global_text.empty end # RESTART def _restart?(string) matches=string.match(/#{CMB[:cigui_restart]}/) if matches __flush?('cigui flush') if not finished _setup @last_action = 'CIGUI restarted' else raise "#{CIGUIERR::CantInterpretCommand}\n\tcurrent line of $do: #{string}" if @finished end end # COMMON UNBRANCH def _common?(string) # select, please and other __swindow? string end def __swindow?(string) matches=string.match(/#{CMB[:select_window]}/) # Only match if matches # Read index or label if string.match(/#{CMB[:select_by_index]}/) index = dec(string,CMB[:select_by_index]) if index>-1 @selection[:type]=:window @selection[:index]=index if index.between?(0...@windows.size) @selection[:label]=@windows[index].label if @windows[index]!=nil && @windows[index].is_a?(Win3) end end elsif string.match(/#{CMB[:select_by_label]}/) label = substr(string,CMB[:select_by_label]) if label!=nil @selection[:type]=:window @selection[:label]=label for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label @selection[:index]=index break end end end end end @last_action = @selection end end#--------------------end of '__swindow?'------------------------- # CIGUI BRANCH def _cigui?(string) __start? string __finish? string __flush? string end def __start?(string) matches=string.match(/#{CMB[:cigui_start]}/) if matches begin @finished = false @last_action = 'CIGUI started' rescue raise "#{CIGUIERR::CantStart}\n\tcurrent line of $do: #{string}" end end end def __finish?(string) matches=string.match(/#{CMB[:cigui_finish]}/) if matches @finished = true @last_action = 'CIGUI finished' end end def __flush?(string) matches=string.match(/#{CMB[:cigui_flush]}/) if matches @windows.each{|item|item.dispose} @windows.clear @sprites.each{|item|item.dispose} @sprites.clear @last_action = 'CIGUI cleared' end end # WINDOW BRANCH def _window?(string) __wcreate? string __wdispose? string __wmove? string __wresize? string __wset? string __wactivate? string __wdeactivate? string __wopen? string __wclose? string end # Examples: # create window (default position and size) # create window at x=DEC, y=DEC # create window with width=DEC,height=DEC # create window at x=DEC, y=DEC with w=DEC, h=DEC def __wcreate?(string) matches=string.match(/#{CMB[:window_create]}/i) # Only create if matches begin begin @windows<<Win3.new if RUBY_VERSION.to_f >= 1.9 rescue @windows<<NilClass end @last_action = @windows.last rescue raise "#{CIGUIERR::CannotCreateWindow}\n\tcurrent line of $do: #{string}" end end # Read params if string.match(/#{CMB[:window_create_atORwith]}/i) # at OR with: check x and y new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows.last.x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows.last.y # at OR with: check w and h new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows.last.width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows.last.height # Set parameters for created window @windows.last.x = new_x @windows.last.y = new_y @windows.last.width = new_w @windows.last.height = new_h end # Set last action to inspect this window @last_action = @windows.last # Select this window @selection[:type]=:window @selection[:index]=@windows.size-1 end #--------------------end of '__wcreate?'------------------------- # Examples: # dispose window index=DEC # dispose window label=STR def __wdispose?(string) # Если какое-то окно уже выбрано, то... matches=string.match(/#{CMB[:window_dispose_this]}/i) if matches if @selection[:type]==:window #(0...@windows.size).include?(@selection[:index]) # ...удалим его как полагается... @windows[@selection[:index]].dispose if @windows[@selection[:index]].methods.include? :dispose @windows.delete_at(@selection[:index]) @last_action = 'CIGUI disposed window' return end end # ... а если же нет, то посмотрим, указаны ли его индекс или метка. matches=string.match(/#{CMB[:window_dispose]}/i) if matches if string.match(/#{CMB[:select_by_index]}/i) index=dec(string,CMB[:select_by_index]) if index.between?(0,@windows.size) # Проверка удаления для попавшихся объектов класса Nil # в результате ошибки создания окна @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) else raise "#{CIGUIERR::WrongWindowIndex}"+ "\n\tinternal windows size: #{@windows.size} (#{index} is not in range of 0..#{@windows.size})"+ "\n\tcurrent line of $do: #{string}" end elsif string.match(/#{CMB[:select_by_label]}/i) label = substr(string,CMB[:select_by_label]) if label!=nil for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label break end end end end @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) end @last_action = 'CIGUI disposed window' end end#--------------------end of '__wdispose?'------------------------- # Examples: # this move to x=DEC,y=DEC # this move to x=DEC,y=DEC with speed=1 # this move to x=DEC,y=DEC with speed=auto def __wmove?(string) matches=string.match(/#{CMB[:window_move]}/i) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].speed = new_s @last_action = @windows[@selection[:index]] end end end end#--------------------end of '__wmove?'------------------------- # example: # this resize to width=DEC,height=DEC def __wresize?(string) matches=string.match(/#{CMB[:window_resize]}/) # Only move if matches begin # Read params new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].resize(new_w,new_h) @last_action = @windows[@selection[:index]] end end end end#--------------------end of '__wresize?'------------------------- # examples: # this window set x=DEC, y=DEC, z=DEC, width=DEC, height=DEC # this window set label=[STR] # this window set opacity=DEC # this window set back opacity=DEC # this window set active=BOOL # this window set skin=[STR] # this window set openness=DEC # this window set cursor rect=[RECT] # this window set tone=[RECT] def __wset?(string) matches=string.match(/#{CMB[:window_set]}/) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_ox = string[/#{CMB[:window_ox_equal]}/i] ? dec(string,CMB[:window_ox_equal]) : @windows[@selection[:index]].ox new_oy = string[/#{CMB[:window_oy_equal]}/i] ? dec(string,CMB[:window_oy_equal]) : @windows[@selection[:index]].oy new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed new_a = string[/#{CMB[:window_a_equal]}/i] ? dec(string,CMB[:window_a_equal]) : @windows[@selection[:index]].opacity new_ba = string[/#{CMB[:window_ba_equal]}/i] ? dec(string,CMB[:window_ba_equal]) : @windows[@selection[:index]].back_opacity new_act = string[/#{CMB[:window_active_equal]}/i] ? boolean(string,CMB[:window_active_equal]) : @windows[@selection[:index]].active new_skin = string[/#{CMB[:window_skin_equal]}/i] ? substr(string,CMB[:window_skin_equal]) : @windows[@selection[:index]].windowskin new_open = string[/#{CMB[:window_openness_equal]}/i] ? dec(string,CMB[:window_openness_equal]) : @windows[@selection[:index]].openness new_label = string[/#{CMB[:select_by_label]}/i] ? substr(string,CMB[:select_by_label]) : @windows[@selection[:index]].label new_tone = string[/#{CMB[:window_tone_index]}/i] ? rect(string) : @windows[@selection[:index]].tone # Change it if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].ox = new_ox @windows[@selection[:index]].oy = new_oy @windows[@selection[:index]].resize(new_w,new_h) @windows[@selection[:index]].speed = new_s @windows[@selection[:index]].opacity = new_a @windows[@selection[:index]].back_opacity = new_ba @windows[@selection[:index]].active = new_act @windows[@selection[:index]].windowskin = new_skin @windows[@selection[:index]].openness = new_open @windows[@selection[:index]].label = new_label if new_tone.is_a? Tone @windows[@selection[:index]].tone.set(new_tone) elsif new_tone.is_a? Array @windows[@selection[:index]].tone.set(new_tone[0],new_tone[1],new_tone[2],new_tone[3]) end @selection[:label] = new_label @last_action = @windows[@selection[:index]] end end end end#--------------------end of '__wset?'------------------------- def __wactivate?(string) matches=string.match(/#{CMB[:window_activate]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].active=true @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wactivate?'------------------------- def __wdeactivate?(string) matches=string.match(/#{CMB[:window_deactivate]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].active=false @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wdeactivate?'------------------------- def __wopen?(string) matches=string.match(/#{CMB[:window_open]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].open @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wopen?'------------------------- def __wclose?(string) matches=string.match(/#{CMB[:window_close]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].close @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wopen?'------------------------- end# END OF CIGUI CLASS end# END OF CIGUI MODULE # test zone # delete this when copy to 'Script editor' in RPG Maker begin $do=[ 'create window', 'this window set tone=[1;20;3]' ] CIGUI.setup CIGUI.update puts CIGUI.last end Substr bug :negative_squared_cross_mark: - Added method 'bool' - Found bug in 'substr' method, try to fix # = Руководство Cigui # В данном руководстве описана работа модуля CIGUI, # а также методы для управления его работой.<br> # Рекомендуется к прочтению пользователям, имеющим навыки программирования # (написания скриптов) на Ruby.<br> # Для получения помощи по командам, обрабатываемым Cigui, # перейдите по адресу: <https://github.com/deadelf79/CIGUI/wiki> # --- # Author:: Sergey 'DeadElf79' Anikin (mailto:deadelf79@gmail.com) # License:: Public Domain (see <http://unlicense.org> for more information) # Модуль, содержащий данные обо всех возможных ошибках, которые # может выдать CIGUI при некорректной работе.<br> # Включает в себя: # * CIGUIERR::CantStart # * CIGUIERR::CantReadNumber # * CIGUIERR::CantReadString # * CIGUIERR::CantInterpretCommand # * CIGUIERR::CannotCreateWindow # * CIGUIERR::WrongWindowIndex # module CIGUIERR # Ошибка, которая появляется при неудачной попытке запуска интерпретатора Cigui # class CantStart < StandardError private def message 'Could not initialize module' end end # Ошибка, которая появляется, если в строке не было обнаружено числовое значение.<br> # Правила оформления строки указаны для каждого типа значений отдельно: # * целые числа - CIGUI.decimal # * дробные числа - CIGUI.fraction # class CantReadNumber < StandardError private def message 'Could not find numerical value in this string' end end # Ошибка, которая появляется, если в строке не было обнаружено строчное значение.<br> # Правила оформления строки и примеры использования указаны в описании # к этому методу: CIGUI.string # class CantReadString < StandardError private def message 'Could not find substring' end end # Ошибка, которая появляется при попытке работать с Cigui после # вызова команды <i>cigui finish</i>. # class CantInterpretCommand < StandardError private def message 'Unable to process the command after CIGUI was finished' end end # Ошибка создания окна. # class CannotCreateWindow < StandardError private def message 'Unable to create window' end end # Ошибка, которая появляется при попытке обращения # к несуществующему индексу в массиве <i>windows</i><br> # Вызывается при некорректном вводе пользователя # class WrongWindowIndex < StandardError private def message 'Index must be included in range of 0 to internal windows array size' end end end # Инициирует классы, если версия Ruby выше 1.9.0 # if RUBY_VERSION.to_f>=1.9 begin # Класс окна с реализацией всех возможностей, доступных при помощи Cigui.<br> # Реализация выполнена для RGSS3. # class Win3 < Window_Selectable # Скорость перемещения attr_accessor :speed # Прозрачность окна. Может принимать значения от 0 до 255 attr_accessor :opacity # Прозрачность фона окна. Может принимать значения от 0 до 255 attr_accessor :back_opacity # Метка окна. Строка, по которой происходит поиск экземпляра # в массиве CIGUI.windows при выборе окна по метке (select by label) attr_reader :label # Создает окно. По умолчанию задается размер 192х64 и # помещается в координаты 0, 0 # def initialize(x=0,y=0,w=192,h=64) super 0,0,192,64 @label=nil @items=[] @texts=[] @speed=1 end # Обновляет окно. Влияет только на положение курсора (параметр cursor_rect), # прозрачность и цветовой тон окна. def update;end # Обновляет окно. В отличие от #update, влияет только # на содержимое окна (производит повторную отрисовку). def refresh self.contents.clear end # Задает метку окну, проверяя ее на правильность перед этим: # * удаляет круглые и квадратгые скобки # * удаляет кавычки # * заменяет пробелы и табуляцию на символы подчеркивания # * заменяет символы "больше" и "меньше" на символы подчеркивания def label=(string) # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end # Этот метод позволяет добавить текст в окно.<br> # Принимает в качестве параметра значение класса Text def add_text(text) end # Этот метод добавляет команду во внутренний массив <i>items</i>. # Команды используются для отображения кнопок.<br> # * command - отображаемый текст кнопки # * procname - название вызываемого метода # По умолчанию значение enable равно true, что значит, # что кнопка включена и может быть нажата. # def add_item(command,procname,enabled=true) @items+=[ { :command=>command, :procname=>procname, :enabled=>enabled, :x=>:auto, :y=>:auto } ] end # Включает кнопку.<br> # В параметр commandORindex помещается либо строковое значение, # являющееся названием кнопки, либо целое число - индекс кнопки во внутреннем массиве <i>items</i>. # enable_item(0) # => @items[0].enabled set 'true' # enable_item('New game') # => @items[0].enabled set 'true' # def enable_item(commandORindex) case commandORindex.class when Integer, Float @items[commandORindex.to_i][:enabled]=true if (0...@items.size).include? commandORindex.to_i when String @items.times{|index|@items[index][:enabled]=true if @items[index][:command]==commandORindex} else raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{string}" end end # С помощью этого метода производится полная отрисовка всех # элементов из массива <i>items</i>.<br> # Параметр ignore_disabled отвечает за отображение выключенных # команд из массива <i>items</i>. Если его значение равно true, # то отрисовка выключенных команд производиться не будет. # def draw_items(ignore_disabled=false) end # Устанавливает новые размеры окна дополнительно изменяя # также и размеры содержимого (contents).<br> # Все части содержимого, которые не помещаются в новые размер, # удаляются безвозратно. # def resize(new_width, new_height) temp=Sprite.new temp.bitmap=self.contents self.contents.dispose src_rect(0,0,temp.width,temp.height) self.contents=Bitmap.new( width - padding * 2, height - padding * 2 ) self.contents.bit(0,0,temp.bitmap,src_rect,255) temp.bitmap.dispose temp.dispose width=new_width height=new_height end # Удаляет окно и все связанные с ним ресурсы # def dispose super end # Возврашает полную информацию обо всех параметрах # в формате строки # def inspect "<#{self.class}:"+ " @back_opacity=#{back_opacity},"+ " @contents_opacity=#{contents_opacity}"+ " @height=#{height},"+ " @opacity=#{opacity},"+ " @speed=#{@speed},"+ " @width=#{width},"+ " @x=#{x},"+ " @y=#{y}>" end end # Если классы инициировать не удалось (ошибка в отсутствии родительских классов), # то в память загружаются исключительно консольные версии (console-only) классов # необходимые для работы с командной строкой. rescue # Класс абстрактного (невизуального) прямоугольника. # Хранит значения о положении и размере прямоугольника class Rect # Координата X attr_accessor :x # Координата Y attr_accessor :y # Ширина прямоугольника attr_accessor :width # Высота прямоугольника attr_accessor :height # Создание прямоугольника # * x, y - назначает положение прямоуголника в пространстве # * width, height - устанавливает ширину и высоту прямоугольника def initialize(x,y,width,height) @x,@y,@width,@height = x,y,width,height end # Задает все параметры единовременно # Может принимать значения: # * Rect - другой экземпляр класса Rect, все значения копируются из него # * x, y, width, height - позиция и размер прямоугольника # # Оба варианта работают аналогично: # set(Rect.new(0,0,192,64)) # set(0,0,192,64) def set(*args) if args.size==1 @x,@y,@width,@height = args[0].x, args[0].y, args[0].width, args[0].height elsif args.size==4 @x,@y,@width,@height = args[0], args[1], args[2], args[3] elsif args.size.between?(2,3) # throw error, but i don't remember which error O_o end end # Устанавливает все параметры прямоугольника равными нулю. def empty @x,@y,@width,@height = 0, 0, 0, 0 end end # Класс, хранящий данные о цвете в формате RGBA # (красный, зеленый, синий и прозрачность). Каждое значение # является рациональным числом (число с плавающей точкой) и # имеет значение от 0.0 до 255.0. Все значения, выходящие # за указанный интервал, корректируются автоматически. # class Color # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * a - задает прозрачность, по умолчанию имеет значение 255.0 (полностью непрозрачный цвет) def initialize(r,g,b,a=255.0) @r,@g,@b,@a = r.to_f,g.to_f,b.to_f,a.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @r end # Возвращает значение синего цвета def blue @r end # Возвращает значение прозрачности def alpha @r end # Задает новые значения цвета и прозрачности.<br> # <b>Варианты параметров:</b> # * set(Color) - в качестве параметра задан другой экземпляр класса Color # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, alpha) - задает новые значения цвета и прозрачности. def set(*args) if args.size==1 @r,@g,@b,@a = args[0].red,args[0].green,args[0].blue,args[0].alpha elsif args.size==4 @r,@g,@b,@a = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@a = args[0],args[1],args[2],255.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=0 if @r<0 @r=255 if @r>255 @g=0 if @g<0 @g=255 if @g>255 @b=0 if @b<0 @b=255 if @b>255 @a=0 if @a<0 @a=255 if @a>255 end end # Класс, хранящий данные о тонировании в ввиде четырех значений: # красный, зеленый, синий и насыщенность. Последнее значение влияет # на цветовую насыщенность, чем ниже его значение, тем сильнее # цветовые оттенки заменяются на оттенки серого. # Каждое значение, кроме последнего, является рациональным числом # (число с плавающей точкой) и имеет значение от -255.0 до 255.0. # Значение насыщенности лежит в пределах от 0 до 255. # Все значения, выходящие за указанные интервалы, # корректируются автоматически. # class Tone # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * gs - задает насыщенность, по умолчанию имеет значение 0 def initialize(r,g,b,gs=0.0) @r,@g,@b,@gs = r.to_f,g.to_f,b.to_f,gs.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @r end # Возвращает значение синего цвета def blue @r end # Возвращает значение насыщенности def gray @gs end # Задает новые значения цвета и насыщенности.<br> # <b>Варианты параметров:</b> # * set(Tone) - в качестве параметра задан другой экземпляр класса Tone # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, greyscale) - задает новые значения цвета и насыщенности. def set(*args) if args.size==1 @r,@g,@b,@gs = args[0].red,args[0].green,args[0].blue,args[0].gray elsif args.size==4 @r,@g,@b,@gs = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@gs = args[0],args[1],args[2],0.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=-255.0 if @r<-255.0 @r=255.0 if @r>255.0 @g=-255.0 if @g<-255.0 @g=255.0 if @g>255.0 @b=-255.0 if @b<-255.0 @b=255.0 if @b>255.0 @gs=0.0 if @gs<0.0 @gs=255.0 if @gs>255.0 end end # Console-only version of this class class Win3#:nodoc: # X Coordinate of Window attr_accessor :x # Y Coordinate of Window attr_accessor :y # X Coordinate of contens attr_accessor :ox # Y Coordinate of contents attr_accessor :oy # Width of Window attr_accessor :width # Height of Window attr_accessor :height # Speed movement attr_accessor :speed # Opacity of window. May be in range of 0 to 255 attr_accessor :opacity # Back opacity of window. May be in range of 0 to 255 attr_accessor :back_opacity # Label of window attr_reader :label # If window is active then it updates attr_accessor :active # Openness of window attr_accessor :openness # Window skin - what window looks like attr_accessor :windowskin # Tone of the window attr_accessor :tone # # Create window def initialize @x,@y,@width,@height = 0, 0, 192, 64 @ox,@oy,@speed=0,0,:auto @opacity, @back_opacity, @contents_opacity = 255, 255, 255 @z, @tone, @openness = 100, Tone.new(0,0,0,0), 255 @active, @label = true, nil @windowskin='window' @items=[] end # Resize (simple) def resize(new_width, new_height) @width=new_width @height=new_height end # Update window (do nothing now) def update;end # Close window def close @openness=0 end # Open window def open @openness=255 end # Dispose window def dispose;end def label=(string) return if string.nil? # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end end # Класс спрайта со всеми параметрами, доступными в RGSS3. Пока пустой, ожидается обновление во время работы над спрайтами # (ветка work-with-sprites в github). # class Spr3 # Создает новый спрайт def initialize;end # Производит обновление спрайта def update;end # Производит повторную отрисовку содержимого спрайта def refresh;end # Удаляет спрайт def dispose;end end end end # Класс, хранящий данные о тексте в окне. Создается для каждого окна отдельно, # имеет индивидуальные настройки. class Text # Название файла изображения, из которого загружаются данные для отрисовки окон.<br> # По умолчанию задан путь 'Graphics\System\Window.png'. attr_accessor :windowskin # Массив цветов для отрисовки текста, по умолчанию содержит 32 цвета attr_accessor :colorset # Переменная класса Color, содержит цвет обводки текста. attr_accessor :out_color # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку обводки текста. По умолчанию, # обводка включена (outline=true) attr_accessor :outline # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку тени от текста. По умолчанию, # тень выключена (shadow=false) attr_accessor :shadow # Устанавливает жирность шрифта для <b>всего</b> текста.<br> # Игнорирует тег < b > в тексте attr_accessor :bold # Устанавливает наклон шрифта (курсив) для <b>всего</b> текста.<br> # Игнорирует тег < i > в тексте attr_accessor :italic # Устанавливает подчеркивание шрифта для <b>всего</b> текста.<br> # Игнорирует тег < u > в тексте attr_accessor :underline # Гарнитура (название) шрифта. По умолчанию - Tahoma attr_accessor :font # Размер шрифта. По умолчанию - 20 attr_accessor :size # Строка текста, которая будет отображена при использовании # экземпляра класса. attr_accessor :string # Создает экземпляр класса.<br> # <b>Параметры:</b> # * string - строка текста # * font_family - массив названий (гарнитур) шрифта, по умолчанию # имеет только "Tahoma". # При выборе гарнитуры шрифта, убедитесь в том, что символы, используемые # в тексте, корректно отображаются при использовании данного шрифта. # * font_size - размер шрифта, по умолчанию равен 20 пунктам # * bold - <b>жирный шрифт</b> (по умолчанию - false) # * italic - <i>курсив</i> (по умолчанию - false) # * underline - <u>подчеркнутый шрифт</u> (по умолчанию - false) def initialize(string, font_family=['Tahoma'], font_size=20, bold=false, italic=false, underline=false) @string=string @font=font_family @size=font_size @bold, @italic, @underline = bold, italic, underline @colorset=[] @out_color=Color.new(0,0,0,128) @shadow, @outline = false, true @windowskin='Graphics\\System\\Window.png' default_colorset end # Восстанавливает первоначальные значения цвета. По возможности, эти данные загружаются # из файла def default_colorset @colorset.clear if FileTest.exist?(@windowskin) bitmap=Bitmap.new(@windowskin) for y in 0..3 for x in 0..7 @colorset<<bitmap.get_pixel(x*8+64,y*8+96) end end bitmap.dispose else # Colors for this set was taken from <RTP path>/Graphics/Window.png file, # not just from the sky @colorset = [ # First row Color.new(255,255,255), # 1 Color.new(32, 160,214), # 2 Color.new(255,120, 76), # 3 Color.new(102,204, 64), # 4 Color.new(153,204,255), # 5 Color.new(204,192,255), # 6 Color.new(255,255,160), # 7 Color.new(128,128,128), # 8 # Second row Color.new(192,192,192), # 1 Color.new(32, 128,204), # 2 Color.new(255, 56, 16), # 3 Color.new( 0,160, 16), # 4 Color.new( 62,154,222), # 5 Color.new(160,152,255), # 6 Color.new(255,204, 32), # 7 Color.new( 0, 0, 0), # 8 # Third row Color.new(132,170,255), # 1 Color.new(255,255, 64), # 2 Color.new(255,120, 76), # 3 Color.new( 32, 32, 64), # 4 Color.new(224,128, 64), # 5 Color.new(240,192, 64), # 6 Color.new( 64,128,192), # 7 Color.new( 64,192,240), # 8 # Fourth row Color.new(128,255,128), # 1 Color.new(192,128,128), # 2 Color.new(128,128,255), # 3 Color.new(255,128,255), # 4 Color.new( 0,160, 64), # 5 Color.new( 0,224, 96), # 6 Color.new(160, 96,224), # 7 Color.new(192,128,255) # 8 ] end end # Сбрасывает все данные, кроме colorset, на значения по умолчанию def empty @string='' @font=['Tahoma'] @size=20 @bold, @italic, @underline = false, false, false @out_color=Color.new(0,0,0,128) @shadow, @outline = false, false @windowskin='Graphics\\System\\Window.png' end end # Основной модуль, обеспечивающий работу Cigui.<br> # Для передачи команд используйте массив $do, например: # * $do<<"команда" # * $do.push("команда") # Оба варианта имеют один и тот же результат.<br> # Перед запуском модуля вызовите метод CIGUI.setup.<br> # Для исполнения команд вызовите метод CIGUI.update.<br> # module CIGUI # Специальный словарь, содержащий все используемые команды Cigui. # Предоставляет возможности не только внесения новых слов, но и добавление # локализации (перевода) имеющихся (см. #update_by_user).<br> # Для удобства поиска разбит по категориям: # * common - общие команды, не имеющие категории; # * cigui - управление интерпретатором; # * event - событиями на карте; # * map - параметрами карты; # * picture - изображениями, используемыми через команды событий; # * sprite - самостоятельными изображениями; # * text - текстом и шрифтами # * window - окнами. # Русификацию этого словаря Вы можете найти в файле localize.rb # по адресу: <https://github.com/deadelf79/CIGUI/>, если этот файл # не приложен к демонстрационной версии проекта, который у Вас есть. # VOCAB={ #--COMMON unbranch :please=>'please', :last=>'last|this', :select=>'select', # by index or label :true=>'true|1', # for active||visible :false=>'false|0', :equal=>'[\s]*[\=]?[\s]*', #--CIGUI branch :cigui=>{ :main=>'cigui', :start=>'start', :finish=>'finish', :flush=>'flush', :restart=>'restart|resetup', }, #--EVENT branch :event=>{ :main=>'event|char(?:acter)?', :create=>'create|созда(?:[йть]|ва[йть])', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :load=>'load', # TAB #1 #~MESSAGE group :show=>'show', :message=>'message|text', :choices=>'choices', :scroll=>'scro[l]*(?:ing|er|ed)?', :input=>'input', :key=>'key|bu[t]*on', :number=>'number', :item=>'item', #to use as - select key item || condition branch item #~GAME PROGRESSION group :set=>'set|cotrol', # other word - see at :condition #~FLOW CONTROL group :condition=>'condition|if|case', :branch=>'bran[ch]|when', :switch=>'swit[ch]', :variable=>'var(?:iable)?', :self=>'self', # to use as - self switch :timer=>'timer', :min=>'min(?:ute[s]?)?', :sec=>'sec(?:[ou]nds)?', :ORmore=>'or[\s]*more', :ORless=>'or[\s]*less', :actor=>'actor', :in_party=>'in[\s]*party', :name=>'name', :applied=>'a[p]*lied', :class=>'cla[s]*', :skill=>'ski[l]*', :weapon=>'wea(?:p(?:on)?)?|wip(?:on)?', :armor=>'armo[u]?r', :state=>'stat(?:e|us)?', :enemy=>'enemy', :appeared=>'a[p]*eared', :inflicted=>'inflicted', # to use as - state inflicted :facing=>'facing', # to use as - event facing :up=>'up', :down=>'down', :left=>'left', :right=>'right', :vehicle=>'vehicle', :gold=>'gold|money', :script=>'script|code', :loop=>'loop', :break=>'break', :exit=>'exit', # to use as - exit event processing :call=>'call', :common=>'common', :label=>'label|link', :jump=>'jump(?:[\s]*to)?', :comment=>'comment', #~PARTY group :change=>'change', :party=>'party', :member=>'member', #~ACTOR group :hp=>'hp', :sp=>'[ms]p', :recover=>'recover', # may be used for one member :all=>'a[l]*', :exp=>'exp(?:irience)?', :level=>'l[e]?v[e]?l', :params=>'param(?:et[e]?r)s', :nickname=>'nick(?:name)?', # TAB#2 #~MOVEMENT group :transfer=>'transfer|teleport(?:ate|ion)', :player=>'player', :map=>'map', # to use as - scroll map || event map x :x=>'x', :y=>'y', :screen=>'scr[e]*n', # to use as - event screen x :route=>'rout(?:e|ing)?', :move=>'move|go', :forward=>'forward|в[\s]*пер[её][дт]', :backward=>'backward|н[ао][\s]*за[дт]', :lower=>'lower', :upper=>'upper', :random=>'rand(?:om[ed]*)?', :toward=>'toward', :away=>'away([\s]*from)?', :step=>'step', :get=>'get', :on=>'on', :off=>'off', # to use as - get on/off vehicle :turn=>'turn', :clockwise=>'clockwise', # по часовой :counterclockwise=>'counter[\s]clockwise', # против часовой :emulate=>'emulate', :click=>'click|tap', :touch=>'touch|enter', :by_event=>'by[\s]*event', :autorun=>'auto[\s]*run', :parallel=>'para[ll]*el', :wait=>'wait', :frames=>'frame[s]?', }, #--MAP branch :map=>{ :main=>'map', :name=>'name', :width=>'width', :height=>'height', }, #--PICTURE branch :picture=>{ :maybe=>'in future versions' }, #--SPRITE branch :sprite=>{ :main=>'sprite|спрайт', :create=>'create|созда(?:[йть]|ва[йть])', :dispose=>'dispose|delete', :move=>'move', :resize=>'resize', :set=>'set', :x=>'x|х|икс', :y=>'y|у|игрек', :width=>'width', :height=>'height', }, #--TEXT branch :text=>{ :main=>'text', :make=>'make', :bigger=>'bigger', :smaller=>'smaller', :set=>'set', :font=>'font', :size=>'size', }, #--WINDOW branch :window=>{ :main=>'window', :create=>'create', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :move=>'move', :to=>'to', :speed=>'speed', :auto=>'auto', :resize=>'resize', :set=>'set', :x=>'x', :y=>'y', :z=>'z', :ox=>'ox', :oy=>'oy', :tone=>'tone', :width=>'width', :height=>'height', :link=>'link', # to use as - set button[DEC] link to switch[DEC] #dunnolol :label=>'label', :index=>'index', :indexed=>'indexed', :labeled=>'labeled', :as=>'as', :opacity=>'opacity', :back=>'back', # to use as - set back opacity :contents=>'contents', # to use as - set contents opacity :open=>'open', :openness=>'openness', :close=>'close', :active=>'active', :activate=>'activate', :deactivate=>'deactivate', :windowskin=>'skin|window[\s_]*skin', :cursor=>'cursor', :rect=>'rect', } } # Хэш-таблица всех возможных сочетаний слов из VOCAB и их положения относительно друг друга в тексте.<br> # Именно по этим сочетаниям производится поиск команд Cigui в тексте. Редактировать без понимания правил # составления регулярных выражений не рекомендуется. CMB={ #~COMMON unbranch # selection window :select_window=>"(?:(?:#{VOCAB[:select]})+[\s]*(?:#{VOCAB[:window][:main]})+)|"+ "(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:select]})+)", :select_by_index=>"(?:(?:#{VOCAB[:window][:index]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:indexed]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?)", :select_by_label=>"(?:(?:#{VOCAB[:window][:label]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:labeled]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?)", #~CIGUI branch # commands only :cigui_start=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:start]})+)+", :cigui_finish=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:finish]})+)+", :cigui_flush=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:flush]})+)+", :cigui_restart=>"((?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:restart]})+)+", #~WINDOW branch # expressions :window_x_equal=>"(?:#{VOCAB[:window][:x]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_y_equal=>"(?:#{VOCAB[:window][:y]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ox_equal=>"(?:#{VOCAB[:window][:ox]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_oy_equal=>"(?:#{VOCAB[:window][:oy]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_w_equal=>"(?:#{VOCAB[:window][:width]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_h_equal=>"(?:#{VOCAB[:window][:height]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_s_equal=>"(?:#{VOCAB[:window][:speed]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_a_equal=>"(?:#{VOCAB[:window][:opacity]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ba_equal=>"(?:(?:#{VOCAB[:window][:back]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_ca_equal=>"(?:(?:#{VOCAB[:window][:contents]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_active_equal=>"(?:#{VOCAB[:window][:active]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_skin_equal=>"(?:(?:#{VOCAB[:window][:windowskin]})+(?:#{VOCAB[:equal]}|[\s]*)+)", :window_openness_equal=>"(?:#{VOCAB[:window][:openness]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_tone_equal=>"(?:#{VOCAB[:window][:tone]})+(?:#{VOCAB[:equal]}|[\s]*)+", # commands :window_create=>"(((?:#{VOCAB[:window][:create]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:create]})+)", :window_create_atORwith=>"((?:#{VOCAB[:window][:at]})+[\s]*(#{VOCAB[:window][:x]}|#{VOCAB[:window][:y]})+)|"+ "((?:#{VOCAB[:window][:with]})+[\s]*(?:#{VOCAB[:window][:width]}|#{VOCAB[:window][:height]}))", :window_dispose=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_dispose_this=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_move=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:move]}))|"+ "(?:(?:#{VOCAB[:window][:move]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_resize=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:resize]}))|"+ "(?:(?:#{VOCAB[:window][:resize]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_set=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:set]})+)|"+ "(?:(?:#{VOCAB[:window][:set]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_activate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:activate]})+)|"+ "(?:(?:#{VOCAB[:window][:activate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_deactivate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:deactivate]})+)|"+ "(?:(?:#{VOCAB[:window][:deactivate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_open=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:open]}))|"+ "(?:(?:#{VOCAB[:window][:open]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", :window_close=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:close]}))|"+ "(?:(?:#{VOCAB[:window][:close]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", } # class <<self # Внутренний массив для вывода информации обо всех созданных окнах.<br> # Открыт только для чтения. # attr_reader :windows # Внутренний массив для вывода информации обо всех созданных спрайтах.<br> # Открыт только для чтения. # attr_reader :sprites # Требуется выполнить этот метод перед началом работы с CIGUI.<br> # Инициализирует массив $do, если он еще не был создан. В этот массив пользователь подает # команды для исполнения при следующем запуске метода #update.<br> # Если даже массив $do был инициализирован ранее, # то исполняет команду <i>cigui start</i> прежде всего.<br> # <b>Пример:</b> # begin # CIGUI.setup # #~~~ some code fragment ~~~ # CIGUI.update # #~~~ some other code fragment ~~~ # end # def setup $do||=[] $do.insert 0,'cigui start' _setup end # Вызывает все методы обработки команд, содержащиеся в массиве $do.<br> # Вызовет исключение CIGUIERR::CantInterpretCommand в том случае, # если после выполнения <i>cigui finish</i> в массиве $do будут находится # новые команды для обработки.<br> # По умолчанию очищает массив $do после обработки всех команд. Если clear_after_update # поставить значение false, то все команды из массива $do будут выполнены повторно # при следующем запуске этого метода.<br> # Помимо приватных методов обработки вызывает также метод #update_by_user, который может быть # модифицирован пользователем (подробнее смотри в описании метода).<br> # def update(clear_after_update=true) $do.each do |line| _restart? line _common? line _cigui? line _window? line #_ update_internal_objects update_by_user(line) end $do.clear if clear_after_update end # Вызывает обновление всех объектов из внутренних массивов ::windows и ::sprites.<br> # Вызывается автоматически по окончании обработки команд из массива $do в методе #update. def update_internal_objects @windows.each{ |win| win.update if win.is_a? Win3 } @sprites.each{ |spr| spr.update if spr.is_a? Spr3 } end # Метод обработки текста, созданный для пользовательских модификаций, не влияющих на работу # встроенных обработчиков.<br> # Используйте <i>alias</i> этого метода при добавлении обработки собственных команд.<br> # <b>Пример:</b> # alias my_update update_by_user # def update_by_user # # add new word # VOCAB[:window][:throw]='throw' # # add 'window throw' combination # CMB[:window_throw]="(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:throw]})+)" # # call method # window_throw? line # end # def update_by_user(string) end # Данный метод возвращает первое попавшееся целое число, найденное в строке source_string.<br> # Производит поиск только в том случае, если число записано: # * в скобки, например (10); # * в квадратные скобки, например [23]; # * в кавычки(апострофы), например '45'; # * в двойные кавычки, например "8765". # Также, вернет всю целую часть числа записанную: # * до точки, так здесь [1.35] вернет 1; # * до запятой, так здесь (103,81) вернет 103; # * до первого пробела (при стандартной конвертации в целое число), так здесь "816 586,64" вернет только 816; # * через символ подчеркивания, так здесь '1_000_0_0_0,143' вернет ровно один миллион (1000000). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # decimal('[10,25]') # => 10 # decimal('[1 0 2]',false) # => 102 # decimal('[1_234_5678 89]',false) # => 123456789 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def decimal(source_string, std_conversion=true) fraction(source_string, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #decimal, но возвращает рациональное число # (число с плавающей запятой или точкой).<br> # Имеется пара замечаний к правилам использования в дополнение к упомянутым в #decimal: # * Все цифры после запятой или точки считаются дробной частью и также могут содержать помимо цифр символ подчёркивания; # * При наличии между цифрами в дробной части пробела вернет ноль (в стандартной конвертации в целое или дробное число). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # fraction('(109,86)') # => 109.86 # fraction('(1 0 9 , 8 6)',false) # => 109.86 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def fraction(source_string, std_conversion=true) match='(?:[\[|"\(\'])[\s]*([\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)(?:[\]|"\)\'])' return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск подстроки, используемой в качестве параметра.<br> # Строка должна быть заключена в одинарные или двойные кавычки или же в круглые # или квадратные скобки. # substring('[Hello cruel world!]') # => Hello cruel world! # substring("set window label='SomeSome' and no more else") # => SomeSome # def substring(source_string) match='(?:[\[\(\"\'])[\s]*([\w\s _\!\#\$\%\^\&\*]*)[\s]*(?:[\]|"\)\'])' return source_string.match(match)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск булевого значения (true или false) в строке и возвращает его. # Если булевое значение в строке не обнаружено, по умолчанию возвращает false. def boolean(source_string) match="((?:#{VOCAB[:true]}|#{VOCAB[:false]}))" if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает массив из четырех значений для передачи в качестве параметра # в объекты класса Rect. Массив в строке должен быть помещен в квадратные скобки, # а значения в нем должны разделяться <b>точкой с запятой.</b><br> # <b>Пример:</b> # rect('[1;2,0;3.5;4.0_5]') # => [ 1, 2.0, 3.5, 4.05 ] # def rect(source_string) read='' start=false arr=[] for index in 0...source_string.size char=source_string[index] if char=='[' start=true next end if start if char!=';' if char!=']' read+=char else arr<<read break end else arr<<read read='' end end end if arr.size<4 for index in 1..4-arr.size arr<<0 end elsif arr.size>4 arr.slice!(4,arr.size) end for index in 0...arr.size arr[index]=dec(arr[index]) if arr[index].is_a? String arr[index]=0 if arr[index].is_a? NilClass end return arr end # Данный метод работает по аналогии с #decimal, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # dec('x=1cm','x=','cm') # => 1 # dec('y=120 m','[xy]=','[\s]*(?:cm|m|km)') # => 120 # В отличие от #frac, возвращает целое число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def dec(source_string, prefix='', postfix='', std_conversion=true) frac(source_string, prefix, postfix, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #fraction, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # frac('x=31.2mm','x=','mm') # => 31.2 # frac('y=987,67 m','[xy]=','[\s]*(?:cm|m|km)') # => 987.67 # В отличие от #dec, возвращает рациональное число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def frac(source_string, prefix='', postfix='', std_conversion=true) match=prefix+'([\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)'+postfix return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #substring, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг подстроки.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # puts 'Who can make me strong?' # someone = substring("Make me invincible",'Make','invincible') # puts 'Only'+someone # => 'Only me' # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def substr(source_string, prefix='', postfix='') match=prefix+"([\w\s _\!\#\$\%\^\&\*]*)"+postfix p source_string.match(/#{match}/i) return source_string.match(/#{match}/i)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает аналогично с #boolean, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # Если булевое значение в строке не обнаружено, по умолчанию возвращает false. def bool(source_string, prefix='', postfix='') match=prefix+"((?:#{VOCAB[:true]}|#{VOCAB[:false]}))"+postfix if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает сообщение о последнем произведенном действии # или классе последнего использованного объекта, используя метод # Kernel.inspect.<br> # <b>Пример:</b> # CIGUI.setup # puts CIGUI.last # => 'CIGUI started' # def last @last_action.is_a?(String) ? @last_action : @last_action.inspect end private # SETUP CIGUI / CLEAR FOR RESTART def _setup @last_action = nil @finished = false @windows = [] @sprites = [] @selection = { :type => nil, # may be window or sprite :index => 0, # index in internal array :label => nil # string in class to find index } @global_text.is_a?(NilClass) ? @global_text=Text.new('') : @global_text.empty end # RESTART def _restart?(string) matches=string.match(/#{CMB[:cigui_restart]}/) if matches __flush?('cigui flush') if not finished _setup @last_action = 'CIGUI restarted' else raise "#{CIGUIERR::CantInterpretCommand}\n\tcurrent line of $do: #{string}" if @finished end end # COMMON UNBRANCH def _common?(string) # select, please and other __swindow? string end def __swindow?(string) matches=string.match(/#{CMB[:select_window]}/) # Only match if matches # Read index or label if string.match(/#{CMB[:select_by_index]}/) index = dec(string,CMB[:select_by_index]) if index>-1 @selection[:type]=:window @selection[:index]=index if index.between?(0...@windows.size) @selection[:label]=@windows[index].label if @windows[index]!=nil && @windows[index].is_a?(Win3) end end elsif string.match(/#{CMB[:select_by_label]}/) label = substr(string,CMB[:select_by_label]) if label!=nil @selection[:type]=:window @selection[:label]=label for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label @selection[:index]=index break end end end end end @last_action = @selection end end#--------------------end of '__swindow?'------------------------- # CIGUI BRANCH def _cigui?(string) __start? string __finish? string __flush? string end def __start?(string) matches=string.match(/#{CMB[:cigui_start]}/) if matches begin @finished = false @last_action = 'CIGUI started' rescue raise "#{CIGUIERR::CantStart}\n\tcurrent line of $do: #{string}" end end end def __finish?(string) matches=string.match(/#{CMB[:cigui_finish]}/) if matches @finished = true @last_action = 'CIGUI finished' end end def __flush?(string) matches=string.match(/#{CMB[:cigui_flush]}/) if matches @windows.each{|item|item.dispose} @windows.clear @sprites.each{|item|item.dispose} @sprites.clear @last_action = 'CIGUI cleared' end end # WINDOW BRANCH def _window?(string) __wcreate? string __wdispose? string __wmove? string __wresize? string __wset? string __wactivate? string __wdeactivate? string __wopen? string __wclose? string end # Examples: # create window (default position and size) # create window at x=DEC, y=DEC # create window with width=DEC,height=DEC # create window at x=DEC, y=DEC with w=DEC, h=DEC def __wcreate?(string) matches=string.match(/#{CMB[:window_create]}/i) # Only create if matches begin begin @windows<<Win3.new if RUBY_VERSION.to_f >= 1.9 rescue @windows<<NilClass end @last_action = @windows.last rescue raise "#{CIGUIERR::CannotCreateWindow}\n\tcurrent line of $do: #{string}" end end # Read params if string.match(/#{CMB[:window_create_atORwith]}/i) # at OR with: check x and y new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows.last.x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows.last.y # at OR with: check w and h new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows.last.width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows.last.height # Set parameters for created window @windows.last.x = new_x @windows.last.y = new_y @windows.last.width = new_w @windows.last.height = new_h end # Set last action to inspect this window @last_action = @windows.last # Select this window @selection[:type]=:window @selection[:index]=@windows.size-1 end #--------------------end of '__wcreate?'------------------------- # Examples: # dispose window index=DEC # dispose window label=STR def __wdispose?(string) # Если какое-то окно уже выбрано, то... matches=string.match(/#{CMB[:window_dispose_this]}/i) if matches if @selection[:type]==:window #(0...@windows.size).include?(@selection[:index]) # ...удалим его как полагается... @windows[@selection[:index]].dispose if @windows[@selection[:index]].methods.include? :dispose @windows.delete_at(@selection[:index]) @last_action = 'CIGUI disposed window' return end end # ... а если же нет, то посмотрим, указаны ли его индекс или метка. matches=string.match(/#{CMB[:window_dispose]}/i) if matches if string.match(/#{CMB[:select_by_index]}/i) index=dec(string,CMB[:select_by_index]) if index.between?(0,@windows.size) # Проверка удаления для попавшихся объектов класса Nil # в результате ошибки создания окна @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) else raise "#{CIGUIERR::WrongWindowIndex}"+ "\n\tinternal windows size: #{@windows.size} (#{index} is not in range of 0..#{@windows.size})"+ "\n\tcurrent line of $do: #{string}" end elsif string.match(/#{CMB[:select_by_label]}/i) label = substr(string,CMB[:select_by_label]) if label!=nil for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label break end end end end @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) end @last_action = 'CIGUI disposed window' end end#--------------------end of '__wdispose?'------------------------- # Examples: # this move to x=DEC,y=DEC # this move to x=DEC,y=DEC with speed=1 # this move to x=DEC,y=DEC with speed=auto def __wmove?(string) matches=string.match(/#{CMB[:window_move]}/i) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].speed = new_s @last_action = @windows[@selection[:index]] end end end end#--------------------end of '__wmove?'------------------------- # example: # this resize to width=DEC,height=DEC def __wresize?(string) matches=string.match(/#{CMB[:window_resize]}/) # Only move if matches begin # Read params new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].resize(new_w,new_h) @last_action = @windows[@selection[:index]] end end end end#--------------------end of '__wresize?'------------------------- # examples: # this window set x=DEC, y=DEC, z=DEC, width=DEC, height=DEC # this window set label=[STR] # this window set opacity=DEC # this window set back opacity=DEC # this window set active=BOOL # this window set skin=[STR] # this window set openness=DEC # this window set cursor rect=[RECT] # this window set tone=[RECT] def __wset?(string) matches=string.match(/#{CMB[:window_set]}/) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_ox = string[/#{CMB[:window_ox_equal]}/i] ? dec(string,CMB[:window_ox_equal]) : @windows[@selection[:index]].ox new_oy = string[/#{CMB[:window_oy_equal]}/i] ? dec(string,CMB[:window_oy_equal]) : @windows[@selection[:index]].oy new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed new_a = string[/#{CMB[:window_a_equal]}/i] ? dec(string,CMB[:window_a_equal]) : @windows[@selection[:index]].opacity new_ba = string[/#{CMB[:window_ba_equal]}/i] ? dec(string,CMB[:window_ba_equal]) : @windows[@selection[:index]].back_opacity new_act = string[/#{CMB[:window_active_equal]}/i] ? bool(string,CMB[:window_active_equal]) : @windows[@selection[:index]].active new_skin = string[/#{CMB[:window_skin_equal]}/i] ? substr(string,CMB[:window_skin_equal]) : @windows[@selection[:index]].windowskin new_open = string[/#{CMB[:window_openness_equal]}/i] ? dec(string,CMB[:window_openness_equal]) : @windows[@selection[:index]].openness new_label = string[/#{CMB[:select_by_label]}/i] ? substring(string) : @windows[@selection[:index]].label new_tone = string[/#{CMB[:window_tone_index]}/i] ? rect(string) : @windows[@selection[:index]].tone # Change it if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].ox = new_ox @windows[@selection[:index]].oy = new_oy @windows[@selection[:index]].resize(new_w,new_h) @windows[@selection[:index]].speed = new_s==0 ? :auto : new_s @windows[@selection[:index]].opacity = new_a @windows[@selection[:index]].back_opacity = new_ba @windows[@selection[:index]].active = new_act @windows[@selection[:index]].windowskin = new_skin @windows[@selection[:index]].openness = new_open @windows[@selection[:index]].label = new_label if new_tone.is_a? Tone @windows[@selection[:index]].tone.set(new_tone) elsif new_tone.is_a? Array @windows[@selection[:index]].tone.set(new_tone[0],new_tone[1],new_tone[2],new_tone[3]) end @selection[:label] = new_label @last_action = @windows[@selection[:index]] end end end end#--------------------end of '__wset?'------------------------- def __wactivate?(string) matches=string.match(/#{CMB[:window_activate]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].active=true @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wactivate?'------------------------- def __wdeactivate?(string) matches=string.match(/#{CMB[:window_deactivate]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].active=false @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wdeactivate?'------------------------- def __wopen?(string) matches=string.match(/#{CMB[:window_open]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].open @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wopen?'------------------------- def __wclose?(string) matches=string.match(/#{CMB[:window_close]}/) if matches if @selection[:type]==:window @windows[@selection[:index]].close @last_action = @windows[@selection[:index]] end end end#--------------------end of '__wopen?'------------------------- end# END OF CIGUI CLASS end# END OF CIGUI MODULE # test zone # delete this when copy to 'Script editor' in RPG Maker begin $do=[ 'create window at x=1540,y=9000 with width=900,height=560', 'this window set ox=22,oy=33,tone=[255;123;40;20],label=[Current],speed=0,windowskin="Something other"', 'close this window', 'deactivate this window', 'this window set active=true' ] CIGUI.setup CIGUI.update puts CIGUI.last end
# = Руководство Cigui # В данном руководстве описана работа модуля CIGUI, # а также методы для управления его работой.<br> # Рекомендуется к прочтению пользователям, имеющим навыки программирования # (написания скриптов) на Ruby.<br> # Для получения помощи по командам, обрабатываемым Cigui, # перейдите по адресу: <https://github.com/deadelf79/CIGUI/wiki> # --- # Author:: Sergey 'DeadElf79' Anikin (mailto:deadelf79@gmail.com) # License:: Public Domain (see <http://unlicense.org> for more information) # Модуль, содержащий данные обо всех возможных ошибках, которые # может выдать CIGUI при некорректной работе.<br> # Включает в себя: # * CIGUIERR::CantStart # * CIGUIERR::CantReadNumber # * CIGUIERR::CantReadString # * CIGUIERR::CantInterpretCommand # * CIGUIERR::CannotCreateWindow # * CIGUIERR::WrongWindowIndex # module CIGUIERR # Ошибка, которая появляется при неудачной попытке запуска интерпретатора Cigui # class CantStart < StandardError private def message 'Could not initialize module' end end # Ошибка, которая появляется, если в строке не было обнаружено числовое значение.<br> # Правила оформления строки указаны для каждого типа значений отдельно: # * целые числа - CIGUI.decimal # * дробные числа - CIGUI.fraction # class CantReadNumber < StandardError private def message 'Could not find numerical value in this string' end end # Ошибка, которая появляется, если в строке не было обнаружено строчное значение.<br> # Правила оформления строки и примеры использования указаны в описании # к этому методу: CIGUI.string # class CantReadString < StandardError private def message 'Could not find substring' end end # Ошибка, которая появляется при попытке работать с Cigui после # вызова команды <i>cigui finish</i>. # class CantInterpretCommand < StandardError private def message 'Unable to process the command after CIGUI was finished' end end # Ошибка создания окна. # class CannotCreateWindow < StandardError private def message 'Unable to create window' end end # Ошибка, которая появляется при попытке обращения # к несуществующему индексу в массиве <i>windows</i><br> # Вызывается при некорректном вводе пользователя # class WrongWindowIndex < StandardError private def message 'Index must be included in range of 0 to internal windows array size' end end end # Инициирует классы, если версия Ruby выше 1.9.0 # if RUBY_VERSION.to_f>=1.9 begin # Класс окна с реализацией всех возможностей, доступных при помощи Cigui.<br> # Реализация выполнена для RGSS3. # class Win3 < Window_Selectable # Скорость перемещения attr_accessor :speed # Прозрачность окна. Может принимать значения от 0 до 255 attr_accessor :opacity # Прозрачность фона окна. Может принимать значения от 0 до 255 attr_accessor :back_opacity # Метка окна. Строка, по которой происходит поиск экземпляра # в массиве CIGUI.windows при выборе окна по метке (select by label) attr_reader :label # Создает окно. По умолчанию задается размер 192х64 и # помещается в координаты 0, 0 # def initialize(x=0,y=0,w=192,h=64) super 0,0,192,64 @label=nil @items=[] @texts=[] @speed=1 end # Обновляет окно. Влияет только на положение курсора (параметр cursor_rect), # прозрачность и цветовой тон окна. def update;end # Обновляет окно. В отличие от #update, влияет только # на содержимое окна (производит повторную отрисовку). def refresh self.contents.clear end # Задает метку окну, проверяя ее на правильность перед этим: # * удаляет круглые и квадратгые скобки # * удаляет кавычки # * заменяет пробелы и табуляцию на символы подчеркивания # * заменяет символы "больше" и "меньше" на символы подчеркивания def label=(string) # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end # Этот метод позволяет добавить текст в окно.<br> # Принимает в качестве параметра значение класса Text def add_text(text) add_item(text, "text_#{@index.last}".to_sym, false, true) end # Этот метод добавляет команду во внутренний массив <i>items</i>. # Команды используются для отображения кнопок.<br> # * command - отображаемый текст кнопки # * procname - название вызываемого метода # По умолчанию значение enable равно true, что значит, # что кнопка включена и может быть нажата. # def add_item(command,procname,enabled=true, text_only=false) @items+=[ { :command=>command, :procname=>procname, :enabled=>enabled, :x=>:auto, :y=>:auto, :text_only=text_only } ] end # Включает кнопку.<br> # В параметр commandORindex помещается либо строковое значение, # являющееся названием кнопки, либо целое число - индекс кнопки во внутреннем массиве <i>items</i>. # enable_item(0) # => @items[0].enabled set 'true' # enable_item('New game') # => @items[0].enabled set 'true' # Включение происходит только если кнопка не имеет тип text_only (устанавливается # при добавлении с помощью метода #add_text). # def enable_item(commandORindex) case commandORindex.class when Integer, Float @items[commandORindex.to_i][:enabled]=true if (0...@items.size).include? commandORindex.to_i @items[commandORindex.to_i][:enabled]=false if @items[commandORindex.to_i][:text_only] when String index=0 @items.times{|index|@items[index][:enabled]=true if @items[index][:command]==commandORindex} @items[index][:enabled]=false if @items[index][:text_only] else raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{string}" end end # Выключает кнопку.<br> # В параметр commandORindex помещается либо строковое значение, # являющееся названием кнопки, либо целое число - индекс кнопки во внутреннем массиве <i>items</i>. # disable_item(0) # => @items[0].enabled set 'false' # disable_item('New game') # => @items[0].enabled set 'false' # Выключение происходит только если кнопка не имеет тип text_only (устанавливается # при добавлении с помощью метода #add_text). # def disable_item(commandORindex) case commandORindex.class when Integer, Float @items[commandORindex.to_i][:enabled]=false if (0...@items.size).include? commandORindex.to_i @items[commandORindex.to_i][:enabled]=false if @items[commandORindex.to_i][:text_only] when String index=0 @items.times{|index|@items[index][:enabled]=false if @items[index][:command]==commandORindex} @items[index][:enabled]=false if @items[index][:text_only] else raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{string}" end end # С помощью этого метода производится полная отрисовка всех # элементов из массива <i>items</i>.<br> # Параметр ignore_disabled отвечает за отображение выключенных # команд из массива <i>items</i>. Если его значение равно true, # то отрисовка выключенных команд производиться не будет. # def draw_items(ignore_disabled=false) end # Устанавливает новые размеры окна дополнительно изменяя # также и размеры содержимого (contents).<br> # Все части содержимого, которые не помещаются в новые размер, # удаляются безвозратно. # def resize(new_width, new_height) temp=Sprite.new temp.bitmap=self.contents self.contents.dispose src_rect(0,0,temp.width,temp.height) self.contents=Bitmap.new( width - padding * 2, height - padding * 2 ) self.contents.bit(0,0,temp.bitmap,src_rect,255) temp.bitmap.dispose temp.dispose width=new_width height=new_height end # Удаляет окно и все связанные с ним ресурсы # def dispose super end # Возврашает полную информацию обо всех параметрах # в формате строки # def inspect "<#{self.class}:"+ " @back_opacity=#{back_opacity},"+ " @contents_opacity=#{contents_opacity}"+ " @height=#{height},"+ " @opacity=#{opacity},"+ " @speed=#{@speed},"+ " @width=#{width},"+ " @x=#{x},"+ " @y=#{y}>" end end # Если классы инициировать не удалось (ошибка в отсутствии родительских классов), # то в память загружаются исключительно консольные версии (console-only) классов # необходимые для работы с командной строкой. rescue # Класс абстрактного (невизуального) прямоугольника. # Хранит значения о положении и размере прямоугольника class Rect # Координата X attr_accessor :x # Координата Y attr_accessor :y # Ширина прямоугольника attr_accessor :width # Высота прямоугольника attr_accessor :height # Создание прямоугольника # * x, y - назначает положение прямоуголника в пространстве # * width, height - устанавливает ширину и высоту прямоугольника def initialize(x,y,width,height) @x,@y,@width,@height = x,y,width,height end # Задает все параметры единовременно # Может принимать значения: # * Rect - другой экземпляр класса Rect, все значения копируются из него # * x, y, width, height - позиция и размер прямоугольника # # Оба варианта работают аналогично: # set(Rect.new(0,0,192,64)) # set(0,0,192,64) def set(*args) if args.size==1 @x,@y,@width,@height = args[0].x, args[0].y, args[0].width, args[0].height elsif args.size==4 @x,@y,@width,@height = args[0], args[1], args[2], args[3] elsif args.size.between?(2,3) # throw error, but i don't remember which error O_o end end # Устанавливает все параметры прямоугольника равными нулю. def empty @x,@y,@width,@height = 0, 0, 0, 0 end end # Класс, хранящий данные о цвете в формате RGBA # (красный, зеленый, синий и прозрачность). Каждое значение # является рациональным числом (число с плавающей точкой) и # имеет значение от 0.0 до 255.0. Все значения, выходящие # за указанный интервал, корректируются автоматически. # class Color # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * a - задает прозрачность, по умолчанию имеет значение 255.0 (полностью непрозрачный цвет) def initialize(r,g,b,a=255.0) @r,@g,@b,@a = r.to_f,g.to_f,b.to_f,a.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @g end # Возвращает значение синего цвета def blue @b end # Возвращает значение прозрачности def alpha @a end # Задает новые значения цвета и прозрачности.<br> # <b>Варианты параметров:</b> # * set(Color) - в качестве параметра задан другой экземпляр класса Color # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, alpha) - задает новые значения цвета и прозрачности. def set(*args) if args.size==1 @r,@g,@b,@a = args[0].red,args[0].green,args[0].blue,args[0].alpha elsif args.size==4 @r,@g,@b,@a = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@a = args[0],args[1],args[2],255.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=0 if @r<0 @r=255 if @r>255 @g=0 if @g<0 @g=255 if @g>255 @b=0 if @b<0 @b=255 if @b>255 @a=0 if @a<0 @a=255 if @a>255 end end # Класс, хранящий данные о тонировании в ввиде четырех значений: # красный, зеленый, синий и насыщенность. Последнее значение влияет # на цветовую насыщенность, чем ниже его значение, тем сильнее # цветовые оттенки заменяются на оттенки серого. # Каждое значение, кроме последнего, является рациональным числом # (число с плавающей точкой) и имеет значение от -255.0 до 255.0. # Значение насыщенности лежит в пределах от 0 до 255. # Все значения, выходящие за указанные интервалы, # корректируются автоматически. # class Tone # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * gs - задает насыщенность, по умолчанию имеет значение 0 def initialize(r,g,b,gs=0.0) @r,@g,@b,@gs = r.to_f,g.to_f,b.to_f,gs.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @g end # Возвращает значение синего цвета def blue @b end # Возвращает значение насыщенности def gray @gs end # Задает новые значения цвета и насыщенности.<br> # <b>Варианты параметров:</b> # * set(Tone) - в качестве параметра задан другой экземпляр класса Tone # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, greyscale) - задает новые значения цвета и насыщенности. def set(*args) if args.size==1 @r,@g,@b,@gs = args[0].red,args[0].green,args[0].blue,args[0].gray elsif args.size==4 @r,@g,@b,@gs = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@gs = args[0],args[1],args[2],0.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=-255.0 if @r<-255.0 @r=255.0 if @r>255.0 @g=-255.0 if @g<-255.0 @g=255.0 if @g>255.0 @b=-255.0 if @b<-255.0 @b=255.0 if @b>255.0 @gs=0.0 if @gs<0.0 @gs=255.0 if @gs>255.0 end end # Console-only version of this class class Win3#:nodoc: # X Coordinate of Window attr_accessor :x # Y Coordinate of Window attr_accessor :y # X Coordinate of contens attr_accessor :ox # Y Coordinate of contents attr_accessor :oy # Width of Window attr_accessor :width # Height of Window attr_accessor :height # Speed movement attr_accessor :speed # Opacity of window. May be in range of 0 to 255 attr_accessor :opacity # Back opacity of window. May be in range of 0 to 255 attr_accessor :back_opacity # Label of window attr_reader :label # If window is active then it updates attr_accessor :active # Openness of window attr_accessor :openness # Window skin - what window looks like attr_accessor :windowskin # Tone of the window attr_accessor :tone # Visibility attr_accessor :visible # Create window def initialize @x,@y,@width,@height = 0, 0, 192, 64 @ox,@oy,@speed=0,0,:auto @opacity, @back_opacity, @contents_opacity = 255, 255, 255 @z, @tone, @openness = 100, Tone.new(0,0,0,0), 255 @active, @label, @visible = true, nil, true @windowskin = 'window' @items=[] end # Resize (simple) def resize(new_width, new_height) @width=new_width @height=new_height end # Update window (do nothing now) def update;end # Close window def close @openness=0 end # Open window def open @openness=255 end # Dispose window def dispose;end def label=(string) return if string.nil? # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end def add_item(command,procname,enabled=true, text_only=false) @items+=[ { :command=>command, :procname=>procname, :enabled=>enabled, :x=>:auto, :y=>:auto, :text_only=text_only } ] end def add_text(text) add_item(text, "text_#{@index.last}".to_sym, false, true) end end # Класс спрайта со всеми параметрами, доступными в RGSS3. Пока пустой, ожидается обновление во время работы над спрайтами # (ветка work-with-sprites в github). # class Spr3 # Создает новый спрайт def initialize;end # Производит обновление спрайта def update;end # Производит повторную отрисовку содержимого спрайта def refresh;end # Удаляет спрайт def dispose;end end end end # Класс, хранящий данные о тексте в окне. Создается для каждого окна отдельно, # имеет индивидуальные настройки. class Text # Название файла изображения, из которого загружаются данные для отрисовки окон.<br> # По умолчанию задан путь 'Graphics\System\Window.png'. attr_accessor :windowskin # Массив цветов для отрисовки текста, по умолчанию содержит 32 цвета attr_accessor :colorset # Переменная класса Color, содержит цвет обводки текста. attr_accessor :out_color # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку обводки текста. По умолчанию, # обводка включена (outline=true) attr_accessor :outline # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку тени от текста. По умолчанию, # тень выключена (shadow=false) attr_accessor :shadow # Устанавливает жирность шрифта для <b>всего</b> текста.<br> # Игнорирует тег < b > в тексте attr_accessor :bold # Устанавливает наклон шрифта (курсив) для <b>всего</b> текста.<br> # Игнорирует тег < i > в тексте attr_accessor :italic # Устанавливает подчеркивание шрифта для <b>всего</b> текста.<br> # Игнорирует тег < u > в тексте attr_accessor :underline # Гарнитура (название) шрифта. По умолчанию - Tahoma attr_accessor :font # Размер шрифта. По умолчанию - 20 attr_accessor :size # Строка текста, которая будет отображена при использовании # экземпляра класса. attr_accessor :string # Создает экземпляр класса.<br> # <b>Параметры:</b> # * string - строка текста # * font_family - массив названий (гарнитур) шрифта, по умолчанию # имеет только "Tahoma". # При выборе гарнитуры шрифта, убедитесь в том, что символы, используемые # в тексте, корректно отображаются при использовании данного шрифта. # * font_size - размер шрифта, по умолчанию равен 20 пунктам # * bold - <b>жирный шрифт</b> (по умолчанию - false) # * italic - <i>курсив</i> (по умолчанию - false) # * underline - <u>подчеркнутый шрифт</u> (по умолчанию - false) def initialize(string, font_family=['Tahoma'], font_size=20, bold=false, italic=false, underline=false) @string=string @font=font_family @size=font_size @bold, @italic, @underline = bold, italic, underline @colorset=[] @out_color=Color.new(0,0,0,128) @shadow, @outline = false, true @windowskin='Graphics\\System\\Window.png' default_colorset end # Восстанавливает первоначальные значения цвета. По возможности, эти данные загружаются # из файла def default_colorset @colorset.clear if FileTest.exist?(@windowskin) bitmap=Bitmap.new(@windowskin) for y in 0..3 for x in 0..7 @colorset<<bitmap.get_pixel(x*8+64,y*8+96) end end bitmap.dispose else # Colors for this set was taken from <RTP path>/Graphics/Window.png file, # not just from the sky @colorset = [ # First row Color.new(255,255,255), # 1 Color.new(32, 160,214), # 2 Color.new(255,120, 76), # 3 Color.new(102,204, 64), # 4 Color.new(153,204,255), # 5 Color.new(204,192,255), # 6 Color.new(255,255,160), # 7 Color.new(128,128,128), # 8 # Second row Color.new(192,192,192), # 1 Color.new(32, 128,204), # 2 Color.new(255, 56, 16), # 3 Color.new( 0,160, 16), # 4 Color.new( 62,154,222), # 5 Color.new(160,152,255), # 6 Color.new(255,204, 32), # 7 Color.new( 0, 0, 0), # 8 # Third row Color.new(132,170,255), # 1 Color.new(255,255, 64), # 2 Color.new(255,120, 76), # 3 Color.new( 32, 32, 64), # 4 Color.new(224,128, 64), # 5 Color.new(240,192, 64), # 6 Color.new( 64,128,192), # 7 Color.new( 64,192,240), # 8 # Fourth row Color.new(128,255,128), # 1 Color.new(192,128,128), # 2 Color.new(128,128,255), # 3 Color.new(255,128,255), # 4 Color.new( 0,160, 64), # 5 Color.new( 0,224, 96), # 6 Color.new(160, 96,224), # 7 Color.new(192,128,255) # 8 ] end end # Сбрасывает все данные, кроме colorset, на значения по умолчанию def empty @string='' @font=['Tahoma'] @size=20 @bold, @italic, @underline = false, false, false @out_color=Color.new(0,0,0,128) @shadow, @outline = false, false @windowskin='Graphics\\System\\Window.png' end end # Основной модуль, обеспечивающий работу Cigui.<br> # Для передачи команд используйте массив $do, например: # * $do<<"команда" # * $do.push("команда") # Оба варианта имеют один и тот же результат.<br> # Перед запуском модуля вызовите метод CIGUI.setup.<br> # Для исполнения команд вызовите метод CIGUI.update.<br> # module CIGUI # Специальный словарь, содержащий все используемые команды Cigui. # Предоставляет возможности не только внесения новых слов, но и добавление # локализации (перевода) имеющихся (см. #update_by_user).<br> # Для удобства поиска разбит по категориям: # * common - общие команды, не имеющие категории; # * cigui - управление интерпретатором; # * event - событиями на карте; # * map - параметрами карты; # * picture - изображениями, используемыми через команды событий; # * sprite - самостоятельными изображениями; # * text - текстом и шрифтами # * window - окнами. # Русификацию этого словаря Вы можете найти в файле localize.rb # по адресу: <https://github.com/deadelf79/CIGUI/>, если этот файл # не приложен к демонстрационной версии проекта, который у Вас есть. # VOCAB={ #--COMMON unbranch :please=>'please', :last=>'last|this', :select=>'select', # by index or label :true=>'true', # for active||visible :false=>'false', :equal=>'[\s]*[\=]?[\s]*', :global=>'global', :switch=>'s[wv]it[ch]', :variable=>'var(?:iable)?', :local=>'local', #--CIGUI branch :cigui=>{ :main=>'cigui', :start=>'start', :finish=>'finish', :flush=>'flush', :restart=>'restart|resetup', }, #--EVENT branch :event=>{ :main=>'event|char(?:acter)?', :create=>'create|созда(?:[йть]|ва[йть])', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :load=>'load', # TAB #1 #~MESSAGE group :show=>'show', :message=>'message|text', :choices=>'choices', :scroll=>'scro[l]*(?:ing|er|ed)?', :input=>'input', :key=>'key|bu[t]*on', :number=>'number', :item=>'item', #to use as - select key item || condition branch item #~GAME PROGRESSION group :set=>'set|cotrol', # other word - see at :condition #~FLOW CONTROL group :condition=>'condition|if|case', :branch=>'bran[ch]|when', :self=>'self', # to use as - self switch :timer=>'timer', :min=>'min(?:ute[s]?)?', :sec=>'sec(?:[ou]nds)?', :ORmore=>'or[\s]*more', :ORless=>'or[\s]*less', :actor=>'actor', :in_party=>'in[\s]*party', :name=>'name', :applied=>'a[p]*lied', :class=>'cla[s]*', :skill=>'ski[l]*', :weapon=>'wea(?:p(?:on)?)?|wip(?:on)?', :armor=>'armo[u]?r', :state=>'stat(?:e|us)?', :enemy=>'enemy', :appeared=>'a[p]*eared', :inflicted=>'inflicted', # to use as - state inflicted :facing=>'facing', # to use as - event facing :up=>'up', :down=>'down', :left=>'left', :right=>'right', :vehicle=>'vehicle', :gold=>'gold|money', :script=>'script|code', :loop=>'loop', :break=>'break', :exit=>'exit', # to use as - exit event processing :call=>'call', :common=>'common', :label=>'label|link', :jump=>'jump(?:[\s]*to)?', :comment=>'comment', #~PARTY group :change=>'change', :party=>'party', :member=>'member', #~ACTOR group :hp=>'hp', :sp=>'[ms]p', :recover=>'recover', # may be used for one member :all=>'a[l]*', :exp=>'exp(?:irience)?', :level=>'l[e]?v[e]?l', :params=>'param(?:et[e]?r)s', :nickname=>'nick(?:name)?', # TAB#2 #~MOVEMENT group :transfer=>'transfer|teleport(?:ate|ion)', :player=>'player', :map=>'map', # to use as - scroll map || event map x :x=>'x', :y=>'y', :screen=>'scr[e]*n', # to use as - event screen x :route=>'rout(?:e|ing)?', :move=>'move|go', :forward=>'forward|в[\s]*пер[её][дт]', :backward=>'backward|н[ао][\s]*за[дт]', :lower=>'lower', :upper=>'upper', :random=>'rand(?:om[ed]*)?', :toward=>'toward', :away=>'away([\s]*from)?', :step=>'step', :get=>'get', :on=>'on', :off=>'off', # to use as - get on/off vehicle :turn=>'turn', :clockwise=>'clockwise', # по часовой :counterclockwise=>'counter[\s]clockwise', # против часовой :emulate=>'emulate', :click=>'click|tap', :touch=>'touch|enter', :by_event=>'by[\s]*event', :autorun=>'auto[\s]*run', :parallel=>'para[l]*e[l]*', :wait=>'wait', :frames=>'frame[s]?', }, #--MAP branch :map=>{ :main=>'map', :set=>'set', :display=>'display', # to use as - set display map name (имя карты для отображения в игре) :editor=>'editor', # to use as - set editor map name (имя картя только для редактора) :name=>'name', :width=>'width', :height=>'height', :mode=>'mode', :field=>'field', :area=>'area', :vx_compatible=>'vx', :visible=>'visible', :ox=>'ox', :oy=>'oy', :tileset=>'tileset', # for RPG Maker VX Ace only :_A=>'A', :_B=>'B', :_C=>'C', :_D=>'D', :_E=>'E', :tile=>'tile', :index=>'index', # to use as - set tile index :terrain=>'terrain', :tag=>'tag', :bush=>'bush', :flag=>'flag', # как я понял, это для ID тайла, привязка случайных битв и все такое :battle=>'battle', :background=>'background|bg', :music=>'music', :sound=>'sound', :effect=>'effect|fx', :scroll=>'scroll', :type=>'type', :loop=>'loop', :no=>'no', :vertical=>'vertical', :horizontal=>'horizontal', :both=>'both', :note=>'note', :dash=>'dash', :dashing=>'dashing', :enable=>'enable', :disable=>'disable', :parallax=>'para[l]*a[xks]', :show=>'show', :in=>'in',# to use as - set map parallax show in the editor :the=>'the', }, #--PICTURE branch :picture=>{ :maybe=>'in future versions' }, #--SPRITE branch :sprite=>{ :main=>'sprite', :create=>'create', :dispose=>'dispose|delete', :move=>'move', :resize=>'resize', :set=>'set', :x=>'x', :y=>'y', :z=>'z', :width=>'width', :height=>'height', :flash=>'flash', :color=>'color', :duration=>'duration', :angle=>'angle', :visibility=>'visibility', :visible=>'visible', :invisible=>'invisible', :opacity=>'opacity', :blend=>'blend', :type=>'type', :mirror=>'mirror', :tone=>'tone', }, #--TEXT branch :text=>{ :main=>'text', :make=>'make', :bigger=>'bigger', :smaller=>'smaller', :set=>'set', :font=>'font', :size=>'size', :bold=>'bold', :italic=>'italic', :underline=>'under[\s]*line', :fit=>'fit', :color=>'color', :out=>'out', # to use as - set out color :line=>'line', # to use as - set outline=BOOL :shadow=>'shadow', }, #--WINDOW branch :window=>{ :main=>'window', :create=>'create', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :move=>'move', :to=>'to', :speed=>'speed', :auto=>'auto', :resize=>'resize', :set=>'set', :x=>'x', :y=>'y', :z=>'z', :ox=>'ox', :oy=>'oy', :tone=>'tone', :width=>'width', :height=>'height', :link=>'link', # to use as - set button[DEC] link to switch[DEC] #dunnolol :label=>'label', :index=>'index', :indexed=>'indexed', :labeled=>'labeled', :as=>'as', :opacity=>'opacity', :back=>'back', # to use as - set back opacity :contents=>'contents', # to use as - set contents opacity :open=>'open', :openness=>'openness', :close=>'close', :active=>'active', :activate=>'activate', :deactivate=>'deactivate', :windowskin=>'skin|window[\s_]*skin', :cursor=>'cursor', :rect=>'rect', :visibility=>'visibility', :visible=>'visible', :invisible=>'invisible', } } # Хэш-таблица всех возможных сочетаний слов из VOCAB и их положения относительно друг друга в тексте.<br> # Именно по этим сочетаниям производится поиск команд Cigui в тексте. Редактировать без понимания правил # составления регулярных выражений не рекомендуется. CMB={ #~COMMON unbranch # selection window :select_window=>"(?:(?:#{VOCAB[:select]})+[\s]*(?:#{VOCAB[:window][:main]})+)|"+ "(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:select]})+)", :select_by_index=>"(?:(?:(?:#{VOCAB[:window][:index]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:indexed]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?))", :select_by_label=>"(?:(?:(?:#{VOCAB[:window][:label]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:labeled]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?))", #~CIGUI branch # commands only :cigui_start=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:start]})+)+", :cigui_finish=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:finish]})+)+", :cigui_flush=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:flush]})+)+", :cigui_restart=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:restart]})+)+", #~TEXT branch # expressions :text_font_size=>"(?:#{VOCAB[:text][:font]})+[\s]*(?:#{VOCAB[:text][:size]})+(?:#{VOCAB[:equal]}|[\s]*)+", # commands :text_set=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:text][:main]})+[\s]*(?:#{VOCAB[:text][:set]})+)", #~WINDOW branch # expressions :window_x_equal=>"(?:#{VOCAB[:window][:x]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_y_equal=>"(?:#{VOCAB[:window][:y]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ox_equal=>"(?:#{VOCAB[:window][:ox]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_oy_equal=>"(?:#{VOCAB[:window][:oy]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_w_equal=>"(?:#{VOCAB[:window][:width]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_h_equal=>"(?:#{VOCAB[:window][:height]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_s_equal=>"(?:#{VOCAB[:window][:speed]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_a_equal=>"(?:#{VOCAB[:window][:opacity]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ba_equal=>"(?:(?:#{VOCAB[:window][:back]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_ca_equal=>"(?:(?:#{VOCAB[:window][:contents]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_active_equal=>"(?:#{VOCAB[:window][:active]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_skin_equal=>"(?:(?:#{VOCAB[:window][:windowskin]})+(?:#{VOCAB[:equal]}|[\s]*)+)", :window_openness_equal=>"(?:#{VOCAB[:window][:openness]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_tone_equal=>"(?:#{VOCAB[:window][:tone]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_visibility_equal=>"(?:#{VOCAB[:window][:visibility]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_set_text=>"(?:(?:#{VOCAB[:window][:set]})*[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})"+ "+[\s]*(?:#{VOCAB[:window][:text]})+(?:#{VOCAB[:equal]}|[\s]*)+)", # commands :window_create=>"(((?:#{VOCAB[:window][:create]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:create]})+)", :window_create_atORwith=>"((?:#{VOCAB[:window][:at]})+[\s]*(#{VOCAB[:window][:x]}|#{VOCAB[:window][:y]})+)|"+ "((?:#{VOCAB[:window][:with]})+[\s]*(?:#{VOCAB[:window][:width]}|#{VOCAB[:window][:height]}))", :window_dispose=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_dispose_this=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_move=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:move]}))|"+ "(?:(?:#{VOCAB[:window][:move]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_resize=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:resize]}))|"+ "(?:(?:#{VOCAB[:window][:resize]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_set=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:set]})+)|"+ "(?:(?:#{VOCAB[:window][:set]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_activate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:activate]})+)|"+ "(?:(?:#{VOCAB[:window][:activate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_deactivate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:deactivate]})+)|"+ "(?:(?:#{VOCAB[:window][:deactivate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_open=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:open]}))|"+ "(?:(?:#{VOCAB[:window][:open]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", :window_close=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:close]}))|"+ "(?:(?:#{VOCAB[:window][:close]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", :window_visible=>"(?:(?:#{VOCAB[:window][:set]})*[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:visible]})+)", :window_invisible=>"(?:(?:#{VOCAB[:window][:set]})*[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:invisible]})+)", } # class <<self # Внутренний массив для вывода информации обо всех созданных окнах.<br> # Открыт только для чтения. # attr_reader :windows # Внутренний массив для вывода информации обо всех созданных спрайтах.<br> # Открыт только для чтения. # attr_reader :sprites # Хранит массив всех произведенных действий (все записи #last).<br> # Действия записываются только если параметр ::logging имеет значение # true. Результаты работы #decimal, #fraction, #boolean, #substring # и их расширенных аналогов не логгируются.<br> # Открыт только для чтения. # attr_reader :last_log # Флаг включения/выключения логгирования действий. # Если имеет значение true, то записи всех произведенных # действий с момента применения значения будут записываться # в массив ::last_log attr_accessor :logging # Требуется выполнить этот метод перед началом работы с CIGUI.<br> # Инициализирует массив $do, если он еще не был создан. В этот массив пользователь подает # команды для исполнения при следующем запуске метода #update.<br> # Если даже массив $do был инициализирован ранее, # то исполняет команду <i>cigui start</i> прежде всего.<br> # <b>Пример:</b> # begin # CIGUI.setup # #~~~ some code fragment ~~~ # CIGUI.update # #~~~ some other code fragment ~~~ # end # def setup $do||=[] $do.insert 0,'cigui start' _setup end # Вызывает все методы обработки команд, содержащиеся в массиве $do.<br> # Вызовет исключение CIGUIERR::CantInterpretCommand в том случае, # если после выполнения <i>cigui finish</i> в массиве $do будут находится # новые команды для обработки.<br> # По умолчанию очищает массив $do после обработки всех команд. Если clear_after_update # поставить значение false, то все команды из массива $do будут выполнены повторно # при следующем запуске этого метода.<br> # Помимо приватных методов обработки вызывает также метод #update_by_user, который может быть # модифицирован пользователем (подробнее смотри в описании метода).<br> # def update(clear_after_update=true) $do.each do |line| _restart? line _common? line _cigui? line _window? line #_ update_internal_objects update_by_user(line) end $do.clear if clear_after_update end # Вызывает обновление всех объектов из внутренних массивов ::windows и ::sprites.<br> # Вызывается автоматически по окончании обработки команд из массива $do в методе #update. def update_internal_objects @windows.each{ |win| win.update if win.is_a? Win3 } @sprites.each{ |spr| spr.update if spr.is_a? Spr3 } end # Метод обработки текста, созданный для пользовательских модификаций, не влияющих на работу # встроенных обработчиков.<br> # Используйте <i>alias</i> этого метода при добавлении обработки собственных команд.<br> # <b>Пример:</b> # alias my_update update_by_user # def update_by_user # # add new word # VOCAB[:window][:throw]='throw' # # add 'window throw' combination # CMB[:window_throw]="(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:throw]})+)" # # call method # window_throw? line # end # def update_by_user(string) end # Данный метод возвращает первое попавшееся целое число, найденное в строке source_string.<br> # Производит поиск только в том случае, если число записано: # * в скобки, например (10); # * в квадратные скобки, например [23]; # * в кавычки(апострофы), например '45'; # * в двойные кавычки, например "8765". # Также, вернет всю целую часть числа записанную: # * до точки, так здесь [1.35] вернет 1; # * до запятой, так здесь (103,81) вернет 103; # * до первого пробела (при стандартной конвертации в целое число), так здесь "816 586,64" вернет только 816; # * через символ подчеркивания, так здесь '1_000_0_0_0,143' вернет ровно один миллион (1000000). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # decimal('[10,25]') # => 10 # decimal('[1 0 2]',false) # => 102 # decimal('[1_234_5678 89]',false) # => 123456789 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def decimal(source_string, std_conversion=true) fraction(source_string, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #decimal, но возвращает рациональное число # (число с плавающей запятой или точкой).<br> # Имеется пара замечаний к правилам использования в дополнение к упомянутым в #decimal: # * Все цифры после запятой или точки считаются дробной частью и также могут содержать помимо цифр символ подчёркивания; # * При наличии между цифрами в дробной части пробела вернет ноль (в стандартной конвертации в целое или дробное число). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # fraction('(109,86)') # => 109.86 # fraction('(1 0 9 , 8 6)',false) # => 109.86 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def fraction(source_string, std_conversion=true) match='(?:[\[|"\(\'])[\s]*([\-\+]?[\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)(?:[\]|"\)\'])' return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск подстроки, используемой в качестве параметра.<br> # Строка должна быть заключена в одинарные или двойные кавычки или же в круглые # или квадратные скобки. # <b>Пример:</b> # substring('[Hello cruel world!]') # => Hello cruel world! # substring("set window label='SomeSome' and no more else") # => SomeSome # def substring(source_string) match='(?:[\[\(\"\'])[\s]*([\w\s _\!\#\$\%\^\&\*]*)[\s]*(?:[\]|"\)\'])' return source_string.match(match)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск булевого значения (true или false) в строке и возвращает его. # Если булевое значение в строке не обнаружено, по умолчанию возвращает false.<br> # Слова true и false берутся из словаря VOCAB, что значит, что их локализованные версии # также могут быть успешно найдены при поиске. def boolean(source_string) match="((?:#{VOCAB[:true]}|#{VOCAB[:false]}))" if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает массив из четырех значений для передачи в качестве параметра # в объекты класса Rect. Массив в строке должен быть помещен в квадратные скобки, # а значения в нем должны разделяться <b>точкой с запятой.</b><br> # <b>Пример:</b> # rect('[1;2,0;3.5;4.0_5]') # => [ 1, 2.0, 3.5, 4.05 ] # def rect(source_string) read='' start=false arr=[] for index in 0...source_string.size char=source_string[index] if char=='[' start=true next end if start if char!=';' if char!=']' read+=char else arr<<read break end else arr<<read read='' end end end if arr.size<4 for index in 1..4-arr.size arr<<0 end elsif arr.size>4 arr.slice!(4,arr.size) end for index in 0...arr.size arr[index]=dec(arr[index]) if arr[index].is_a? String arr[index]=0 if arr[index].is_a? NilClass end return arr end # Данный метод работает по аналогии с #decimal, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # dec('x=1cm','x=','cm') # => 1 # dec('y=120 m','[xy]=','[\s]*(?:cm|m|km)') # => 120 # В отличие от #frac, возвращает целое число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def dec(source_string, prefix='', postfix='', std_conversion=true) frac(source_string, prefix, postfix, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #fraction, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # frac('x=31.2mm','x=','mm') # => 31.2 # frac('y=987,67 m','[xy]=','[\s]*(?:cm|m|km)') # => 987.67 # В отличие от #dec, возвращает рациональное число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def frac(source_string, prefix='', postfix='', std_conversion=true) match=prefix+'([\-\+]?[\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)'+postfix return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #substring, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # Указание квадратных или круглый скобок, а также экранированных одинарных или двойных кавычек # в строке после префикса обязательно. # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска.<br> # <b>Пример:</b> # puts 'Who can make me strong?' # someone = substring("Make[ me ]invincible",'Make','invincible') # puts 'Only'+someone # => 'Only me' # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def substr(source_string, prefix='', postfix='') match=prefix+'(?:[\[\(\"\'])[\s]*([\w\s _\!\#\$\%\^\&\*]*)[\s]*(?:[\]|"\)\'])'+postfix return source_string.match(/#{match}/i)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #boolean, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # Если булевое значение в строке не обнаружено, по умолчанию возвращает false. def bool(source_string, prefix='', postfix='') match=prefix+"((?:#{VOCAB[:true]}|#{VOCAB[:false]}))"+postfix if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает сообщение о последнем произведенном действии # или классе последнего использованного объекта, используя метод # Kernel.inspect.<br> # <b>Пример:</b> # CIGUI.setup # puts CIGUI.last # => 'CIGUI started' # def last @last_action.is_a?(String) ? @last_action : @last_action.inspect end private # SETUP CIGUI / CLEAR FOR RESTART def _setup @last_action ||= nil @logging ||= true @last_log ||= [] @finished = false @windows = [] @sprites = [] @selection = { :type => nil, # may be window or sprite :index => 0, # index in internal array :label => nil # string in class to find index } @global_text.is_a?(NilClass) ? @global_text=Text.new('') : @global_text.empty end # RESTART def _restart?(string) matches=string.match(/#{CMB[:cigui_restart]}/) if matches __flush?('cigui flush') if not @finished _setup @last_action = 'CIGUI restarted' @last_log << @last_action if @logging else raise "#{CIGUIERR::CantInterpretCommand}\n\tcurrent line of $do: #{string}" if @finished end end # COMMON UNBRANCH def _common?(string) # select, please and other __swindow? string end def __swindow?(string) matches=string.match(/#{CMB[:select_window]}/) # Only match if matches # Read index or label if string.match(/#{CMB[:select_by_index]}/) index = dec(string,CMB[:select_by_index]) if index>-1 @selection[:type]=:window @selection[:index]=index if index.between?(0...@windows.size) @selection[:label]=@windows[index].label if @windows[index]!=nil && @windows[index].is_a?(Win3) end end elsif string.match(/#{CMB[:select_by_label]}/) label = substr(string,CMB[:select_by_label]) if label!=nil @selection[:type]=:window @selection[:label]=label for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label @selection[:index]=index break end end end end end @last_action = @selection @last_log << @last_action if @logging end end#--------------------end of '__swindow?'------------------------- # CIGUI BRANCH def _cigui?(string) __start? string __finish? string __flush? string end def __start?(string) matches=string.match(/#{CMB[:cigui_start]}/) if matches begin @finished = false @last_action = 'CIGUI started' @last_log << @last_action if @logging rescue raise "#{CIGUIERR::CantStart}\n\tcurrent line of $do: #{string}" end end end def __finish?(string) matches=string.match(/#{CMB[:cigui_finish]}/) if matches @finished = true @last_action = 'CIGUI finished' @last_log << @last_action if @logging end end def __flush?(string) matches=string.match(/#{CMB[:cigui_flush]}/) if matches @windows.each{|item|item.dispose} @windows.clear @sprites.each{|item|item.dispose} @sprites.clear @last_action = 'CIGUI cleared' @last_log << @last_action if @logging end end # WINDOW BRANCH def _window?(string) __wcreate? string __wdispose? string __wmove? string __wresize? string __wset? string __wactivate? string __wdeactivate? string __wopen? string __wclose? string __wvisible? string __winvisible? string end # Examples: # create window (default position and size) # create window at x=DEC, y=DEC # create window with width=DEC,height=DEC # create window at x=DEC, y=DEC with w=DEC, h=DEC def __wcreate?(string) matches=string.match(/#{CMB[:window_create]}/i) # Only create if matches begin begin @windows<<Win3.new if RUBY_VERSION.to_f >= 1.9 rescue @windows<<NilClass end rescue raise "#{CIGUIERR::CannotCreateWindow}\n\tcurrent line of $do: #{string}" end # Read params if string.match(/#{CMB[:window_create_atORwith]}/i) # at OR with: check x and y new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows.last.x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows.last.y # at OR with: check w and h new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows.last.width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows.last.height # Set parameters for created window @windows.last.x = new_x @windows.last.y = new_y @windows.last.width = new_w @windows.last.height = new_h end # Set last action to inspect this window @last_action = @windows.last @last_log << @last_action if @logging # Select this window @selection[:type]=:window @selection[:index]=@windows.size-1 end end #--------------------end of '__wcreate?'------------------------- # Examples: # dispose window index=DEC # dispose window label=STR def __wdispose?(string) # Если какое-то окно уже выбрано, то... matches=string.match(/#{CMB[:window_dispose_this]}/i) if matches if @selection[:type]==:window #(0...@windows.size).include?(@selection[:index]) # ...удалим его как полагается... @windows[@selection[:index]].dispose if @windows[@selection[:index]].methods.include? :dispose @windows.delete_at(@selection[:index]) @last_action = 'CIGUI disposed window' @last_log << @last_action if @logging return end end # ... а если же нет, то посмотрим, указаны ли его индекс или метка. matches=string.match(/#{CMB[:window_dispose]}/i) if matches if string.match(/#{CMB[:select_by_index]}/i) index=dec(string,CMB[:select_by_index]) if index.between?(0,@windows.size) # Проверка удаления для попавшихся объектов класса Nil # в результате ошибки создания окна @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) else raise "#{CIGUIERR::WrongWindowIndex}"+ "\n\tinternal windows size: #{@windows.size} (#{index} is not in range of 0..#{@windows.size})"+ "\n\tcurrent line of $do: #{string}" end elsif string.match(/#{CMB[:select_by_label]}/i) label = substr(string,CMB[:select_by_label]) if label!=nil for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label break end end end end @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) end @last_action = 'CIGUI disposed window by index or label' @last_log << @last_action if @logging end end#--------------------end of '__wdispose?'------------------------- # Examples: # this move to x=DEC,y=DEC # this move to x=DEC,y=DEC with speed=1 # this move to x=DEC,y=DEC with speed=auto def __wmove?(string) matches=string.match(/#{CMB[:window_move]}/i) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].speed = new_s @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end end#--------------------end of '__wmove?'------------------------- # example: # this resize to width=DEC,height=DEC def __wresize?(string) matches=string.match(/#{CMB[:window_resize]}/) # Only move if matches begin # Read params new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].resize(new_w,new_h) @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end end#--------------------end of '__wresize?'------------------------- # examples: # this window set x=DEC, y=DEC, z=DEC, width=DEC, height=DEC # this window set label=[STR] # this window set opacity=DEC # this window set back opacity=DEC # this window set active=BOOL # this window set skin=[STR] # this window set openness=DEC # this window set cursor rect=[RECT] # this window set tone=[RECT] def __wset?(string) matches=string.match(/#{CMB[:window_set]}/) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_ox = string[/#{CMB[:window_ox_equal]}/i] ? dec(string,CMB[:window_ox_equal]) : @windows[@selection[:index]].ox new_oy = string[/#{CMB[:window_oy_equal]}/i] ? dec(string,CMB[:window_oy_equal]) : @windows[@selection[:index]].oy new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed new_a = string[/#{CMB[:window_a_equal]}/i] ? dec(string,CMB[:window_a_equal]) : @windows[@selection[:index]].opacity new_ba = string[/#{CMB[:window_ba_equal]}/i] ? dec(string,CMB[:window_ba_equal]) : @windows[@selection[:index]].back_opacity new_act = string[/#{CMB[:window_active_equal]}/i] ? bool(string,CMB[:window_active_equal]) : @windows[@selection[:index]].active new_skin = string[/#{CMB[:window_skin_equal]}/i] ? substr(string,CMB[:window_skin_equal]) : @windows[@selection[:index]].windowskin new_open = string[/#{CMB[:window_openness_equal]}/i] ? dec(string,CMB[:window_openness_equal]) : @windows[@selection[:index]].openness new_label = string[/#{CMB[:select_by_label]}/i] ? substr(string,CMB[:select_by_label]) : @windows[@selection[:index]].label new_tone = string[/#{CMB[:window_tone_equal]}/i] ? rect(string) : @windows[@selection[:index]].tone new_vis = string[/#{CMB[:window_visibility_equal]}/i] ? bool(string,CMB[:window_visibility_equal]) : @windows[@selection[:index]].visible # Change it if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].ox = new_ox @windows[@selection[:index]].oy = new_oy @windows[@selection[:index]].resize(new_w,new_h) @windows[@selection[:index]].speed = new_s==0 ? :auto : new_s @windows[@selection[:index]].opacity = new_a @windows[@selection[:index]].back_opacity = new_ba @windows[@selection[:index]].active = new_act @windows[@selection[:index]].windowskin = new_skin @windows[@selection[:index]].openness = new_open @windows[@selection[:index]].label = new_label @windows[@selection[:index]].visible = new_vis if new_tone.is_a? Tone @windows[@selection[:index]].tone.set(new_tone) elsif new_tone.is_a? Array @windows[@selection[:index]].tone.set(new_tone[0],new_tone[1],new_tone[2],new_tone[3]) end @selection[:label] = new_label @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end end#--------------------end of '__wset?'------------------------- def __wactivate?(string) matches=string.match(/#{CMB[:window_activate]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].active=true @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wactivate?'------------------------- def __wdeactivate?(string) matches=string.match(/#{CMB[:window_deactivate]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].active=false @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wdeactivate?'------------------------- def __wopen?(string) matches=string.match(/#{CMB[:window_open]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].open @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wopen?'------------------------- def __wclose?(string) matches=string.match(/#{CMB[:window_close]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].close @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wclose?'------------------------- def __wvisible?(string) matches=string.match(/#{CMB[:window_set_visible]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].visible = true @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wvisible?'------------------------- def __winvisible?(string) matches=string.match(/#{CMB[:window_set_invisible]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].visible = false @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__winvisible?'------------------------- def __wset_text?(string) matches=string.match(/#{CMB[:window_set_text]}/i) if matches new_text = substr(string,CMB[:window_set_text]) if @selection[:type]==:window @windows[@selection[:index]].add_text = new_text @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wset_text?'------------------------- end# END OF CIGUI CLASS end# END OF CIGUI MODULE # test zone # delete this when copy to 'Script editor' in RPG Maker begin $do=[ 'create window at x=1540,y=9000 with width=900,height=560', 'this window set ox=22,oy=33,tone=[255;123;40;20],label=[Current],speed=0,windowskin="Something other"', 'close this window', 'deactivate this window', 'this window set active=true', 'cigui restart' ] CIGUI.setup CIGUI.update puts CIGUI.last puts CIGUI.decimal('[-100]') end Added empty def 'delete item' # = Руководство Cigui # В данном руководстве описана работа модуля CIGUI, # а также методы для управления его работой.<br> # Рекомендуется к прочтению пользователям, имеющим навыки программирования # (написания скриптов) на Ruby.<br> # Для получения помощи по командам, обрабатываемым Cigui, # перейдите по адресу: <https://github.com/deadelf79/CIGUI/wiki> # --- # Author:: Sergey 'DeadElf79' Anikin (mailto:deadelf79@gmail.com) # License:: Public Domain (see <http://unlicense.org> for more information) # Модуль, содержащий данные обо всех возможных ошибках, которые # может выдать CIGUI при некорректной работе.<br> # Включает в себя: # * CIGUIERR::CantStart # * CIGUIERR::CantReadNumber # * CIGUIERR::CantReadString # * CIGUIERR::CantInterpretCommand # * CIGUIERR::CannotCreateWindow # * CIGUIERR::WrongWindowIndex # module CIGUIERR # Ошибка, которая появляется при неудачной попытке запуска интерпретатора Cigui # class CantStart < StandardError private def message 'Could not initialize module' end end # Ошибка, которая появляется, если в строке не было обнаружено числовое значение.<br> # Правила оформления строки указаны для каждого типа значений отдельно: # * целые числа - CIGUI.decimal # * дробные числа - CIGUI.fraction # class CantReadNumber < StandardError private def message 'Could not find numerical value in this string' end end # Ошибка, которая появляется, если в строке не было обнаружено строчное значение.<br> # Правила оформления строки и примеры использования указаны в описании # к этому методу: CIGUI.string # class CantReadString < StandardError private def message 'Could not find substring' end end # Ошибка, которая появляется при попытке работать с Cigui после # вызова команды <i>cigui finish</i>. # class CantInterpretCommand < StandardError private def message 'Unable to process the command after CIGUI was finished' end end # Ошибка создания окна. # class CannotCreateWindow < StandardError private def message 'Unable to create window' end end # Ошибка, которая появляется при попытке обращения # к несуществующему индексу в массиве <i>windows</i><br> # Вызывается при некорректном вводе пользователя # class WrongWindowIndex < StandardError private def message 'Index must be included in range of 0 to internal windows array size' end end end # Инициирует классы, если версия Ruby выше 1.9.0 # if RUBY_VERSION.to_f>=1.9 begin # Класс окна с реализацией всех возможностей, доступных при помощи Cigui.<br> # Реализация выполнена для RGSS3. # class Win3 < Window_Selectable # Скорость перемещения attr_accessor :speed # Прозрачность окна. Может принимать значения от 0 до 255 attr_accessor :opacity # Прозрачность фона окна. Может принимать значения от 0 до 255 attr_accessor :back_opacity # Метка окна. Строка, по которой происходит поиск экземпляра # в массиве CIGUI.windows при выборе окна по метке (select by label) attr_reader :label # Создает окно. По умолчанию задается размер 192х64 и # помещается в координаты 0, 0 # def initialize(x=0,y=0,w=192,h=64) super 0,0,192,64 @label=nil @items=[] @texts=[] @speed=1 end # Обновляет окно. Влияет только на положение курсора (параметр cursor_rect), # прозрачность и цветовой тон окна. def update;end # Обновляет окно. В отличие от #update, влияет только # на содержимое окна (производит повторную отрисовку). def refresh self.contents.clear end # Задает метку окну, проверяя ее на правильность перед этим: # * удаляет круглые и квадратгые скобки # * удаляет кавычки # * заменяет пробелы и табуляцию на символы подчеркивания # * заменяет символы "больше" и "меньше" на символы подчеркивания def label=(string) # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end # Этот метод позволяет добавить текст в окно.<br> # Принимает в качестве параметра значение класса Text def add_text(text) add_item(text, "text_#{@index.last}".to_sym, false, true) end # Этот метод добавляет команду во внутренний массив <i>items</i>. # Команды используются для отображения кнопок.<br> # * command - отображаемый текст кнопки # * procname - название вызываемого метода # По умолчанию значение enable равно true, что значит, # что кнопка включена и может быть нажата. # def add_item(command,procname,enabled=true, text_only=false) @items+=[ { :command=>command, :procname=>procname, :enabled=>enabled, :x=>:auto, :y=>:auto, :text_only=text_only } ] end # def delete_item(indexORcomORproc) i=indexORcomORproc case i.class when Fixnum when String # try to find by commands # try to find by procnames end end # Включает кнопку.<br> # В параметр commandORindex помещается либо строковое значение, # являющееся названием кнопки, либо целое число - индекс кнопки во внутреннем массиве <i>items</i>. # enable_item(0) # => @items[0].enabled set 'true' # enable_item('New game') # => @items[0].enabled set 'true' # Включение происходит только если кнопка не имеет тип text_only (устанавливается # при добавлении с помощью метода #add_text). # def enable_item(commandORindex) case commandORindex.class when Fixnum @items[commandORindex.to_i][:enabled]=true if (0...@items.size).include? commandORindex.to_i @items[commandORindex.to_i][:enabled]=false if @items[commandORindex.to_i][:text_only] when String index=0 @items.times{|index|@items[index][:enabled]=true if @items[index][:command]==commandORindex} @items[index][:enabled]=false if @items[index][:text_only] else raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{string}" end end # Выключает кнопку.<br> # В параметр commandORindex помещается либо строковое значение, # являющееся названием кнопки, либо целое число - индекс кнопки во внутреннем массиве <i>items</i>. # disable_item(0) # => @items[0].enabled set 'false' # disable_item('New game') # => @items[0].enabled set 'false' # Выключение происходит только если кнопка не имеет тип text_only (устанавливается # при добавлении с помощью метода #add_text). # def disable_item(commandORindex) case commandORindex.class when Integer, Float @items[commandORindex.to_i][:enabled]=false if (0...@items.size).include? commandORindex.to_i @items[commandORindex.to_i][:enabled]=false if @items[commandORindex.to_i][:text_only] when String index=0 @items.times{|index|@items[index][:enabled]=false if @items[index][:command]==commandORindex} @items[index][:enabled]=false if @items[index][:text_only] else raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{string}" end end # С помощью этого метода производится полная отрисовка всех # элементов из массива <i>items</i>.<br> # Параметр ignore_disabled отвечает за отображение выключенных # команд из массива <i>items</i>. Если его значение равно true, # то отрисовка выключенных команд производиться не будет. # def draw_items(ignore_disabled=false) end # Устанавливает новые размеры окна дополнительно изменяя # также и размеры содержимого (contents).<br> # Все части содержимого, которые не помещаются в новые размер, # удаляются безвозратно. # def resize(new_width, new_height) temp=Sprite.new temp.bitmap=self.contents self.contents.dispose src_rect(0,0,temp.width,temp.height) self.contents=Bitmap.new( width - padding * 2, height - padding * 2 ) self.contents.bit(0,0,temp.bitmap,src_rect,255) temp.bitmap.dispose temp.dispose width=new_width height=new_height end # Удаляет окно и все связанные с ним ресурсы # def dispose super end # Возврашает полную информацию обо всех параметрах # в формате строки # def inspect "<#{self.class}:"+ " @back_opacity=#{back_opacity},"+ " @contents_opacity=#{contents_opacity}"+ " @height=#{height},"+ " @opacity=#{opacity},"+ " @speed=#{@speed},"+ " @width=#{width},"+ " @x=#{x},"+ " @y=#{y}>" end end # Если классы инициировать не удалось (ошибка в отсутствии родительских классов), # то в память загружаются исключительно консольные версии (console-only) классов # необходимые для работы с командной строкой. rescue # Класс абстрактного (невизуального) прямоугольника. # Хранит значения о положении и размере прямоугольника class Rect # Координата X attr_accessor :x # Координата Y attr_accessor :y # Ширина прямоугольника attr_accessor :width # Высота прямоугольника attr_accessor :height # Создание прямоугольника # * x, y - назначает положение прямоуголника в пространстве # * width, height - устанавливает ширину и высоту прямоугольника def initialize(x,y,width,height) @x,@y,@width,@height = x,y,width,height end # Задает все параметры единовременно # Может принимать значения: # * Rect - другой экземпляр класса Rect, все значения копируются из него # * x, y, width, height - позиция и размер прямоугольника # # Оба варианта работают аналогично: # set(Rect.new(0,0,192,64)) # set(0,0,192,64) def set(*args) if args.size==1 @x,@y,@width,@height = args[0].x, args[0].y, args[0].width, args[0].height elsif args.size==4 @x,@y,@width,@height = args[0], args[1], args[2], args[3] elsif args.size.between?(2,3) # throw error, but i don't remember which error O_o end end # Устанавливает все параметры прямоугольника равными нулю. def empty @x,@y,@width,@height = 0, 0, 0, 0 end end # Класс, хранящий данные о цвете в формате RGBA # (красный, зеленый, синий и прозрачность). Каждое значение # является рациональным числом (число с плавающей точкой) и # имеет значение от 0.0 до 255.0. Все значения, выходящие # за указанный интервал, корректируются автоматически. # class Color # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * a - задает прозрачность, по умолчанию имеет значение 255.0 (полностью непрозрачный цвет) def initialize(r,g,b,a=255.0) @r,@g,@b,@a = r.to_f,g.to_f,b.to_f,a.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @g end # Возвращает значение синего цвета def blue @b end # Возвращает значение прозрачности def alpha @a end # Задает новые значения цвета и прозрачности.<br> # <b>Варианты параметров:</b> # * set(Color) - в качестве параметра задан другой экземпляр класса Color # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, alpha) - задает новые значения цвета и прозрачности. def set(*args) if args.size==1 @r,@g,@b,@a = args[0].red,args[0].green,args[0].blue,args[0].alpha elsif args.size==4 @r,@g,@b,@a = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@a = args[0],args[1],args[2],255.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=0 if @r<0 @r=255 if @r>255 @g=0 if @g<0 @g=255 if @g>255 @b=0 if @b<0 @b=255 if @b>255 @a=0 if @a<0 @a=255 if @a>255 end end # Класс, хранящий данные о тонировании в ввиде четырех значений: # красный, зеленый, синий и насыщенность. Последнее значение влияет # на цветовую насыщенность, чем ниже его значение, тем сильнее # цветовые оттенки заменяются на оттенки серого. # Каждое значение, кроме последнего, является рациональным числом # (число с плавающей точкой) и имеет значение от -255.0 до 255.0. # Значение насыщенности лежит в пределах от 0 до 255. # Все значения, выходящие за указанные интервалы, # корректируются автоматически. # class Tone # Создает экземпляр класса. # * r, g, b - задает изначальные значения красного, зеленого и синего цветов # * gs - задает насыщенность, по умолчанию имеет значение 0 def initialize(r,g,b,gs=0.0) @r,@g,@b,@gs = r.to_f,g.to_f,b.to_f,gs.to_f _normalize end # Возвращает значение красного цвета def red @r end # Возвращает значение зеленого цвета def green @g end # Возвращает значение синего цвета def blue @b end # Возвращает значение насыщенности def gray @gs end # Задает новые значения цвета и насыщенности.<br> # <b>Варианты параметров:</b> # * set(Tone) - в качестве параметра задан другой экземпляр класса Tone # Все значения цвета и прозрачности будут скопированы из него. # * set(red, green, blue) - задает новые значения цвета. # Прозрачность по умолчанию становится равна 255.0 # * set(red, green, blue, greyscale) - задает новые значения цвета и насыщенности. def set(*args) if args.size==1 @r,@g,@b,@gs = args[0].red,args[0].green,args[0].blue,args[0].gray elsif args.size==4 @r,@g,@b,@gs = args[0],args[1],args[2],args[3] elsif args.size==3 @r,@g,@b,@gs = args[0],args[1],args[2],0.0 elsif args.size==2 # throw error like in Rect class end _normalize end private def _normalize @r=-255.0 if @r<-255.0 @r=255.0 if @r>255.0 @g=-255.0 if @g<-255.0 @g=255.0 if @g>255.0 @b=-255.0 if @b<-255.0 @b=255.0 if @b>255.0 @gs=0.0 if @gs<0.0 @gs=255.0 if @gs>255.0 end end # Console-only version of this class class Win3#:nodoc: # X Coordinate of Window attr_accessor :x # Y Coordinate of Window attr_accessor :y # X Coordinate of contens attr_accessor :ox # Y Coordinate of contents attr_accessor :oy # Width of Window attr_accessor :width # Height of Window attr_accessor :height # Speed movement attr_accessor :speed # Opacity of window. May be in range of 0 to 255 attr_accessor :opacity # Back opacity of window. May be in range of 0 to 255 attr_accessor :back_opacity # Label of window attr_reader :label # If window is active then it updates attr_accessor :active # Openness of window attr_accessor :openness # Window skin - what window looks like attr_accessor :windowskin # Tone of the window attr_accessor :tone # Visibility attr_accessor :visible # Create window def initialize @x,@y,@width,@height = 0, 0, 192, 64 @ox,@oy,@speed=0,0,:auto @opacity, @back_opacity, @contents_opacity = 255, 255, 255 @z, @tone, @openness = 100, Tone.new(0,0,0,0), 255 @active, @label, @visible = true, nil, true @windowskin = 'window' @items=[] end # Resize (simple) def resize(new_width, new_height) @width=new_width @height=new_height end # Update window (do nothing now) def update;end # Close window def close @openness=0 end # Open window def open @openness=255 end # Dispose window def dispose;end def label=(string) return if string.nil? # make right label string.gsub!(/[\[\]\(\)\'\"]/){''} string.gsub!(/[ \t\<\>]/){'_'} # then label it @label = string end def add_item(command,procname,enabled=true, text_only=false) @items+=[ { :command=>command, :procname=>procname, :enabled=>enabled, :x=>:auto, :y=>:auto, :text_only=text_only } ] end def add_text(text) add_item(text, "text_#{@index.last}".to_sym, false, true) end end # Класс спрайта со всеми параметрами, доступными в RGSS3. Пока пустой, ожидается обновление во время работы над спрайтами # (ветка work-with-sprites в github). # class Spr3 # Создает новый спрайт def initialize;end # Производит обновление спрайта def update;end # Производит повторную отрисовку содержимого спрайта def refresh;end # Удаляет спрайт def dispose;end end end end # Класс, хранящий данные о тексте в окне. Создается для каждого окна отдельно, # имеет индивидуальные настройки. class Text # Название файла изображения, из которого загружаются данные для отрисовки окон.<br> # По умолчанию задан путь 'Graphics\System\Window.png'. attr_accessor :windowskin # Массив цветов для отрисовки текста, по умолчанию содержит 32 цвета attr_accessor :colorset # Переменная класса Color, содержит цвет обводки текста. attr_accessor :out_color # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку обводки текста. По умолчанию, # обводка включена (outline=true) attr_accessor :outline # Булевая переменная (принимает только значения true или false), # которая отвечает за отрисовку тени от текста. По умолчанию, # тень выключена (shadow=false) attr_accessor :shadow # Устанавливает жирность шрифта для <b>всего</b> текста.<br> # Игнорирует тег < b > в тексте attr_accessor :bold # Устанавливает наклон шрифта (курсив) для <b>всего</b> текста.<br> # Игнорирует тег < i > в тексте attr_accessor :italic # Устанавливает подчеркивание шрифта для <b>всего</b> текста.<br> # Игнорирует тег < u > в тексте attr_accessor :underline # Гарнитура (название) шрифта. По умолчанию - Tahoma attr_accessor :font # Размер шрифта. По умолчанию - 20 attr_accessor :size # Строка текста, которая будет отображена при использовании # экземпляра класса. attr_accessor :string # Создает экземпляр класса.<br> # <b>Параметры:</b> # * string - строка текста # * font_family - массив названий (гарнитур) шрифта, по умолчанию # имеет только "Tahoma". # При выборе гарнитуры шрифта, убедитесь в том, что символы, используемые # в тексте, корректно отображаются при использовании данного шрифта. # * font_size - размер шрифта, по умолчанию равен 20 пунктам # * bold - <b>жирный шрифт</b> (по умолчанию - false) # * italic - <i>курсив</i> (по умолчанию - false) # * underline - <u>подчеркнутый шрифт</u> (по умолчанию - false) def initialize(string, font_family=['Tahoma'], font_size=20, bold=false, italic=false, underline=false) @string=string @font=font_family @size=font_size @bold, @italic, @underline = bold, italic, underline @colorset=[] @out_color=Color.new(0,0,0,128) @shadow, @outline = false, true @windowskin='Graphics\\System\\Window.png' default_colorset end # Восстанавливает первоначальные значения цвета. По возможности, эти данные загружаются # из файла def default_colorset @colorset.clear if FileTest.exist?(@windowskin) bitmap=Bitmap.new(@windowskin) for y in 0..3 for x in 0..7 @colorset<<bitmap.get_pixel(x*8+64,y*8+96) end end bitmap.dispose else # Colors for this set was taken from <RTP path>/Graphics/Window.png file, # not just from the sky @colorset = [ # First row Color.new(255,255,255), # 1 Color.new(32, 160,214), # 2 Color.new(255,120, 76), # 3 Color.new(102,204, 64), # 4 Color.new(153,204,255), # 5 Color.new(204,192,255), # 6 Color.new(255,255,160), # 7 Color.new(128,128,128), # 8 # Second row Color.new(192,192,192), # 1 Color.new(32, 128,204), # 2 Color.new(255, 56, 16), # 3 Color.new( 0,160, 16), # 4 Color.new( 62,154,222), # 5 Color.new(160,152,255), # 6 Color.new(255,204, 32), # 7 Color.new( 0, 0, 0), # 8 # Third row Color.new(132,170,255), # 1 Color.new(255,255, 64), # 2 Color.new(255,120, 76), # 3 Color.new( 32, 32, 64), # 4 Color.new(224,128, 64), # 5 Color.new(240,192, 64), # 6 Color.new( 64,128,192), # 7 Color.new( 64,192,240), # 8 # Fourth row Color.new(128,255,128), # 1 Color.new(192,128,128), # 2 Color.new(128,128,255), # 3 Color.new(255,128,255), # 4 Color.new( 0,160, 64), # 5 Color.new( 0,224, 96), # 6 Color.new(160, 96,224), # 7 Color.new(192,128,255) # 8 ] end end # Сбрасывает все данные, кроме colorset, на значения по умолчанию def empty @string='' @font=['Tahoma'] @size=20 @bold, @italic, @underline = false, false, false @out_color=Color.new(0,0,0,128) @shadow, @outline = false, false @windowskin='Graphics\\System\\Window.png' end end # Основной модуль, обеспечивающий работу Cigui.<br> # Для передачи команд используйте массив $do, например: # * $do<<"команда" # * $do.push("команда") # Оба варианта имеют один и тот же результат.<br> # Перед запуском модуля вызовите метод CIGUI.setup.<br> # Для исполнения команд вызовите метод CIGUI.update.<br> # module CIGUI # Специальный словарь, содержащий все используемые команды Cigui. # Предоставляет возможности не только внесения новых слов, но и добавление # локализации (перевода) имеющихся (см. #update_by_user).<br> # Для удобства поиска разбит по категориям: # * common - общие команды, не имеющие категории; # * cigui - управление интерпретатором; # * event - событиями на карте; # * map - параметрами карты; # * picture - изображениями, используемыми через команды событий; # * sprite - самостоятельными изображениями; # * text - текстом и шрифтами # * window - окнами. # Русификацию этого словаря Вы можете найти в файле localize.rb # по адресу: <https://github.com/deadelf79/CIGUI/>, если этот файл # не приложен к демонстрационной версии проекта, который у Вас есть. # VOCAB={ #--COMMON unbranch :please=>'please', :last=>'last|this', :select=>'select', # by index or label :true=>'true', # for active||visible :false=>'false', :equal=>'[\s]*[\=]?[\s]*', :global=>'global', :switch=>'s[wv]it[ch]', :variable=>'var(?:iable)?', :local=>'local', #--CIGUI branch :cigui=>{ :main=>'cigui', :start=>'start', :finish=>'finish', :flush=>'flush', :restart=>'restart|resetup', }, #--EVENT branch :event=>{ :main=>'event|char(?:acter)?', :create=>'create|созда(?:[йть]|ва[йть])', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :load=>'load', # TAB #1 #~MESSAGE group :show=>'show', :message=>'message|text', :choices=>'choices', :scroll=>'scro[l]*(?:ing|er|ed)?', :input=>'input', :key=>'key|bu[t]*on', :number=>'number', :item=>'item', #to use as - select key item || condition branch item #~GAME PROGRESSION group :set=>'set|cotrol', # other word - see at :condition #~FLOW CONTROL group :condition=>'condition|if|case', :branch=>'bran[ch]|when', :self=>'self', # to use as - self switch :timer=>'timer', :min=>'min(?:ute[s]?)?', :sec=>'sec(?:[ou]nds)?', :ORmore=>'or[\s]*more', :ORless=>'or[\s]*less', :actor=>'actor', :in_party=>'in[\s]*party', :name=>'name', :applied=>'a[p]*lied', :class=>'cla[s]*', :skill=>'ski[l]*', :weapon=>'wea(?:p(?:on)?)?|wip(?:on)?', :armor=>'armo[u]?r', :state=>'stat(?:e|us)?', :enemy=>'enemy', :appeared=>'a[p]*eared', :inflicted=>'inflicted', # to use as - state inflicted :facing=>'facing', # to use as - event facing :up=>'up', :down=>'down', :left=>'left', :right=>'right', :vehicle=>'vehicle', :gold=>'gold|money', :script=>'script|code', :loop=>'loop', :break=>'break', :exit=>'exit', # to use as - exit event processing :call=>'call', :common=>'common', :label=>'label|link', :jump=>'jump(?:[\s]*to)?', :comment=>'comment', #~PARTY group :change=>'change', :party=>'party', :member=>'member', #~ACTOR group :hp=>'hp', :sp=>'[ms]p', :recover=>'recover', # may be used for one member :all=>'a[l]*', :exp=>'exp(?:irience)?', :level=>'l[e]?v[e]?l', :params=>'param(?:et[e]?r)s', :nickname=>'nick(?:name)?', # TAB#2 #~MOVEMENT group :transfer=>'transfer|teleport(?:ate|ion)', :player=>'player', :map=>'map', # to use as - scroll map || event map x :x=>'x', :y=>'y', :screen=>'scr[e]*n', # to use as - event screen x :route=>'rout(?:e|ing)?', :move=>'move|go', :forward=>'forward|в[\s]*пер[её][дт]', :backward=>'backward|н[ао][\s]*за[дт]', :lower=>'lower', :upper=>'upper', :random=>'rand(?:om[ed]*)?', :toward=>'toward', :away=>'away([\s]*from)?', :step=>'step', :get=>'get', :on=>'on', :off=>'off', # to use as - get on/off vehicle :turn=>'turn', :clockwise=>'clockwise', # по часовой :counterclockwise=>'counter[\s]clockwise', # против часовой :emulate=>'emulate', :click=>'click|tap', :touch=>'touch|enter', :by_event=>'by[\s]*event', :autorun=>'auto[\s]*run', :parallel=>'para[l]*e[l]*', :wait=>'wait', :frames=>'frame[s]?', }, #--MAP branch :map=>{ :main=>'map', :set=>'set', :display=>'display', # to use as - set display map name (имя карты для отображения в игре) :editor=>'editor', # to use as - set editor map name (имя картя только для редактора) :name=>'name', :width=>'width', :height=>'height', :mode=>'mode', :field=>'field', :area=>'area', :vx_compatible=>'vx', :visible=>'visible', :ox=>'ox', :oy=>'oy', :tileset=>'tileset', # for RPG Maker VX Ace only :_A=>'A', :_B=>'B', :_C=>'C', :_D=>'D', :_E=>'E', :tile=>'tile', :index=>'index', # to use as - set tile index :terrain=>'terrain', :tag=>'tag', :bush=>'bush', :flag=>'flag', # как я понял, это для ID тайла, привязка случайных битв и все такое :battle=>'battle', :background=>'background|bg', :music=>'music', :sound=>'sound', :effect=>'effect|fx', :scroll=>'scroll', :type=>'type', :loop=>'loop', :no=>'no', :vertical=>'vertical', :horizontal=>'horizontal', :both=>'both', :note=>'note', :dash=>'dash', :dashing=>'dashing', :enable=>'enable', :disable=>'disable', :parallax=>'para[l]*a[xks]', :show=>'show', :in=>'in',# to use as - set map parallax show in the editor :the=>'the', }, #--PICTURE branch :picture=>{ :maybe=>'in future versions' }, #--SPRITE branch :sprite=>{ :main=>'sprite', :create=>'create', :dispose=>'dispose|delete', :move=>'move', :resize=>'resize', :set=>'set', :x=>'x', :y=>'y', :z=>'z', :width=>'width', :height=>'height', :flash=>'flash', :color=>'color', :duration=>'duration', :angle=>'angle', :visibility=>'visibility', :visible=>'visible', :invisible=>'invisible', :opacity=>'opacity', :blend=>'blend', :type=>'type', :mirror=>'mirror', :tone=>'tone', }, #--TEXT branch :text=>{ :main=>'text', :make=>'make', :bigger=>'bigger', :smaller=>'smaller', :set=>'set', :font=>'font', :size=>'size', :bold=>'bold', :italic=>'italic', :underline=>'under[\s]*line', :fit=>'fit', :color=>'color', :out=>'out', # to use as - set out color :line=>'line', # to use as - set outline=BOOL :shadow=>'shadow', }, #--WINDOW branch :window=>{ :main=>'window', :create=>'create', :at=>'at', :with=>'with', :dispose=>'dispose|delete', :move=>'move', :to=>'to', :speed=>'speed', :auto=>'auto', :resize=>'resize', :set=>'set', :x=>'x', :y=>'y', :z=>'z', :ox=>'ox', :oy=>'oy', :tone=>'tone', :width=>'width', :height=>'height', :link=>'link', # to use as - set button[DEC] link to switch[DEC] #dunnolol :label=>'label', :index=>'index', :indexed=>'indexed', :labeled=>'labeled', :as=>'as', :opacity=>'opacity', :back=>'back', # to use as - set back opacity :contents=>'contents', # to use as - set contents opacity :open=>'open', :openness=>'openness', :close=>'close', :active=>'active', :activate=>'activate', :deactivate=>'deactivate', :windowskin=>'skin|window[\s_]*skin', :cursor=>'cursor', :rect=>'rect', :visibility=>'visibility', :visible=>'visible', :invisible=>'invisible', } } # Хэш-таблица всех возможных сочетаний слов из VOCAB и их положения относительно друг друга в тексте.<br> # Именно по этим сочетаниям производится поиск команд Cigui в тексте. Редактировать без понимания правил # составления регулярных выражений не рекомендуется. CMB={ #~COMMON unbranch # selection window :select_window=>"(?:(?:#{VOCAB[:select]})+[\s]*(?:#{VOCAB[:window][:main]})+)|"+ "(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:select]})+)", :select_by_index=>"(?:(?:(?:#{VOCAB[:window][:index]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:indexed]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?))", :select_by_label=>"(?:(?:(?:#{VOCAB[:window][:label]})+(?:#{VOCAB[:equal]}|[\s]*)+)|"+ "(?:(?:#{VOCAB[:window][:labeled]})+[\s]*(?:#{VOCAB[:window][:as]})?(?:#{VOCAB[:equal]}|[\s]*)?))", #~CIGUI branch # commands only :cigui_start=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:start]})+)+", :cigui_finish=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:finish]})+)+", :cigui_flush=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:flush]})+)+", :cigui_restart=>"(?:(?:#{VOCAB[:cigui][:main]})+[\s]*(?:#{VOCAB[:cigui][:restart]})+)+", #~TEXT branch # expressions :text_font_size=>"(?:#{VOCAB[:text][:font]})+[\s]*(?:#{VOCAB[:text][:size]})+(?:#{VOCAB[:equal]}|[\s]*)+", # commands :text_set=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:text][:main]})+[\s]*(?:#{VOCAB[:text][:set]})+)", #~WINDOW branch # expressions :window_x_equal=>"(?:#{VOCAB[:window][:x]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_y_equal=>"(?:#{VOCAB[:window][:y]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ox_equal=>"(?:#{VOCAB[:window][:ox]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_oy_equal=>"(?:#{VOCAB[:window][:oy]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_w_equal=>"(?:#{VOCAB[:window][:width]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_h_equal=>"(?:#{VOCAB[:window][:height]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_s_equal=>"(?:#{VOCAB[:window][:speed]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_a_equal=>"(?:#{VOCAB[:window][:opacity]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_ba_equal=>"(?:(?:#{VOCAB[:window][:back]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_ca_equal=>"(?:(?:#{VOCAB[:window][:contents]})+[\s_]*(?:#{VOCAB[:window][:opacity]}))+(?:#{VOCAB[:equal]}|[\s])+", :window_active_equal=>"(?:#{VOCAB[:window][:active]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_skin_equal=>"(?:(?:#{VOCAB[:window][:windowskin]})+(?:#{VOCAB[:equal]}|[\s]*)+)", :window_openness_equal=>"(?:#{VOCAB[:window][:openness]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_tone_equal=>"(?:#{VOCAB[:window][:tone]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_visibility_equal=>"(?:#{VOCAB[:window][:visibility]})+(?:#{VOCAB[:equal]}|[\s]*)+", :window_set_text=>"(?:(?:#{VOCAB[:window][:set]})*[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})"+ "+[\s]*(?:#{VOCAB[:window][:text]})+(?:#{VOCAB[:equal]}|[\s]*)+)", # commands :window_create=>"(((?:#{VOCAB[:window][:create]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:create]})+)", :window_create_atORwith=>"((?:#{VOCAB[:window][:at]})+[\s]*(#{VOCAB[:window][:x]}|#{VOCAB[:window][:y]})+)|"+ "((?:#{VOCAB[:window][:with]})+[\s]*(?:#{VOCAB[:window][:width]}|#{VOCAB[:window][:height]}))", :window_dispose=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_dispose_this=>"(((?:#{VOCAB[:window][:dispose]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)+)|"+ "((?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s\.\,]*(?:#{VOCAB[:window][:dispose]})+)", :window_move=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:move]}))|"+ "(?:(?:#{VOCAB[:window][:move]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_resize=>"(?:(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:resize]}))|"+ "(?:(?:#{VOCAB[:window][:resize]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})))", :window_set=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:set]})+)|"+ "(?:(?:#{VOCAB[:window][:set]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_activate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:activate]})+)|"+ "(?:(?:#{VOCAB[:window][:activate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_deactivate=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:deactivate]})+)|"+ "(?:(?:#{VOCAB[:window][:deactivate]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+)", :window_open=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:open]}))|"+ "(?:(?:#{VOCAB[:window][:open]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", :window_close=>"(?:(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:close]}))|"+ "(?:(?:#{VOCAB[:window][:close]})+[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]}))", :window_visible=>"(?:(?:#{VOCAB[:window][:set]})*[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:visible]})+)", :window_invisible=>"(?:(?:#{VOCAB[:window][:set]})*[\s]*(?:#{VOCAB[:last]})+[\s]*(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:invisible]})+)", } # class <<self # Внутренний массив для вывода информации обо всех созданных окнах.<br> # Открыт только для чтения. # attr_reader :windows # Внутренний массив для вывода информации обо всех созданных спрайтах.<br> # Открыт только для чтения. # attr_reader :sprites # Хранит массив всех произведенных действий (все записи #last).<br> # Действия записываются только если параметр ::logging имеет значение # true. Результаты работы #decimal, #fraction, #boolean, #substring # и их расширенных аналогов не логгируются.<br> # Открыт только для чтения. # attr_reader :last_log # Флаг включения/выключения логгирования действий. # Если имеет значение true, то записи всех произведенных # действий с момента применения значения будут записываться # в массив ::last_log attr_accessor :logging # Требуется выполнить этот метод перед началом работы с CIGUI.<br> # Инициализирует массив $do, если он еще не был создан. В этот массив пользователь подает # команды для исполнения при следующем запуске метода #update.<br> # Если даже массив $do был инициализирован ранее, # то исполняет команду <i>cigui start</i> прежде всего.<br> # <b>Пример:</b> # begin # CIGUI.setup # #~~~ some code fragment ~~~ # CIGUI.update # #~~~ some other code fragment ~~~ # end # def setup $do||=[] $do.insert 0,'cigui start' _setup end # Вызывает все методы обработки команд, содержащиеся в массиве $do.<br> # Вызовет исключение CIGUIERR::CantInterpretCommand в том случае, # если после выполнения <i>cigui finish</i> в массиве $do будут находится # новые команды для обработки.<br> # По умолчанию очищает массив $do после обработки всех команд. Если clear_after_update # поставить значение false, то все команды из массива $do будут выполнены повторно # при следующем запуске этого метода.<br> # Помимо приватных методов обработки вызывает также метод #update_by_user, который может быть # модифицирован пользователем (подробнее смотри в описании метода).<br> # def update(clear_after_update=true) $do.each do |line| _restart? line _common? line _cigui? line _window? line #_ update_internal_objects update_by_user(line) end $do.clear if clear_after_update end # Вызывает обновление всех объектов из внутренних массивов ::windows и ::sprites.<br> # Вызывается автоматически по окончании обработки команд из массива $do в методе #update. def update_internal_objects @windows.each{ |win| win.update if win.is_a? Win3 } @sprites.each{ |spr| spr.update if spr.is_a? Spr3 } end # Метод обработки текста, созданный для пользовательских модификаций, не влияющих на работу # встроенных обработчиков.<br> # Используйте <i>alias</i> этого метода при добавлении обработки собственных команд.<br> # <b>Пример:</b> # alias my_update update_by_user # def update_by_user # # add new word # VOCAB[:window][:throw]='throw' # # add 'window throw' combination # CMB[:window_throw]="(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:throw]})+)" # # call method # window_throw? line # end # def update_by_user(string) end # Данный метод возвращает первое попавшееся целое число, найденное в строке source_string.<br> # Производит поиск только в том случае, если число записано: # * в скобки, например (10); # * в квадратные скобки, например [23]; # * в кавычки(апострофы), например '45'; # * в двойные кавычки, например "8765". # Также, вернет всю целую часть числа записанную: # * до точки, так здесь [1.35] вернет 1; # * до запятой, так здесь (103,81) вернет 103; # * до первого пробела (при стандартной конвертации в целое число), так здесь "816 586,64" вернет только 816; # * через символ подчеркивания, так здесь '1_000_0_0_0,143' вернет ровно один миллион (1000000). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # decimal('[10,25]') # => 10 # decimal('[1 0 2]',false) # => 102 # decimal('[1_234_5678 89]',false) # => 123456789 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def decimal(source_string, std_conversion=true) fraction(source_string, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #decimal, но возвращает рациональное число # (число с плавающей запятой или точкой).<br> # Имеется пара замечаний к правилам использования в дополнение к упомянутым в #decimal: # * Все цифры после запятой или точки считаются дробной частью и также могут содержать помимо цифр символ подчёркивания; # * При наличии между цифрами в дробной части пробела вернет ноль (в стандартной конвертации в целое или дробное число). # Если присвоить std_conversion значение false, то это отменит стандартную конвертацию строки, # встроенную в Ruby, и метод попробует найти число, игнорируя пробелы, табуляцию # и знаки подчеркивания. # Выключение std_conversion может привести к неожиданным последствиям. # fraction('(109,86)') # => 109.86 # fraction('(1 0 9 , 8 6)',false) # => 109.86 # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def fraction(source_string, std_conversion=true) match='(?:[\[|"\(\'])[\s]*([\-\+]?[\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)(?:[\]|"\)\'])' return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск подстроки, используемой в качестве параметра.<br> # Строка должна быть заключена в одинарные или двойные кавычки или же в круглые # или квадратные скобки. # <b>Пример:</b> # substring('[Hello cruel world!]') # => Hello cruel world! # substring("set window label='SomeSome' and no more else") # => SomeSome # def substring(source_string) match='(?:[\[\(\"\'])[\s]*([\w\s _\!\#\$\%\^\&\*]*)[\s]*(?:[\]|"\)\'])' return source_string.match(match)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод производит поиск булевого значения (true или false) в строке и возвращает его. # Если булевое значение в строке не обнаружено, по умолчанию возвращает false.<br> # Слова true и false берутся из словаря VOCAB, что значит, что их локализованные версии # также могут быть успешно найдены при поиске. def boolean(source_string) match="((?:#{VOCAB[:true]}|#{VOCAB[:false]}))" if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает массив из четырех значений для передачи в качестве параметра # в объекты класса Rect. Массив в строке должен быть помещен в квадратные скобки, # а значения в нем должны разделяться <b>точкой с запятой.</b><br> # <b>Пример:</b> # rect('[1;2,0;3.5;4.0_5]') # => [ 1, 2.0, 3.5, 4.05 ] # def rect(source_string) read='' start=false arr=[] for index in 0...source_string.size char=source_string[index] if char=='[' start=true next end if start if char!=';' if char!=']' read+=char else arr<<read break end else arr<<read read='' end end end if arr.size<4 for index in 1..4-arr.size arr<<0 end elsif arr.size>4 arr.slice!(4,arr.size) end for index in 0...arr.size arr[index]=dec(arr[index]) if arr[index].is_a? String arr[index]=0 if arr[index].is_a? NilClass end return arr end # Данный метод работает по аналогии с #decimal, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # dec('x=1cm','x=','cm') # => 1 # dec('y=120 m','[xy]=','[\s]*(?:cm|m|km)') # => 120 # В отличие от #frac, возвращает целое число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def dec(source_string, prefix='', postfix='', std_conversion=true) frac(source_string, prefix, postfix, std_conversion).to_i rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #fraction, но производит поиск в строке # с учетом указанных префикса (текста перед числом) и постфикса (после числа).<br> # Метод не требует обязательного указания символов квадратных и круглых скобок, # а также одинарных и двойных кавычек вокруг числа.<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска. # frac('x=31.2mm','x=','mm') # => 31.2 # frac('y=987,67 m','[xy]=','[\s]*(?:cm|m|km)') # => 987.67 # В отличие от #dec, возвращает рациональное число. # <br> # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def frac(source_string, prefix='', postfix='', std_conversion=true) match=prefix+'([\-\+]?[\d\s_]*(?:[\s]*[\,\.][\s]*(?:[\d\s_]*))*)'+postfix return source_string.match(/#{match}/i)[1].gsub!(/[\s_]*/){}.to_f if !std_conversion source_string.match(/#{match}/i)[1].to_f rescue raise "#{CIGUIERR::CantReadNumber}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #substring, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # Указание квадратных или круглый скобок, а также экранированных одинарных или двойных кавычек # в строке после префикса обязательно. # prefix и postfix могут содержать символы, используемые в регулярных выражениях # для более точного поиска.<br> # <b>Пример:</b> # puts 'Who can make me strong?' # someone = substring("Make[ me ]invincible",'Make','invincible') # puts 'Only'+someone # => 'Only me' # Метод работает вне зависимости от работы модуля - нет необходимости # запускать для вычисления #setup и #update. # def substr(source_string, prefix='', postfix='') match=prefix+'(?:[\[\(\"\'])[\s]*([\w\s _\!\#\$\%\^\&\*]*)[\s]*(?:[\]|"\)\'])'+postfix return source_string.match(/#{match}/i)[1] rescue raise "#{CIGUIERR::CantReadString}\n\tcurrent line of $do: #{source_string}" end # Данный метод работает по аналогии с #boolean, но производит поиск в строке # с учетом указанных префикса (текста перед подстрокой) и постфикса (после подстроки).<br> # prefix и postfix могут содержать символы, используемые в регулярных выражениях # Если булевое значение в строке не обнаружено, по умолчанию возвращает false. def bool(source_string, prefix='', postfix='') match=prefix+"((?:#{VOCAB[:true]}|#{VOCAB[:false]}))"+postfix if source_string.match(match).size>1 return false if source_string.match(/#{match}/i)[1]==nil match2="(#{VOCAB[:true]})" return true if source_string.match(/#{match2}/i)[1] end return false end # Возвращает сообщение о последнем произведенном действии # или классе последнего использованного объекта, используя метод # Kernel.inspect.<br> # <b>Пример:</b> # CIGUI.setup # puts CIGUI.last # => 'CIGUI started' # def last @last_action.is_a?(String) ? @last_action : @last_action.inspect end private # SETUP CIGUI / CLEAR FOR RESTART def _setup @last_action ||= nil @logging ||= true @last_log ||= [] @finished = false @windows = [] @sprites = [] @selection = { :type => nil, # may be window or sprite :index => 0, # index in internal array :label => nil # string in class to find index } @global_text.is_a?(NilClass) ? @global_text=Text.new('') : @global_text.empty end # RESTART def _restart?(string) matches=string.match(/#{CMB[:cigui_restart]}/) if matches __flush?('cigui flush') if not @finished _setup @last_action = 'CIGUI restarted' @last_log << @last_action if @logging else raise "#{CIGUIERR::CantInterpretCommand}\n\tcurrent line of $do: #{string}" if @finished end end # COMMON UNBRANCH def _common?(string) # select, please and other __swindow? string end def __swindow?(string) matches=string.match(/#{CMB[:select_window]}/) # Only match if matches # Read index or label if string.match(/#{CMB[:select_by_index]}/) index = dec(string,CMB[:select_by_index]) if index>-1 @selection[:type]=:window @selection[:index]=index if index.between?(0...@windows.size) @selection[:label]=@windows[index].label if @windows[index]!=nil && @windows[index].is_a?(Win3) end end elsif string.match(/#{CMB[:select_by_label]}/) label = substr(string,CMB[:select_by_label]) if label!=nil @selection[:type]=:window @selection[:label]=label for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label @selection[:index]=index break end end end end end @last_action = @selection @last_log << @last_action if @logging end end#--------------------end of '__swindow?'------------------------- # CIGUI BRANCH def _cigui?(string) __start? string __finish? string __flush? string end def __start?(string) matches=string.match(/#{CMB[:cigui_start]}/) if matches begin @finished = false @last_action = 'CIGUI started' @last_log << @last_action if @logging rescue raise "#{CIGUIERR::CantStart}\n\tcurrent line of $do: #{string}" end end end def __finish?(string) matches=string.match(/#{CMB[:cigui_finish]}/) if matches @finished = true @last_action = 'CIGUI finished' @last_log << @last_action if @logging end end def __flush?(string) matches=string.match(/#{CMB[:cigui_flush]}/) if matches @windows.each{|item|item.dispose} @windows.clear @sprites.each{|item|item.dispose} @sprites.clear @last_action = 'CIGUI cleared' @last_log << @last_action if @logging end end # WINDOW BRANCH def _window?(string) __wcreate? string __wdispose? string __wmove? string __wresize? string __wset? string __wactivate? string __wdeactivate? string __wopen? string __wclose? string __wvisible? string __winvisible? string end # Examples: # create window (default position and size) # create window at x=DEC, y=DEC # create window with width=DEC,height=DEC # create window at x=DEC, y=DEC with w=DEC, h=DEC def __wcreate?(string) matches=string.match(/#{CMB[:window_create]}/i) # Only create if matches begin begin @windows<<Win3.new if RUBY_VERSION.to_f >= 1.9 rescue @windows<<NilClass end rescue raise "#{CIGUIERR::CannotCreateWindow}\n\tcurrent line of $do: #{string}" end # Read params if string.match(/#{CMB[:window_create_atORwith]}/i) # at OR with: check x and y new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows.last.x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows.last.y # at OR with: check w and h new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows.last.width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows.last.height # Set parameters for created window @windows.last.x = new_x @windows.last.y = new_y @windows.last.width = new_w @windows.last.height = new_h end # Set last action to inspect this window @last_action = @windows.last @last_log << @last_action if @logging # Select this window @selection[:type]=:window @selection[:index]=@windows.size-1 end end #--------------------end of '__wcreate?'------------------------- # Examples: # dispose window index=DEC # dispose window label=STR def __wdispose?(string) # Если какое-то окно уже выбрано, то... matches=string.match(/#{CMB[:window_dispose_this]}/i) if matches if @selection[:type]==:window #(0...@windows.size).include?(@selection[:index]) # ...удалим его как полагается... @windows[@selection[:index]].dispose if @windows[@selection[:index]].methods.include? :dispose @windows.delete_at(@selection[:index]) @last_action = 'CIGUI disposed window' @last_log << @last_action if @logging return end end # ... а если же нет, то посмотрим, указаны ли его индекс или метка. matches=string.match(/#{CMB[:window_dispose]}/i) if matches if string.match(/#{CMB[:select_by_index]}/i) index=dec(string,CMB[:select_by_index]) if index.between?(0,@windows.size) # Проверка удаления для попавшихся объектов класса Nil # в результате ошибки создания окна @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) else raise "#{CIGUIERR::WrongWindowIndex}"+ "\n\tinternal windows size: #{@windows.size} (#{index} is not in range of 0..#{@windows.size})"+ "\n\tcurrent line of $do: #{string}" end elsif string.match(/#{CMB[:select_by_label]}/i) label = substr(string,CMB[:select_by_label]) if label!=nil for index in 0...@windows.size if @windows[index]!=nil && @windows[index].is_a?(Win3) if @windows[index].label==label break end end end end @windows[index].dispose if @windows[index].methods.include? :dispose @windows.delete_at(index) end @last_action = 'CIGUI disposed window by index or label' @last_log << @last_action if @logging end end#--------------------end of '__wdispose?'------------------------- # Examples: # this move to x=DEC,y=DEC # this move to x=DEC,y=DEC with speed=1 # this move to x=DEC,y=DEC with speed=auto def __wmove?(string) matches=string.match(/#{CMB[:window_move]}/i) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].speed = new_s @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end end#--------------------end of '__wmove?'------------------------- # example: # this resize to width=DEC,height=DEC def __wresize?(string) matches=string.match(/#{CMB[:window_resize]}/) # Only move if matches begin # Read params new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height # CHANGED TO SELECTED if @selection[:type]==:window @windows[@selection[:index]].resize(new_w,new_h) @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end end#--------------------end of '__wresize?'------------------------- # examples: # this window set x=DEC, y=DEC, z=DEC, width=DEC, height=DEC # this window set label=[STR] # this window set opacity=DEC # this window set back opacity=DEC # this window set active=BOOL # this window set skin=[STR] # this window set openness=DEC # this window set cursor rect=[RECT] # this window set tone=[RECT] def __wset?(string) matches=string.match(/#{CMB[:window_set]}/) # Only move if matches begin # Read params new_x = string[/#{CMB[:window_x_equal]}/i] ? dec(string,CMB[:window_x_equal]) : @windows[@selection[:index]].x new_y = string[/#{CMB[:window_y_equal]}/i] ? dec(string,CMB[:window_y_equal]) : @windows[@selection[:index]].y new_ox = string[/#{CMB[:window_ox_equal]}/i] ? dec(string,CMB[:window_ox_equal]) : @windows[@selection[:index]].ox new_oy = string[/#{CMB[:window_oy_equal]}/i] ? dec(string,CMB[:window_oy_equal]) : @windows[@selection[:index]].oy new_w = string[/#{CMB[:window_w_equal]}/i] ? dec(string,CMB[:window_w_equal]) : @windows[@selection[:index]].width new_h = string[/#{CMB[:window_h_equal]}/i] ? dec(string,CMB[:window_h_equal]) : @windows[@selection[:index]].height new_s = string[/#{CMB[:window_s_equal]}/i] ? dec(string,CMB[:window_s_equal]) : @windows[@selection[:index]].speed new_a = string[/#{CMB[:window_a_equal]}/i] ? dec(string,CMB[:window_a_equal]) : @windows[@selection[:index]].opacity new_ba = string[/#{CMB[:window_ba_equal]}/i] ? dec(string,CMB[:window_ba_equal]) : @windows[@selection[:index]].back_opacity new_act = string[/#{CMB[:window_active_equal]}/i] ? bool(string,CMB[:window_active_equal]) : @windows[@selection[:index]].active new_skin = string[/#{CMB[:window_skin_equal]}/i] ? substr(string,CMB[:window_skin_equal]) : @windows[@selection[:index]].windowskin new_open = string[/#{CMB[:window_openness_equal]}/i] ? dec(string,CMB[:window_openness_equal]) : @windows[@selection[:index]].openness new_label = string[/#{CMB[:select_by_label]}/i] ? substr(string,CMB[:select_by_label]) : @windows[@selection[:index]].label new_tone = string[/#{CMB[:window_tone_equal]}/i] ? rect(string) : @windows[@selection[:index]].tone new_vis = string[/#{CMB[:window_visibility_equal]}/i] ? bool(string,CMB[:window_visibility_equal]) : @windows[@selection[:index]].visible # Change it if @selection[:type]==:window @windows[@selection[:index]].x = new_x @windows[@selection[:index]].y = new_y @windows[@selection[:index]].ox = new_ox @windows[@selection[:index]].oy = new_oy @windows[@selection[:index]].resize(new_w,new_h) @windows[@selection[:index]].speed = new_s==0 ? :auto : new_s @windows[@selection[:index]].opacity = new_a @windows[@selection[:index]].back_opacity = new_ba @windows[@selection[:index]].active = new_act @windows[@selection[:index]].windowskin = new_skin @windows[@selection[:index]].openness = new_open @windows[@selection[:index]].label = new_label @windows[@selection[:index]].visible = new_vis if new_tone.is_a? Tone @windows[@selection[:index]].tone.set(new_tone) elsif new_tone.is_a? Array @windows[@selection[:index]].tone.set(new_tone[0],new_tone[1],new_tone[2],new_tone[3]) end @selection[:label] = new_label @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end end#--------------------end of '__wset?'------------------------- def __wactivate?(string) matches=string.match(/#{CMB[:window_activate]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].active=true @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wactivate?'------------------------- def __wdeactivate?(string) matches=string.match(/#{CMB[:window_deactivate]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].active=false @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wdeactivate?'------------------------- def __wopen?(string) matches=string.match(/#{CMB[:window_open]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].open @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wopen?'------------------------- def __wclose?(string) matches=string.match(/#{CMB[:window_close]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].close @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wclose?'------------------------- def __wvisible?(string) matches=string.match(/#{CMB[:window_set_visible]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].visible = true @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wvisible?'------------------------- def __winvisible?(string) matches=string.match(/#{CMB[:window_set_invisible]}/i) if matches if @selection[:type]==:window @windows[@selection[:index]].visible = false @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__winvisible?'------------------------- def __wset_text?(string) matches=string.match(/#{CMB[:window_set_text]}/i) if matches new_text = substr(string,CMB[:window_set_text]) if @selection[:type]==:window @windows[@selection[:index]].add_text = new_text @last_action = @windows[@selection[:index]] @last_log << @last_action if @logging end end end#--------------------end of '__wset_text?'------------------------- end# END OF CIGUI CLASS end# END OF CIGUI MODULE # test zone # delete this when copy to 'Script editor' in RPG Maker begin $do=[ 'create window at x=1540,y=9000 with width=900,height=560', 'this window set ox=22,oy=33,tone=[255;123;40;20],label=[Current],speed=0,windowskin="Something other"', 'close this window', 'deactivate this window', 'this window set active=true', 'cigui restart' ] CIGUI.setup CIGUI.update puts CIGUI.last puts CIGUI.decimal('[-100]') end
class BHLEADConverter < EADConverter def self.import_types(show_hidden = false) [ { :name => "bhl_ead_xml", :description => "Import BHL EAD records from an XML file" } ] end def self.instance_for(type, input_file) if type == "bhl_ead_xml" self.new(input_file) else nil end end def self.profile "Convert EAD To ArchivesSpace JSONModel records" end def format_content(content) super.gsub(/[, ]+$/,"") # Remove trailing commas and spaces end def self.configure super # BEGIN UNITID CUSTOMIZATIONS # Let's take those brackets off of unitids and just add them in the exporter with 'unitid' do |node| ancestor(:note_multipart, :resource, :archival_object) do |obj| case obj.class.record_type when 'resource' # inner_xml.split(/[\/_\-\.\s]/).each_with_index do |id, i| # set receiver, "id_#{i}".to_sym, id # end set obj, :id_0, inner_xml when 'archival_object' set obj, :component_id, inner_xml.gsub("[","").gsub("]","").strip end end end # BEGIN TITLEPROPER AND AUTHOR CUSTOMIZATIONS # The stock ArchivesSpace converter sets the author and titleproper elements each time it finds a titleproper or author elements # This means that it first creates the elements using titlestmt/author and titlestmt/titleproper, and then overwrites the values when it reaches titlepage # We want to use the titlepage statements. Changing this to be more explicit about using the statement that we want, and to remove some unwanted linebreaks. # The EAD importer ignores titlepage; we need to unignore it with "titlepage" do @ignore = false end with 'titlepage/titleproper' do type = att('type') title_statement = inner_xml.gsub("<lb/>"," <lb/>") case type when 'filing' set :finding_aid_filing_title, title_statement.gsub("<lb/>","").gsub(/<date(.*?)<\/date>/,"").gsub(/\s+/," ").strip else set :finding_aid_title, title_statement.gsub("<lb/>","").gsub(/<date(.*?)<\/date>/,"").gsub(/\s+/," ").strip end end with 'titlepage/author' do author_statement = inner_xml.gsub("<lb/>"," <lb/>") set :finding_aid_author, author_statement.gsub("<lb/>","").gsub(/\s+/," ").strip end # Skip the titleproper and author statements from titlestmt with 'titlestmt/titleproper' do next end with 'titlestmt/author' do next end # Skip these to override the default ArchiveSpace functionality, which searches for a titleproper or an author anywhere with 'titleproper' do next end with 'author' do next end # END TITLEPROPER CUSTOMIZATIONS # BEGIN CLASSIFICATION CUSTOMIZATIONS # In our EADs, the most consistent way that MHC and UARP finding aids are identified is via the titlepage/publisher # In ArchivesSpace, we will be using Classifications to distinguish between the two # This modification will link the resource being created to the appropriate Classification in ArchivesSpace with 'classification' do set :classifications, {'ref' => att('ref')} end # END CLASSIFICATION CUSTOMIZATIONS # BEGIN CHRONLIST CUSTOMIZATIONS # For some reason the stock importer doesn't separate <chronlist>s out of notes like it does with <list>s # Like, it includes the mixed content <chronlist> within the note text and also makes a chronological list, duplicating the content # The addition of (split_tag = 'chronlist') to the insert_into_subnotes method call here fixes that with 'chronlist' do if ancestor(:note_multipart) left_overs = insert_into_subnotes(split_tag = 'chronlist') else left_overs = nil make :note_multipart, { :type => node.name, :persistent_id => att('id'), } do |note| set ancestor(:resource, :archival_object), :notes, note end end make :note_chronology do |note| set ancestor(:note_multipart), :subnotes, note end # and finally put the leftovers back in the list of subnotes... if ( !left_overs.nil? && left_overs["content"] && left_overs["content"].length > 0 ) set ancestor(:note_multipart), :subnotes, left_overs end end # END CHRONLIST CUSTOMIZATIONS # BEGIN BIBLIOGRAPHY CUSTOMIZATIONS # Our bibliographies are really more like general notes with paragraphs, lists, etc. We don't have any bibliographies # that are simply a collection of <bibref>s, and all of the bibliographies that do have <bibref>s have them inserted into # items in lists. This change will import bibliographies as a general note, which is really more appropriate given their content with 'bibliography' do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => 'odd', :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end %w(bibliography index).each do |x| next if x == 'bibliography' with "index/head" do |node| set :label, format_content( inner_xml ) end with "index/p" do set :content, format_content( inner_xml ) end end with 'bibliography/bibref' do next end with 'bibliography/p' do next end with 'bibliography/head' do next end # END BIBLIOGRAPHY CUSTOMIZATIONS # BEGIN BLOCKQUOTE P TAG FIX # The ArchivesSpace EAD importer replaces all <p> tags with double line breaks # This leads to too many line breaks surrounding closing block quote tags # On export, this invalidates the EAD # The following code is really hacky workaround to reinsert <p> tags within <blockquote>s # Note: We only have blockquotes in bioghists and scopecontents, so call modified_format_content on just this block is sufficient # This function calls the regular format_content function, and then does a few other things, like preserving blockquote p tags and removing opening and closing parens from some notes, before returning the content def modified_format_content(content, note) content = format_content(content) # Remove parentheses from single-paragraph odds blocks = content.split("\n\n") if blocks.length == 1 case note when 'odd','abstract','accessrestrict','daodesc' if content =~ /^\((.*?)\)$/ content = $1 elsif content =~ /^\[(.*?)\]$/ content = $1 end end end content.gsub(/<blockquote>\s*?/,"<blockquote><p>").gsub(/\s*?<\/blockquote>/,"</p></blockquote>") end %w(accessrestrict accessrestrict/legalstatus \ accruals acqinfo altformavail appraisal arrangement \ bioghist custodhist dimensions \ fileplan odd otherfindaid originalsloc phystech \ prefercite processinfo relatedmaterial scopecontent \ separatedmaterial userestrict ).each do |note| with note do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :publish => true, :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => modified_format_content( content, note ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end # END BLOCKQUOTE P TAG FIX # BEGIN CONDITIONAL SKIPS # We have lists and indexes with all sorts of crazy things, like <container>, <physdesc>, <physloc>, etc. tags within <item> or <ref> tags # So, we need to tell the importer to skip those things only when they appear in places where they shouldn't, otherwise do # it's normal thing # REMINDER: If using the container management plugin, add the line 'next if context == :note_orderedlist' to "with 'container' do" in # the converter_extra_container_values mixin %w(abstract langmaterial materialspec physloc).each do |note| next if note == "langmaterial" with note do |node| next if context == :note_orderedlist # skip these next if context == :items # these too content = inner_xml next if content =~ /\A<language langcode=\"[a-z]+\"\/>\Z/ if content.match(/\A<language langcode=\"[a-z]+\"\s*>([^<]+)<\/language>\Z/) content = $1 end make :note_singlepart, { :type => note, :persistent_id => att('id'), :publish => true, :content => modified_format_content( content.sub(/<head>.*?<\/head>/, ''), note ) } do |note| set ancestor(:resource, :archival_object), :notes, note end end end with 'list' do next if ancestor(:note_index) if ancestor(:note_multipart) left_overs = insert_into_subnotes else left_overs = nil make :note_multipart, { :type => 'odd', :persistent_id => att('id'), :publish => true, } do |note| set ancestor(:resource, :archival_object), :notes, note end end # now let's make the subnote list type = att('type') if type == 'deflist' || (type.nil? && inner_xml.match(/<deflist>/)) make :note_definedlist do |note| set ancestor(:note_multipart), :subnotes, note end else make :note_orderedlist, { :enumeration => att('numeration') } do |note| set ancestor(:note_multipart), :subnotes, note end end # and finally put the leftovers back in the list of subnotes... if ( !left_overs.nil? && left_overs["content"] && left_overs["content"].length > 0 ) set ancestor(:note_multipart), :subnotes, left_overs end end with 'list/item' do # Okay this is another one of those hacky things that work # The problem: we have many items nested within items, like <list><item>First item <list><item>Subitem</item></list></item></list> # This would make one item like: # First item <list><item>Subitem</item></list> # And another like: # Subitem # ArchivesSpace lists are flat and do not allow for nesting lists within lists within items within lists within.. (you get the idea)... # Now, it would be nice to have a better way to tell the importer to only account for subitems one time, but there doesn't seem to be # With this modification we can change nested lists to <sublist> and nested items to <subitem> before migration # That way, the importer will ignore those sublists and subitems and sub out those tags for the correct tags set :items, inner_xml.gsub("sublist","list").gsub("subitem","item") if context == :note_orderedlist end # END CONDITIONAL SKIPS # BEGIN CONTAINER MODIFICATIONS # Skip containers that appear in lists # Don't downcase the instance_label # Import att('type') as the container type for top containers, att('label') as the container type for subcontainers # example of a 1:many tag:record relation (1+ <container> => 1 instance with 1 container) with 'container' do next if context == :note_orderedlist @containers ||= {} # we've found that the container has a parent att and the parent is in # our queue if att("parent") && @containers[att('parent')] cont = @containers[att('parent')] else # there is not a parent. if there is an id, let's check if there's an # instance before we proceed inst = context == :instance ? context_obj : context_obj.instances.last # if there are no instances, we need to make a new one. # or, if there is an @id ( but no @parent) we can assume its a new # top level container that will be referenced later, so we need to # make a new instance if ( inst.nil? or att('id') ) instance_label = att("label") ? att("label") : 'mixed_materials' if instance_label =~ /(.*)\s\[([0-9]+)\]$/ instance_label = $1 barcode = $2 end make :instance, { :instance_type => instance_label } do |instance| set ancestor(:resource, :archival_object), :instances, instance end inst = context_obj end # now let's check out instance to see if there's a container... if inst.container.nil? make :container do |cont| set inst, :container, cont end end # and now finally we get the container. cont = inst.container || context_obj cont['barcode_1'] = barcode if barcode cont['container_profile_key'] = att("altrender") end # now we fill it in (1..3).to_a.each do |i| next unless cont["type_#{i}"].nil? if i == 1 cont["type_#{i}"] = att('type') elsif i == 2 or i == 3 cont["type_#{i}"] = att('label') end cont["indicator_#{i}"] = format_content( inner_xml ) break end #store it here incase we find it has a parent @containers[att("id")] = cont if att("id") end # END CONTAINER MODIFICATIONS # BEGIN CUSTOM SUBJECT AND AGENT IMPORTS # We'll be importing most of our subjects and agents separately and linking directly to the URI from our finding # aids and accession records. # This will check our subject, geogname, genreform, corpname, famname, and persname elements in our EADs for a ref attribute # If a ref attribute is present, it will use that to link the agent to the resource. # If there is no ref attribute, it will make a new agent as usual. # We also have compound agents (agents with both a persname, corpname or famname and subdivided subject terms) # In ArchivesSpace, this kind of agent can be represented in a resource by linking to the agent and adding terms/subdivisions # within the resource. We will be accomplishing this by invalidating our EAD at some point (gasp!) to add <term> tags # around the individual terms in a corpname, persname, or famname. This modification will also make sure that those terms # get imported properly. { 'function' => 'function', 'genreform' => 'genre_form', 'geogname' => 'geographic', 'occupation' => 'occupation', 'subject' => 'topical', 'title' => 'uniform_title' # added title since we have some <title> tags in our controlaccesses }.each do |tag, type| with "controlaccess/#{tag}" do if att('ref') set ancestor(:resource, :archival_object), :subjects, {'ref' => att('ref')} else make :subject, { :terms => {'term' => inner_xml, 'term_type' => type, 'vocabulary' => '/vocabularies/1'}, :vocabulary => '/vocabularies/1', :source => att('source') || 'ingest' } do |subject| set ancestor(:resource, :archival_object), :subjects, {'ref' => subject.uri} end end end end with 'origination/corpname' do if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'creator'} else make_corp_template(:role => 'creator') end end with 'controlaccess/corpname' do corpname = Nokogiri::XML::DocumentFragment.parse(inner_xml) terms ||= [] corpname.children.each do |child| if child.respond_to?(:name) && child.name == 'term' term = child.content.strip term_type = child['type'] terms << {'term' => term, 'term_type' => term_type, 'vocabulary' => '/vocabularies/1'} end end relator = nil if att('encodinganalog') == '710' relator = 'ctb' end if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'subject', 'terms' => terms, 'relator' => relator} else make_corp_template(:role => 'subject') end end with 'origination/famname' do if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'creator'} else make_family_template(:role => 'creator') end end with 'controlaccess/famname' do famname = Nokogiri::XML::DocumentFragment.parse(inner_xml) terms ||= [] famname.children.each do |child| if child.respond_to?(:name) && child.name == 'term' term = child.content.strip term_type = child['type'] terms << {'term' => term, 'term_type' => term_type, 'vocabulary' => '/vocabularies/1'} end end relator = nil if att('encodinganalog') == '700' relator = 'ctb' end if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'subject', 'terms' => terms, 'relator' => relator} else make_family_template(:role => 'subject') end end with 'origination/persname' do if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'creator'} else make_person_template(:role => 'creator') end end with 'controlaccess/persname' do persname = Nokogiri::XML::DocumentFragment.parse(inner_xml) terms ||= [] persname.children.each do |child| if child.respond_to?(:name) && child.name == 'term' term = child.content.strip term_type = child['type'] terms << {'term' => term, 'term_type' => term_type, 'vocabulary' => '/vocabularies/1'} end end relator = nil if att('encodinganalog') == '700' relator = 'ctb' end if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'subject', 'terms' => terms, 'relator' => relator} else make_person_template(:role => 'subject') end end # END CUSTOM SUBJECT AND AGENT IMPORTS # BEGIN PHYSDESC CUSTOMIZATIONS # The stock EAD importer doesn't import <physfacet> and <dimensions> tags into extent objects; instead making them notes # This is a corrected version # first, some methods for generating note objects def make_single_note(note_name, tag, tag_name="") content = tag.inner_text if !tag_name.empty? content = tag_name + ": " + content end make :note_singlepart, { :type => note_name, :persistent_id => att('id'), :publish => true, :content => format_content( content.sub(/<head>.?<\/head>/, '').strip) } do |note| set ancestor(:resource, :archival_object), :notes, note end end def make_nested_note(note_name, tag) content = tag.inner_text make :note_multipart, { :type => note_name, :persistent_id => att('id'), :publish => true, :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end with 'physdesc' do next if context == :note_orderedlist # skip these physdesc = Nokogiri::XML::DocumentFragment.parse(inner_xml) extent_number_and_type = nil dimensions = [] physfacets = [] container_summaries = [] other_extent_data = [] container_summary_texts = [] dimensions_texts = [] physfacet_texts = [] # If there is already a portion specified, use it portion = att('altrender') || 'whole' physdesc.children.each do |child| # "extent" can have one of two kinds of semantic meanings: either a true extent with number and type, # or a container summary. Disambiguation is done through a regex. if child.name == 'extent' child_content = child.content.strip if extent_number_and_type.nil? && child_content =~ /^([0-9\.]+)+\s+(.*)$/ extent_number_and_type = {:number => $1, :extent_type => $2} else container_summaries << child container_summary_texts << child.content.strip end elsif child.name == 'physfacet' physfacets << child physfacet_texts << child.content.strip elsif child.name == 'dimensions' dimensions << child dimensions_texts << child.content.strip elsif child.name != 'text' other_extent_data << child end end # only make an extent if we got a number and type, otherwise put all physdesc contents into a note if extent_number_and_type make :extent, { :number => $1, :extent_type => $2, :portion => portion, :container_summary => container_summary_texts.join('; '), :physical_details => physfacet_texts.join('; '), :dimensions => dimensions_texts.join('; ') } do |extent| set ancestor(:resource, :archival_object), :extents, extent end # there's no true extent; split up the rest into individual notes else container_summaries.each do |summary| make_single_note("physdesc", summary) end physfacets.each do |physfacet| make_single_note("physfacet", physfacet) end # dimensions.each do |dimension| make_nested_note("dimensions", dimension) end end other_extent_data.each do |unknown_tag| make_single_note("physdesc", unknown_tag, unknown_tag.name) end end # overwriting the default dimensions and physfacet functionality with "dimensions" do next end with "physfacet" do next end # END PHYSDESC CUSTOMIZATIONS # BEGIN LANGUAGE CUSTOMIZATIONS # By default, ASpace just uses the last <language> tag it finds as the primary # language of the material described. This results in incorrect finding-aid languages for many eads. # for example, ead with the following <langmaterial> tag: ## <langmaterial> ## The material is mostly in <language langcode="eng" encodinganalog="041">English</language>; ## some correspondence is in <language langcode="arm" encodinganalog="041">Armenian;</language>; ## select items are in <language langcode="ger" encodinganalog="041">German</language>. ## </langmaterial> # will result in a primary material language of German. # these changes fix that with "langmaterial" do # first, assign the primary language to the ead langmaterial = Nokogiri::XML::DocumentFragment.parse(inner_xml) langmaterial.children.each do |child| if child.name == 'language' set ancestor(:resource, :archival_object), :language, child.attr("langcode") break end end # write full tag content to a note, subbing out the language tags content = inner_xml next if content =~ /\A<language langcode=\"[a-z]+\"\/>\Z/ if content.match(/\A<language langcode=\"[a-z]+\"\s*>([^<]+)<\/language>\Z/) content = $1 end make :note_singlepart, { :type => "langmaterial", :persistent_id => att('id'), :publish => true, :content => format_content( content.sub(/<head>.*?<\/head>/, '') ) } do |note| set ancestor(:resource, :archival_object), :notes, note end end # overwrite the default langusage tag behavior with "language" do next end # END LANGUAGE CUSTOMIZATIONS # BEGIN INDEX CUSTOMIZATIONS # The stock EAD converter creates separate index items for each indexentry, # one for the value (persname, famname, etc) and one for the reference (ref), # even when they are within the same indexentry and are related # (i.e., the persname is a correspondent, the ref is a date or a location at which # correspondence with that person can be found). # The Bentley's <indexentry>s generally look something like: # # <indexentry><persname>Some person</persname><ref>Some date or folder</ref></indexentry> # # As the <persname> and the <ref> are associated with one another, # we want to keep them together in the same index item in ArchiveSpace. # This will treat each <indexentry> as one item, # creating an index item with a 'value' from the <persname>, <famname>, etc. # and a 'reference_text' from the <ref>. with 'indexentry' do entry_type = '' entry_value = '' entry_reference = '' indexentry = Nokogiri::XML::DocumentFragment.parse(inner_xml) indexentry.children.each do |child| case child.name when 'name' entry_value << child.content entry_type << 'name' when 'persname' entry_value << child.content entry_type << 'person' when 'famname' entry_value << child.content entry_type << 'family' when 'corpname' entry_value << child.content entry_type << 'corporate_entity' when 'subject' entry_value << child.content entry_type << 'subject' when 'function' entry_value << child.content entry_type << 'function' when 'occupation' entry_value << child.content entry_type << 'occupation' when 'genreform' entry_value << child.content entry_type << 'genre_form' when 'title' entry_value << child.content entry_type << 'title' when 'geogname' entry_value << child.content entry_type << 'geographic_name' end if child.name == 'ref' entry_reference << child.content end end make :note_index_item, { :type => entry_type, :value => entry_value, :reference_text => entry_reference } do |item| set ancestor(:note_index), :items, item end end # Skip the stock importer actions to avoid confusion/duplication { 'name' => 'name', 'persname' => 'person', 'famname' => 'family', 'corpname' => 'corporate_entity', 'subject' => 'subject', 'function' => 'function', 'occupation' => 'occupation', 'genreform' => 'genre_form', 'title' => 'title', 'geogname' => 'geographic_name' }.each do |k, v| with "indexentry/#{k}" do |node| next end end with 'indexentry/ref' do next end # END INDEX CUSTOMIZATIONS # BEGIN HEAD CUSTOMIZATIONS # This issue is similar to the language issue -- if there is a note with multiple <head> elements (say, a bioghist with its own head and sublists with their own heads), # the stock importer action is to set the note label to the very last <head> it finds. This modification will only set the label if it does not already exist, ensuring # that it will only be set once. with 'head' do if context == :note_multipart ancestor(:note_multipart) do |note| next unless note["label"].nil? set :label, format_content( inner_xml ) end elsif context == :note_chronology ancestor(:note_chronology) do |note| next unless note["title"].nil? set :title, format_content( inner_xml ) end end end # END HEAD CUSTOMIZATIONS # BEGIN DAO TITLE CUSTOMIZATIONS # The Bentley has many EADs with <dao> tags that lack title attributes. # The stock ArchivesSpace EAD Converter uses each <dao>'s title attribute as # the value for the imported digital object's title, which is a required property. # As a result, all of our EADs with <dao> tags fail when trying to import into ArchivesSpace. # This section of the BHL EAD Converter plugin modifies the stock ArchivesSpace EAD Converter # by forming a string containing the digital object's parent archival object's title and date (if both exist), # or just its title (if only the title exists), or just it's date (if only the date exists) # and then using that string as the imported digital object's title. with 'dao' do if att('ref') # A digital object has already been made make :instance, { :instance_type => 'digital_object', :digital_object => {'ref' => att('ref')} } do |instance| set ancestor(:resource, :archival_object), :instances, instance end else # Make a digital object make :instance, { :instance_type => 'digital_object' } do |instance| set ancestor(:resource, :archival_object), :instances, instance end # We'll use either the <dao> title attribute (if it exists) or our display_string (if the title attribute does not exist) # This forms a title string using the parent archival object's title, if it exists daotitle = nil ancestor(:archival_object ) do |ao| if ao.title && ao.title.length > 0 daotitle = ao.title end end # This forms a date string using the parent archival object's date expression, # or its begin date - end date, or just it's begin date, if any exist # (Actually, we have expressions for all of our dates...let's just use those for the sake of simplicity) daodates = [] ancestor(:archival_object) do |aod| if aod.dates && aod.dates.length > 0 aod.dates.each do |dl| if dl['expression'].length > 0 daodates << dl['expression'] end end end end title = daotitle date_label = daodates.join(', ') if daodates.length > 0 # This forms a display string using the parent archival object's title and date (if both exist), # or just its title or date (if only one exists) display_string = title || '' display_string += ', ' if title && date_label display_string += date_label if date_label make :digital_object, { :digital_object_id => SecureRandom.uuid, :title => att('title') || display_string, } do |obj| obj.file_versions << { :use_statement => att('role'), :file_uri => att('href'), :xlink_actuate_attribute => att('actuate'), :xlink_show_attribute => att('show') } set ancestor(:instance), :digital_object, obj end end end end with 'daodesc' do ancestor(:digital_object) do |dobj| next if dobj.ref end make :note_digital_object, { :type => 'note', :persistent_id => att('id'), :content => modified_format_content(inner_xml.strip,'daodesc') } do |note| set ancestor(:digital_object), :notes, note end end # END DAO TITLE CUSTOMIZATIONS =begin # Note: The following bits are here for historical reasons # We have either decided against implementing the functionality OR the ArchivesSpace importer has changed, deprecating the following customizations # START IGNORE # Setting some of these to ignore because we have some physdesc, container, etc. # Within list/items in our descgrps at the end of finding aids. # Without setting these to ignore, ASpace both makes the list AND makes separate # notes for physdesc, dimension, etc. and tries to make instances out of the # containers, causing import errors. # Note: if using this in conjunction with the Yale container management plugin, # be sure to include the line 'next ignore if @ignore' within the with container do # section of the ConverterExtraContainerValues module. with 'archref/container' do @ignore = true end with 'archref/physdesc/dimensions' do @ignore = true end with 'archref/unittitle' do @ignore = true end with 'archref/unittitle/unitdate' do @ignore = true end with 'archref/note' do @ignore = true end with 'archref/note/p/unitdate' do @ignore = true end with 'archref/note/p/geogname' do @ignore = true end with 'unittitle' do |node| ancestor(:note_multipart, :resource, :archival_object) do |obj| unless obj.class.record_type == "note_multipart" or context == "note_orderedlist" title = Nokogiri::XML::DocumentFragment.parse(inner_xml.strip) title.xpath(".//unitdate").remove obj.title = format_content( title.to_xml(:encoding => 'utf-8') ) end end end with 'unitdate' do |node| next ignore if @ignore norm_dates = (att('normal') || "").sub(/^\s/, '').sub(/\s$/, '').split('/') if norm_dates.length == 1 norm_dates[1] = norm_dates[0] end norm_dates.map! {|d| d =~ /^([0-9]{4}(\-(1[0-2]|0[1-9])(\-(0[1-9]|[12][0-9]|3[01]))?)?)$/ ? d : nil} make :date, { :date_type => att('type') || 'inclusive', :expression => inner_xml, :label => 'creation', :begin => norm_dates[0], :end => norm_dates[1], :calendar => att('calendar'), :era => att('era'), :certainty => att('certainty') } do |date| set ancestor(:resource, :archival_object), :dates, date end end with 'dimensions' do |node| next ignore if @ignore unless context == :note_orderedlist content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end %w(accessrestrict accessrestrict/legalstatus \ accruals acqinfo altformavail appraisal arrangement \ bioghist custodhist \ fileplan odd otherfindaid originalsloc phystech \ prefercite processinfo relatedmaterial scopecontent \ separatedmaterial userestrict ).each do |note| with note do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end # START RIGHTS STATEMENTS # The stock ASpace EAD importer only makes "Conditions Governing Access" notes out of <accessrestrict> tags # We want to also import our <accessrestrict> tags that have a restriction end date as a "Rights Statements" # Let ArchivesSpace do its normal thing with accessrestrict %w(accessrestrict accessrestrict/legalstatus \ accruals acqinfo altformavail appraisal arrangement \ bioghist custodhist dimensions \ fileplan odd otherfindaid originalsloc phystech \ prefercite processinfo relatedmaterial scopecontent \ separatedmaterial userestrict ).each do |note| with note do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end # Now make a Rights Statement using the content from the "Conditions Governing Access" note # and the restriction end date from the accessrestrict/date with 'accessrestrict/date' do ancestor(:archival_object) do |ao| ao.notes.each do |n| if n['type'] == 'accessrestrict' n['subnotes'].each do |sn| make :rights_statement, { :rights_type => 'institutional_policy', :restrictions => sn['content'], :restriction_end_date => att('normal') } do |rights| set ancestor(:resource, :archival_object), :rights_statements, rights end end end end end end =end end slightly better sublist/subitem replacement class BHLEADConverter < EADConverter def self.import_types(show_hidden = false) [ { :name => "bhl_ead_xml", :description => "Import BHL EAD records from an XML file" } ] end def self.instance_for(type, input_file) if type == "bhl_ead_xml" self.new(input_file) else nil end end def self.profile "Convert EAD To ArchivesSpace JSONModel records" end def format_content(content) super.gsub(/[, ]+$/,"") # Remove trailing commas and spaces end def self.configure super # BEGIN UNITID CUSTOMIZATIONS # Let's take those brackets off of unitids and just add them in the exporter with 'unitid' do |node| ancestor(:note_multipart, :resource, :archival_object) do |obj| case obj.class.record_type when 'resource' # inner_xml.split(/[\/_\-\.\s]/).each_with_index do |id, i| # set receiver, "id_#{i}".to_sym, id # end set obj, :id_0, inner_xml when 'archival_object' set obj, :component_id, inner_xml.gsub("[","").gsub("]","").strip end end end # BEGIN TITLEPROPER AND AUTHOR CUSTOMIZATIONS # The stock ArchivesSpace converter sets the author and titleproper elements each time it finds a titleproper or author elements # This means that it first creates the elements using titlestmt/author and titlestmt/titleproper, and then overwrites the values when it reaches titlepage # We want to use the titlepage statements. Changing this to be more explicit about using the statement that we want, and to remove some unwanted linebreaks. # The EAD importer ignores titlepage; we need to unignore it with "titlepage" do @ignore = false end with 'titlepage/titleproper' do type = att('type') title_statement = inner_xml.gsub("<lb/>"," <lb/>") case type when 'filing' set :finding_aid_filing_title, title_statement.gsub("<lb/>","").gsub(/<date(.*?)<\/date>/,"").gsub(/\s+/," ").strip else set :finding_aid_title, title_statement.gsub("<lb/>","").gsub(/<date(.*?)<\/date>/,"").gsub(/\s+/," ").strip end end with 'titlepage/author' do author_statement = inner_xml.gsub("<lb/>"," <lb/>") set :finding_aid_author, author_statement.gsub("<lb/>","").gsub(/\s+/," ").strip end # Skip the titleproper and author statements from titlestmt with 'titlestmt/titleproper' do next end with 'titlestmt/author' do next end # Skip these to override the default ArchiveSpace functionality, which searches for a titleproper or an author anywhere with 'titleproper' do next end with 'author' do next end # END TITLEPROPER CUSTOMIZATIONS # BEGIN CLASSIFICATION CUSTOMIZATIONS # In our EADs, the most consistent way that MHC and UARP finding aids are identified is via the titlepage/publisher # In ArchivesSpace, we will be using Classifications to distinguish between the two # This modification will link the resource being created to the appropriate Classification in ArchivesSpace with 'classification' do set :classifications, {'ref' => att('ref')} end # END CLASSIFICATION CUSTOMIZATIONS # BEGIN CHRONLIST CUSTOMIZATIONS # For some reason the stock importer doesn't separate <chronlist>s out of notes like it does with <list>s # Like, it includes the mixed content <chronlist> within the note text and also makes a chronological list, duplicating the content # The addition of (split_tag = 'chronlist') to the insert_into_subnotes method call here fixes that with 'chronlist' do if ancestor(:note_multipart) left_overs = insert_into_subnotes(split_tag = 'chronlist') else left_overs = nil make :note_multipart, { :type => node.name, :persistent_id => att('id'), } do |note| set ancestor(:resource, :archival_object), :notes, note end end make :note_chronology do |note| set ancestor(:note_multipart), :subnotes, note end # and finally put the leftovers back in the list of subnotes... if ( !left_overs.nil? && left_overs["content"] && left_overs["content"].length > 0 ) set ancestor(:note_multipart), :subnotes, left_overs end end # END CHRONLIST CUSTOMIZATIONS # BEGIN BIBLIOGRAPHY CUSTOMIZATIONS # Our bibliographies are really more like general notes with paragraphs, lists, etc. We don't have any bibliographies # that are simply a collection of <bibref>s, and all of the bibliographies that do have <bibref>s have them inserted into # items in lists. This change will import bibliographies as a general note, which is really more appropriate given their content with 'bibliography' do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => 'odd', :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end %w(bibliography index).each do |x| next if x == 'bibliography' with "index/head" do |node| set :label, format_content( inner_xml ) end with "index/p" do set :content, format_content( inner_xml ) end end with 'bibliography/bibref' do next end with 'bibliography/p' do next end with 'bibliography/head' do next end # END BIBLIOGRAPHY CUSTOMIZATIONS # BEGIN BLOCKQUOTE P TAG FIX # The ArchivesSpace EAD importer replaces all <p> tags with double line breaks # This leads to too many line breaks surrounding closing block quote tags # On export, this invalidates the EAD # The following code is really hacky workaround to reinsert <p> tags within <blockquote>s # Note: We only have blockquotes in bioghists and scopecontents, so call modified_format_content on just this block is sufficient # This function calls the regular format_content function, and then does a few other things, like preserving blockquote p tags and removing opening and closing parens from some notes, before returning the content def modified_format_content(content, note) content = format_content(content) # Remove parentheses from single-paragraph odds blocks = content.split("\n\n") if blocks.length == 1 case note when 'odd','abstract','accessrestrict','daodesc' if content =~ /^\((.*?)\)$/ content = $1 elsif content =~ /^\[(.*?)\]$/ content = $1 end end end content.gsub(/<blockquote>\s*?/,"<blockquote><p>").gsub(/\s*?<\/blockquote>/,"</p></blockquote>") end %w(accessrestrict accessrestrict/legalstatus \ accruals acqinfo altformavail appraisal arrangement \ bioghist custodhist dimensions \ fileplan odd otherfindaid originalsloc phystech \ prefercite processinfo relatedmaterial scopecontent \ separatedmaterial userestrict ).each do |note| with note do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :publish => true, :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => modified_format_content( content, note ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end # END BLOCKQUOTE P TAG FIX # BEGIN CONDITIONAL SKIPS # We have lists and indexes with all sorts of crazy things, like <container>, <physdesc>, <physloc>, etc. tags within <item> or <ref> tags # So, we need to tell the importer to skip those things only when they appear in places where they shouldn't, otherwise do # it's normal thing # REMINDER: If using the container management plugin, add the line 'next if context == :note_orderedlist' to "with 'container' do" in # the converter_extra_container_values mixin %w(abstract langmaterial materialspec physloc).each do |note| next if note == "langmaterial" with note do |node| next if context == :note_orderedlist # skip these next if context == :items # these too content = inner_xml next if content =~ /\A<language langcode=\"[a-z]+\"\/>\Z/ if content.match(/\A<language langcode=\"[a-z]+\"\s*>([^<]+)<\/language>\Z/) content = $1 end make :note_singlepart, { :type => note, :persistent_id => att('id'), :publish => true, :content => modified_format_content( content.sub(/<head>.*?<\/head>/, ''), note ) } do |note| set ancestor(:resource, :archival_object), :notes, note end end end with 'list' do next if ancestor(:note_index) if ancestor(:note_multipart) left_overs = insert_into_subnotes else left_overs = nil make :note_multipart, { :type => 'odd', :persistent_id => att('id'), :publish => true, } do |note| set ancestor(:resource, :archival_object), :notes, note end end # now let's make the subnote list type = att('type') if type == 'deflist' || (type.nil? && inner_xml.match(/<deflist>/)) make :note_definedlist do |note| set ancestor(:note_multipart), :subnotes, note end else make :note_orderedlist, { :enumeration => att('numeration') } do |note| set ancestor(:note_multipart), :subnotes, note end end # and finally put the leftovers back in the list of subnotes... if ( !left_overs.nil? && left_overs["content"] && left_overs["content"].length > 0 ) set ancestor(:note_multipart), :subnotes, left_overs end end with 'list/item' do # Okay this is another one of those hacky things that work # The problem: we have many items nested within items, like <list><item>First item <list><item>Subitem</item></list></item></list> # This would make one item like: # First item <list><item>Subitem</item></list> # And another like: # Subitem # ArchivesSpace lists are flat and do not allow for nesting lists within lists within items within lists within.. (you get the idea)... # Now, it would be nice to have a better way to tell the importer to only account for subitems one time, but there doesn't seem to be # With this modification we can change nested lists to <sublist> and nested items to <subitem> before migration # That way, the importer will ignore those sublists and subitems and sub out those tags for the correct tags set :items, inner_xml.gsub("<sublist","<list").gsub("<subitem","<item") if context == :note_orderedlist end # END CONDITIONAL SKIPS # BEGIN CONTAINER MODIFICATIONS # Skip containers that appear in lists # Don't downcase the instance_label # Import att('type') as the container type for top containers, att('label') as the container type for subcontainers # example of a 1:many tag:record relation (1+ <container> => 1 instance with 1 container) with 'container' do next if context == :note_orderedlist @containers ||= {} # we've found that the container has a parent att and the parent is in # our queue if att("parent") && @containers[att('parent')] cont = @containers[att('parent')] else # there is not a parent. if there is an id, let's check if there's an # instance before we proceed inst = context == :instance ? context_obj : context_obj.instances.last # if there are no instances, we need to make a new one. # or, if there is an @id ( but no @parent) we can assume its a new # top level container that will be referenced later, so we need to # make a new instance if ( inst.nil? or att('id') ) instance_label = att("label") ? att("label") : 'mixed_materials' if instance_label =~ /(.*)\s\[([0-9]+)\]$/ instance_label = $1 barcode = $2 end make :instance, { :instance_type => instance_label } do |instance| set ancestor(:resource, :archival_object), :instances, instance end inst = context_obj end # now let's check out instance to see if there's a container... if inst.container.nil? make :container do |cont| set inst, :container, cont end end # and now finally we get the container. cont = inst.container || context_obj cont['barcode_1'] = barcode if barcode cont['container_profile_key'] = att("altrender") end # now we fill it in (1..3).to_a.each do |i| next unless cont["type_#{i}"].nil? if i == 1 cont["type_#{i}"] = att('type') elsif i == 2 or i == 3 cont["type_#{i}"] = att('label') end cont["indicator_#{i}"] = format_content( inner_xml ) break end #store it here incase we find it has a parent @containers[att("id")] = cont if att("id") end # END CONTAINER MODIFICATIONS # BEGIN CUSTOM SUBJECT AND AGENT IMPORTS # We'll be importing most of our subjects and agents separately and linking directly to the URI from our finding # aids and accession records. # This will check our subject, geogname, genreform, corpname, famname, and persname elements in our EADs for a ref attribute # If a ref attribute is present, it will use that to link the agent to the resource. # If there is no ref attribute, it will make a new agent as usual. # We also have compound agents (agents with both a persname, corpname or famname and subdivided subject terms) # In ArchivesSpace, this kind of agent can be represented in a resource by linking to the agent and adding terms/subdivisions # within the resource. We will be accomplishing this by invalidating our EAD at some point (gasp!) to add <term> tags # around the individual terms in a corpname, persname, or famname. This modification will also make sure that those terms # get imported properly. { 'function' => 'function', 'genreform' => 'genre_form', 'geogname' => 'geographic', 'occupation' => 'occupation', 'subject' => 'topical', 'title' => 'uniform_title' # added title since we have some <title> tags in our controlaccesses }.each do |tag, type| with "controlaccess/#{tag}" do if att('ref') set ancestor(:resource, :archival_object), :subjects, {'ref' => att('ref')} else make :subject, { :terms => {'term' => inner_xml, 'term_type' => type, 'vocabulary' => '/vocabularies/1'}, :vocabulary => '/vocabularies/1', :source => att('source') || 'ingest' } do |subject| set ancestor(:resource, :archival_object), :subjects, {'ref' => subject.uri} end end end end with 'origination/corpname' do if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'creator'} else make_corp_template(:role => 'creator') end end with 'controlaccess/corpname' do corpname = Nokogiri::XML::DocumentFragment.parse(inner_xml) terms ||= [] corpname.children.each do |child| if child.respond_to?(:name) && child.name == 'term' term = child.content.strip term_type = child['type'] terms << {'term' => term, 'term_type' => term_type, 'vocabulary' => '/vocabularies/1'} end end relator = nil if att('encodinganalog') == '710' relator = 'ctb' end if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'subject', 'terms' => terms, 'relator' => relator} else make_corp_template(:role => 'subject') end end with 'origination/famname' do if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'creator'} else make_family_template(:role => 'creator') end end with 'controlaccess/famname' do famname = Nokogiri::XML::DocumentFragment.parse(inner_xml) terms ||= [] famname.children.each do |child| if child.respond_to?(:name) && child.name == 'term' term = child.content.strip term_type = child['type'] terms << {'term' => term, 'term_type' => term_type, 'vocabulary' => '/vocabularies/1'} end end relator = nil if att('encodinganalog') == '700' relator = 'ctb' end if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'subject', 'terms' => terms, 'relator' => relator} else make_family_template(:role => 'subject') end end with 'origination/persname' do if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'creator'} else make_person_template(:role => 'creator') end end with 'controlaccess/persname' do persname = Nokogiri::XML::DocumentFragment.parse(inner_xml) terms ||= [] persname.children.each do |child| if child.respond_to?(:name) && child.name == 'term' term = child.content.strip term_type = child['type'] terms << {'term' => term, 'term_type' => term_type, 'vocabulary' => '/vocabularies/1'} end end relator = nil if att('encodinganalog') == '700' relator = 'ctb' end if att('ref') set ancestor(:resource, :archival_object), :linked_agents, {'ref' => att('ref'), 'role' => 'subject', 'terms' => terms, 'relator' => relator} else make_person_template(:role => 'subject') end end # END CUSTOM SUBJECT AND AGENT IMPORTS # BEGIN PHYSDESC CUSTOMIZATIONS # The stock EAD importer doesn't import <physfacet> and <dimensions> tags into extent objects; instead making them notes # This is a corrected version # first, some methods for generating note objects def make_single_note(note_name, tag, tag_name="") content = tag.inner_text if !tag_name.empty? content = tag_name + ": " + content end make :note_singlepart, { :type => note_name, :persistent_id => att('id'), :publish => true, :content => format_content( content.sub(/<head>.?<\/head>/, '').strip) } do |note| set ancestor(:resource, :archival_object), :notes, note end end def make_nested_note(note_name, tag) content = tag.inner_text make :note_multipart, { :type => note_name, :persistent_id => att('id'), :publish => true, :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end with 'physdesc' do next if context == :note_orderedlist # skip these physdesc = Nokogiri::XML::DocumentFragment.parse(inner_xml) extent_number_and_type = nil dimensions = [] physfacets = [] container_summaries = [] other_extent_data = [] container_summary_texts = [] dimensions_texts = [] physfacet_texts = [] # If there is already a portion specified, use it portion = att('altrender') || 'whole' physdesc.children.each do |child| # "extent" can have one of two kinds of semantic meanings: either a true extent with number and type, # or a container summary. Disambiguation is done through a regex. if child.name == 'extent' child_content = child.content.strip if extent_number_and_type.nil? && child_content =~ /^([0-9\.]+)+\s+(.*)$/ extent_number_and_type = {:number => $1, :extent_type => $2} else container_summaries << child container_summary_texts << child.content.strip end elsif child.name == 'physfacet' physfacets << child physfacet_texts << child.content.strip elsif child.name == 'dimensions' dimensions << child dimensions_texts << child.content.strip elsif child.name != 'text' other_extent_data << child end end # only make an extent if we got a number and type, otherwise put all physdesc contents into a note if extent_number_and_type make :extent, { :number => $1, :extent_type => $2, :portion => portion, :container_summary => container_summary_texts.join('; '), :physical_details => physfacet_texts.join('; '), :dimensions => dimensions_texts.join('; ') } do |extent| set ancestor(:resource, :archival_object), :extents, extent end # there's no true extent; split up the rest into individual notes else container_summaries.each do |summary| make_single_note("physdesc", summary) end physfacets.each do |physfacet| make_single_note("physfacet", physfacet) end # dimensions.each do |dimension| make_nested_note("dimensions", dimension) end end other_extent_data.each do |unknown_tag| make_single_note("physdesc", unknown_tag, unknown_tag.name) end end # overwriting the default dimensions and physfacet functionality with "dimensions" do next end with "physfacet" do next end # END PHYSDESC CUSTOMIZATIONS # BEGIN LANGUAGE CUSTOMIZATIONS # By default, ASpace just uses the last <language> tag it finds as the primary # language of the material described. This results in incorrect finding-aid languages for many eads. # for example, ead with the following <langmaterial> tag: ## <langmaterial> ## The material is mostly in <language langcode="eng" encodinganalog="041">English</language>; ## some correspondence is in <language langcode="arm" encodinganalog="041">Armenian;</language>; ## select items are in <language langcode="ger" encodinganalog="041">German</language>. ## </langmaterial> # will result in a primary material language of German. # these changes fix that with "langmaterial" do # first, assign the primary language to the ead langmaterial = Nokogiri::XML::DocumentFragment.parse(inner_xml) langmaterial.children.each do |child| if child.name == 'language' set ancestor(:resource, :archival_object), :language, child.attr("langcode") break end end # write full tag content to a note, subbing out the language tags content = inner_xml next if content =~ /\A<language langcode=\"[a-z]+\"\/>\Z/ if content.match(/\A<language langcode=\"[a-z]+\"\s*>([^<]+)<\/language>\Z/) content = $1 end make :note_singlepart, { :type => "langmaterial", :persistent_id => att('id'), :publish => true, :content => format_content( content.sub(/<head>.*?<\/head>/, '') ) } do |note| set ancestor(:resource, :archival_object), :notes, note end end # overwrite the default langusage tag behavior with "language" do next end # END LANGUAGE CUSTOMIZATIONS # BEGIN INDEX CUSTOMIZATIONS # The stock EAD converter creates separate index items for each indexentry, # one for the value (persname, famname, etc) and one for the reference (ref), # even when they are within the same indexentry and are related # (i.e., the persname is a correspondent, the ref is a date or a location at which # correspondence with that person can be found). # The Bentley's <indexentry>s generally look something like: # # <indexentry><persname>Some person</persname><ref>Some date or folder</ref></indexentry> # # As the <persname> and the <ref> are associated with one another, # we want to keep them together in the same index item in ArchiveSpace. # This will treat each <indexentry> as one item, # creating an index item with a 'value' from the <persname>, <famname>, etc. # and a 'reference_text' from the <ref>. with 'indexentry' do entry_type = '' entry_value = '' entry_reference = '' indexentry = Nokogiri::XML::DocumentFragment.parse(inner_xml) indexentry.children.each do |child| case child.name when 'name' entry_value << child.content entry_type << 'name' when 'persname' entry_value << child.content entry_type << 'person' when 'famname' entry_value << child.content entry_type << 'family' when 'corpname' entry_value << child.content entry_type << 'corporate_entity' when 'subject' entry_value << child.content entry_type << 'subject' when 'function' entry_value << child.content entry_type << 'function' when 'occupation' entry_value << child.content entry_type << 'occupation' when 'genreform' entry_value << child.content entry_type << 'genre_form' when 'title' entry_value << child.content entry_type << 'title' when 'geogname' entry_value << child.content entry_type << 'geographic_name' end if child.name == 'ref' entry_reference << child.content end end make :note_index_item, { :type => entry_type, :value => entry_value, :reference_text => entry_reference } do |item| set ancestor(:note_index), :items, item end end # Skip the stock importer actions to avoid confusion/duplication { 'name' => 'name', 'persname' => 'person', 'famname' => 'family', 'corpname' => 'corporate_entity', 'subject' => 'subject', 'function' => 'function', 'occupation' => 'occupation', 'genreform' => 'genre_form', 'title' => 'title', 'geogname' => 'geographic_name' }.each do |k, v| with "indexentry/#{k}" do |node| next end end with 'indexentry/ref' do next end # END INDEX CUSTOMIZATIONS # BEGIN HEAD CUSTOMIZATIONS # This issue is similar to the language issue -- if there is a note with multiple <head> elements (say, a bioghist with its own head and sublists with their own heads), # the stock importer action is to set the note label to the very last <head> it finds. This modification will only set the label if it does not already exist, ensuring # that it will only be set once. with 'head' do if context == :note_multipart ancestor(:note_multipart) do |note| next unless note["label"].nil? set :label, format_content( inner_xml ) end elsif context == :note_chronology ancestor(:note_chronology) do |note| next unless note["title"].nil? set :title, format_content( inner_xml ) end end end # END HEAD CUSTOMIZATIONS # BEGIN DAO TITLE CUSTOMIZATIONS # The Bentley has many EADs with <dao> tags that lack title attributes. # The stock ArchivesSpace EAD Converter uses each <dao>'s title attribute as # the value for the imported digital object's title, which is a required property. # As a result, all of our EADs with <dao> tags fail when trying to import into ArchivesSpace. # This section of the BHL EAD Converter plugin modifies the stock ArchivesSpace EAD Converter # by forming a string containing the digital object's parent archival object's title and date (if both exist), # or just its title (if only the title exists), or just it's date (if only the date exists) # and then using that string as the imported digital object's title. with 'dao' do if att('ref') # A digital object has already been made make :instance, { :instance_type => 'digital_object', :digital_object => {'ref' => att('ref')} } do |instance| set ancestor(:resource, :archival_object), :instances, instance end else # Make a digital object make :instance, { :instance_type => 'digital_object' } do |instance| set ancestor(:resource, :archival_object), :instances, instance end # We'll use either the <dao> title attribute (if it exists) or our display_string (if the title attribute does not exist) # This forms a title string using the parent archival object's title, if it exists daotitle = nil ancestor(:archival_object ) do |ao| if ao.title && ao.title.length > 0 daotitle = ao.title end end # This forms a date string using the parent archival object's date expression, # or its begin date - end date, or just it's begin date, if any exist # (Actually, we have expressions for all of our dates...let's just use those for the sake of simplicity) daodates = [] ancestor(:archival_object) do |aod| if aod.dates && aod.dates.length > 0 aod.dates.each do |dl| if dl['expression'].length > 0 daodates << dl['expression'] end end end end title = daotitle date_label = daodates.join(', ') if daodates.length > 0 # This forms a display string using the parent archival object's title and date (if both exist), # or just its title or date (if only one exists) display_string = title || '' display_string += ', ' if title && date_label display_string += date_label if date_label make :digital_object, { :digital_object_id => SecureRandom.uuid, :title => att('title') || display_string, } do |obj| obj.file_versions << { :use_statement => att('role'), :file_uri => att('href'), :xlink_actuate_attribute => att('actuate'), :xlink_show_attribute => att('show') } set ancestor(:instance), :digital_object, obj end end end end with 'daodesc' do ancestor(:digital_object) do |dobj| next if dobj.ref end make :note_digital_object, { :type => 'note', :persistent_id => att('id'), :content => modified_format_content(inner_xml.strip,'daodesc') } do |note| set ancestor(:digital_object), :notes, note end end # END DAO TITLE CUSTOMIZATIONS =begin # Note: The following bits are here for historical reasons # We have either decided against implementing the functionality OR the ArchivesSpace importer has changed, deprecating the following customizations # START IGNORE # Setting some of these to ignore because we have some physdesc, container, etc. # Within list/items in our descgrps at the end of finding aids. # Without setting these to ignore, ASpace both makes the list AND makes separate # notes for physdesc, dimension, etc. and tries to make instances out of the # containers, causing import errors. # Note: if using this in conjunction with the Yale container management plugin, # be sure to include the line 'next ignore if @ignore' within the with container do # section of the ConverterExtraContainerValues module. with 'archref/container' do @ignore = true end with 'archref/physdesc/dimensions' do @ignore = true end with 'archref/unittitle' do @ignore = true end with 'archref/unittitle/unitdate' do @ignore = true end with 'archref/note' do @ignore = true end with 'archref/note/p/unitdate' do @ignore = true end with 'archref/note/p/geogname' do @ignore = true end with 'unittitle' do |node| ancestor(:note_multipart, :resource, :archival_object) do |obj| unless obj.class.record_type == "note_multipart" or context == "note_orderedlist" title = Nokogiri::XML::DocumentFragment.parse(inner_xml.strip) title.xpath(".//unitdate").remove obj.title = format_content( title.to_xml(:encoding => 'utf-8') ) end end end with 'unitdate' do |node| next ignore if @ignore norm_dates = (att('normal') || "").sub(/^\s/, '').sub(/\s$/, '').split('/') if norm_dates.length == 1 norm_dates[1] = norm_dates[0] end norm_dates.map! {|d| d =~ /^([0-9]{4}(\-(1[0-2]|0[1-9])(\-(0[1-9]|[12][0-9]|3[01]))?)?)$/ ? d : nil} make :date, { :date_type => att('type') || 'inclusive', :expression => inner_xml, :label => 'creation', :begin => norm_dates[0], :end => norm_dates[1], :calendar => att('calendar'), :era => att('era'), :certainty => att('certainty') } do |date| set ancestor(:resource, :archival_object), :dates, date end end with 'dimensions' do |node| next ignore if @ignore unless context == :note_orderedlist content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end %w(accessrestrict accessrestrict/legalstatus \ accruals acqinfo altformavail appraisal arrangement \ bioghist custodhist \ fileplan odd otherfindaid originalsloc phystech \ prefercite processinfo relatedmaterial scopecontent \ separatedmaterial userestrict ).each do |note| with note do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end # START RIGHTS STATEMENTS # The stock ASpace EAD importer only makes "Conditions Governing Access" notes out of <accessrestrict> tags # We want to also import our <accessrestrict> tags that have a restriction end date as a "Rights Statements" # Let ArchivesSpace do its normal thing with accessrestrict %w(accessrestrict accessrestrict/legalstatus \ accruals acqinfo altformavail appraisal arrangement \ bioghist custodhist dimensions \ fileplan odd otherfindaid originalsloc phystech \ prefercite processinfo relatedmaterial scopecontent \ separatedmaterial userestrict ).each do |note| with note do |node| content = inner_xml.tap {|xml| xml.sub!(/<head>.*?<\/head>/m, '') # xml.sub!(/<list [^>]*>.*?<\/list>/m, '') # xml.sub!(/<chronlist [^>]*>.*<\/chronlist>/m, '') } make :note_multipart, { :type => node.name, :persistent_id => att('id'), :subnotes => { 'jsonmodel_type' => 'note_text', 'content' => format_content( content ) } } do |note| set ancestor(:resource, :archival_object), :notes, note end end end # Now make a Rights Statement using the content from the "Conditions Governing Access" note # and the restriction end date from the accessrestrict/date with 'accessrestrict/date' do ancestor(:archival_object) do |ao| ao.notes.each do |n| if n['type'] == 'accessrestrict' n['subnotes'].each do |sn| make :rights_statement, { :rights_type => 'institutional_policy', :restrictions => sn['content'], :restriction_end_date => att('normal') } do |rights| set ancestor(:resource, :archival_object), :rights_statements, rights end end end end end end =end end
class Kibana43 < Formula desc "Analytics and search dashboard for Elasticsearch" homepage "https://www.elastic.co/products/kibana" url "https://github.com/elastic/kibana.git", :tag => "v4.3.2", :revision => "85c0f729b12f6a6efe2003cbcc28aa1c271f9595" head "https://github.com/elastic/kibana.git" bottle do sha256 "ee6bc72327bb31e78f4c32480d27dc73140bce8a1f3a36c725ffba1710c6a320" => :el_capitan sha256 "c77b20408bda87a9d01da47341433872ee42cbd2953406953874fcee0d9bc90d" => :yosemite sha256 "d9f0cc1bc56f92cc96e245a78e21d942c973878f76f7977db6ef622519e1b767" => :mavericks end conflicts_with "kibana", :because => "Different versions of same formula" resource "node" do url "https://nodejs.org/dist/v0.12.10/node-v0.12.10.tar.gz" sha256 "edbd3710512ec7518a3de4cabf9bfee6d12f278eef2e4b53422c7b063f6b976d" end def install resource("node").stage buildpath/"node" cd buildpath/"node" do system "./configure", "--prefix=#{libexec}/node" system "make", "install" end # do not download binary installs of Node.js inreplace buildpath/"tasks/build/index.js", /('_build:downloadNodeBuilds:\w+',)/, "// \\1" # do not build packages for other platforms platforms = Set.new(["darwin-x64", "linux-x64", "linux-x86", "windows"]) if OS.mac? && Hardware::CPU.is_64_bit? platform = "darwin-x64" elsif OS.linux? platform = Hardware::CPU.is_64_bit? ? "linux-x64" : "linux-x86" else raise "Installing Kibana via Homebrew is only supported on Darwin x86_64, Linux i386, Linux i686, and Linux x86_64" end platforms.delete(platform) sub = platforms.to_a.join("|") inreplace buildpath/"tasks/config/platforms.js", /('(#{sub})',?(?!;))/, "// \\1" # do not build zip package inreplace buildpath/"tasks/build/archives.js", /(await exec\('zip'.*)/, "// \\1" ENV.prepend_path "PATH", prefix/"libexec/node/bin" system "npm", "install" system "npm", "run", "build" mkdir "tar" do system "tar", "--strip-components", "1", "-xf", Dir[buildpath/"target/kibana-*-#{platform}.tar.gz"].first rm_f Dir["bin/*.bat"] prefix.install "bin", "config", "node_modules", "optimize", "package.json", "src", "webpackShims" end inreplace "#{bin}/kibana", %r{/node/bin/node}, "/libexec/node/bin/node" cd prefix do inreplace "config/kibana.yml", %r{/var/run/kibana.pid}, var/"run/kibana.pid" (etc/"kibana").install Dir["config/*"] rm_rf "config" end end def post_install ln_s etc/"kibana", prefix/"config" (prefix/"installedPlugins").mkdir end plist_options :manual => "kibana" def caveats; <<-EOS.undent Config: #{etc}/kibana/ If you wish to preserve your plugins upon upgrade, make a copy of #{prefix}/installedPlugins before upgrading, and copy it into the new keg location after upgrading. EOS end def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>Program</key> <string>#{opt_bin}/kibana</string> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do ENV["BABEL_CACHE_PATH"] = testpath/".babelcache.json" assert_match /#{version}/, shell_output("#{bin}/kibana -V") end end kibana43: update 4.3.2 bottle. class Kibana43 < Formula desc "Analytics and search dashboard for Elasticsearch" homepage "https://www.elastic.co/products/kibana" url "https://github.com/elastic/kibana.git", :tag => "v4.3.2", :revision => "85c0f729b12f6a6efe2003cbcc28aa1c271f9595" head "https://github.com/elastic/kibana.git" bottle do sha256 "22e38975b7f61f50d49ed4b2571642829d11d8eca6ad1bd75d120f72eabd8cc2" => :el_capitan sha256 "b622c74c9dca43cd46ed36794e4c10d059e88f1c034f0df990b4e2339acfbc69" => :yosemite sha256 "d64c784ca2cd4cdc5cf31da49e7e49217ddf160c02afa6162b07e4d2d3d6bea2" => :mavericks end conflicts_with "kibana", :because => "Different versions of same formula" resource "node" do url "https://nodejs.org/dist/v0.12.10/node-v0.12.10.tar.gz" sha256 "edbd3710512ec7518a3de4cabf9bfee6d12f278eef2e4b53422c7b063f6b976d" end def install resource("node").stage buildpath/"node" cd buildpath/"node" do system "./configure", "--prefix=#{libexec}/node" system "make", "install" end # do not download binary installs of Node.js inreplace buildpath/"tasks/build/index.js", /('_build:downloadNodeBuilds:\w+',)/, "// \\1" # do not build packages for other platforms platforms = Set.new(["darwin-x64", "linux-x64", "linux-x86", "windows"]) if OS.mac? && Hardware::CPU.is_64_bit? platform = "darwin-x64" elsif OS.linux? platform = Hardware::CPU.is_64_bit? ? "linux-x64" : "linux-x86" else raise "Installing Kibana via Homebrew is only supported on Darwin x86_64, Linux i386, Linux i686, and Linux x86_64" end platforms.delete(platform) sub = platforms.to_a.join("|") inreplace buildpath/"tasks/config/platforms.js", /('(#{sub})',?(?!;))/, "// \\1" # do not build zip package inreplace buildpath/"tasks/build/archives.js", /(await exec\('zip'.*)/, "// \\1" ENV.prepend_path "PATH", prefix/"libexec/node/bin" system "npm", "install" system "npm", "run", "build" mkdir "tar" do system "tar", "--strip-components", "1", "-xf", Dir[buildpath/"target/kibana-*-#{platform}.tar.gz"].first rm_f Dir["bin/*.bat"] prefix.install "bin", "config", "node_modules", "optimize", "package.json", "src", "webpackShims" end inreplace "#{bin}/kibana", %r{/node/bin/node}, "/libexec/node/bin/node" cd prefix do inreplace "config/kibana.yml", %r{/var/run/kibana.pid}, var/"run/kibana.pid" (etc/"kibana").install Dir["config/*"] rm_rf "config" end end def post_install ln_s etc/"kibana", prefix/"config" (prefix/"installedPlugins").mkdir end plist_options :manual => "kibana" def caveats; <<-EOS.undent Config: #{etc}/kibana/ If you wish to preserve your plugins upon upgrade, make a copy of #{prefix}/installedPlugins before upgrading, and copy it into the new keg location after upgrading. EOS end def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>Program</key> <string>#{opt_bin}/kibana</string> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do ENV["BABEL_CACHE_PATH"] = testpath/".babelcache.json" assert_match /#{version}/, shell_output("#{bin}/kibana -V") end end
# Generated by jeweler # DO NOT EDIT THIS FILE # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec` # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{kin} s.version = "0.4.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Anthony Williams"] s.date = %q{2009-09-09} s.description = %q{Components commonly used in Showcase which can be applied to other projects.} s.email = %q{anthony@ninecraft.com} s.extra_rdoc_files = [ "CHANGELOG", "LICENSE" ] s.files = [ "CHANGELOG", "LICENSE", "Rakefile", "VERSION.yml", "lib/kin.rb", "lib/kin/assets/javascripts/kin.js", "lib/kin/assets/stylesheets/_forms.sass", "lib/kin/assets/stylesheets/_modal.sass", "lib/kin/configurable.rb", "lib/kin/core_ext/date.rb", "lib/kin/core_ext/string.rb", "lib/kin/core_ext/time.rb", "lib/kin/form_builder.rb", "lib/kin/masthead.rb", "lib/kin/nav.rb", "lib/kin/nav/builder.rb", "lib/kin/nav/formatters.rb", "lib/kin/nav/helper_mixin.rb", "lib/kin/sprites.rb", "lib/kin/sprites/image_generator.rb", "lib/kin/sprites/rake_runner.rb", "lib/kin/sprites/sass_generator.rb", "lib/kin/tasks/sprites.rb", "lib/kin/tasks/sync_assets.rb", "spec/configurable_spec.rb", "spec/core_ext/date_spec.rb", "spec/core_ext/string_spec.rb", "spec/core_ext/time_spec.rb", "spec/fixture/app/controllers/application.rb", "spec/fixture/app/controllers/exceptions.rb", "spec/fixture/app/controllers/form_builder_specs.rb", "spec/fixture/app/controllers/masthead_specs.rb", "spec/fixture/app/controllers/nav_specs.rb", "spec/fixture/app/controllers/spec_controller.rb", "spec/fixture/app/helpers/global_helpers.rb", "spec/fixture/app/models/fake_model.rb", "spec/fixture/app/views/exceptions/not_acceptable.html.erb", "spec/fixture/app/views/exceptions/not_found.html.erb", "spec/fixture/app/views/form_builder_specs/bound_date_field.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_with_error.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_with_value.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_with_error.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_with_value.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_with_error.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_with_value.html.haml", "spec/fixture/app/views/form_builder_specs/date_field.html.haml", "spec/fixture/app/views/form_builder_specs/date_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_classes.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_date_value.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_datetime_value.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_time_value.html.haml", "spec/fixture/app/views/form_builder_specs/label.html.haml", "spec/fixture/app/views/form_builder_specs/label_with_note.html.haml", "spec/fixture/app/views/form_builder_specs/label_with_note_in_parens.html.haml", "spec/fixture/app/views/form_builder_specs/label_with_requirement.html.haml", "spec/fixture/app/views/form_builder_specs/time_field.html.haml", "spec/fixture/app/views/form_builder_specs/time_field_with_label.html.haml", "spec/fixture/app/views/layout/application.html.erb", "spec/fixture/app/views/layout/masthead.html.haml", "spec/fixture/app/views/masthead_specs/all.html.haml", "spec/fixture/app/views/masthead_specs/border.html.haml", "spec/fixture/app/views/masthead_specs/escaping.html.haml", "spec/fixture/app/views/masthead_specs/no_extras.html.haml", "spec/fixture/app/views/masthead_specs/no_subtitles.html.haml", "spec/fixture/app/views/masthead_specs/right_subtitle.html.haml", "spec/fixture/app/views/masthead_specs/right_title.html.haml", "spec/fixture/app/views/masthead_specs/subtitle.html.haml", "spec/fixture/app/views/masthead_specs/with_css_classes.html.haml", "spec/fixture/app/views/masthead_specs/with_links.html.haml", "spec/fixture/app/views/masthead_specs/with_no_escape.html.haml", "spec/fixture/app/views/nav_specs/_guarded.html.haml", "spec/fixture/app/views/nav_specs/active.html.haml", "spec/fixture/app/views/nav_specs/content_injection.html.haml", "spec/fixture/app/views/nav_specs/escaped_content_injection.html.haml", "spec/fixture/app/views/nav_specs/generic_nav.html.haml", "spec/fixture/app/views/nav_specs/guard_with_all_params.html.haml", "spec/fixture/app/views/nav_specs/guard_with_single_param.html.haml", "spec/fixture/app/views/nav_specs/guard_without_param.html.haml", "spec/fixture/app/views/nav_specs/has_right_formatter.html.haml", "spec/fixture/app/views/nav_specs/item_with_title.html.haml", "spec/fixture/app/views/nav_specs/item_without_title.html.haml", "spec/fixture/app/views/nav_specs/multiple_injection.html.haml", "spec/fixture/app/views/nav_specs/resource_url.html.haml", "spec/fixture/app/views/nav_specs/resource_url_without_resource.html.haml", "spec/fixture/app/views/nav_specs/show_resource_url.html.haml", "spec/fixture/app/views/nav_specs/subnav_formatter.html.haml", "spec/fixture/app/views/nav_specs/with_custom_formatter.html.haml", "spec/fixture/config/environments/development.rb", "spec/fixture/config/environments/production.rb", "spec/fixture/config/environments/rake.rb", "spec/fixture/config/environments/staging.rb", "spec/fixture/config/environments/test.rb", "spec/fixture/config/init.rb", "spec/fixture/config/rack.rb", "spec/fixture/config/router.rb", "spec/fixture/config/sprites.different.yml", "spec/fixture/config/sprites.yml", "spec/fixture/public/images/merb.jpg", "spec/fixture/public/images/sprites/src/one.png", "spec/fixture/public/images/sprites/src/three.png", "spec/fixture/public/images/sprites/src/two.png", "spec/fixture/public/stylesheets/master.css", "spec/form_builder_spec.rb", "spec/masthead_spec.rb", "spec/nav_spec.rb", "spec/spec_helper.rb", "spec/sprites_spec.rb" ] s.has_rdoc = false s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.5} s.summary = %q{Components commonly used in Showcase which can be applied to other projects.} s.test_files = [ "spec/configurable_spec.rb", "spec/core_ext/date_spec.rb", "spec/core_ext/string_spec.rb", "spec/core_ext/time_spec.rb", "spec/fixture/app/controllers/application.rb", "spec/fixture/app/controllers/exceptions.rb", "spec/fixture/app/controllers/form_builder_specs.rb", "spec/fixture/app/controllers/masthead_specs.rb", "spec/fixture/app/controllers/nav_specs.rb", "spec/fixture/app/controllers/spec_controller.rb", "spec/fixture/app/helpers/global_helpers.rb", "spec/fixture/app/models/fake_model.rb", "spec/fixture/config/environments/development.rb", "spec/fixture/config/environments/production.rb", "spec/fixture/config/environments/rake.rb", "spec/fixture/config/environments/staging.rb", "spec/fixture/config/environments/test.rb", "spec/fixture/config/init.rb", "spec/fixture/config/rack.rb", "spec/fixture/config/router.rb", "spec/form_builder_spec.rb", "spec/masthead_spec.rb", "spec/nav_spec.rb", "spec/spec_helper.rb", "spec/sprites_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::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end Regenerated gemspec for version 0.4.1 # Generated by jeweler # DO NOT EDIT THIS FILE # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec` # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{kin} s.version = "0.4.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Anthony Williams"] s.date = %q{2009-11-22} s.description = %q{Components commonly used in Showcase which can be applied to other projects.} s.email = %q{anthony@ninecraft.com} s.extra_rdoc_files = [ "CHANGELOG", "LICENSE" ] s.files = [ "CHANGELOG", "LICENSE", "Rakefile", "VERSION.yml", "lib/kin.rb", "lib/kin/assets/javascripts/kin.js", "lib/kin/assets/stylesheets/_forms.sass", "lib/kin/assets/stylesheets/_modal.sass", "lib/kin/configurable.rb", "lib/kin/core_ext/date.rb", "lib/kin/core_ext/string.rb", "lib/kin/core_ext/time.rb", "lib/kin/form_builder.rb", "lib/kin/masthead.rb", "lib/kin/nav.rb", "lib/kin/nav/builder.rb", "lib/kin/nav/formatters.rb", "lib/kin/nav/helper_mixin.rb", "lib/kin/sprites.rb", "lib/kin/sprites/image_generator.rb", "lib/kin/sprites/rake_runner.rb", "lib/kin/sprites/sass_generator.rb", "lib/kin/tasks/sprites.rb", "lib/kin/tasks/sync_assets.rb", "spec/configurable_spec.rb", "spec/core_ext/date_spec.rb", "spec/core_ext/string_spec.rb", "spec/core_ext/time_spec.rb", "spec/fixture/app/controllers/application.rb", "spec/fixture/app/controllers/exceptions.rb", "spec/fixture/app/controllers/form_builder_specs.rb", "spec/fixture/app/controllers/masthead_specs.rb", "spec/fixture/app/controllers/nav_specs.rb", "spec/fixture/app/controllers/spec_controller.rb", "spec/fixture/app/helpers/global_helpers.rb", "spec/fixture/app/models/fake_model.rb", "spec/fixture/app/views/exceptions/not_acceptable.html.erb", "spec/fixture/app/views/exceptions/not_found.html.erb", "spec/fixture/app/views/form_builder_specs/bound_date_field.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_with_error.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/bound_date_field_with_value.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_with_error.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/bound_datetime_field_with_value.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_with_error.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/bound_time_field_with_value.html.haml", "spec/fixture/app/views/form_builder_specs/date_field.html.haml", "spec/fixture/app/views/form_builder_specs/date_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_disabled.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_classes.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_date_value.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_datetime_value.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_label.html.haml", "spec/fixture/app/views/form_builder_specs/datetime_field_with_time_value.html.haml", "spec/fixture/app/views/form_builder_specs/label.html.haml", "spec/fixture/app/views/form_builder_specs/label_with_note.html.haml", "spec/fixture/app/views/form_builder_specs/label_with_note_in_parens.html.haml", "spec/fixture/app/views/form_builder_specs/label_with_requirement.html.haml", "spec/fixture/app/views/form_builder_specs/time_field.html.haml", "spec/fixture/app/views/form_builder_specs/time_field_with_label.html.haml", "spec/fixture/app/views/layout/application.html.erb", "spec/fixture/app/views/layout/masthead.html.haml", "spec/fixture/app/views/masthead_specs/all.html.haml", "spec/fixture/app/views/masthead_specs/border.html.haml", "spec/fixture/app/views/masthead_specs/escaping.html.haml", "spec/fixture/app/views/masthead_specs/no_extras.html.haml", "spec/fixture/app/views/masthead_specs/no_subtitles.html.haml", "spec/fixture/app/views/masthead_specs/right_subtitle.html.haml", "spec/fixture/app/views/masthead_specs/right_title.html.haml", "spec/fixture/app/views/masthead_specs/subtitle.html.haml", "spec/fixture/app/views/masthead_specs/with_css_classes.html.haml", "spec/fixture/app/views/masthead_specs/with_links.html.haml", "spec/fixture/app/views/masthead_specs/with_no_escape.html.haml", "spec/fixture/app/views/nav_specs/_guarded.html.haml", "spec/fixture/app/views/nav_specs/active.html.haml", "spec/fixture/app/views/nav_specs/content_injection.html.haml", "spec/fixture/app/views/nav_specs/escaped_content_injection.html.haml", "spec/fixture/app/views/nav_specs/generic_nav.html.haml", "spec/fixture/app/views/nav_specs/guard_with_all_params.html.haml", "spec/fixture/app/views/nav_specs/guard_with_single_param.html.haml", "spec/fixture/app/views/nav_specs/guard_without_param.html.haml", "spec/fixture/app/views/nav_specs/has_right_formatter.html.haml", "spec/fixture/app/views/nav_specs/item_with_title.html.haml", "spec/fixture/app/views/nav_specs/item_without_title.html.haml", "spec/fixture/app/views/nav_specs/multiple_injection.html.haml", "spec/fixture/app/views/nav_specs/resource_url.html.haml", "spec/fixture/app/views/nav_specs/resource_url_without_resource.html.haml", "spec/fixture/app/views/nav_specs/show_resource_url.html.haml", "spec/fixture/app/views/nav_specs/subnav_formatter.html.haml", "spec/fixture/app/views/nav_specs/with_custom_formatter.html.haml", "spec/fixture/config/environments/development.rb", "spec/fixture/config/environments/production.rb", "spec/fixture/config/environments/rake.rb", "spec/fixture/config/environments/staging.rb", "spec/fixture/config/environments/test.rb", "spec/fixture/config/init.rb", "spec/fixture/config/rack.rb", "spec/fixture/config/router.rb", "spec/fixture/config/sprites.different.yml", "spec/fixture/config/sprites.yml", "spec/fixture/public/images/merb.jpg", "spec/fixture/public/images/sprites/src/one.png", "spec/fixture/public/images/sprites/src/three.png", "spec/fixture/public/images/sprites/src/two.png", "spec/fixture/public/stylesheets/master.css", "spec/form_builder_spec.rb", "spec/masthead_spec.rb", "spec/nav_spec.rb", "spec/spec_helper.rb", "spec/sprites_spec.rb" ] s.has_rdoc = false s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.5} s.summary = %q{Components commonly used in Showcase which can be applied to other projects.} s.test_files = [ "spec/configurable_spec.rb", "spec/core_ext/date_spec.rb", "spec/core_ext/string_spec.rb", "spec/core_ext/time_spec.rb", "spec/fixture/app/controllers/application.rb", "spec/fixture/app/controllers/exceptions.rb", "spec/fixture/app/controllers/form_builder_specs.rb", "spec/fixture/app/controllers/masthead_specs.rb", "spec/fixture/app/controllers/nav_specs.rb", "spec/fixture/app/controllers/spec_controller.rb", "spec/fixture/app/helpers/global_helpers.rb", "spec/fixture/app/models/fake_model.rb", "spec/fixture/config/environments/development.rb", "spec/fixture/config/environments/production.rb", "spec/fixture/config/environments/rake.rb", "spec/fixture/config/environments/staging.rb", "spec/fixture/config/environments/test.rb", "spec/fixture/config/init.rb", "spec/fixture/config/rack.rb", "spec/fixture/config/router.rb", "spec/form_builder_spec.rb", "spec/masthead_spec.rb", "spec/nav_spec.rb", "spec/spec_helper.rb", "spec/sprites_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::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else 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 = "ksk" s.version = "0.1.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Anton Pawlik"] s.date = "2013-07-06" s.description = "Fast and friendly" s.email = "anton.pawlik@gmail.com" s.extra_rdoc_files = [ "README.md" ] s.files = [ "app/controllers/ksk/navigations_controller.rb", "app/helpers/ksk/application_helper.rb", "app/views/bhf/entries/form/belongs_to/_category.html.haml", "app/views/bhf/entries/form/column/_image.html.haml", "app/views/bhf/entries/form/column/_s3_file.html.haml", "app/views/bhf/entries/form/column/_select_file_assets.html.haml", "app/views/bhf/entries/form/has_many/__assets.html.haml", "app/views/bhf/entries/form/has_many/_assets.html.haml", "app/views/bhf/entries/form/has_many/_upload.html.haml", "app/views/bhf/entries/form/has_one/_asset.html.haml", "app/views/bhf/pages/_navi.html.haml", "app/views/bhf/pages/macro/column/_extern_link.haml", "config/locales/de.yml", "config/locales/en.yml", "config/routes.rb", "lib/actives/asset.rb", "lib/actives/category.rb", "lib/actives/navigation.rb", "lib/actives/navigation_type.rb", "lib/actives/post.rb", "lib/actives/preview.rb", "lib/actives/static.rb", "lib/apdown.rb", "lib/ksk.rb", "lib/rails/generators/ksk/templates/initializer.rb", "vendor/assets/javascripts/ksk/classes/NaviAdmin.js", "vendor/assets/stylesheets/ksk/application.css.sass" ] s.homepage = "http://github.com/antpaw/ksk" s.require_paths = ["lib"] s.rubyforge_project = "nowarning" s.rubygems_version = "1.8.25" s.summary = "CMS for bhf" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<bhf>, [">= 0.5.0"]) s.add_runtime_dependency(%q<stringex>, [">= 0"]) else s.add_dependency(%q<bhf>, [">= 0.5.0"]) s.add_dependency(%q<stringex>, [">= 0"]) end else s.add_dependency(%q<bhf>, [">= 0.5.0"]) s.add_dependency(%q<stringex>, [">= 0"]) end end Regenerate gemspec for version 0.1.4 # 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 = "ksk" s.version = "0.1.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Anton Pawlik"] s.date = "2013-07-06" s.description = "Fast and friendly" s.email = "anton.pawlik@gmail.com" s.extra_rdoc_files = [ "README.md" ] s.files = [ "app/controllers/ksk/navigations_controller.rb", "app/helpers/ksk/application_helper.rb", "app/views/bhf/entries/form/belongs_to/_category.html.haml", "app/views/bhf/entries/form/column/_image.html.haml", "app/views/bhf/entries/form/column/_s3_file.html.haml", "app/views/bhf/entries/form/column/_select_file_assets.html.haml", "app/views/bhf/entries/form/has_many/__assets.html.haml", "app/views/bhf/entries/form/has_many/_assets.html.haml", "app/views/bhf/entries/form/has_many/_upload.html.haml", "app/views/bhf/entries/form/has_one/_asset.html.haml", "app/views/bhf/pages/_navi.html.haml", "app/views/bhf/pages/macro/column/_extern_link.haml", "config/locales/de.yml", "config/locales/en.yml", "config/routes.rb", "lib/actives/asset.rb", "lib/actives/category.rb", "lib/actives/navigation.rb", "lib/actives/navigation_type.rb", "lib/actives/post.rb", "lib/actives/preview.rb", "lib/actives/static.rb", "lib/apdown.rb", "lib/ksk.rb", "lib/rails/generators/ksk/templates/initializer.rb", "vendor/assets/javascripts/ksk/classes/NaviAdmin.js", "vendor/assets/stylesheets/ksk/application.css.sass" ] s.homepage = "http://github.com/antpaw/ksk" s.require_paths = ["lib"] s.rubyforge_project = "nowarning" s.rubygems_version = "1.8.25" s.summary = "CMS for bhf" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<bhf>, [">= 0.5.0"]) s.add_runtime_dependency(%q<stringex>, [">= 0"]) else s.add_dependency(%q<bhf>, [">= 0.5.0"]) s.add_dependency(%q<stringex>, [">= 0"]) end else s.add_dependency(%q<bhf>, [">= 0.5.0"]) s.add_dependency(%q<stringex>, [">= 0"]) end end
class Chess attr_reader :pieces_by_piece, :pieces_by_square def initialize @board = [] @pieces_by_piece = starting_pieces @pieces_by_square = pieces_to_squares @active_player = nil start_game end def to_s update_board start = 64 8.times do p "#{start/8}|#{@board.slice(start - 8, 8).map { |s| (s)? s : '___' }.join("|")}|" start -= 8 end p " | a | b | c | d | e | f | g | h |" return nil end def starting_pieces {white: {'wR1': 0, 'wN1': 1, 'wB1': 2, 'wQ1': 3, 'wK1': 4, 'wB2': 5, 'wN2': 6, 'wR2': 7, 'wP1': 8, 'wP2': 9, 'wP3': 10, 'wP4': 11, 'wP5': 12, 'wP6': 13, 'wP7': 14, 'wP8': 15}, black: {'bP1': 48, 'bP2': 49, 'bP3': 50, 'bP4': 51, 'bP5': 52, 'bP6': 53, 'bP7': 54, 'bP8': 55, 'bR1': 56, 'bN1': 57, 'bB1': 58, 'bQ1': 59, 'bK1': 60, 'bB2': 61, 'bN2': 62, 'bR2': 63}} end def pieces_to_squares squares = {white: {}, black: {}} @pieces_by_piece[:white].each do |p| squares[:white][p[1]] = p[0] end @pieces_by_piece[:black].each do |p| squares[:black][p[1]] = p[0] end squares end def update_board @board = [nil]*64 @pieces_by_piece[:white].each do |p| @board[p[1]] = p[0] end @pieces_by_piece[:black].each do |p| @board[p[1]] = p[0] end end def in_column?(col, square) square % 8 + 1 == col end def in_row?(row, square) square >= (row - 1) * 8 && square < row * 8 end def add_single_square?(square, row, col, offset, color) target_square = square + offset if !in_row?(row, square) && !in_column?(col, square) && !@pieces_by_square[color].include?(target_square) @moveable_squares << target_square end end def add_square?(square, row, col, offset, color) target_square = square + offset other_color = (color == :white)? :black : :white if !in_row?(row, square) && !in_column?(col, square) && !@pieces_by_square[color].include?(target_square) @moveable_squares << target_square add_square?(target_square, row, col, offset, color) unless @pieces_by_square[other_color].include?(target_square) end end def add_knight_square?(square, row1, row2, col1, col2, offset, color) target_square = square + offset if !in_row?(row1, square) && !in_row?(row2, square) && !in_column?(col1, square) && !in_column?(col2, square) && !@pieces_by_square[color].include?(target_square) @moveable_squares << target_square end end def get_pawn_moves(square, color) @moveable_squares = [] add_single_square?(square, 0, 0, (color == :white)? 8 : -8, color) @moveable_squares end def get_knight_moves(square, color) @moveable_squares = [] add_knight_square?(square, 1, 2, 1, 0, -17 , color) add_knight_square?(square, 1, 2, 8, 0, -15 , color) add_knight_square?(square, 1, 0, 1, 2, -10 , color) add_knight_square?(square, 1, 0, 7, 8, -6 , color) add_knight_square?(square, 8, 0, 1, 2, 6 , color) add_knight_square?(square, 8, 0, 7, 8, 10 , color) add_knight_square?(square, 7, 8, 1, 0, 15 , color) add_knight_square?(square, 7, 8, 8, 0, 17 , color) @moveable_squares end def get_bishop_moves(square, color) @moveable_squares = [] add_square?(square, 1, 1, -9, color) add_square?(square, 1, 8, -7, color) add_square?(square, 8, 1, 7, color) add_square?(square, 8, 8, 9, color) @moveable_squares end def get_rook_moves(square, color) @moveable_squares = [] add_square?(square, 1, 0, -8, color) add_square?(square, 0, 1, -1, color) add_square?(square, 0, 8, 1, color) add_square?(square, 8, 0, 8, color) @moveable_squares end def get_queen_moves(square, color) @moveable_squares = [] add_square?(square, 1, 1, -9, color) add_square?(square, 1, 0, -8, color) add_square?(square, 1, 8, -7, color) add_square?(square, 0, 1, -1, color) add_square?(square, 0, 8, 1, color) add_square?(square, 8, 1, 7, color) add_square?(square, 8, 0, 8, color) add_square?(square, 8, 8, 9, color) @moveable_squares end def get_king_moves(square, color) @moveable_squares = [] add_single_square?(square, 1, 1, -9, color) add_single_square?(square, 1, 0, -8, color) add_single_square?(square, 1, 8, -7, color) add_single_square?(square, 0, 1, -1, color) add_single_square?(square, 0, 8, 1, color) add_single_square?(square, 8, 1, 7, color) add_single_square?(square, 8, 0, 8, color) add_single_square?(square, 8, 8, 9, color) @moveable_squares end def start_game puts "WELCOME TO CHESS AND SHIT" puts self wait_for_move end def wait_for_move unless win if !@active_player || @active_player == :black @active_player = :white else @active_player = :black end puts "Player #{@active_player.to_s}: your turn" confirm = false move_valid = false while !confirm || !move_valid piece = get_player_piece user_square = get_player_square square = convert_user_square(user_square) confirm = get_player_confirmation(piece, user_square) move_valid = check_valid_move(piece, square, @active_player) puts "Move invalid!" unless move_valid end @pieces_by_piece[@active_player][piece] = square @pieces_by_square = pieces_to_squares puts self wait_for_move else #do win stuff end end def get_player_piece print "What piece would you like to move? (eg. wP1) " gets.chomp.to_sym end def get_player_square print "Where should it go? (eg. a3) " gets.chomp end def convert_user_square(user_square) ary_square = (user_square[1].to_i - 1) * 8 case user_square[0].downcase when 'a' ary_square += 0 when 'b' ary_square += 1 when 'c' ary_square += 2 when 'd' ary_square += 3 when 'e' ary_square += 4 when 'f' ary_square += 5 when 'g' ary_square += 6 when 'h' ary_square += 7 end end def get_player_confirmation(piece, square) print "Confirm #{piece} to #{square} y/n: " gets.chomp == 'y' end def check_valid_move(piece, square, color) return false if @pieces_by_piece[color].values.include?(piece) case piece[1] when 'P' get_pawn_moves(@pieces_by_piece[color][piece], color).include?(square) when 'N' get_knight_moves(@pieces_by_piece[color][piece], color).include?(square) when 'B' get_bishop_moves(@pieces_by_piece[color][piece], color).include?(square) when 'R' get_rook_moves(@pieces_by_piece[color][piece], color).include?(square) when 'Q' get_queen_moves(@pieces_by_piece[color][piece], color).include?(square) when 'K' get_king_moves(@pieces_by_piece[color][piece], color).include?(square) end end def win end end chess = Chess.new added en passant and removal of taken pieces class Chess attr_reader :pieces_by_piece, :pieces_by_square def initialize @board = [] @pieces_by_piece = starting_pieces @pieces_by_square = pieces_to_squares @active_player = nil reset_en_passant_squares end def to_s update_board start = 64 8.times do p "#{start/8}|#{@board.slice(start - 8, 8).map { |s| (s)? s : '___' }.join("|")}|" start -= 8 end p " | a | b | c | d | e | f | g | h |" return nil end def starting_pieces {white: {wR1: 0, wN1: 1, wB1: 2, wQ1: 3, wK1: 4, wB2: 5, wN2: 6, wR2: 7, wP1: 8, wP2: 9, wP3: 10, wP4: 11, wP5: 12, wP6: 13, wP7: 14, wP8: 15}, black: {bP1: 48, bP2: 49, bP3: 50, bP4: 51, bP5: 52, bP6: 53, bP7: 54, bP8: 55, bR1: 56, bN1: 57, bB1: 58, bQ1: 59, bK1: 60, bB2: 61, bN2: 62, bR2: 63}} end def pieces_to_squares squares = {white: {}, black: {}} @pieces_by_piece[:white].each do |p| squares[:white][p[1]] = p[0] end @pieces_by_piece[:black].each do |p| squares[:black][p[1]] = p[0] end squares end def update_board @board = [nil]*64 @pieces_by_piece[:white].each do |p| @board[p[1]] = p[0] end @pieces_by_piece[:black].each do |p| @board[p[1]] = p[0] end end def in_column?(col, square) square % 8 + 1 == col end def in_row?(row, square) square >= (row - 1) * 8 && square < row * 8 end def add_king_square?(square, row, col, offset, color) target_square = square + offset if !in_row?(row, square) && !in_column?(col, square) && !@pieces_by_square[color].include?(target_square) @moveable_squares << target_square end end def add_pawn_move_square?(square, offset, color) target_square = square + offset other_color = (color == :white)? :black : :white if !@pieces_by_square[:white].include?(target_square) && !@pieces_by_square[:black].include?(target_square) @moveable_squares << target_square end target_square = square + offset * 2 if (in_row?(2, square) && color == :white) || (in_row?(7, square) && color == :black) && !@pieces_by_square[:white].include?(target_square) && !@pieces_by_square[:black].include?(target_square) @moveable_squares << target_square end end def add_pawn_attack_square?(square, col, offset, color) other_color = (color == :white)? :black : :white target_square = square + offset if !in_column?(col, square) && (@pieces_by_square[other_color].include?(target_square) || @en_passant_squares[other_color].include?(target_square)) @moveable_squares << target_square end end def add_square?(square, row, col, offset, color) other_color = (color == :white)? :black : :white target_square = square + offset if !in_row?(row, square) && !in_column?(col, square) && !@pieces_by_square[color].include?(target_square) @moveable_squares << target_square add_square?(target_square, row, col, offset, color) unless @pieces_by_square[other_color].include?(target_square) end end def add_knight_square?(square, row1, row2, col1, col2, offset, color) target_square = square + offset if !in_row?(row1, square) && !in_row?(row2, square) && !in_column?(col1, square) && !in_column?(col2, square) && !@pieces_by_square[color].include?(target_square) @moveable_squares << target_square end end def get_pawn_moves(square, color) @moveable_squares = [] add_pawn_move_square?(square, (color == :white)? 8 : -8, color) add_pawn_attack_square?(square, 1, (color == :white)? 7 : -9, color) add_pawn_attack_square?(square, 8, (color == :white)? 9 : -7, color) @moveable_squares end def get_knight_moves(square, color) @moveable_squares = [] add_knight_square?(square, 1, 2, 1, 0, -17 , color) add_knight_square?(square, 1, 2, 8, 0, -15 , color) add_knight_square?(square, 1, 0, 1, 2, -10 , color) add_knight_square?(square, 1, 0, 7, 8, -6 , color) add_knight_square?(square, 8, 0, 1, 2, 6 , color) add_knight_square?(square, 8, 0, 7, 8, 10 , color) add_knight_square?(square, 7, 8, 1, 0, 15 , color) add_knight_square?(square, 7, 8, 8, 0, 17 , color) @moveable_squares end def get_bishop_moves(square, color) @moveable_squares = [] add_square?(square, 1, 1, -9, color) add_square?(square, 1, 8, -7, color) add_square?(square, 8, 1, 7, color) add_square?(square, 8, 8, 9, color) @moveable_squares end def get_rook_moves(square, color) @moveable_squares = [] add_square?(square, 1, 0, -8, color) add_square?(square, 0, 1, -1, color) add_square?(square, 0, 8, 1, color) add_square?(square, 8, 0, 8, color) @moveable_squares end def get_queen_moves(square, color) @moveable_squares = [] add_square?(square, 1, 1, -9, color) add_square?(square, 1, 0, -8, color) add_square?(square, 1, 8, -7, color) add_square?(square, 0, 1, -1, color) add_square?(square, 0, 8, 1, color) add_square?(square, 8, 1, 7, color) add_square?(square, 8, 0, 8, color) add_square?(square, 8, 8, 9, color) @moveable_squares end def get_king_moves(square, color) @moveable_squares = [] add_king_square?(square, 1, 1, -9, color) add_king_square?(square, 1, 0, -8, color) add_king_square?(square, 1, 8, -7, color) add_king_square?(square, 0, 1, -1, color) add_king_square?(square, 0, 8, 1, color) add_king_square?(square, 8, 1, 7, color) add_king_square?(square, 8, 0, 8, color) add_king_square?(square, 8, 8, 9, color) @moveable_squares end def start_game puts "***********************************" puts "*****WELCOME TO CHESS AND SHIT*****" puts "***********************************" puts self wait_for_move end def wait_for_move unless win if !@active_player || @active_player == :black @active_player = :white else @active_player = :black end color = @active_player puts "Player #{color.to_s}: your turn" confirm = false while !confirm move_valid = false while !move_valid piece = get_player_piece user_square = get_player_square square = convert_user_square(user_square) move_valid = check_valid_move(piece, square, color) puts "Move invalid!" unless move_valid end confirm = get_player_confirmation(piece, user_square) end remove_taken_piece(square, color) reset_en_passant_squares add_en_passant_squares(piece, square, color) if piece[1] == 'P' @pieces_by_piece[color][piece] = square @pieces_by_square = pieces_to_squares puts self wait_for_move else #do win stuff end end def get_player_piece print "What piece would you like to move? (eg. wP1) " gets.chomp.to_sym end def get_player_square print "Where should it go? (eg. a3) " gets.chomp end def convert_user_square(user_square) ary_square = (user_square[1].to_i - 1) * 8 case user_square[0].downcase when 'a' ary_square += 0 when 'b' ary_square += 1 when 'c' ary_square += 2 when 'd' ary_square += 3 when 'e' ary_square += 4 when 'f' ary_square += 5 when 'g' ary_square += 6 when 'h' ary_square += 7 end end def get_player_confirmation(piece, square) print "Confirm #{piece} to #{square} y/n: " gets.chomp == 'y' end def check_valid_move(piece, square, color) return false if @pieces_by_piece[color].values.include?(piece) case piece[1] when 'P' get_pawn_moves(@pieces_by_piece[color][piece], color).include?(square) when 'N' get_knight_moves(@pieces_by_piece[color][piece], color).include?(square) when 'B' get_bishop_moves(@pieces_by_piece[color][piece], color).include?(square) when 'R' get_rook_moves(@pieces_by_piece[color][piece], color).include?(square) when 'Q' get_queen_moves(@pieces_by_piece[color][piece], color).include?(square) when 'K' get_king_moves(@pieces_by_piece[color][piece], color).include?(square) end end def remove_taken_piece(square, color) other_color = (color == :white)? :black : :white if @en_passant_squares[other_color].include?(square) ep_offset = (color == :white)? -8 : 8 @pieces_by_piece[other_color].delete(@pieces_by_square[other_color][square + ep_offset]) elsif @pieces_by_square[other_color].include?(square) @pieces_by_piece[other_color].delete(@pieces_by_square[other_color][square]) end end def reset_en_passant_squares @en_passant_squares = {white: [], black: []} end def add_en_passant_squares(piece, square, color) ep_offset = (color == :white)? 16 : -16 if @pieces_by_piece[color][piece] + ep_offset == square @en_passant_squares[color] << square - ep_offset / 2 end end def win end end
require 'circular_dependency_exception' require 'same_dependency_exception' class Queue attr_reader :jobs, :dependencies def initialize(args={}) args = defaults.merge(args) @jobs = args[:jobs].chars @dependencies = args[:dependencies] end # Im using a defaults method to set an empty string if the user dont sent jobs. # This is necessary because im going to do args[:jobs].chars to initialize jobs. def defaults {:jobs => ''} end def run return unless has_same_dependencies? # we only continue if we have valid dependencies. ordered_jobs = [] while jobs.size > 0 job = jobs[0] # we check first job in our queue, we only remove the job from the queue # depending of the dependencies. unless (dependency = last_job_in_dependency(job, ordered_jobs, job)) == job # we have a dependency and we need to extract it from our jobs array. ordered_jobs << jobs.delete_at(jobs.index(dependency)) else # we move our job to the final ordered jobs. ordered_jobs << jobs.shift end end # becasue we hare using a string and chars to represent our jobs I show it as a string # to check results. ordered_jobs.join('') end private def last_job_in_dependency(job, queued, job_start, previous=[]) previous << job dependency = has_dependency?(job) if dependency.nil? || queued.include?(dependency) # if we dont have a dependency or our dependency was added before, we return the job evaluated job else # we continue with the recursive call to the the rest of the dependencies if is not processed # before and if is not a ciruclar dependency queued.include?(dependency) ? dependency : last_job_in_dependency(dependency, queued, job_start, previous) if is_not_circular_dependency?(dependency, job_start, previous) end end def has_dependency?(job) dependencies && dependencies.keys.include?(job) ? dependencies[job] : nil end def has_same_dependencies? raise SameDependencyException if dependencies && dependencies.select{|k,v| k==v}.size > 0 true end # we check circular dependencies in two ways: # 1. started job with the current dependency # 2. any previous job with current dependency def is_not_circular_dependency?(dependency, start_job, previous) raise CircularDependencyException if dependency == start_job || previous.include?(dependency) true end end remove comments from queue file require 'circular_dependency_exception' require 'same_dependency_exception' class Queue attr_reader :jobs, :dependencies def initialize(args={}) args = defaults.merge(args) @jobs = args[:jobs].chars @dependencies = args[:dependencies] end def defaults {:jobs => ''} end def run return unless has_same_dependencies? ordered_jobs = [] while jobs.size > 0 job = jobs[0] unless (dependency = last_job_in_dependency(job, ordered_jobs, job)) == job ordered_jobs << jobs.delete_at(jobs.index(dependency)) else ordered_jobs << jobs.shift end end ordered_jobs.join('') end private def last_job_in_dependency(job, queued, job_start, previous=[]) previous << job dependency = has_dependency?(job) if dependency.nil? || queued.include?(dependency) job else queued.include?(dependency) ? dependency : last_job_in_dependency(dependency, queued, job_start, previous) if is_not_circular_dependency?(dependency, job_start, previous) end end def has_dependency?(job) dependencies && dependencies.keys.include?(job) ? dependencies[job] : nil end def has_same_dependencies? raise SameDependencyException if dependencies && dependencies.select{|k,v| k==v}.size > 0 true end def is_not_circular_dependency?(dependency, start_job, previous) raise CircularDependencyException if dependency == start_job || previous.include?(dependency) true end end
Added binary_tree_postorder_traversal # Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} root # @return {Integer[]} def postorder_traversal(root) res = [] return res if root.nil? stack = [] stack.push(root) until stack.empty? root = stack.pop res.push(root.val) stack.push(root.left) unless root.left.nil? stack.push(root.right) unless root.right.nil? end res.reverse! end
# # raccs.rb # # Copyright (c) 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp> # require 'racc/scanner' class Racc class RaccScanner < Scanner # pattern COMMENT = /\A\#[^\n\r]*/o BEGIN_C = /\A\/\*[^\n\r\*\/]*/o ATOM = /\A[a-zA-Z_]\w*|\A\$end/o CODEBLOCK = /\A(?:\n|\r\n|\r)\-\-\-\-+/o def scan ret = nil while true do unless @scan.rest? then ret = [false, false] break end @scan.skip SPC unless @scan.skip COMMENT then if @scan.skip BEGIN_C then scan_comment next end end if temp = @scan.scan( CODEBLOCK ) then @lineno += 1 @scan.clear next end if @scan.skip EOL then @lineno += 1 next end if atm = @scan.scan( ATOM ) then ret = scan_atom( atm ) break end case fch = @scan.getch when '"', "'" ret = [:STRING, scan_string( fch )] when '{' ret = [:ACTION, scan_action] else ret = [fch, fch] end break end debug_report ret if @debug ret end private def scan_atom( cur ) sret = :TOKEN vret = cur.intern case cur when 'end' then sret = :XEND when 'token' then sret = :XTOKEN when 'right' then sret = :RIGHT when 'left' then sret = :LEFT when 'nonassoc' then sret = :NONASSOC when 'preclow' then sret = :PRECLOW when 'prechigh' then sret = :PRECHIGH when 'start' then sret = :START when 'class' then sret = :CLASS when 'rule' then sret = :RULE when 'file' then sret = :XFILE when '$end' then vret = Parser::Anchor end [sret, vret] end # BEGIN_C = /\A\/\*[^\n\r\*\/]*/o COM_ENT = /\A[^\n\r*]+/o COM_ENT2 = /\A\*+[^*\/\r\n]/o END_C = /\A\*+\//o def scan_comment while @scan.rest? do if @scan.skip COM_ENT elsif @scan.skip COM_ENT2 elsif @scan.skip EOL then @lineno += 1 elsif @scan.skip END_C then return else scan_bug! 'in comment, no exp match' end end scan_error! 'find unterminated comment' end SKIP = /\A[^\'\"\`\{\}\/\#\r\n]+/o COMMENT_CONT = /\A[^\r\n]*/o def scan_action ret = '' nest = 0 while @scan.rest? do if temp = @scan.scan( SKIP ) then ret << temp end if temp = @scan.scan( EOL ) then ret << temp @lineno += 1 next end case ch = @scan.getch when '{' nest += 1 ret << ch when '}' nest -= 1 if nest < 0 then break end ret << ch when "'", '"', '`' ret << ch << scan_string( ch ) << ch when '/' if SPC === ret[-1,1] then if @scan.peep(1) != '=' then ret << ch << scan_string( ch ) << ch next end end ret << ch when '#' ret << ch << @scan.scan( COMMENT_CONT ) << @scan.scan( EOL ) @lineno += 1 else bug! 'must not huppen' end end return ret end end end o $end is obsolute git-svn-id: 5afd3ca03d14561cc8c2bbb9ff9d69d00c7a72c2@1628 1b9489fe-b721-0410-924e-b54b9192deb8 # # raccs.rb # # Copyright (c) 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp> # require 'racc/scanner' class Racc class RaccScanner < Scanner # pattern COMMENT = /\A\#[^\n\r]*/o BEGIN_C = /\A\/\*[^\n\r\*\/]*/o ATOM = /\A[a-zA-Z_]\w*/o CODEBLOCK = /\A(?:\n|\r\n|\r)\-\-\-\-+/o def scan ret = nil while true do unless @scan.rest? then ret = [false, false] break end @scan.skip SPC unless @scan.skip COMMENT then if @scan.skip BEGIN_C then scan_comment next end end if temp = @scan.scan( CODEBLOCK ) then @lineno += 1 @scan.clear next end if @scan.skip EOL then @lineno += 1 next end if atm = @scan.scan( ATOM ) then ret = scan_atom( atm ) break end case fch = @scan.getch when '"', "'" ret = [:STRING, scan_string( fch )] when '{' ret = [:ACTION, scan_action] else ret = [fch, fch] end break end debug_report ret if @debug ret end private def scan_atom( cur ) sret = :TOKEN vret = cur.intern case cur when 'end' then sret = :XEND when 'token' then sret = :XTOKEN when 'right' then sret = :RIGHT when 'left' then sret = :LEFT when 'nonassoc' then sret = :NONASSOC when 'preclow' then sret = :PRECLOW when 'prechigh' then sret = :PRECHIGH when 'start' then sret = :START when 'class' then sret = :CLASS when 'rule' then sret = :RULE when 'file' then sret = :XFILE end [sret, vret] end # BEGIN_C = /\A\/\*[^\n\r\*\/]*/o COM_ENT = /\A[^\n\r*]+/o COM_ENT2 = /\A\*+[^*\/\r\n]/o END_C = /\A\*+\//o def scan_comment while @scan.rest? do if @scan.skip COM_ENT elsif @scan.skip COM_ENT2 elsif @scan.skip EOL then @lineno += 1 elsif @scan.skip END_C then return else scan_bug! 'in comment, no exp match' end end scan_error! 'find unterminated comment' end SKIP = /\A[^\'\"\`\{\}\/\#\r\n]+/o COMMENT_CONT = /\A[^\r\n]*/o def scan_action ret = '' nest = 0 while @scan.rest? do if temp = @scan.scan( SKIP ) then ret << temp end if temp = @scan.scan( EOL ) then ret << temp @lineno += 1 next end case ch = @scan.getch when '{' nest += 1 ret << ch when '}' nest -= 1 if nest < 0 then break end ret << ch when "'", '"', '`' ret << ch << scan_string( ch ) << ch when '/' if SPC === ret[-1,1] then if @scan.peep(1) != '=' then ret << ch << scan_string( ch ) << ch next end end ret << ch when '#' ret << ch << @scan.scan( COMMENT_CONT ) << @scan.scan( EOL ) @lineno += 1 else bug! 'must not huppen' end end return ret end end end
Iinitial commit # 3 5 1 arr = [-1,3,-4,5,1,-6,2,1] # arr = [0,0,0,3,0,-1,1] arr.each_with_index.reject {|el,i| i == 0}.each do |el, index| p arr[0..index+1] if (arr[0..index-1].reduce :+) == (arr[index+1..arr.last].reduce :+) puts el else puts "." end end # puts arr.reduce :+ # arr.each_with_index.reject {|el,i| i == 0}.each do |el, index| # index # if arr[0..index].inject(0) {|sum, n| sum + n} == arr[index..arr.last].inject(0) {|sum, n| sum + n} # p el # else # puts "." # end # end