CombinedText stringlengths 4 3.42M |
|---|
module CapybaraHelpers
# Execute a block a certain number of times before considering it a failure
#
# The given block is called, and if it raises a `Capybara::ExpectationNotMet`
# error, we wait `interval` seconds and then try again, until `retries` is
# met.
#
# This allows for better handling of timing-sensitive expectations in a
# sketchy CI environment, for example.
#
# interval - Delay between retries in seconds (default: 0.5)
# retries - Number of times to execute before failing (default: 5)
def allowing_for_delay(interval: 0.5, retries: 5)
tries = 0
begin
sleep interval
yield
rescue Capybara::ExpectationNotMet => ex
if tries <= retries
tries += 1
sleep interval
retry
else
raise ex
end
end
end
# Refresh the page. Calling `visit current_url` doesn't seem to work consistently.
#
def refresh
url = current_url
visit 'about:blank'
visit url
end
# Simulate a browser restart by clearing the session cookie.
def clear_browser_session
page.driver.remove_cookie('_gitlab_session')
end
end
RSpec.configure do |config|
config.include CapybaraHelpers, type: :feature
end
Rename remove_cookie -> delete_cookie in Capybara helper for Selenium driver
module CapybaraHelpers
# Execute a block a certain number of times before considering it a failure
#
# The given block is called, and if it raises a `Capybara::ExpectationNotMet`
# error, we wait `interval` seconds and then try again, until `retries` is
# met.
#
# This allows for better handling of timing-sensitive expectations in a
# sketchy CI environment, for example.
#
# interval - Delay between retries in seconds (default: 0.5)
# retries - Number of times to execute before failing (default: 5)
def allowing_for_delay(interval: 0.5, retries: 5)
tries = 0
begin
sleep interval
yield
rescue Capybara::ExpectationNotMet => ex
if tries <= retries
tries += 1
sleep interval
retry
else
raise ex
end
end
end
# Refresh the page. Calling `visit current_url` doesn't seem to work consistently.
#
def refresh
url = current_url
visit 'about:blank'
visit url
end
# Simulate a browser restart by clearing the session cookie.
def clear_browser_session
page.driver.delete_cookie('_gitlab_session')
end
end
RSpec.configure do |config|
config.include CapybaraHelpers, type: :feature
end
|
#
# Copyright:: Copyright (c) 2014 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
require 'chef-dk/component_test'
require 'pathname'
describe ChefDK::ComponentTest do
let(:component) do
ChefDK::ComponentTest.new("berkshelf").tap do |c|
c.base_dir = "berkshelf"
end
end
it "defines the component" do
expect(component.name).to eq("berkshelf")
end
it "sets the component base directory" do
expect(component.base_dir).to eq("berkshelf")
end
it "defines a default unit test" do
expect(component.run_unit_test.exitstatus).to eq(0)
expect(component.run_unit_test.stdout).to eq("")
expect(component.run_unit_test.stderr).to eq("")
end
it "defines a default integration test" do
expect(component.run_integration_test.exitstatus).to eq(0)
expect(component.run_integration_test.stdout).to eq("")
expect(component.run_integration_test.stderr).to eq("")
end
it "defines a default smoke test" do
expect(component.run_smoke_test.exitstatus).to eq(0)
expect(component.run_smoke_test.stdout).to eq("")
expect(component.run_smoke_test.stderr).to eq("")
end
context "with basic tests defined" do
let(:result) { {} }
before do
# capture a reference to results hash so we can use it in tests.
result_hash = result
component.tap do |c|
c.unit_test { result_hash[:unit_test] = true }
c.integration_test { result_hash[:integration_test] = true }
c.smoke_test { result_hash[:smoke_test] = true }
end
end
it "defines a unit test block" do
component.run_unit_test
expect(result[:unit_test]).to be_true
end
it "defines an integration test block" do
component.run_integration_test
expect(result[:integration_test]).to be_true
end
it "defines a smoke test block" do
component.run_smoke_test
expect(result[:smoke_test]).to be_true
end
end
context "with tests that shell out to commands" do
let(:omnibus_root) { File.join(fixtures_path, "eg_omnibus_dir/valid/") }
before do
component.tap do |c|
# Have to set omnibus dir so command can run with correct cwd
c.omnibus_root = omnibus_root
c.unit_test { sh("true") }
c.integration_test { sh("pwd") }
c.smoke_test { run_in_tmpdir("pwd") }
end
end
it "shells out and returns the shell out object" do
expect(component.run_unit_test.exitstatus).to eq(0)
expect(component.run_unit_test.stdout).to eq("")
expect(component.run_unit_test.stderr).to eq("")
end
it "runs the command in the app's root" do
result = component.run_integration_test
expected_path = Pathname.new(File.join(omnibus_root, "embedded/apps/berkshelf")).realpath
expect(Pathname.new(result.stdout.strip).realpath).to eq(expected_path)
end
it "runs commands in a temporary directory when specified" do
result = component.run_smoke_test
parent_of_cwd = Pathname.new(result.stdout.strip).parent.realpath
tempdir = Pathname.new(Dir.tmpdir).realpath
expect(parent_of_cwd).to eq(tempdir)
end
end
end
Avoid using `pwd` command in tests
On my windows system, pwd.exe bundled with omnibus gives very odd
results.
#
# Copyright:: Copyright (c) 2014 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
require 'chef-dk/component_test'
require 'pathname'
describe ChefDK::ComponentTest do
let(:component) do
ChefDK::ComponentTest.new("berkshelf").tap do |c|
c.base_dir = "berkshelf"
end
end
it "defines the component" do
expect(component.name).to eq("berkshelf")
end
it "sets the component base directory" do
expect(component.base_dir).to eq("berkshelf")
end
it "defines a default unit test" do
expect(component.run_unit_test.exitstatus).to eq(0)
expect(component.run_unit_test.stdout).to eq("")
expect(component.run_unit_test.stderr).to eq("")
end
it "defines a default integration test" do
expect(component.run_integration_test.exitstatus).to eq(0)
expect(component.run_integration_test.stdout).to eq("")
expect(component.run_integration_test.stderr).to eq("")
end
it "defines a default smoke test" do
expect(component.run_smoke_test.exitstatus).to eq(0)
expect(component.run_smoke_test.stdout).to eq("")
expect(component.run_smoke_test.stderr).to eq("")
end
context "with basic tests defined" do
let(:result) { {} }
before do
# capture a reference to results hash so we can use it in tests.
result_hash = result
component.tap do |c|
c.unit_test { result_hash[:unit_test] = true }
c.integration_test { result_hash[:integration_test] = true }
c.smoke_test { result_hash[:smoke_test] = true }
end
end
it "defines a unit test block" do
component.run_unit_test
expect(result[:unit_test]).to be_true
end
it "defines an integration test block" do
component.run_integration_test
expect(result[:integration_test]).to be_true
end
it "defines a smoke test block" do
component.run_smoke_test
expect(result[:smoke_test]).to be_true
end
end
context "with tests that shell out to commands" do
let(:omnibus_root) { File.join(fixtures_path, "eg_omnibus_dir/valid/") }
before do
component.tap do |c|
# Have to set omnibus dir so command can run with correct cwd
c.omnibus_root = omnibus_root
c.unit_test { sh("true") }
c.integration_test { sh("ruby -e 'puts Dir.pwd'", env: { "RUBYOPT" => "" }) }
c.smoke_test { run_in_tmpdir("ruby -e 'puts Dir.pwd'", env: { "RUBYOPT" => "" }) }
end
end
it "shells out and returns the shell out object" do
expect(component.run_unit_test.exitstatus).to eq(0)
expect(component.run_unit_test.stdout).to eq("")
expect(component.run_unit_test.stderr).to eq("")
end
it "runs the command in the app's root" do
result = component.run_integration_test
expected_path = Pathname.new(File.join(omnibus_root, "embedded/apps/berkshelf")).realpath
expect(Pathname.new(result.stdout.strip).realpath).to eq(expected_path)
end
it "runs commands in a temporary directory when specified" do
result = component.run_smoke_test
parent_of_cwd = Pathname.new(result.stdout.strip).parent.realpath
tempdir = Pathname.new(Dir.tmpdir).realpath
expect(parent_of_cwd).to eq(tempdir)
end
end
end
|
Unit tests which expose ProductsController having invalid API calls.
# frozen_string_literal: true
require "test_helper"
require "test_helpers/fake_session_storage"
require "utils/generated_sources"
require "generators/shopify_app/products_controller/products_controller_generator"
require "generators/shopify_app/authenticated_controller/authenticated_controller_generator"
require "dummy/app/controllers/application_controller"
class ProductsControllerGeneratorWithExecutionTest < ActiveSupport::TestCase
test "generates valid ProductController class" do
with_products_controller do
assert(defined?(ProductsController))
assert(ProductsController < AuthenticatedController)
end
end
test "generates ProductController which fetches products" do
with_products_controller do
ShopifyAPI::Context.setup(
api_key: "API_KEY",
api_secret_key: "API_SECRET_KEY",
api_version: "unstable",
host_name: "app-address.com",
scope: ["scope1", "scope2"],
is_private: false,
is_embedded: false,
session_storage: TestHelpers::FakeSessionStorage.new,
user_agent_prefix: nil
)
controller = ProductsController.new
def controller.current_shopify_session
ShopifyAPI::Auth::Session.new(shop: "my-shop")
end
stub_request(:get, "https://my-shop/admin/api/unstable/products.json?limit=10")
.to_return(status: 200, body: "{\"products\":[]}", headers: {})
controller.index
end
end
private
def with_products_controller(&block)
WebMock.enable!
sources = Utils::GeneratedSources.new
sources.run_generator(ShopifyApp::Generators::AuthenticatedControllerGenerator)
sources.run_generator(ShopifyApp::Generators::ProductsControllerGenerator)
refute(defined?(ProductsController))
sources.load_generated_classes("app/controllers/authenticated_controller.rb")
sources.load_generated_classes("app/controllers/products_controller.rb")
block.call(sources)
ensure
WebMock.reset!
WebMock.disable!
sources.clear
end
end |
# TODO: verify with x509_certificate
describe file('/etc/apache2/ssl/dnsimple.xyz.crt') do
its('content') { should match /-----BEGIN CERTIFICATE-----/ }
end
# TODO: verify with key_rsa
describe file('/etc/apache2/ssl/dnsimple.xyz.key') do
its('content') { should match /-----BEGIN RSA PRIVATE KEY-----/ }
end
Test cert and key with x509_certificate and key_rsa, respectively
describe x509_certificate('/etc/apache2/ssl/dnsimple.xyz.crt') do
its('key_length') { should be 2048 }
its('subject.CN') { should eq 'www.dnsimple.xyz' }
end
describe key_rsa('/etc/apache2/ssl/dnsimple.xyz.key') do
it { should be_private }
it { should be_public }
its('key_length') { should be 2048 }
end
|
# encoding: utf-8
require File.expand_path("../spec_helper", __FILE__)
describe "FileField" do
before :each do
browser.goto(WatirSpec.url_for("forms_with_input_elements.html"))
end
describe "#exist?" do
it "returns true if the file field exists" do
browser.file_field(:id, 'new_user_portrait').should exist
browser.file_field(:id, /new_user_portrait/).should exist
browser.file_field(:name, 'new_user_portrait').should exist
browser.file_field(:name, /new_user_portrait/).should exist
browser.file_field(:class, 'portrait').should exist
browser.file_field(:class, /portrait/).should exist
browser.file_field(:index, 0).should exist
browser.file_field(:xpath, "//input[@id='new_user_portrait']").should exist
end
it "returns the first file field if given no args" do
browser.file_field.should exist
end
it "returns true for element with upper case type" do
browser.file_field(:id, "new_user_resume").should exist
end
it "returns false if the file field doesn't exist" do
browser.file_field(:id, 'no_such_id').should_not exist
browser.file_field(:id, /no_such_id/).should_not exist
browser.file_field(:name, 'no_such_name').should_not exist
browser.file_field(:name, /no_such_name/).should_not exist
browser.file_field(:class, 'no_such_class').should_not exist
browser.file_field(:class, /no_such_class/).should_not exist
browser.file_field(:index, 1337).should_not exist
browser.file_field(:xpath, "//input[@id='no_such_id']").should_not exist
end
it "raises TypeError when 'what' argument is invalid" do
lambda { browser.file_field(:id, 3.14).exists? }.should raise_error(TypeError)
end
it "raises MissingWayOfFindingObjectException when 'how' argument is invalid" do
lambda { browser.file_field(:no_such_how, 'some_value').exists? }.should raise_error(MissingWayOfFindingObjectException)
end
end
# Attribute methods
describe "#class_name" do
it "returns the class attribute if the text field exists" do
browser.file_field(:index, 0).class_name.should == "portrait"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).class_name }.should raise_error(UnknownObjectException)
end
end
describe "#id" do
it "returns the id attribute if the text field exists" do
browser.file_field(:index, 0).id.should == "new_user_portrait"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).id }.should raise_error(UnknownObjectException)
end
end
describe "#name" do
it "returns the name attribute if the text field exists" do
browser.file_field(:index, 0).name.should == "new_user_portrait"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).name }.should raise_error(UnknownObjectException)
end
end
describe "#title" do
it "returns the title attribute if the text field exists" do
browser.file_field(:id, "new_user_portrait").title.should == "Smile!"
end
end
describe "#type" do
it "returns the type attribute if the text field exists" do
browser.file_field(:index, 0).type.should == "file"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).type }.should raise_error(UnknownObjectException)
end
end
describe "#respond_to?" do
it "returns true for all attribute methods" do
browser.file_field(:index, 0).should respond_to(:class_name)
browser.file_field(:index, 0).should respond_to(:id)
browser.file_field(:index, 0).should respond_to(:name)
browser.file_field(:index, 0).should respond_to(:title)
browser.file_field(:index, 0).should respond_to(:type)
browser.file_field(:index, 0).should respond_to(:value)
end
end
# Manipulation methods
describe "#set" do
not_compliant_on [:webdriver, :iphone] do
bug "https://github.com/detro/ghostdriver/issues/158", :phantomjs do
it "is able to set a file path in the field and click the upload button and fire the onchange event" do
browser.goto WatirSpec.url_for("forms_with_input_elements.html", :needs_server => true)
path = File.expand_path(__FILE__)
element = browser.file_field(:name, "new_user_portrait")
element.set path
element.value.should include(File.basename(path)) # only some browser will return the full path
messages.first.should include(File.basename(path))
browser.button(:name, "new_user_submit").click
end
end
it "raises an error if the file does not exist" do
lambda {
browser.file_field.set(File.join(Dir.tmpdir, 'unlikely-to-exist'))
}.should raise_error(Errno::ENOENT)
end
end
end
describe "#value=" do
not_compliant_on [:webdriver, :iphone] do
bug "https://github.com/detro/ghostdriver/issues/158", :phantomjs do
it "is able to set a file path in the field and click the upload button and fire the onchange event" do
browser.goto WatirSpec.url_for("forms_with_input_elements.html", :needs_server => true)
path = File.expand_path(__FILE__)
element = browser.file_field(:name, "new_user_portrait")
element.value = path
element.value.should include(File.basename(path)) # only some browser will return the full path
end
end
end
not_compliant_on :internet_explorer, [:webdriver, :chrome], [:webdriver, :iphone] do
bug "https://github.com/detro/ghostdriver/issues/158", [:webdriver, :phantomjs] do
# for chrome, the check also happens in the driver
it "does not raise an error if the file does not exist" do
path = File.join(Dir.tmpdir, 'unlikely-to-exist')
browser.file_field.value = path
expected = path
expected.gsub!("/", "\\") if WatirSpec.platform == :windows
browser.file_field.value.should == expected
end
it "does not alter its argument" do
value = '/foo/bar'
browser.file_field.value = value
value.should == '/foo/bar'
end
end
end
end
end
Fix PhantomJS guards.
# encoding: utf-8
require File.expand_path("../spec_helper", __FILE__)
describe "FileField" do
before :each do
browser.goto(WatirSpec.url_for("forms_with_input_elements.html"))
end
describe "#exist?" do
it "returns true if the file field exists" do
browser.file_field(:id, 'new_user_portrait').should exist
browser.file_field(:id, /new_user_portrait/).should exist
browser.file_field(:name, 'new_user_portrait').should exist
browser.file_field(:name, /new_user_portrait/).should exist
browser.file_field(:class, 'portrait').should exist
browser.file_field(:class, /portrait/).should exist
browser.file_field(:index, 0).should exist
browser.file_field(:xpath, "//input[@id='new_user_portrait']").should exist
end
it "returns the first file field if given no args" do
browser.file_field.should exist
end
it "returns true for element with upper case type" do
browser.file_field(:id, "new_user_resume").should exist
end
it "returns false if the file field doesn't exist" do
browser.file_field(:id, 'no_such_id').should_not exist
browser.file_field(:id, /no_such_id/).should_not exist
browser.file_field(:name, 'no_such_name').should_not exist
browser.file_field(:name, /no_such_name/).should_not exist
browser.file_field(:class, 'no_such_class').should_not exist
browser.file_field(:class, /no_such_class/).should_not exist
browser.file_field(:index, 1337).should_not exist
browser.file_field(:xpath, "//input[@id='no_such_id']").should_not exist
end
it "raises TypeError when 'what' argument is invalid" do
lambda { browser.file_field(:id, 3.14).exists? }.should raise_error(TypeError)
end
it "raises MissingWayOfFindingObjectException when 'how' argument is invalid" do
lambda { browser.file_field(:no_such_how, 'some_value').exists? }.should raise_error(MissingWayOfFindingObjectException)
end
end
# Attribute methods
describe "#class_name" do
it "returns the class attribute if the text field exists" do
browser.file_field(:index, 0).class_name.should == "portrait"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).class_name }.should raise_error(UnknownObjectException)
end
end
describe "#id" do
it "returns the id attribute if the text field exists" do
browser.file_field(:index, 0).id.should == "new_user_portrait"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).id }.should raise_error(UnknownObjectException)
end
end
describe "#name" do
it "returns the name attribute if the text field exists" do
browser.file_field(:index, 0).name.should == "new_user_portrait"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).name }.should raise_error(UnknownObjectException)
end
end
describe "#title" do
it "returns the title attribute if the text field exists" do
browser.file_field(:id, "new_user_portrait").title.should == "Smile!"
end
end
describe "#type" do
it "returns the type attribute if the text field exists" do
browser.file_field(:index, 0).type.should == "file"
end
it "raises UnknownObjectException if the text field doesn't exist" do
lambda { browser.file_field(:index, 1337).type }.should raise_error(UnknownObjectException)
end
end
describe "#respond_to?" do
it "returns true for all attribute methods" do
browser.file_field(:index, 0).should respond_to(:class_name)
browser.file_field(:index, 0).should respond_to(:id)
browser.file_field(:index, 0).should respond_to(:name)
browser.file_field(:index, 0).should respond_to(:title)
browser.file_field(:index, 0).should respond_to(:type)
browser.file_field(:index, 0).should respond_to(:value)
end
end
# Manipulation methods
describe "#set" do
not_compliant_on [:webdriver, :iphone] do
it "is able to set a file path in the field and click the upload button and fire the onchange event" do
browser.goto WatirSpec.url_for("forms_with_input_elements.html", :needs_server => true)
path = File.expand_path(__FILE__)
element = browser.file_field(:name, "new_user_portrait")
element.set path
element.value.should include(File.basename(path)) # only some browser will return the full path
messages.first.should include(File.basename(path))
browser.button(:name, "new_user_submit").click
end
bug "https://github.com/detro/ghostdriver/issues/183", :phantomjs do
it "raises an error if the file does not exist" do
lambda {
browser.file_field.set(File.join(Dir.tmpdir, 'unlikely-to-exist'))
}.should raise_error(Errno::ENOENT)
end
end
end
end
describe "#value=" do
not_compliant_on [:webdriver, :iphone] do
bug "https://github.com/detro/ghostdriver/issues/183", :phantomjs do
it "is able to set a file path in the field and click the upload button and fire the onchange event" do
browser.goto WatirSpec.url_for("forms_with_input_elements.html", :needs_server => true)
path = File.expand_path(__FILE__)
element = browser.file_field(:name, "new_user_portrait")
element.value = path
element.value.should include(File.basename(path)) # only some browser will return the full path
end
end
end
not_compliant_on :internet_explorer, [:webdriver, :chrome], [:webdriver, :iphone] do
bug "https://github.com/detro/ghostdriver/issues/183", :phantomjs do
# for chrome, the check also happens in the driver
it "does not raise an error if the file does not exist" do
path = File.join(Dir.tmpdir, 'unlikely-to-exist')
browser.file_field.value = path
expected = path
expected.gsub!("/", "\\") if WatirSpec.platform == :windows
browser.file_field.value.should == expected
end
it "does not alter its argument" do
value = '/foo/bar'
browser.file_field.value = value
value.should == '/foo/bar'
end
end
end
end
end
|
# frozen_string_literal: true
require_relative "../acceptance_test"
# :stopdoc:
class CategoriesTest < AcceptanceTest
test "edit" do
FactoryBot.create(:discipline)
Calculations::V3::Calculation.create!(
members_only: true,
name: "Ironman",
points_for_place: 1
)
login_as FactoryBot.create(:administrator)
visit "/calculations"
end
end
Fix name clash in test
# frozen_string_literal: true
require_relative "../acceptance_test"
# :stopdoc:
class Admin::CategoriesTest < AcceptanceTest
test "edit" do
FactoryBot.create(:discipline)
Calculations::V3::Calculation.create!(
members_only: true,
name: "Ironman",
points_for_place: 1
)
login_as FactoryBot.create(:administrator)
visit "/calculations"
end
end
|
require 'rake-tasks/checks.rb'
namespace :se_ide do
base_ide_dir = File.expand_path(File.dirname(Dir.glob("Rakefile")[0]))
files = []
task :setup_proxy do
if unix?
# the files in core -- except for the scripts directory which already exists in the target
ln_s Dir.glob(base_ide_dir + "/common/src/js/core/*").select { |fn| fn != base_ide_dir + "/common/src/js/core/scripts" },
"ide/src/extension/content/selenium"
# and now the script dir
ln_s Dir.glob(base_ide_dir + "/common/src/js/core/scripts/*").select { |fn| fn != base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js"},
"ide/src/extension/content/selenium/scripts"
mkdir "ide/src/extension/content-files"
ln_s Dir.glob(base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js"), "ide/src/extension/content-files"
elsif windows?
# the files in core -- except for the scripts directory which already exists in the target
f = Dir.glob(base_ide_dir + "/common/src/js/core/*").select { |fn| fn != base_ide_dir + "/common/src/js/core/scripts" }
f.each do |c|
files << c.gsub(base_ide_dir + "/common/src/js/core/", "ide/src/extension/content/selenium/")
cp_r c, "ide/src/extension/content/selenium", :remove_destination => true
end
# and now the script dir
f = Dir.glob(base_ide_dir + "/common/src/js/core/scripts/*").select { |fn| fn != base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js"}
f.each do |c|
files << c.gsub(base_ide_dir + "/common/src/js/core/scripts", "ide/src/extension/content/selenium/scripts")
cp c, "ide/src/extension/content/selenium/scripts"
end
# and lastly the scriptrunner
mkdir "ide/src/extension/content-files"
f = Dir.glob(base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js")
f.each do |c|
files << base_ide_dir + "ide/src/extension/content-files/selenium-testrunner.js"
cp c, "ide/src/extension/content-files"
end
end
# jsunit
if unix?
ln_s Dir.glob(base_ide_dir + "/common/src/js/jsunit"), "ide/src/extension/content/", :force => true
elsif windows?
f = Dir.glob(base_ide_dir + "/common/src/js/jsunit")
f.each do |c|
files << c.gsub(base_ide_dir + "/common/src/js/", "ide/src/extension/content/")
cp_r c, "ide/src/extension/content/jsunit", :remove_destination => true
end
end
# autocomplete
# note: xpt files cannot be symlinks
cp base_ide_dir + "/ide/prebuilt/SeleniumIDEGenericAutoCompleteSearch.xpt", "ide/src/extension/components" unless File.exists?("ide/src/extension/components/SeleniumIDEGenericAutoCompleteSearch.xpt")
if windows?
listoffiles = File.new(base_ide_dir + "/proxy_files.txt", "w")
files.each do |f|
listoffiles.write(f + "\r\n")
end
listoffiles.close()
end
end
task :remove_proxy do
if unix?
Dir.glob("ide/**/*").select { |fn| rm fn if File.symlink?(fn) }
elsif windows?
listoffiles = File.open(base_ide_dir + "/proxy_files.txt", "r")
listoffiles.each do |f|
if File.directory?(f.strip())
rm_rf f.strip()
elsif File.file?(f.strip())
rm f.strip()
end
end
listoffiles.close()
rm base_ide_dir + "/proxy_files.txt"
end
rmdir "ide/src/extension/content-files"
rm "ide/src/extension/components/SeleniumIDEGenericAutoCompleteSearch.xpt"
end
end
AdamGoucher - fixing the proxy tasks for ide given the new user-extensions.js that lets the testrunner work
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@8479 07704840-8298-11de-bf8c-fd130f914ac9
require 'rake-tasks/checks.rb'
namespace :se_ide do
base_ide_dir = File.expand_path(File.dirname(Dir.glob("Rakefile")[0]))
files = []
task :setup_proxy do
if unix?
# the files in core -- except for the scripts directory which already exists in the target
ln_s Dir.glob(base_ide_dir + "/common/src/js/core/*").select { |fn| fn != base_ide_dir + "/common/src/js/core/scripts" },
"ide/src/extension/content/selenium"
# and now the script dir
ln_s Dir.glob(base_ide_dir + "/common/src/js/core/scripts/*").select { |fn| not [base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js", base_ide_dir + "/common/src/js/core/scripts/user-extensions.js"].include?(fn)},
"ide/src/extension/content/selenium/scripts"
mkdir "ide/src/extension/content-files"
ln_s Dir.glob(base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js"), "ide/src/extension/content-files"
elsif windows?
# the files in core -- except for the scripts directory which already exists in the target
f = Dir.glob(base_ide_dir + "/common/src/js/core/*").select { |fn| fn != base_ide_dir + "/common/src/js/core/scripts" }
f.each do |c|
files << c.gsub(base_ide_dir + "/common/src/js/core/", "ide/src/extension/content/selenium/")
cp_r c, "ide/src/extension/content/selenium", :remove_destination => true
end
# and now the script dir
f = Dir.glob(base_ide_dir + "/common/src/js/core/scripts/*").select { |fn| not [base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js", base_ide_dir + "/common/src/js/core/scripts/user-extensions.js"].include?(fn)},
f.each do |c|
files << c.gsub(base_ide_dir + "/common/src/js/core/scripts", "ide/src/extension/content/selenium/scripts")
cp c, "ide/src/extension/content/selenium/scripts"
end
# and lastly the scriptrunner
mkdir "ide/src/extension/content-files"
f = Dir.glob(base_ide_dir + "/common/src/js/core/scripts/selenium-testrunner.js")
f.each do |c|
files << base_ide_dir + "ide/src/extension/content-files/selenium-testrunner.js"
cp c, "ide/src/extension/content-files"
end
# no, really, this lis lastly; user-extensions.js
mkdir "ide/src/extension/content-files"
f = Dir.glob(base_ide_dir + "/common/src/js/core/scripts/user-extensions.js")
f.each do |c|
files << base_ide_dir + "ide/src/extension/content-files/user-extensions.js"
cp c, "ide/src/extension/content-files"
end
end
# jsunit
if unix?
ln_s Dir.glob(base_ide_dir + "/common/src/js/jsunit"), "ide/src/extension/content/", :force => true
elsif windows?
f = Dir.glob(base_ide_dir + "/common/src/js/jsunit")
f.each do |c|
files << c.gsub(base_ide_dir + "/common/src/js/", "ide/src/extension/content/")
cp_r c, "ide/src/extension/content/jsunit", :remove_destination => true
end
end
# autocomplete
# note: xpt files cannot be symlinks
cp base_ide_dir + "/ide/prebuilt/SeleniumIDEGenericAutoCompleteSearch.xpt", "ide/src/extension/components" unless File.exists?("ide/src/extension/components/SeleniumIDEGenericAutoCompleteSearch.xpt")
if windows?
listoffiles = File.new(base_ide_dir + "/proxy_files.txt", "w")
files.each do |f|
listoffiles.write(f + "\r\n")
end
listoffiles.close()
end
end
task :remove_proxy do
if unix?
Dir.glob("ide/**/*").select { |fn| rm fn if File.symlink?(fn) }
elsif windows?
listoffiles = File.open(base_ide_dir + "/proxy_files.txt", "r")
listoffiles.each do |f|
if File.directory?(f.strip())
rm_rf f.strip()
elsif File.file?(f.strip())
rm f.strip()
end
end
listoffiles.close()
rm base_ide_dir + "/proxy_files.txt"
end
rmdir "ide/src/extension/content-files"
rm "ide/src/extension/components/SeleniumIDEGenericAutoCompleteSearch.xpt"
end
end |
namespace :apis do
desc 'Generate a new android_api.xml from the current api descriptions.'
task :compile do
require 'rakelib/android_api_gen'
all = ApiTag.compile_platforms
print "Writing results..."
all.write_to("lib/java_class_gen/android_api.xml")
puts "done."
end
desc 'Pull a version of the API descriptions onto the local drive.'
task :get do
require 'rakelib/android_api_gen'
require 'rexml/document'
require 'open-uri'
REPOSITORY_BASE = 'https://dl-ssl.google.com/android/repository'
# Todo: Make sure there is not a newer repository
REPOSITORY_URL = "#{REPOSITORY_BASE}/repository-8.xml"
# odoT
$stdout.sync = true
mkdir('apis') unless File.exists?("apis")
print "Getting 1 (1.0)..."
file = open(Api.platform_url(1))
File.open("apis/1.xml", 'w'){|f| f << file.read}
puts "done."
doc = REXML::Document.new(open(REPOSITORY_URL))
doc.root.elements.each("sdk:platform") do |i|
number = i.elements['sdk:api-level'].text.to_i
print "Getting #{number} (#{i.elements['sdk:version'].text})..."
url = Api.platform_url(number)
if url.nil?
puts "branch unknown (set branch for current.txt)."
else
file = open(url)
File.open("apis/#{number}.#{url[-3..-1]}", 'w'){|f| f << file.read}
puts "done."
end
end
end
end
Added '.' to path if not present
namespace :apis do
desc 'Generate a new android_api.xml from the current api descriptions.'
task :compile do
$: << "." unless $:.include?(".")
require 'rakelib/android_api_gen'
all = ApiTag.compile_platforms
print "Writing results..."
all.write_to("lib/java_class_gen/android_api.xml")
puts "done."
end
desc 'Pull a version of the API descriptions onto the local drive.'
task :get do
$: << "." unless $:.include?(".")
require 'rakelib/android_api_gen'
require 'rexml/document'
require 'open-uri'
REPOSITORY_BASE = 'https://dl-ssl.google.com/android/repository'
# Todo: Make sure there is not a newer repository
REPOSITORY_URL = "#{REPOSITORY_BASE}/repository-8.xml"
# odoT
$stdout.sync = true
mkdir('apis') unless File.exists?("apis")
print "Getting 1 (1.0)..."
file = open(Api.platform_url(1))
File.open("apis/1.xml", 'w'){|f| f << file.read}
puts "done."
doc = REXML::Document.new(open(REPOSITORY_URL))
doc.root.elements.each("sdk:platform") do |i|
number = i.elements['sdk:api-level'].text.to_i
print "Getting #{number} (#{i.elements['sdk:version'].text})..."
url = Api.platform_url(number)
if url.nil?
puts "branch unknown (set branch for current.txt)."
else
file = open(url)
File.open("apis/#{number}.#{url[-3..-1]}", 'w'){|f| f << file.read}
puts "done."
end
end
end
end
|
Daedalus.blueprint do |i|
gcc = i.gcc!(Rubinius::BUILD_CONFIG[:cc],
Rubinius::BUILD_CONFIG[:cxx],
Rubinius::BUILD_CONFIG[:ldshared],
Rubinius::BUILD_CONFIG[:ldsharedxx])
# First define all flags that all code needs to be build with.
# -fno-omit-frame-pointer is needed to get a backtrace on FreeBSD.
# It is enabled by default on OS X, on the other hand, not on Linux.
# To use same build flags across platforms, it is added explicitly.
gcc.cflags << "-pipe -fPIC -fno-omit-frame-pointer -g"
# Due to a Clang bug (http://llvm.org/bugs/show_bug.cgi?id=9825),
# -mno-omit-leaf-frame-pointer is needed for Clang on Linux.
# On other combinations of platform and compiler, this flag is implicitly
# assumed from -fno-omit-frame-pointer. To use same build flags across
# platforms, -mno-omit-leaf-frame-pointer is added explicitly.
gcc.cflags << "-mno-omit-leaf-frame-pointer" if Rubinius::BUILD_CONFIG[:cc] == "clang"
# We don't need RTTI information, so disable it. This makes it possible
# to link Rubinius to an LLVM build with RTTI disabled. We also enable
# visibility-inlines-hidden for slightly smaller code size and prevents
# warnings when LLVM is also built with this flag.
gcc.cxxflags << "-fno-rtti -fvisibility-inlines-hidden"
gcc.cflags << Rubinius::BUILD_CONFIG[:system_cflags]
gcc.cflags << Rubinius::BUILD_CONFIG[:user_cflags]
gcc.cxxflags << Rubinius::BUILD_CONFIG[:system_cxxflags]
gcc.cxxflags << Rubinius::BUILD_CONFIG[:user_cxxflags]
if Rubinius::BUILD_CONFIG[:debug_build]
gcc.cflags << "-O0"
gcc.mtime_only = true
else
gcc.cflags << "-O2"
end
if ENV['POKE']
gcc.mtime_only = true
end
Rubinius::BUILD_CONFIG[:defines].each do |flag|
gcc.cflags << "-D#{flag}"
end
gcc.ldflags << "-lm"
if Rubinius::BUILD_CONFIG[:dtrace]
gcc.ldflags << "-lelf"
gcc.ldflags << "machine/dtrace/probes.o"
gcc.add_pre_link "rm -f machine/dtrace/probes.o"
blk = lambda { |files| files.select { |f| f =~ %r[machine/.*\.o$] } }
cmd = "dtrace -G -s machine/dtrace/probes.d -o machine/dtrace/probes.o %objects%"
gcc.add_pre_link(cmd, &blk)
end
make = Rubinius::BUILD_CONFIG[:build_make]
if RUBY_PLATFORM =~ /bsd/ and
Rubinius::BUILD_CONFIG[:defines].include?('HAS_EXECINFO')
gcc.ldflags << "-lexecinfo"
end
gcc.ldflags << Rubinius::BUILD_CONFIG[:system_ldflags]
gcc.ldflags << Rubinius::BUILD_CONFIG[:user_ldflags]
# Files
subdirs = %w[ class data capi util instruments instructions memory jit missing ].map do |x|
"machine/#{x}/**/*.{cpp,c}"
end
files = i.source_files "machine/*.{cpp,c}", *subdirs
Dir["machine/interpreter/*.cpp"].each do |name|
files << InstructionSourceFile.new(name)
end
perl = Rubinius::BUILD_CONFIG[:build_perl] || "perl"
src = Rubinius::BUILD_CONFIG[:sourcedir]
# Libraries
gcc.cflags << "-I#{src}/vendor/rapidjson"
ltm = i.external_lib "vendor/libtommath" do |l|
l.cflags = ["-I#{src}/vendor/libtommath"] + gcc.cflags
l.objects = [l.file("libtommath.a")]
l.to_build do |x|
x.command make
end
end
gcc.add_library ltm
files << ltm
oniguruma = i.library_group "vendor/oniguruma" do |g|
g.depends_on "config.h", "configure"
gcc.cflags.unshift "-I#{src}/vendor/oniguruma"
g.cflags = [ "-DHAVE_CONFIG_H", "-I#{src}/machine/include/capi" ]
g.cflags += gcc.cflags
g.static_library "libonig" do |l|
l.source_files "*.c", "enc/*.c"
end
g.shared_library "enc/trans/big5"
g.shared_library "enc/trans/chinese"
g.shared_library "enc/trans/emoji"
g.shared_library "enc/trans/emoji_iso2022_kddi"
g.shared_library "enc/trans/emoji_sjis_docomo"
g.shared_library "enc/trans/emoji_sjis_kddi"
g.shared_library "enc/trans/emoji_sjis_softbank"
g.shared_library "enc/trans/escape"
g.shared_library "enc/trans/gb18030"
g.shared_library "enc/trans/gbk"
g.shared_library "enc/trans/iso2022"
g.shared_library "enc/trans/japanese"
g.shared_library "enc/trans/japanese_euc"
g.shared_library "enc/trans/japanese_sjis"
g.shared_library "enc/trans/korean"
g.shared_library "enc/trans/newline"
g.shared_library "enc/trans/single_byte"
g.shared_library "enc/trans/utf8_mac"
g.shared_library "enc/trans/utf_16_32"
end
files << oniguruma
double_conversion = i.external_lib "vendor/double-conversion" do |l|
l.cflags = ["-Ivendor/double-conversion/src"] + gcc.cflags
l.objects = [l.file("libdoubleconversion.a")]
l.to_build do |x|
x.command make
end
end
gcc.add_library double_conversion
files << double_conversion
ffi = i.external_lib "vendor/libffi" do |l|
l.cflags = ["-I#{src}/vendor/libffi/include"] + gcc.cflags
l.objects = [l.file(".libs/libffi.a")]
l.to_build do |x|
x.command "sh -c './configure --disable-builddir'" unless File.exist?("Makefile")
x.command make
end
end
gcc.add_library ffi
files << ffi
if Rubinius::BUILD_CONFIG[:vendor_zlib]
zlib = i.external_lib "vendor/zlib" do |l|
l.cflags = ["-I#{src}/vendor/zlib"] + gcc.cflags
l.objects = [l.file("libz.a")]
l.to_build do |x|
unless File.exist?("Makefile") and File.exist?("zconf.h")
x.command "sh -c ./configure"
end
if Rubinius::BUILD_CONFIG[:windows]
x.command "make -f win32/Makefile.gcc"
else
x.command make
end
end
end
gcc.add_library zlib
files << zlib
else
gcc.ldflags << "-lz"
end
if Rubinius::BUILD_CONFIG[:vendor_libsodium]
sodium = i.external_lib "vendor/libsodium" do |l|
l.cflags = ["-I#{src}/vendor/libsodium/src/libsodium/include"] + gcc.cflags
l.objects = [l.file("src/libsodium/.libs/libsodium.a")]
l.to_build do |x|
unless File.exist?("Makefile")
x.command "sh -c ./configure"
end
x.command make
end
end
gcc.add_library sodium
files << sodium
end
if Rubinius::BUILD_CONFIG[:windows]
winp = i.external_lib "vendor/winpthreads" do |l|
l.cflags = ["-I#{src}/vendor/winpthreads/include"] + gcc.cflags
l.objects = [l.file("libpthread.a")]
l.to_build do |x|
x.command "sh -c ./configure" unless File.exist?("Makefile")
x.command make
end
end
gcc.add_library winp
files << winp
end
conf = Rubinius::BUILD_CONFIG[:llvm_configure]
include_dir = `#{conf} --includedir`.chomp
gcc.cflags << "-I#{include_dir}"
gcc.cxxflags << Rubinius::BUILD_CONFIG[:llvm_cxxflags]
flags = `#{conf} --cflags`.strip.split(/\s+/)
flags.keep_if { |x| x =~ /^-[DI]/ }
flags.delete_if { |x| x.index("-O") == 0 }
flags.delete_if { |x| x =~ /-D__STDC/ }
flags.delete_if { |x| x == "-DNDEBUG" }
flags.delete_if { |x| x == "-fomit-frame-pointer" }
flags.delete_if { |x| x == "-pedantic" }
flags.delete_if { |x| x == "-W" }
flags.delete_if { |x| x == "-Wextra" }
# llvm-config may leak FORTIFY_SOURCE in the CFLAGS list on certain
# platforms. If this is the case then debug builds will fail. Sadly there's
# no strict guarantee on how LLVM formats this option, hence the Regexp.
#
# For example, on CentOS the option is added as -Wp,-D_FORTIFY_SOURCE=2.
# There's no strict guarantee that I know of that it will always be this
# exact format.
if Rubinius::BUILD_CONFIG[:debug_build]
flags.delete_if { |x| x =~ /_FORTIFY_SOURCE/ }
end
flags << "-DENABLE_LLVM"
ldflags = Rubinius::BUILD_CONFIG[:llvm_ldflags]
if Rubinius::BUILD_CONFIG[:llvm_shared_objs]
objects = Rubinius::BUILD_CONFIG[:llvm_shared_objs]
else
objects = `#{conf} --libfiles`.strip.split(/\s+/)
end
if Rubinius::BUILD_CONFIG[:windows]
ldflags = ldflags.sub(%r[-L/([a-zA-Z])/], '-L\1:/')
objects.select do |f|
f.sub!(%r[^/([a-zA-Z])/], '\1:/')
File.file? f
end
end
gcc.cflags.concat flags
gcc.ldflags.concat objects
gcc.ldflags << ldflags
# Make sure to push these up front so machine/ stuff has priority
dirs = %w[ /machine /machine/include ]
gcc.cflags.unshift "#{dirs.map { |d| "-I#{src}#{d}" }.join(" ")} -I. -Imachine/test/cxxtest"
gcc.cflags << "-Wall"
gcc.cflags << "-Werror"
gcc.cflags << "-Wno-unused-function"
gcc.cflags << "-Wno-unused-parameter"
gcc.cflags << "-Wwrite-strings"
gcc.cflags << "-Wmissing-field-initializers"
gcc.cflags << "-Wcovered-switch-default"
gcc.cflags << "-D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS"
gcc.cflags << "-D_LARGEFILE_SOURCE"
gcc.cflags << "-D_FILE_OFFSET_BITS=64"
cli = files.dup
cli << i.source_file("machine/drivers/cli.cpp")
exe = RUBY_PLATFORM =~ /mingw|mswin/ ? 'machine/vm.exe' : 'machine/vm'
i.program exe, *cli
test_files = files.dup
test_files << i.source_file("machine/test/runner.cpp") { |f|
tests = Dir["machine/test/**/test_*.hpp"].sort
f.depends_on tests
f.autogenerate do |x|
x.command("#{perl} machine/test/cxxtest/cxxtestgen.pl --error-printer --have-eh " +
"--abort-on-fail -include=machine/test/test_setup.h -o machine/test/runner.cpp " +
tests.join(' '))
end
}
i.program "machine/test/runner", *test_files
end
Use llvm-config --libs instead of --libfiles.
Daedalus.blueprint do |i|
gcc = i.gcc!(Rubinius::BUILD_CONFIG[:cc],
Rubinius::BUILD_CONFIG[:cxx],
Rubinius::BUILD_CONFIG[:ldshared],
Rubinius::BUILD_CONFIG[:ldsharedxx])
# First define all flags that all code needs to be build with.
# -fno-omit-frame-pointer is needed to get a backtrace on FreeBSD.
# It is enabled by default on OS X, on the other hand, not on Linux.
# To use same build flags across platforms, it is added explicitly.
gcc.cflags << "-pipe -fPIC -fno-omit-frame-pointer -g"
# Due to a Clang bug (http://llvm.org/bugs/show_bug.cgi?id=9825),
# -mno-omit-leaf-frame-pointer is needed for Clang on Linux.
# On other combinations of platform and compiler, this flag is implicitly
# assumed from -fno-omit-frame-pointer. To use same build flags across
# platforms, -mno-omit-leaf-frame-pointer is added explicitly.
gcc.cflags << "-mno-omit-leaf-frame-pointer" if Rubinius::BUILD_CONFIG[:cc] == "clang"
# We don't need RTTI information, so disable it. This makes it possible
# to link Rubinius to an LLVM build with RTTI disabled. We also enable
# visibility-inlines-hidden for slightly smaller code size and prevents
# warnings when LLVM is also built with this flag.
gcc.cxxflags << "-fno-rtti -fvisibility-inlines-hidden"
gcc.cflags << Rubinius::BUILD_CONFIG[:system_cflags]
gcc.cflags << Rubinius::BUILD_CONFIG[:user_cflags]
gcc.cxxflags << Rubinius::BUILD_CONFIG[:system_cxxflags]
gcc.cxxflags << Rubinius::BUILD_CONFIG[:user_cxxflags]
if Rubinius::BUILD_CONFIG[:debug_build]
gcc.cflags << "-O0"
gcc.mtime_only = true
else
gcc.cflags << "-O2"
end
if ENV['POKE']
gcc.mtime_only = true
end
Rubinius::BUILD_CONFIG[:defines].each do |flag|
gcc.cflags << "-D#{flag}"
end
gcc.ldflags << "-lm"
if Rubinius::BUILD_CONFIG[:dtrace]
gcc.ldflags << "-lelf"
gcc.ldflags << "machine/dtrace/probes.o"
gcc.add_pre_link "rm -f machine/dtrace/probes.o"
blk = lambda { |files| files.select { |f| f =~ %r[machine/.*\.o$] } }
cmd = "dtrace -G -s machine/dtrace/probes.d -o machine/dtrace/probes.o %objects%"
gcc.add_pre_link(cmd, &blk)
end
make = Rubinius::BUILD_CONFIG[:build_make]
if RUBY_PLATFORM =~ /bsd/ and
Rubinius::BUILD_CONFIG[:defines].include?('HAS_EXECINFO')
gcc.ldflags << "-lexecinfo"
end
gcc.ldflags << Rubinius::BUILD_CONFIG[:system_ldflags]
gcc.ldflags << Rubinius::BUILD_CONFIG[:user_ldflags]
# Files
subdirs = %w[ class data capi util instruments instructions memory jit missing ].map do |x|
"machine/#{x}/**/*.{cpp,c}"
end
files = i.source_files "machine/*.{cpp,c}", *subdirs
Dir["machine/interpreter/*.cpp"].each do |name|
files << InstructionSourceFile.new(name)
end
perl = Rubinius::BUILD_CONFIG[:build_perl] || "perl"
src = Rubinius::BUILD_CONFIG[:sourcedir]
# Libraries
gcc.cflags << "-I#{src}/vendor/rapidjson"
ltm = i.external_lib "vendor/libtommath" do |l|
l.cflags = ["-I#{src}/vendor/libtommath"] + gcc.cflags
l.objects = [l.file("libtommath.a")]
l.to_build do |x|
x.command make
end
end
gcc.add_library ltm
files << ltm
oniguruma = i.library_group "vendor/oniguruma" do |g|
g.depends_on "config.h", "configure"
gcc.cflags.unshift "-I#{src}/vendor/oniguruma"
g.cflags = [ "-DHAVE_CONFIG_H", "-I#{src}/machine/include/capi" ]
g.cflags += gcc.cflags
g.static_library "libonig" do |l|
l.source_files "*.c", "enc/*.c"
end
g.shared_library "enc/trans/big5"
g.shared_library "enc/trans/chinese"
g.shared_library "enc/trans/emoji"
g.shared_library "enc/trans/emoji_iso2022_kddi"
g.shared_library "enc/trans/emoji_sjis_docomo"
g.shared_library "enc/trans/emoji_sjis_kddi"
g.shared_library "enc/trans/emoji_sjis_softbank"
g.shared_library "enc/trans/escape"
g.shared_library "enc/trans/gb18030"
g.shared_library "enc/trans/gbk"
g.shared_library "enc/trans/iso2022"
g.shared_library "enc/trans/japanese"
g.shared_library "enc/trans/japanese_euc"
g.shared_library "enc/trans/japanese_sjis"
g.shared_library "enc/trans/korean"
g.shared_library "enc/trans/newline"
g.shared_library "enc/trans/single_byte"
g.shared_library "enc/trans/utf8_mac"
g.shared_library "enc/trans/utf_16_32"
end
files << oniguruma
double_conversion = i.external_lib "vendor/double-conversion" do |l|
l.cflags = ["-Ivendor/double-conversion/src"] + gcc.cflags
l.objects = [l.file("libdoubleconversion.a")]
l.to_build do |x|
x.command make
end
end
gcc.add_library double_conversion
files << double_conversion
ffi = i.external_lib "vendor/libffi" do |l|
l.cflags = ["-I#{src}/vendor/libffi/include"] + gcc.cflags
l.objects = [l.file(".libs/libffi.a")]
l.to_build do |x|
x.command "sh -c './configure --disable-builddir'" unless File.exist?("Makefile")
x.command make
end
end
gcc.add_library ffi
files << ffi
if Rubinius::BUILD_CONFIG[:vendor_zlib]
zlib = i.external_lib "vendor/zlib" do |l|
l.cflags = ["-I#{src}/vendor/zlib"] + gcc.cflags
l.objects = [l.file("libz.a")]
l.to_build do |x|
unless File.exist?("Makefile") and File.exist?("zconf.h")
x.command "sh -c ./configure"
end
if Rubinius::BUILD_CONFIG[:windows]
x.command "make -f win32/Makefile.gcc"
else
x.command make
end
end
end
gcc.add_library zlib
files << zlib
else
gcc.ldflags << "-lz"
end
if Rubinius::BUILD_CONFIG[:vendor_libsodium]
sodium = i.external_lib "vendor/libsodium" do |l|
l.cflags = ["-I#{src}/vendor/libsodium/src/libsodium/include"] + gcc.cflags
l.objects = [l.file("src/libsodium/.libs/libsodium.a")]
l.to_build do |x|
unless File.exist?("Makefile")
x.command "sh -c ./configure"
end
x.command make
end
end
gcc.add_library sodium
files << sodium
end
if Rubinius::BUILD_CONFIG[:windows]
winp = i.external_lib "vendor/winpthreads" do |l|
l.cflags = ["-I#{src}/vendor/winpthreads/include"] + gcc.cflags
l.objects = [l.file("libpthread.a")]
l.to_build do |x|
x.command "sh -c ./configure" unless File.exist?("Makefile")
x.command make
end
end
gcc.add_library winp
files << winp
end
conf = Rubinius::BUILD_CONFIG[:llvm_configure]
include_dir = `#{conf} --includedir`.chomp
gcc.cflags << "-I#{include_dir}"
gcc.cxxflags << Rubinius::BUILD_CONFIG[:llvm_cxxflags]
flags = `#{conf} --cflags`.strip.split(/\s+/)
flags.keep_if { |x| x =~ /^-[DI]/ }
flags.delete_if { |x| x.index("-O") == 0 }
flags.delete_if { |x| x =~ /-D__STDC/ }
flags.delete_if { |x| x == "-DNDEBUG" }
flags.delete_if { |x| x == "-fomit-frame-pointer" }
flags.delete_if { |x| x == "-pedantic" }
flags.delete_if { |x| x == "-W" }
flags.delete_if { |x| x == "-Wextra" }
# llvm-config may leak FORTIFY_SOURCE in the CFLAGS list on certain
# platforms. If this is the case then debug builds will fail. Sadly there's
# no strict guarantee on how LLVM formats this option, hence the Regexp.
#
# For example, on CentOS the option is added as -Wp,-D_FORTIFY_SOURCE=2.
# There's no strict guarantee that I know of that it will always be this
# exact format.
if Rubinius::BUILD_CONFIG[:debug_build]
flags.delete_if { |x| x =~ /_FORTIFY_SOURCE/ }
end
flags << "-DENABLE_LLVM"
ldflags = Rubinius::BUILD_CONFIG[:llvm_ldflags]
if Rubinius::BUILD_CONFIG[:llvm_shared_objs]
objects = Rubinius::BUILD_CONFIG[:llvm_shared_objs]
else
objects = `#{conf} --libs`.strip.split(/\s+/)
end
if Rubinius::BUILD_CONFIG[:windows]
ldflags = ldflags.sub(%r[-L/([a-zA-Z])/], '-L\1:/')
objects.select do |f|
f.sub!(%r[^/([a-zA-Z])/], '\1:/')
File.file? f
end
end
gcc.cflags.concat flags
gcc.ldflags.concat objects
gcc.ldflags << ldflags
# Make sure to push these up front so machine/ stuff has priority
dirs = %w[ /machine /machine/include ]
gcc.cflags.unshift "#{dirs.map { |d| "-I#{src}#{d}" }.join(" ")} -I. -Imachine/test/cxxtest"
gcc.cflags << "-Wall"
gcc.cflags << "-Werror"
gcc.cflags << "-Wno-unused-function"
gcc.cflags << "-Wno-unused-parameter"
gcc.cflags << "-Wwrite-strings"
gcc.cflags << "-Wmissing-field-initializers"
gcc.cflags << "-Wcovered-switch-default"
gcc.cflags << "-D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS"
gcc.cflags << "-D_LARGEFILE_SOURCE"
gcc.cflags << "-D_FILE_OFFSET_BITS=64"
cli = files.dup
cli << i.source_file("machine/drivers/cli.cpp")
exe = RUBY_PLATFORM =~ /mingw|mswin/ ? 'machine/vm.exe' : 'machine/vm'
i.program exe, *cli
test_files = files.dup
test_files << i.source_file("machine/test/runner.cpp") { |f|
tests = Dir["machine/test/**/test_*.hpp"].sort
f.depends_on tests
f.autogenerate do |x|
x.command("#{perl} machine/test/cxxtest/cxxtestgen.pl --error-printer --have-eh " +
"--abort-on-fail -include=machine/test/test_setup.h -o machine/test/runner.cpp " +
tests.join(' '))
end
}
i.program "machine/test/runner", *test_files
end
|
desc 'Open the Cycript console'
task :console do
tmp = "/tmp/Cycript-AppleTV-Helpers.cy"
cycript = "cycript -p AppleTV"
helpers = File.join(File.dirname(__FILE__), File.basename(__FILE__, '.rake') + '.cy')
# First copy and load the helpers
system "cat #{helpers} | ssh #{DEVICE_HOSTNAME} 'cat > #{tmp}; #{cycript} #{tmp}'"
# Then open console
system "ssh -t #{DEVICE_HOSTNAME} '#{cycript}'"
end
Add some doc about Cycript.
# This requires Cycript to be installed on the device:
#
# $ apt-get install cycript
#
# This task then loads the helpers, defined in the file with the same path as
# this file except for the extension ‘.cy’, and then opens a ssh connection and
# attaches cycript to the AppleTV process.
desc 'Open the Cycript console'
task :console do
tmp = "/tmp/Cycript-AppleTV-Helpers.cy"
cycript = "cycript -p AppleTV"
helpers = File.join(File.dirname(__FILE__), File.basename(__FILE__, '.rake') + '.cy')
# First copy and load the helpers
system "cat #{helpers} | ssh #{DEVICE_HOSTNAME} 'cat > #{tmp}; #{cycript} #{tmp}'"
# Then open console
system "ssh -t #{DEVICE_HOSTNAME} '#{cycript}'"
end
|
# Optional publish task for Rake
begin
require 'rake/contrib/sshpublisher'
require 'rake/contrib/rubyforgepublisher'
publisher = Rake::CompositePublisher.new
publisher.add Rake::RubyForgePublisher.new('re-lib', 'jimweirich')
namespace "publish" do
desc "Publish the Documentation to RubyForge."
task :rdoc => ["rake:rdoc"] do
publisher.upload
end
end
rescue LoadError => ex
puts "#{ex.message} (#{ex.class})"
puts "No Publisher Task Available"
end
Added publish gem
# Optional publish task for Rake
begin
require 'rake/contrib/sshpublisher'
require 'rake/contrib/rubyforgepublisher'
publisher = Rake::CompositePublisher.new
publisher.add Rake::RubyForgePublisher.new('re-lib', 'jimweirich')
namespace "publish" do
desc "Publish the Documentation to RubyForge."
task :rdoc => ["rake:rdoc"] do
publisher.upload
end
desc "Publish gem re-#{Re::VERSION} to Gem Cutter"
task :gem => "rake:gem" do
sh "gem push pkg/re-#{Re::VERSION}.gem"
end
end
rescue LoadError => ex
puts "#{ex.message} (#{ex.class})"
puts "No Publisher Task Available"
end
|
#
# Cookbook Name:: mongodb
# Recipe:: mms-agent
#
# Copyright 2011, Treasure Data, Inc.
#
# All rights reserved - Do Not Redistribute
#
#
if node['mongodb']['mms_agent']['api_key'].nil?
Chef::Log.warn 'Found empty mms_agent.api_key attribute'
end
require 'fileutils'
include_recipe 'python'
include_recipe 'mongodb::mongo_gem'
# munin-node for hardware info
package node['mongodb']['mms_agent']['munin_package'] do
action :install
only_if { node['mongodb']['mms_agent']['install_munin'] }
end
# python dependencies
python_pip 'pymongo' do
version node['mongodb']['mms_agent']['pymongo_version']
action :install
end
# download, and unzip if it's changed
package 'unzip'
user node[:mongodb][:mms_agent][:user] do
home node[:mongodb][:mms_agent][:install_dir]
supports :manage_home => true
action :create
end
directory node['mongodb']['mms_agent']['install_dir'] do
user node['mongodb']['mms_agent']['user']
group node['mongodb']['mms_agent']['group']
recursive true
action :create
end
directory ::File.dirname(node['mongodb']['mms_agent']['log_dir']) do
user node['mongodb']['mms_agent']['user']
group node['mongodb']['mms_agent']['group']
recursive true
action :create
end
remote_file "#{Chef::Config[:file_cache_path]}/mms-monitoring-agent.zip" do
source node['mongodb']['mms_agent']['install_url']
# irrelevant because of https://jira.mongodb.org/browse/MMS-1495
checksum node['mongodb']['mms_agent']['checksum'] if node['mongodb']['mms_agent'].key?(:checksum)
notifies :run, 'bash[unzip mms-monitoring-agent]', :immediately
end
bash 'unzip mms-monitoring-agent' do
code <<-EOS
rm -rf #{node['mongodb']['mms_agent']['install_dir']}
unzip -o -d #{::File.dirname(node['mongodb']['mms_agent']['install_dir'])} #{Chef::Config[:file_cache_path]}/mms-monitoring-agent.zip"
chown -R #{node['mongodb']['mms_agent']['user']}
chgrp -R #{node['mongodb']['mms_agent']['group']}
EOS
action :nothing
only_if do
def checksum_zip_contents(zipfile)
require 'zip/filesystem'
require 'digest'
files = Zip::File.open(zipfile).collect.reject { |f| f.name_is_directory? }.sort
content = files.map { |f| f.get_input_stream.read }.join
Digest::SHA256.hexdigest content
end
new_checksum = checksum_zip_contents("#{Chef::Config[:file_cache_path]}/mms-monitoring-agent.zip")
existing_checksum = node['mongodb']['mms_agent'].key?(:checksum) ? node['mongodb']['mms_agent']['checksum'] : 'NONE'
Chef::Log.debug "new checksum = #{new_checksum}, expected = #{existing_checksum}"
should_install = !File.exist?("#{node['mongodb']['mms_agent']['install_dir']}/settings.py") || new_checksum != existing_checksum
# update the expected checksum in chef, for reference
node.set['mongodb']['mms_agent']['checksum'] = new_checksum
should_install
end
end
# runit and agent logging
directory node['mongodb']['mms_agent']['log_dir'] do
owner node[:mongodb][:mms_agent][:user]
group node[:mongodb][:mms_agent][:group]
action :create
recursive true
end
include_recipe 'runit::default'
mms_agent_service = runit_service 'mms-agent' do
template_name 'mms-agent'
cookbook 'mongodb'
options(
:mms_agent_dir => node['mongodb']['mms_agent']['install_dir'],
:mms_agent_log_dir => node['mongodb']['mms_agent']['log_dir'],
:mms_agent_user => node['mongodb']['mms_agent']['user'],
:mms_agent_group => node['mongodb']['mms_agent']['group']
)
action :nothing
end
# update settings.py and restart the agent if there were any key changes
ruby_block 'modify settings.py' do
block do
orig_s = ''
open("#{node['mongodb']['mms_agent']['install_dir']}/settings.py") do |f|
orig_s = f.read
end
s = orig_s
s = s.gsub(/@MMS_SERVER@/, "#{node['mongodb']['mms_agent']['mms_server']}")
s = s.gsub(/@API_KEY@/, "#{node['mongodb']['mms_agent']['api_key']}")
# python uses True/False not true/false
s = s.gsub(/enableMunin = .*/, "enableMunin = #{node['mongodb']['mms_agent']['enable_munin'] ? "True" : "False"}")
s = s.gsub(/@DEFAULT_REQUIRE_VALID_SERVER_CERTIFICATES@/, "#{node['mongodb']['mms_agent']['require_valid_server_cert'] ? "True" : "False"}")
if s != orig_s
Chef::Log.debug 'Settings changed, overwriting and restarting service'
open("#{node['mongodb']['mms_agent']['install_dir']}/settings.py", 'w') do |f|
f.puts(s)
end
# update the agent version in chef, for reference
mms_agent_version = /settingsAgentVersion = "(.*)"/.match(s)[1]
node['mongodb']['mms_agent']['version']= mms_agent_version
notifies :enable, mms_agent_service, :delayed
notifies :restart, mms_agent_service, :delayed
end
end
end
remove extraneous quote from unzip, consolidate chown/chgrp and give it a directory to work with, need to force set
#
# Cookbook Name:: mongodb
# Recipe:: mms-agent
#
# Copyright 2011, Treasure Data, Inc.
#
# All rights reserved - Do Not Redistribute
#
#
if node['mongodb']['mms_agent']['api_key'].nil?
Chef::Log.warn 'Found empty mms_agent.api_key attribute'
end
require 'fileutils'
include_recipe 'python'
include_recipe 'mongodb::mongo_gem'
# munin-node for hardware info
package node['mongodb']['mms_agent']['munin_package'] do
action :install
only_if { node['mongodb']['mms_agent']['install_munin'] }
end
# python dependencies
python_pip 'pymongo' do
version node['mongodb']['mms_agent']['pymongo_version']
action :install
end
# download, and unzip if it's changed
package 'unzip'
user node[:mongodb][:mms_agent][:user] do
home node[:mongodb][:mms_agent][:install_dir]
supports :manage_home => true
action :create
end
directory node['mongodb']['mms_agent']['install_dir'] do
user node['mongodb']['mms_agent']['user']
group node['mongodb']['mms_agent']['group']
recursive true
action :create
end
directory ::File.dirname(node['mongodb']['mms_agent']['log_dir']) do
user node['mongodb']['mms_agent']['user']
group node['mongodb']['mms_agent']['group']
recursive true
action :create
end
remote_file "#{Chef::Config[:file_cache_path]}/mms-monitoring-agent.zip" do
source node['mongodb']['mms_agent']['install_url']
# irrelevant because of https://jira.mongodb.org/browse/MMS-1495
checksum node['mongodb']['mms_agent']['checksum'] if node['mongodb']['mms_agent'].key?(:checksum)
notifies :run, 'bash[unzip mms-monitoring-agent]', :immediately
end
bash 'unzip mms-monitoring-agent' do
code <<-EOS
rm -rf #{node['mongodb']['mms_agent']['install_dir']}
unzip -o -d #{::File.dirname(node['mongodb']['mms_agent']['install_dir'])} #{Chef::Config[:file_cache_path]}/mms-monitoring-agent.zip
chown -R #{node['mongodb']['mms_agent']['user']}:#{node['mongodb']['mms_agent']['group']} #{::File.dirname(node['mongodb']['mms_agent']['install_dir'])}
EOS
action :nothing
only_if do
def checksum_zip_contents(zipfile)
require 'zip/filesystem'
require 'digest'
files = Zip::File.open(zipfile).collect.reject { |f| f.name_is_directory? }.sort
content = files.map { |f| f.get_input_stream.read }.join
Digest::SHA256.hexdigest content
end
new_checksum = checksum_zip_contents("#{Chef::Config[:file_cache_path]}/mms-monitoring-agent.zip")
existing_checksum = node['mongodb']['mms_agent'].key?(:checksum) ? node['mongodb']['mms_agent']['checksum'] : 'NONE'
Chef::Log.debug "new checksum = #{new_checksum}, expected = #{existing_checksum}"
should_install = !File.exist?("#{node['mongodb']['mms_agent']['install_dir']}/settings.py") || new_checksum != existing_checksum
# update the expected checksum in chef, for reference
node.set['mongodb']['mms_agent']['checksum'] = new_checksum
should_install
end
end
# runit and agent logging
directory node['mongodb']['mms_agent']['log_dir'] do
owner node[:mongodb][:mms_agent][:user]
group node[:mongodb][:mms_agent][:group]
action :create
recursive true
end
include_recipe 'runit::default'
mms_agent_service = runit_service 'mms-agent' do
template_name 'mms-agent'
cookbook 'mongodb'
options(
:mms_agent_dir => node['mongodb']['mms_agent']['install_dir'],
:mms_agent_log_dir => node['mongodb']['mms_agent']['log_dir'],
:mms_agent_user => node['mongodb']['mms_agent']['user'],
:mms_agent_group => node['mongodb']['mms_agent']['group']
)
action :nothing
end
# update settings.py and restart the agent if there were any key changes
ruby_block 'modify settings.py' do
block do
orig_s = ''
open("#{node['mongodb']['mms_agent']['install_dir']}/settings.py") do |f|
orig_s = f.read
end
s = orig_s
s = s.gsub(/@MMS_SERVER@/, "#{node['mongodb']['mms_agent']['mms_server']}")
s = s.gsub(/@API_KEY@/, "#{node['mongodb']['mms_agent']['api_key']}")
# python uses True/False not true/false
s = s.gsub(/enableMunin = .*/, "enableMunin = #{node['mongodb']['mms_agent']['enable_munin'] ? "True" : "False"}")
s = s.gsub(/@DEFAULT_REQUIRE_VALID_SERVER_CERTIFICATES@/, "#{node['mongodb']['mms_agent']['require_valid_server_cert'] ? "True" : "False"}")
if s != orig_s
Chef::Log.debug 'Settings changed, overwriting and restarting service'
open("#{node['mongodb']['mms_agent']['install_dir']}/settings.py", 'w') do |f|
f.puts(s)
end
# update the agent version in chef, for reference
mms_agent_version = /settingsAgentVersion = "(.*)"/.match(s)[1]
node.set['mongodb']['mms_agent']['version'] = mms_agent_version
notifies :enable, mms_agent_service, :delayed
notifies :restart, mms_agent_service, :delayed
end
end
end
|
# install the mongo ruby gem at compile time to make it globally available
if(Gem.const_defined?("Version") and Gem::Version.new(Chef::VERSION) < Gem::Version.new('10.12.0'))
gem_package 'mongo' do
action :nothing
end.run_action(:install)
Gem.clear_paths
else
chef_gem 'mongo' do
action :install
end
end
install bson_ext with mongo gem to suppress warning
# install the mongo and bson_ext ruby gems at compile time to make them globally available
gems = 'mongo', 'bson_ext'
gems.each do |g|
if Gem.const_defined?("Version") and Gem::Version.new(Chef::VERSION) < Gem::Version.new('10.12.0')
gem_package g do
action :nothing
end.run_action(:install)
Gem.clear_paths
else
chef_gem g do
action :install
end
end
end
|
include_recipe "zabbix::common"
# Install nginx and disable default site
node.override['nginx']['default_site_enabled'] = false
node.override['php-fpm']['pool']['www']['listen'] = node['zabbix']['web']['php']['fastcgi_listen']
include_recipe "php-fpm"
include_recipe "nginx"
# Install php-fpm to execute PHP code from nginx
include_recipe "php-fpm"
case node['platform_family']
when "debian"
%w{ php5-mysql php5-gd }.each do |pck|
package pck do
action :install
notifies :restart, "service[nginx]"
end
end
when "rhel"
if node['platform_version'].to_f < 6.0
%w{ php53-mysql php53-gd php53-bcmath php53-mbstring }.each do |pck|
package pck do
action :install
notifies :restart, "service[nginx]"
end
end
else
%w{ php-mysql php-gd php-bcmath php-mbstring }.each do |pck|
package pck do
action :install
notifies :restart, "service[nginx]"
end
end
end
end
zabbix_source "extract_zabbix_web" do
branch node['zabbix']['server']['branch']
version node['zabbix']['server']['version']
source_url node['zabbix']['server']['source_url']
code_dir node['zabbix']['src_dir']
target_dir "zabbix-#{node['zabbix']['server']['version']}"
install_dir node['zabbix']['install_dir']
action :extract_only
end
# Link to the web interface version
link node['zabbix']['web_dir'] do
to "#{node['zabbix']['src_dir']}/zabbix-#{node['zabbix']['server']['version']}/frontends/php"
end
conf_dir = ::File.join(node['zabbix']['src_dir'], "zabbix-#{node['zabbix']['server']['version']}", "frontends", "php", "conf")
directory conf_dir do
owner node['nginx']['user']
group node['nginx']['group']
mode "0755"
action :create
end
# install zabbix PHP config file
template ::File.join(conf_dir, "zabbix.conf.php") do
source "zabbix_web.conf.php.erb"
owner "root"
group "root"
mode "754"
notifies :restart, "service[php-fpm]", :delayed
end
# install host for zabbix
template "/etc/nginx/sites-available/zabbix" do
source "zabbix_nginx.erb"
owner "root"
group "root"
mode "754"
variables ({
:server_name => node['zabbix']['web']['fqdn'],
:php_settings => node['zabbix']['web']['php']['settings'],
:web_port => node['zabbix']['web']['port'],
:web_dir => node['zabbix']['web_dir'],
:fastcgi_listen => node['zabbix']['web']['php']['fastcgi_listen']
})
notifies :reload, "service[nginx]"
end
nginx_site "zabbix"
Add missing variables in zabbix.conf.php template generation
must fix #94
include_recipe "zabbix::common"
# Install nginx and disable default site
node.override['nginx']['default_site_enabled'] = false
node.override['php-fpm']['pool']['www']['listen'] = node['zabbix']['web']['php']['fastcgi_listen']
include_recipe "php-fpm"
include_recipe "nginx"
# Install php-fpm to execute PHP code from nginx
include_recipe "php-fpm"
case node['platform_family']
when "debian"
%w{ php5-mysql php5-gd }.each do |pck|
package pck do
action :install
notifies :restart, "service[nginx]"
end
end
when "rhel"
if node['platform_version'].to_f < 6.0
%w{ php53-mysql php53-gd php53-bcmath php53-mbstring }.each do |pck|
package pck do
action :install
notifies :restart, "service[nginx]"
end
end
else
%w{ php-mysql php-gd php-bcmath php-mbstring }.each do |pck|
package pck do
action :install
notifies :restart, "service[nginx]"
end
end
end
end
zabbix_source "extract_zabbix_web" do
branch node['zabbix']['server']['branch']
version node['zabbix']['server']['version']
source_url node['zabbix']['server']['source_url']
code_dir node['zabbix']['src_dir']
target_dir "zabbix-#{node['zabbix']['server']['version']}"
install_dir node['zabbix']['install_dir']
action :extract_only
end
# Link to the web interface version
link node['zabbix']['web_dir'] do
to "#{node['zabbix']['src_dir']}/zabbix-#{node['zabbix']['server']['version']}/frontends/php"
end
conf_dir = ::File.join(node['zabbix']['src_dir'], "zabbix-#{node['zabbix']['server']['version']}", "frontends", "php", "conf")
directory conf_dir do
owner node['nginx']['user']
group node['nginx']['group']
mode "0755"
action :create
end
# install zabbix PHP config file
template ::File.join(conf_dir, "zabbix.conf.php") do
source "zabbix_web.conf.php.erb"
owner "root"
group "root"
mode "754"
variables (
:database => node['zabbix']['database'],
:server => node['zabbix']['server']
)
notifies :restart, "service[php-fpm]", :delayed
end
# install host for zabbix
template "/etc/nginx/sites-available/zabbix" do
source "zabbix_nginx.erb"
owner "root"
group "root"
mode "754"
variables ({
:server_name => node['zabbix']['web']['fqdn'],
:php_settings => node['zabbix']['web']['php']['settings'],
:web_port => node['zabbix']['web']['port'],
:web_dir => node['zabbix']['web_dir'],
:fastcgi_listen => node['zabbix']['web']['php']['fastcgi_listen']
})
notifies :reload, "service[nginx]"
end
nginx_site "zabbix"
|
#
# Cookbook Name:: appserver
# Recipe:: webserver
#
# Set deploy_usr
deploy_usr = 'vagrant'
def chef_solo_search_installed?
klass = ::Search.const_get('Helper')
return klass.is_a?(Class)
rescue NameError
return false
end
unless Chef::Config[:solo] && !chef_solo_search_installed?
search(:users, 'id:deploy NOT action:remove').each do |u|
deploy_usr = u['id']
end
end
# Compass
include_recipe 'compass'
# Node JS & packages
include_recipe 'nodejs'
nodejs_npm 'bower'
nodejs_npm 'gulp'
# PHP FPM
package 'php5-fpm' do
action :install
end
service 'php-fpm' do
provider ::Chef::Provider::Service::Upstart
service_name 'php5-fpm'
supports enable: true, start: true, stop: true, restart: true
# :reload doesnt work on ubuntu 14.04 because of a bug...
action [:enable, :start]
end
# PHP with plugins
%w(php5 php5-cli php5-mysql php5-curl php5-mcrypt php5-gd imagemagick php5-imagick).each do |pkg|
package pkg do
action :install
end
end
template '/etc/php5/fpm/php.ini' do
source 'php.ini.erb'
owner 'root'
group 'root'
mode '0644'
notifies :restart, 'service[php-fpm]'
end
template '/etc/php5/mods-available/opcache.ini' do
source 'opcache.ini.erb'
owner 'root'
group 'root'
mode '0644'
notifies :restart, 'service[php-fpm]'
end
execute 'Enable Mcrypt' do
command 'php5enmod mcrypt'
action :run
notifies :restart, 'service[php-fpm]'
end
# Upgrade or install composer
execute 'Upgrade Composer' do
command 'composer self-update'
only_if { ::File.exist?('/usr/local/bin/composer') }
action :run
end
execute 'Install Composer' do # ~FC041
command 'curl -sS https://getcomposer.org/installer | php;mv composer.phar /usr/local/bin/composer'
not_if { ::File.exist?('/usr/local/bin/composer') }
action :run
end
# NGINX install
include_recipe 'nginx::server'
directory '/var/www' do
owner deploy_usr
group 'sysadmin'
mode '0775'
action :create
not_if { ::File.directory?('/var/www') }
end
node['nginx']['sites'].each do |site|
webroot_path = "#{site['base_path']}/#{site['webroot_subpath']}"
git_path = "#{site['base_path']}/#{site['git_subpath']}" if site['git']
composer_path = "#{site['base_path']}/#{site['composer_subpath']}" if site['composer_install']
artisan_path = "#{site['base_path']}/#{site['artisan_subpath']}" if site['artisan_migrate']
compass_path = "#{site['base_path']}/#{site['compass_subpath']}" if site['compass_compile']
npm_path = "#{site['base_path']}/#{site['npm_subpath']}" if site['npm_install']
bower_path = "#{site['base_path']}/#{site['bower_subpath']}" if site['bower_install']
gulp_path = "#{site['base_path']}/#{site['gulp_subpath']}" if site['gulp_run']
# Create ssl cert files
if site['ssl']
directory "#{node['nginx']['dir']}/ssl" do
owner 'root'
group 'root'
mode '0775'
action :create
not_if { ::File.directory?("#{node['nginx']['dir']}/ssl") }
end
file "#{node['nginx']['dir']}/ssl/#{site['name']}.crt" do
content site['ssl_crt']
owner 'root'
group 'root'
mode '0400'
not_if { ::File.exist?("#{node['nginx']['dir']}/ssl/#{site['name']}/.crt") }
end
file "#{node['nginx']['dir']}/ssl/#{site['name']}.key" do
content site['ssl_key']
owner 'root'
group 'root'
mode '0400'
not_if { ::File.exist?("#{node['nginx']['dir']}/ssl/#{site['name']}/.crt") }
end
end
# Set up nginx server block
custom_data = {
'environment' => site['environment'],
'db_host' => site['db_host'],
'db_database' => site['db_database'],
'db_username' => site['db_username'],
'db_password' => site['db_password'],
'ssl' => site['ssl'],
'ssl_crt' => "#{node['nginx']['dir']}/ssl/#{site['name']}.crt",
'ssl_key' => "#{node['nginx']['dir']}/ssl/#{site['name']}.key"
}
nginx_site site['name'] do # ~FC022
listen '*:80'
host site['host']
root webroot_path
index site['index']
location site['location']
phpfpm site['phpfpm']
custom_data custom_data
template_cookbook site['template_cookbook']
template_source site['template_source']
action [:create, :enable]
not_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
notifies :restart, 'service[php-fpm]'
notifies :restart, 'service[nginx]'
notifies :sync, "git[Syncing git repository for #{site['name']}]"
notifies :run, "execute[Composer install #{site['name']}]"
notifies :run, "execute[Artisan migrate #{site['name']}]"
end
# Sync with git repository
git "Syncing git repository for #{site['name']}" do
destination git_path
repository site['git_repo']
revision site['git_branch']
action :sync
user deploy_usr
ssh_wrapper "/home/#{deploy_usr}/git_wrapper.sh"
only_if { site['git'] && ::File.exist?("/home/#{deploy_usr}/.ssh/git_rsa") }
only_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
notifies :run, "execute[Composer install #{site['name']} after git sync]"
notifies :run, "execute[Artisan migrate #{site['name']} after git sync]"
notifies :compile, "compass_project[Compile sass for #{site['name']} after git sync]", :immediately
notifies :run, "execute[Npm install #{site['name']} after git sync]"
notifies :run, "ruby_block[Set writeable dirs for #{site['name']} after git sync]"
end
# Composer install triggered by git sync
execute "Composer install #{site['name']} after git sync" do
command "composer install -n -d #{composer_path}"
action :nothing
user deploy_usr
only_if { site['composer_install'] }
only_if { ::File.directory?(composer_path) }
notifies :run, "execute[Artisan migrate #{site['name']} after composer]"
end
# Composer install without git
execute "Composer install #{site['name']}" do
command "composer install -n -d #{composer_path}"
action :run
user deploy_usr
only_if { site['composer_install'] }
only_if { ::File.directory?(composer_path) }
only_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
not_if { site['git'] }
notifies :run, "execute[Artisan migrate #{site['name']} after composer]"
end
# Artisan migrate triggered by composer install
execute "Artisan migrate #{site['name']} after composer" do
command "php #{artisan_path} --env=#{site['environment']} migrate"
action :nothing
user deploy_usr
only_if { site['artisan_migrate'] }
only_if { ::File.directory?(artisan_path) }
end
# Artisan migrate after git, when not running composer install
execute "Artisan migrate #{site['name']} after git sync" do
command "php #{artisan_path} --env=#{site['environment']} migrate"
action :nothing
user deploy_usr
only_if { site['artisan_migrate'] }
only_if { ::File.directory?(artisan_path) }
not_if { site['composer_install'] }
end
# Artisan migrate without either composer or git
execute "Artisan migrate #{site['name']}" do
command "php #{artisan_path} --env=#{site['environment']} migrate"
action :run
user deploy_usr
only_if { site['artisan_migrate'] }
only_if { ::File.directory?(artisan_path) }
only_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
not_if { site['composer_install'] }
not_if { site['git'] }
end
# Compass compile without git
compass_project "Compile sass for #{site['name']}" do
path compass_path
action :compile
user deploy_usr
only_if { site['compass_compile'] }
only_if { ::File.directory?(compass_path) }
not_if { site['git'] }
end
# Compass compile triggered by git
compass_project "Compile sass for #{site['name']} after git sync" do
path compass_path
action :nothing
user deploy_usr
only_if { site['compass_compile'] }
only_if { ::File.directory?(compass_path) }
end
# Npm install without git
execute "Npm install #{site['name']}" do
cwd npm_path
command 'npm install'
action :run
user deploy_usr
only_if { site['npm_install'] }
only_if { ::File.directory?(npm_path) }
not_if { site['git'] }
notifies :run, "execute[Bower install #{site['name']}]"
notifies :run, "execute[Gulp #{site['name']}]"
end
# Npm install triggered by git
execute "Npm install #{site['name']} after git sync" do
cwd npm_path
command 'npm install --silent'
action :nothing
user deploy_usr
only_if { site['npm_install'] }
only_if { ::File.directory?(npm_path) }
notifies :run, "execute[Bower install #{site['name']}]"
notifies :run, "execute[Gulp #{site['name']}]"
end
# Bower install after npm install
execute "Bower install #{site['name']}" do
cwd bower_path
command 'bower install --silent'
action :nothing
user deploy_usr
only_if { site['bower_install'] }
only_if { ::File.directory?(bower_path) }
notifies :run, "execute[Gulp #{site['name']}]"
end
# Gulp run after bower install
execute "Gulp #{site['name']} after bower" do
cwd gulp_path
command 'gulp --silent --production'
action :nothing
user deploy_usr
only_if { site['gulp_run'] }
only_if { ::File.directory?(gulp_path) }
end
# Gulp run after npm install
execute "Gulp #{site['name']}" do
cwd gulp_path
command 'gulp --silent --production'
action :nothing
user deploy_usr
only_if { site['gulp_run'] }
only_if { ::File.directory?(gulp_path) }
not_if { site['bower_install'] }
end
# Set writeable directories without git
if site['writeable_dirs'].is_a?(Array) && !site['git']
site['writeable_dirs'].each do |dir_path|
dir_path = "#{site['base_path']}/#{dir_path}" unless dir_path[0, 1] == '/'
execute "Set owner of #{dir_path} to #{deploy_usr}:www-data" do
command "chown -R #{deploy_usr}:www-data #{dir_path}"
action :run
only_if { ::File.directory?(dir_path) }
end
execute "Change mode of #{dir_path} to 775" do
command "chmod -R 775 #{dir_path}"
only_if { ::File.directory?(dir_path) }
end
end
end
# Set writeable directories after git sync
ruby_block "Set writeable dirs for #{site['name']} after git sync" do
block do
site['writeable_dirs'].each do |dir_path|
dir_path = "#{site['base_path']}/#{dir_path}" unless dir_path[0, 1] == '/'
r = Chef::Resource::Execute.new("Set owner of #{dir_path} to #{deploy_usr}:www-data", run_context)
r.command "chown -R #{deploy_usr}:www-data #{dir_path}"
r.run_action(:run)
r = Chef::Resource::Execute.new("Change mode of #{dir_path} to 775", run_context)
r.command "chmod -R 775 #{dir_path}"
r.run_action(:run)
end
end
action :nothing
only_if { site['writeable_dirs'].is_a?(Array) }
end
end
Composer quiet
#
# Cookbook Name:: appserver
# Recipe:: webserver
#
# Set deploy_usr
deploy_usr = 'vagrant'
def chef_solo_search_installed?
klass = ::Search.const_get('Helper')
return klass.is_a?(Class)
rescue NameError
return false
end
unless Chef::Config[:solo] && !chef_solo_search_installed?
search(:users, 'id:deploy NOT action:remove').each do |u|
deploy_usr = u['id']
end
end
# Compass
include_recipe 'compass'
# Node JS & packages
include_recipe 'nodejs'
nodejs_npm 'bower'
nodejs_npm 'gulp'
# PHP FPM
package 'php5-fpm' do
action :install
end
service 'php-fpm' do
provider ::Chef::Provider::Service::Upstart
service_name 'php5-fpm'
supports enable: true, start: true, stop: true, restart: true
# :reload doesnt work on ubuntu 14.04 because of a bug...
action [:enable, :start]
end
# PHP with plugins
%w(php5 php5-cli php5-mysql php5-curl php5-mcrypt php5-gd imagemagick php5-imagick).each do |pkg|
package pkg do
action :install
end
end
template '/etc/php5/fpm/php.ini' do
source 'php.ini.erb'
owner 'root'
group 'root'
mode '0644'
notifies :restart, 'service[php-fpm]'
end
template '/etc/php5/mods-available/opcache.ini' do
source 'opcache.ini.erb'
owner 'root'
group 'root'
mode '0644'
notifies :restart, 'service[php-fpm]'
end
execute 'Enable Mcrypt' do
command 'php5enmod mcrypt'
action :run
notifies :restart, 'service[php-fpm]'
end
# Upgrade or install composer
execute 'Upgrade Composer' do
command 'composer self-update'
only_if { ::File.exist?('/usr/local/bin/composer') }
action :run
end
execute 'Install Composer' do # ~FC041
command 'curl -sS https://getcomposer.org/installer | php;mv composer.phar /usr/local/bin/composer'
not_if { ::File.exist?('/usr/local/bin/composer') }
action :run
end
# NGINX install
include_recipe 'nginx::server'
directory '/var/www' do
owner deploy_usr
group 'sysadmin'
mode '0775'
action :create
not_if { ::File.directory?('/var/www') }
end
node['nginx']['sites'].each do |site|
webroot_path = "#{site['base_path']}/#{site['webroot_subpath']}"
git_path = "#{site['base_path']}/#{site['git_subpath']}" if site['git']
composer_path = "#{site['base_path']}/#{site['composer_subpath']}" if site['composer_install']
artisan_path = "#{site['base_path']}/#{site['artisan_subpath']}" if site['artisan_migrate']
compass_path = "#{site['base_path']}/#{site['compass_subpath']}" if site['compass_compile']
npm_path = "#{site['base_path']}/#{site['npm_subpath']}" if site['npm_install']
bower_path = "#{site['base_path']}/#{site['bower_subpath']}" if site['bower_install']
gulp_path = "#{site['base_path']}/#{site['gulp_subpath']}" if site['gulp_run']
# Create ssl cert files
if site['ssl']
directory "#{node['nginx']['dir']}/ssl" do
owner 'root'
group 'root'
mode '0775'
action :create
not_if { ::File.directory?("#{node['nginx']['dir']}/ssl") }
end
file "#{node['nginx']['dir']}/ssl/#{site['name']}.crt" do
content site['ssl_crt']
owner 'root'
group 'root'
mode '0400'
not_if { ::File.exist?("#{node['nginx']['dir']}/ssl/#{site['name']}/.crt") }
end
file "#{node['nginx']['dir']}/ssl/#{site['name']}.key" do
content site['ssl_key']
owner 'root'
group 'root'
mode '0400'
not_if { ::File.exist?("#{node['nginx']['dir']}/ssl/#{site['name']}/.crt") }
end
end
# Set up nginx server block
custom_data = {
'environment' => site['environment'],
'db_host' => site['db_host'],
'db_database' => site['db_database'],
'db_username' => site['db_username'],
'db_password' => site['db_password'],
'ssl' => site['ssl'],
'ssl_crt' => "#{node['nginx']['dir']}/ssl/#{site['name']}.crt",
'ssl_key' => "#{node['nginx']['dir']}/ssl/#{site['name']}.key"
}
nginx_site site['name'] do # ~FC022
listen '*:80'
host site['host']
root webroot_path
index site['index']
location site['location']
phpfpm site['phpfpm']
custom_data custom_data
template_cookbook site['template_cookbook']
template_source site['template_source']
action [:create, :enable]
not_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
notifies :restart, 'service[php-fpm]'
notifies :restart, 'service[nginx]'
notifies :sync, "git[Syncing git repository for #{site['name']}]"
notifies :run, "execute[Composer install #{site['name']}]"
notifies :run, "execute[Artisan migrate #{site['name']}]"
end
# Sync with git repository
git "Syncing git repository for #{site['name']}" do
destination git_path
repository site['git_repo']
revision site['git_branch']
action :sync
user deploy_usr
ssh_wrapper "/home/#{deploy_usr}/git_wrapper.sh"
only_if { site['git'] && ::File.exist?("/home/#{deploy_usr}/.ssh/git_rsa") }
only_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
notifies :run, "execute[Composer install #{site['name']} after git sync]"
notifies :run, "execute[Artisan migrate #{site['name']} after git sync]"
notifies :compile, "compass_project[Compile sass for #{site['name']} after git sync]", :immediately
notifies :run, "execute[Npm install #{site['name']} after git sync]"
notifies :run, "ruby_block[Set writeable dirs for #{site['name']} after git sync]"
end
# Composer install triggered by git sync
execute "Composer install #{site['name']} after git sync" do
command "composer install -n -q -d #{composer_path}"
action :nothing
user deploy_usr
only_if { site['composer_install'] }
only_if { ::File.directory?(composer_path) }
notifies :run, "execute[Artisan migrate #{site['name']} after composer]"
end
# Composer install without git
execute "Composer install #{site['name']}" do
command "composer install -n -q -d #{composer_path}"
action :run
user deploy_usr
only_if { site['composer_install'] }
only_if { ::File.directory?(composer_path) }
only_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
not_if { site['git'] }
notifies :run, "execute[Artisan migrate #{site['name']} after composer]"
end
# Artisan migrate triggered by composer install
execute "Artisan migrate #{site['name']} after composer" do
command "php #{artisan_path} --env=#{site['environment']} migrate"
action :nothing
user deploy_usr
only_if { site['artisan_migrate'] }
only_if { ::File.directory?(artisan_path) }
end
# Artisan migrate after git, when not running composer install
execute "Artisan migrate #{site['name']} after git sync" do
command "php #{artisan_path} --env=#{site['environment']} migrate"
action :nothing
user deploy_usr
only_if { site['artisan_migrate'] }
only_if { ::File.directory?(artisan_path) }
not_if { site['composer_install'] }
end
# Artisan migrate without either composer or git
execute "Artisan migrate #{site['name']}" do
command "php #{artisan_path} --env=#{site['environment']} migrate"
action :run
user deploy_usr
only_if { site['artisan_migrate'] }
only_if { ::File.directory?(artisan_path) }
only_if { ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{site['name']}") }
not_if { site['composer_install'] }
not_if { site['git'] }
end
# Compass compile without git
compass_project "Compile sass for #{site['name']}" do
path compass_path
action :compile
user deploy_usr
only_if { site['compass_compile'] }
only_if { ::File.directory?(compass_path) }
not_if { site['git'] }
end
# Compass compile triggered by git
compass_project "Compile sass for #{site['name']} after git sync" do
path compass_path
action :nothing
user deploy_usr
only_if { site['compass_compile'] }
only_if { ::File.directory?(compass_path) }
end
# Npm install without git
execute "Npm install #{site['name']}" do
cwd npm_path
command 'npm install'
action :run
user deploy_usr
only_if { site['npm_install'] }
only_if { ::File.directory?(npm_path) }
not_if { site['git'] }
notifies :run, "execute[Bower install #{site['name']}]"
notifies :run, "execute[Gulp #{site['name']}]"
end
# Npm install triggered by git
execute "Npm install #{site['name']} after git sync" do
cwd npm_path
command 'npm install --silent'
action :nothing
user deploy_usr
only_if { site['npm_install'] }
only_if { ::File.directory?(npm_path) }
notifies :run, "execute[Bower install #{site['name']}]"
notifies :run, "execute[Gulp #{site['name']}]"
end
# Bower install after npm install
execute "Bower install #{site['name']}" do
cwd bower_path
command 'bower install --silent'
action :nothing
user deploy_usr
only_if { site['bower_install'] }
only_if { ::File.directory?(bower_path) }
notifies :run, "execute[Gulp #{site['name']}]"
end
# Gulp run after bower install
execute "Gulp #{site['name']} after bower" do
cwd gulp_path
command 'gulp --silent --production'
action :nothing
user deploy_usr
only_if { site['gulp_run'] }
only_if { ::File.directory?(gulp_path) }
end
# Gulp run after npm install
execute "Gulp #{site['name']}" do
cwd gulp_path
command 'gulp --silent --production'
action :nothing
user deploy_usr
only_if { site['gulp_run'] }
only_if { ::File.directory?(gulp_path) }
not_if { site['bower_install'] }
end
# Set writeable directories without git
if site['writeable_dirs'].is_a?(Array) && !site['git']
site['writeable_dirs'].each do |dir_path|
dir_path = "#{site['base_path']}/#{dir_path}" unless dir_path[0, 1] == '/'
execute "Set owner of #{dir_path} to #{deploy_usr}:www-data" do
command "chown -R #{deploy_usr}:www-data #{dir_path}"
action :run
only_if { ::File.directory?(dir_path) }
end
execute "Change mode of #{dir_path} to 775" do
command "chmod -R 775 #{dir_path}"
only_if { ::File.directory?(dir_path) }
end
end
end
# Set writeable directories after git sync
ruby_block "Set writeable dirs for #{site['name']} after git sync" do
block do
site['writeable_dirs'].each do |dir_path|
dir_path = "#{site['base_path']}/#{dir_path}" unless dir_path[0, 1] == '/'
r = Chef::Resource::Execute.new("Set owner of #{dir_path} to #{deploy_usr}:www-data", run_context)
r.command "chown -R #{deploy_usr}:www-data #{dir_path}"
r.run_action(:run)
r = Chef::Resource::Execute.new("Change mode of #{dir_path} to 775", run_context)
r.command "chmod -R 775 #{dir_path}"
r.run_action(:run)
end
end
action :nothing
only_if { site['writeable_dirs'].is_a?(Array) }
end
end
|
$:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = 'recommengine'
s.version = '0.1.3'
s.date = '2015-09-12'
s.summary = "A flexible recommendation engine."
s.description = "A flexible recommendation engine supporting multiple similarity algorithms for use in ecommerce sites, marketplaces, social sharing apps, and more."
s.authors = ["Cody Knauer"]
s.email = 'codyknauer@gmail.com'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.homepage = 'http://github.com/c0d3s/recommengine'
s.license = 'MIT'
s.require_paths = ["lib"]
s.required_ruby_version = '>= 2.1.0'
s.add_development_dependency 'rspec', '~> 3.1'
end
update gemspec version
$:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = 'recommengine'
s.version = '0.1.4'
s.date = '2015-09-12'
s.summary = "A flexible recommendation engine."
s.description = "A flexible recommendation engine supporting multiple similarity algorithms for use in ecommerce sites, marketplaces, social sharing apps, and more."
s.authors = ["Cody Knauer"]
s.email = 'codyknauer@gmail.com'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.homepage = 'http://github.com/c0d3s/recommengine'
s.license = 'MIT'
s.require_paths = ["lib"]
s.required_ruby_version = '>= 2.1.0'
s.add_development_dependency 'rspec', '~> 3.1'
end |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'reform/rails/version'
Gem::Specification.new do |spec|
spec.name = "reform-rails"
spec.version = Reform::Rails::VERSION
spec.authors = ["Nick Sutterer"]
spec.email = ["apotonick@gmail.com"]
spec.summary = %q{Automatically load and include all common Rails form features.}
spec.description = %q{Automatically load and include all common Reform features for a standard Rails environment.}
spec.homepage = "https://github.com/trailblazer/reform-rails"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "reform", "~> 2.0.0"
spec.add_dependency "activemodel", ">= 3.2"
spec.add_development_dependency "rails"
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest"
spec.add_development_dependency "actionpack"
spec.add_development_dependency "activerecord"
spec.add_development_dependency "mongoid"
end
limit to reform 2.2+.
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'reform/rails/version'
Gem::Specification.new do |spec|
spec.name = "reform-rails"
spec.version = Reform::Rails::VERSION
spec.authors = ["Nick Sutterer"]
spec.email = ["apotonick@gmail.com"]
spec.summary = %q{Automatically load and include all common Rails form features.}
spec.description = %q{Automatically load and include all common Reform features for a standard Rails environment.}
spec.homepage = "https://github.com/trailblazer/reform-rails"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "reform", ">= 2.2.0"
spec.add_dependency "activemodel", ">= 3.2"
spec.add_development_dependency "rails"
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest"
spec.add_development_dependency "actionpack"
spec.add_development_dependency "activerecord"
spec.add_development_dependency "mongoid"
end
|
Woops
Swagger::Docs::Config.register_apis({
"1.0" => {
# the extension used for the API
:api_extension_type => :json,
# the output location where your .json files are written to
:api_file_path => "public/api/v1/",
# if you want to delete all .json files at each generation
:clean_directory => false
}
}) |
require "formula"
HOMEBREW_RNSSH_VERSION="0.3.1"
class Rnssh < Formula
homepage 'https://github.com/reiki4040/rnssh'
if OS.mac?
if Hardware.is_64_bit?
url "https://github.com/reiki4040/rnssh/releases/download/v#{HOMEBREW_RNSSH_VERSION}/rnssh-#{HOMEBREW_RNSSH_VERSION}-darwin-amd64.zip"
sha1 '2493693a373240a726f074e056283a03d5490526'
else
url "https://github.com/reiki4040/rnssh/releases/download/v#{HOMEBREW_RNSSH_VERSION}/rnssh-#{HOMEBREW_RNSSH_VERSION}-darwin-amd32.zip"
sha1 '17f283b198c27c8ca9ff256a677e5990eb76ac3a'
end
end
version HOMEBREW_RNSSH_VERSION
def install
bin.install Dir['./rnssh']
end
# show message after installation.
def caveats
msg = <<-EOF.undent
# rnssh need AWS access key for working.
# Please set environment variable for AWS connection.
# (~/.bashrc, ~/.zshrc or other.)
export AWS_ACCESS_KEY_ID="YOUR AWS ACCESS KEY"
export AWS_SECRET_ACCESS_KEY="YOUR AWS SECRET ACCESS KEY"
# Option: you can set default aws region.
export AWS_REGION="ap-northeast-1"
EOF
end
end
updated to 0.3.2
require "formula"
HOMEBREW_RNSSH_VERSION="0.3.2"
class Rnssh < Formula
homepage 'https://github.com/reiki4040/rnssh'
if OS.mac?
if Hardware.is_64_bit?
url "https://github.com/reiki4040/rnssh/releases/download/v#{HOMEBREW_RNSSH_VERSION}/rnssh-#{HOMEBREW_RNSSH_VERSION}-darwin-amd64.zip"
sha1 '12b0f20a92039bcd5b3c81ed35119bb3477f3e26'
else
url "https://github.com/reiki4040/rnssh/releases/download/v#{HOMEBREW_RNSSH_VERSION}/rnssh-#{HOMEBREW_RNSSH_VERSION}-darwin-amd32.zip"
sha1 '2b45d665161da1b2284877fee42a07d0dba8e38f'
end
end
version HOMEBREW_RNSSH_VERSION
def install
bin.install Dir['./rnssh']
end
# show message after installation.
def caveats
msg = <<-EOF.undent
# rnssh need AWS access key for working.
# Please set environment variable for AWS connection.
# (~/.bashrc, ~/.zshrc or other.)
export AWS_ACCESS_KEY_ID="YOUR AWS ACCESS KEY"
export AWS_SECRET_ACCESS_KEY="YOUR AWS SECRET ACCESS KEY"
# Option: you can set default aws region.
export AWS_REGION="ap-northeast-1"
EOF
end
end
|
# fill out the method below, then run the tests with
# $ rake 1:2
# Given two numbers, a and b, return half of whichever is smallest, as a float
#
# arithmetic2(1, 2) # => 0.5
# arithmetic2(19, 10) # => 5.0
# arithmetic2(-6, -7) # => -3.5
def arithmetic2(a, b)
end
s01c02
# fill out the method below, then run the tests with
# $ rake 1:2
# Given two numbers, a and b, return half of whichever is smallest, as a float
#
# arithmetic2(1, 2) # => 0.5
# arithmetic2(19, 10) # => 5.0
# arithmetic2(-6, -7) # => -3.5
def arithmetic2(a, b)
if a < b
return a / 2.0
else
return b / 2.0
end
end
|
require 'sinatra'
require 'json'
require 'octokit'
#require 'open3'
require 'fileutils'
require "serialport"
$LOAD_PATH << '.'
require 'ci_utils.rb'
require_relative "bucket"
require_relative "cam"
set :bind, '0.0.0.0'
set :environment, :production
# XXX webrick has issues in recent versions accepting non-localhost transfers
set :server, :thin
set :port, 4567
$nshport = ENV['NSHPORT']
$ACCESS_TOKEN = ENV['GITTOKEN']
$logdir = './'
$commandlog = 'commandlog.txt'
$consolelog = 'consolelog.txt'
$bucket_name = 'results.dronetest.io'
$host = 'zurich01'
$results_url = ""
$continuous_branch = nil
$clonedir = "Firmware"
$lf = '.lockfile'
def do_lock(board)
# XXX put this into a function and check for a free worker
# also requires to name directories after the free worker
while File.file?(board)
# Check if the lock file is really old, if yes, take our chances and wipe it
if ((Time.now - File.stat(board).mtime).to_i > (60 * 10)) then
do_unlock('boardname')
break
end
# Keep waiting as long as the lock file exists
sleep(1)
end
# This is the critical section - we might want to lock it
# using a 2nd file, or something smarter and proper.
# XXX for now, we just bet on timing - yay!
FileUtils.touch($lf)
end
def do_unlock(board)
# We're done - delete lock file
FileUtils.rm_rf(board)
end
def do_work (command, error_message)
Open3.popen2e(command) do |stdin, stdout_err, wait_thr|
logfile = File.open($logdir + $commandlog, 'a')
while line = stdout_err.gets
puts "OUT> " + line
logfile << line
end
exit_status = wait_thr.value
unless exit_status.success?
do_unlock($lf)
set_PR_Status $full_repo_name, $sha, 'failure', error_message
failmsg = "The command #{command} failed!"
puts failmsg
logfile << failmsg
logfile.close
# Do not run through the standard exit handlers
exit!(1)
end
end
end
def do_clone (srcdir, branch, html_url)
puts "do_clone: " + branch
system 'mkdir', '-p', srcdir
Dir.chdir(srcdir) do
#git clone <url> --branch <branch> --single-branch [<folder>]
#result = `git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch `
#puts result
do_work "git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch #{$clonedir}", "Cloning repo failed."
Dir.chdir("#{$clonedir}") do
#result = `git submodule init && git submodule update`
#puts result
do_work "git submodule init", "GIT submodule init failed"
do_work "git submodule update", "GIT submodule update failed"
end
end
end
def do_master_merge (srcdir, base_repo, base_branch)
puts "do_merge of #{base_repo}/#{base_branch}"
Dir.chdir(srcdir + "/#{$clonedir}") do
do_work "git remote add base_repo #{base_repo}.git", "GIT adding upstream failed"
do_work "git fetch base_repo", "GIT fetching upstream failed"
do_work "git merge base_repo/#{base_branch} -m 'Merged #{base_repo}/#{base_branch} into test branch'", "Failed merging #{base_repo}/#{base_branch}"
end
end
def do_build (srcdir)
puts "Starting build"
Dir.chdir(srcdir+"/#{$clonedir}") do
do_work 'J=8 BOARDS="px4fmu-v2 px4io-v2" make archives', "make archives failed"
do_work "make -j8 px4fmu-v2_test", "make px4fmu-v2_test failed"
end
end
def openserialport (timeout)
#Open serial port - safe
#params for serial port
port_str = $nshport
baud_rate = 57600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
begin
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
puts "Opening port: " + port_str
sp.read_timeout = timeout
return sp
rescue Errno::ENOENT
puts "Serial port not available! Please (re)connect!"
sleep(1)
retry
end
end
def make_hwtest (pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link, hw_timeout)
# Execute hardware test
sender = ENV['MAILSENDER']
testcmd = "Tools/px_uploader.py --port \"/dev/serial/by-id/usb-3D_Robotics*,/dev/tty.usbmodem1\" Images/px4fmu-v2_test.px4"
#some variables need to be initialized
testResult = ""
finished = false
puts "----------------- Hardware-Test running ----------------"
sp = openserialport 100
#Push enter to cause output of remnants
sp.write "\n"
input = sp.gets()
puts "Remnants:"
puts input
sp.close
Dir.chdir(srcdir+"/Firmware") do
#puts "Call: " + testcmd
#result = `#{testcmd}`
puts "---------------command output---------------"
do_work testcmd, "Firmware upload failed"
puts "---------- end of command output------------"
end
# Total test timeout in seconds
test_timeout_s = hw_timeout;
# Wait 0.5 s for new data
read_timeout_ms = 500
sp = openserialport read_timeout_ms
test_passed = false
# XXX prepend each line with a time marker
# so we know if output comes in with huge delays
test_start_time = Time.now
begin
begin
input = sp.gets()
rescue Errno::ENXIO
puts "Serial port not available! Please connect"
sleep(1)
sp = openserialport read_timeout_ms
retry
end
if !input.nil?
#if input != nil and !input.empty?
testResult = testResult + input
if testResult.include? "NuttShell"
finished = true
puts "---------------- Testresult----------------"
#puts testResult
# Write test results to console log file
File.open($logdir + $consolelog, 'w') {|f| f.write(testResult) }
if (testResult.include? "TEST FAILED") || (testResult.include? "Tests FAILED")
puts "TEST FAILED!"
test_passed = false
else
test_passed = true
puts "Test successful!"
end
end
elsif ((test_timeout_s > 0) && ((Time.now() - test_start_time) > test_timeout_s))
finished = true
File.open($logdir + $consolelog, 'w') {|f| f.write(testResult + "\nSERIAL READ TIMEOUT!\n") }
puts "Serial port timeout"
end
end until finished
# Send out email
make_mmail pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link
# Prepare result for upload
generate_results_page 'index.html', pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link
sp.close
# Provide exit status
if (test_passed)
return 0
else
return 1
end
end
def set_PR_Status (repo, sha, prstatus, description)
puts "Access token: " + $ACCESS_TOKEN
client = Octokit::Client.new(:access_token => $ACCESS_TOKEN)
# XXX replace the URL below with the web server status details URL
options = {
"state" => prstatus,
"target_url" => $results_url,
"description" => description,
"context" => "continuous-integration/hans-ci"
};
puts "Setting commit status on repo: " + repo + " sha: " + sha + " to: " + prstatus + " description: " + description
res = client.create_status(repo, sha, prstatus, options)
puts res
end
def fork_hwtest (continuous_branch, pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha)
#Starts the hardware test in a subshell
pid = Process.fork
if pid.nil? then
# Lock this board for operations
do_lock($lf)
# Clean up any mess left behind by a previous potential fail
FileUtils.rm_rf(srcdir)
FileUtils.mkdir(srcdir);
FileUtils.touch($logdir + $consolelog)
# In child
s3_dirname = results_claim_directory($bucket_name, $host)
$results_url = sprintf("http://%s/%s/index.html", $bucket_name, s3_dirname);
results_still = sprintf("http://%s/%s/still.jpg", $bucket_name, s3_dirname);
# Set relevant global variables for PR status
$full_repo_name = full_repo_name
$sha = sha
tgit_start = Time.now
do_clone srcdir, branch, url
if !pr.nil?
do_master_merge srcdir, pr['base']['repo']['html_url'], pr['base']['ref']
end
tgit_duration = Time.now - tgit_start
tbuild_start = Time.now
do_build srcdir
tbuild_duration = Time.now - tbuild_start
# Run the hardware test
hw_timeout = 30;
# If the continuous integration branch name
# is set, indicate that the HW test should
# never actually time out
if (!continuous_branch.nil?)
hw_timeout = 0;
end
thw_start = Time.now
result = make_hwtest pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, $results_url, results_still, hw_timeout
thw_duration = Time.now - thw_start
# Take webcam image
take_picture(".")
# Upload still JPEG
results_upload($bucket_name, 'still.jpg', '%s/%s' % [s3_dirname, 'still.jpg'])
FileUtils.rm_rf('still.jpg')
timingstr = sprintf("%4.2fs", tgit_duration + tbuild_duration + thw_duration)
puts "HW TEST RESULT:" + result.to_s
if (result == 0) then
set_PR_Status full_repo_name, sha, 'success', 'Pixhawk HW test passed: ' + timingstr
else
set_PR_Status full_repo_name, sha, 'failure', 'Pixhawk HW test FAILED: ' + timingstr
end
# Logfile
results_upload($bucket_name, $logdir + $commandlog, '%s/%s' % [s3_dirname, 'commandlog.txt'])
FileUtils.rm_rf($commandlog)
results_upload($bucket_name, $logdir + $consolelog, '%s/%s' % [s3_dirname, 'consolelog.txt'])
FileUtils.rm_rf($logdir + $consolelog)
# GIF
results_upload($bucket_name, 'animated.gif', '%s/%s' % [s3_dirname, 'animated.gif'])
FileUtils.rm_rf('animated.gif')
# Index page
results_upload($bucket_name, 'index.html', '%s/%s' % [s3_dirname, 'index.html'])
FileUtils.rm_rf('index.html')
# Clean up by deleting the work directory
FileUtils.rm_rf(srcdir)
# Unlock this board
do_unlock($lf)
exit! 0
else
# In parent
puts "Worker PID: " + pid.to_s
Process.detach(pid)
end
end
# ---------- Routing ------------
get '/' do
"Hello unknown"
end
get '/payload' do
"This URL is intended to be used with POST, not GET"
end
post '/payload' do
body = JSON.parse(request.body.read)
github_event = request.env['HTTP_X_GITHUB_EVENT']
case github_event
when 'ping'
"Hello"
when 'pull_request'
begin
pr = body["pull_request"]
number = body['number']
puts pr['state']
action = body['action']
if (['opened', 'reopened'].include?(action))
sha = pr['head']['sha']
srcdir = sha
$logdir = Dir.pwd + "/" + srcdir + "/"
full_name = pr['base']['repo']['full_name']
puts "Source directory: #{srcdir}"
#Set environment vars for sub processes
# Pull last commiter email for PR from GH
client = Octokit::Client.new(:access_token => $ACCESS_TOKEN)
commit = client.commit(full_name, sha)
pushername = commit['commit']['author']['name']
pusheremail = commit['commit']['author']['email']
branch = pr['head']['ref']
url = pr['head']['repo']['html_url']
puts "Adding to queue: Pull request: #{number} " + branch + " from "+ url
set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..'
fork_hwtest nil, pushername, pusheremail, pr, srcdir, branch, url, full_name, sha
puts 'Pull request event queued for testing.'
else
puts 'Ignoring closing of pull request #' + String(number)
end
end
when 'push'
branch = body['ref']
if !(body['head_commit'].nil?) && body['head_commit'] != 'null'
sha = body['head_commit']['id']
srcdir = sha
$logdir = Dir.pwd + "/" + srcdir + "/";
puts "Source directory: #{srcdir}"
#Set environment vars for sub processes
pushername = body ['pusher']['name']
pusheremail = body ['pusher']['email']
a = branch.split('/')
branch = a[a.count-1] #last part is the bare branchname
puts "Adding to queue: Branch: " + branch + " from "+ body['repository']['html_url']
full_name = body['repository']['full_name']
puts "Full name: " + full_name
set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..'
fork_hwtest $continuous_branch, pushername, pusheremail, nil, srcdir, branch, body['repository']['html_url'], full_name, sha
puts 'Push event queued for testing.'
end
when 'status'
puts "Ignoring GH status event"
when 'fork'
puts 'Ignoring GH fork repo event'
when 'delete'
puts 'Ignoring GH delete branch event'
when 'issue_comment'
puts 'Ignoring comments'
when 'issues'
puts 'Ignoring issues'
when 'pull_request_review_comment'
puts 'Ignoring review comment'
when 'started'
puts 'Ignoring started request'
else
puts "Unhandled request:"
puts "Envelope: " + JSON.pretty_generate(request.env)
puts "JSON: " + JSON.pretty_generate(body)
puts "Unknown Event: " + github_event
end
end
Longer HW test timeout
require 'sinatra'
require 'json'
require 'octokit'
#require 'open3'
require 'fileutils'
require "serialport"
$LOAD_PATH << '.'
require 'ci_utils.rb'
require_relative "bucket"
require_relative "cam"
set :bind, '0.0.0.0'
set :environment, :production
# XXX webrick has issues in recent versions accepting non-localhost transfers
set :server, :thin
set :port, 4567
$nshport = ENV['NSHPORT']
$ACCESS_TOKEN = ENV['GITTOKEN']
$logdir = './'
$commandlog = 'commandlog.txt'
$consolelog = 'consolelog.txt'
$bucket_name = 'results.dronetest.io'
$host = 'zurich01'
$results_url = ""
$continuous_branch = nil
$clonedir = "Firmware"
$hardware_test_timeout = 60
$lf = '.lockfile'
def do_lock(board)
# XXX put this into a function and check for a free worker
# also requires to name directories after the free worker
while File.file?(board)
# Check if the lock file is really old, if yes, take our chances and wipe it
if ((Time.now - File.stat(board).mtime).to_i > (60 * 10)) then
do_unlock('boardname')
break
end
# Keep waiting as long as the lock file exists
sleep(1)
end
# This is the critical section - we might want to lock it
# using a 2nd file, or something smarter and proper.
# XXX for now, we just bet on timing - yay!
FileUtils.touch($lf)
end
def do_unlock(board)
# We're done - delete lock file
FileUtils.rm_rf(board)
end
def do_work (command, error_message)
Open3.popen2e(command) do |stdin, stdout_err, wait_thr|
logfile = File.open($logdir + $commandlog, 'a')
while line = stdout_err.gets
puts "OUT> " + line
logfile << line
end
exit_status = wait_thr.value
unless exit_status.success?
do_unlock($lf)
set_PR_Status $full_repo_name, $sha, 'failure', error_message
failmsg = "The command #{command} failed!"
puts failmsg
logfile << failmsg
logfile.close
# Do not run through the standard exit handlers
exit!(1)
end
end
end
def do_clone (srcdir, branch, html_url)
puts "do_clone: " + branch
system 'mkdir', '-p', srcdir
Dir.chdir(srcdir) do
#git clone <url> --branch <branch> --single-branch [<folder>]
#result = `git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch `
#puts result
do_work "git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch #{$clonedir}", "Cloning repo failed."
Dir.chdir("#{$clonedir}") do
#result = `git submodule init && git submodule update`
#puts result
do_work "git submodule init", "GIT submodule init failed"
do_work "git submodule update", "GIT submodule update failed"
end
end
end
def do_master_merge (srcdir, base_repo, base_branch)
puts "do_merge of #{base_repo}/#{base_branch}"
Dir.chdir(srcdir + "/#{$clonedir}") do
do_work "git remote add base_repo #{base_repo}.git", "GIT adding upstream failed"
do_work "git fetch base_repo", "GIT fetching upstream failed"
do_work "git merge base_repo/#{base_branch} -m 'Merged #{base_repo}/#{base_branch} into test branch'", "Failed merging #{base_repo}/#{base_branch}"
end
end
def do_build (srcdir)
puts "Starting build"
Dir.chdir(srcdir+"/#{$clonedir}") do
do_work 'J=8 BOARDS="px4fmu-v2 px4io-v2" make archives', "make archives failed"
do_work "make -j8 px4fmu-v2_test", "make px4fmu-v2_test failed"
end
end
def openserialport (timeout)
#Open serial port - safe
#params for serial port
port_str = $nshport
baud_rate = 57600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
begin
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
puts "Opening port: " + port_str
sp.read_timeout = timeout
return sp
rescue Errno::ENOENT
puts "Serial port not available! Please (re)connect!"
sleep(1)
retry
end
end
def make_hwtest (pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link, hw_timeout)
# Execute hardware test
sender = ENV['MAILSENDER']
testcmd = "Tools/px_uploader.py --port \"/dev/serial/by-id/usb-3D_Robotics*,/dev/tty.usbmodem1\" Images/px4fmu-v2_test.px4"
#some variables need to be initialized
testResult = ""
finished = false
puts "----------------- Hardware-Test running ----------------"
sp = openserialport 100
#Push enter to cause output of remnants
sp.write "\n"
input = sp.gets()
puts "Remnants:"
puts input
sp.close
Dir.chdir(srcdir+"/Firmware") do
#puts "Call: " + testcmd
#result = `#{testcmd}`
puts "---------------command output---------------"
do_work testcmd, "Firmware upload failed"
puts "---------- end of command output------------"
end
# Total test timeout in seconds
test_timeout_s = hw_timeout;
# Wait 0.5 s for new data
read_timeout_ms = 500
sp = openserialport read_timeout_ms
test_passed = false
# XXX prepend each line with a time marker
# so we know if output comes in with huge delays
test_start_time = Time.now
begin
begin
input = sp.gets()
rescue Errno::ENXIO
puts "Serial port not available! Please connect"
sleep(1)
sp = openserialport read_timeout_ms
retry
end
if !input.nil?
#if input != nil and !input.empty?
testResult = testResult + input
if testResult.include? "NuttShell"
finished = true
puts "---------------- Testresult----------------"
#puts testResult
# Write test results to console log file
File.open($logdir + $consolelog, 'w') {|f| f.write(testResult) }
if (testResult.include? "TEST FAILED") || (testResult.include? "Tests FAILED")
puts "TEST FAILED!"
test_passed = false
else
test_passed = true
puts "Test successful!"
end
end
elsif ((test_timeout_s > 0) && ((Time.now() - test_start_time) > test_timeout_s))
finished = true
File.open($logdir + $consolelog, 'w') {|f| f.write(testResult + "\nSERIAL READ TIMEOUT!\n") }
puts "Serial port timeout"
end
end until finished
# Send out email
make_mmail pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link
# Prepare result for upload
generate_results_page 'index.html', pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link
sp.close
# Provide exit status
if (test_passed)
return 0
else
return 1
end
end
def set_PR_Status (repo, sha, prstatus, description)
puts "Access token: " + $ACCESS_TOKEN
client = Octokit::Client.new(:access_token => $ACCESS_TOKEN)
# XXX replace the URL below with the web server status details URL
options = {
"state" => prstatus,
"target_url" => $results_url,
"description" => description,
"context" => "continuous-integration/hans-ci"
};
puts "Setting commit status on repo: " + repo + " sha: " + sha + " to: " + prstatus + " description: " + description
res = client.create_status(repo, sha, prstatus, options)
puts res
end
def fork_hwtest (continuous_branch, pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha)
#Starts the hardware test in a subshell
pid = Process.fork
if pid.nil? then
# Lock this board for operations
do_lock($lf)
# Clean up any mess left behind by a previous potential fail
FileUtils.rm_rf(srcdir)
FileUtils.mkdir(srcdir);
FileUtils.touch($logdir + $consolelog)
# In child
s3_dirname = results_claim_directory($bucket_name, $host)
$results_url = sprintf("http://%s/%s/index.html", $bucket_name, s3_dirname);
results_still = sprintf("http://%s/%s/still.jpg", $bucket_name, s3_dirname);
# Set relevant global variables for PR status
$full_repo_name = full_repo_name
$sha = sha
tgit_start = Time.now
do_clone srcdir, branch, url
if !pr.nil?
do_master_merge srcdir, pr['base']['repo']['html_url'], pr['base']['ref']
end
tgit_duration = Time.now - tgit_start
tbuild_start = Time.now
do_build srcdir
tbuild_duration = Time.now - tbuild_start
# Run the hardware test
hw_timeout = $hardware_test_timeout;
# If the continuous integration branch name
# is set, indicate that the HW test should
# never actually time out
if (!continuous_branch.nil?)
hw_timeout = 0;
end
thw_start = Time.now
result = make_hwtest pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, $results_url, results_still, hw_timeout
thw_duration = Time.now - thw_start
# Take webcam image
take_picture(".")
# Upload still JPEG
results_upload($bucket_name, 'still.jpg', '%s/%s' % [s3_dirname, 'still.jpg'])
FileUtils.rm_rf('still.jpg')
timingstr = sprintf("%4.2fs", tgit_duration + tbuild_duration + thw_duration)
puts "HW TEST RESULT:" + result.to_s
if (result == 0) then
set_PR_Status full_repo_name, sha, 'success', 'Pixhawk HW test passed: ' + timingstr
else
set_PR_Status full_repo_name, sha, 'failure', 'Pixhawk HW test FAILED: ' + timingstr
end
# Logfile
results_upload($bucket_name, $logdir + $commandlog, '%s/%s' % [s3_dirname, 'commandlog.txt'])
FileUtils.rm_rf($commandlog)
results_upload($bucket_name, $logdir + $consolelog, '%s/%s' % [s3_dirname, 'consolelog.txt'])
FileUtils.rm_rf($logdir + $consolelog)
# GIF
results_upload($bucket_name, 'animated.gif', '%s/%s' % [s3_dirname, 'animated.gif'])
FileUtils.rm_rf('animated.gif')
# Index page
results_upload($bucket_name, 'index.html', '%s/%s' % [s3_dirname, 'index.html'])
FileUtils.rm_rf('index.html')
# Clean up by deleting the work directory
FileUtils.rm_rf(srcdir)
# Unlock this board
do_unlock($lf)
exit! 0
else
# In parent
puts "Worker PID: " + pid.to_s
Process.detach(pid)
end
end
# ---------- Routing ------------
get '/' do
"Hello unknown"
end
get '/payload' do
"This URL is intended to be used with POST, not GET"
end
post '/payload' do
body = JSON.parse(request.body.read)
github_event = request.env['HTTP_X_GITHUB_EVENT']
case github_event
when 'ping'
"Hello"
when 'pull_request'
begin
pr = body["pull_request"]
number = body['number']
puts pr['state']
action = body['action']
if (['opened', 'reopened'].include?(action))
sha = pr['head']['sha']
srcdir = sha
$logdir = Dir.pwd + "/" + srcdir + "/"
full_name = pr['base']['repo']['full_name']
puts "Source directory: #{srcdir}"
#Set environment vars for sub processes
# Pull last commiter email for PR from GH
client = Octokit::Client.new(:access_token => $ACCESS_TOKEN)
commit = client.commit(full_name, sha)
pushername = commit['commit']['author']['name']
pusheremail = commit['commit']['author']['email']
branch = pr['head']['ref']
url = pr['head']['repo']['html_url']
puts "Adding to queue: Pull request: #{number} " + branch + " from "+ url
set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..'
fork_hwtest nil, pushername, pusheremail, pr, srcdir, branch, url, full_name, sha
puts 'Pull request event queued for testing.'
else
puts 'Ignoring closing of pull request #' + String(number)
end
end
when 'push'
branch = body['ref']
if !(body['head_commit'].nil?) && body['head_commit'] != 'null'
sha = body['head_commit']['id']
srcdir = sha
$logdir = Dir.pwd + "/" + srcdir + "/";
puts "Source directory: #{srcdir}"
#Set environment vars for sub processes
pushername = body ['pusher']['name']
pusheremail = body ['pusher']['email']
a = branch.split('/')
branch = a[a.count-1] #last part is the bare branchname
puts "Adding to queue: Branch: " + branch + " from "+ body['repository']['html_url']
full_name = body['repository']['full_name']
puts "Full name: " + full_name
set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..'
fork_hwtest $continuous_branch, pushername, pusheremail, nil, srcdir, branch, body['repository']['html_url'], full_name, sha
puts 'Push event queued for testing.'
end
when 'status'
puts "Ignoring GH status event"
when 'fork'
puts 'Ignoring GH fork repo event'
when 'delete'
puts 'Ignoring GH delete branch event'
when 'issue_comment'
puts 'Ignoring comments'
when 'issues'
puts 'Ignoring issues'
when 'pull_request_review_comment'
puts 'Ignoring review comment'
when 'started'
puts 'Ignoring started request'
else
puts "Unhandled request:"
puts "Envelope: " + JSON.pretty_generate(request.env)
puts "JSON: " + JSON.pretty_generate(body)
puts "Unknown Event: " + github_event
end
end
|
Adding build script for Test submodule
#!/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" |
module Harmony
# Build filename
FINAL = "build/final.rb"
# Source files
TARGETS = [
"src/config.rb",
"src/data-parser.rb",
"src/character-sprite.rb",
"src/panel-sprite.rb",
"src/panel-manager.rb",
"src/astar-algorithm.rb",
"src/battler-properties.rb",
"src/battle-prepare.rb",
"src/battle-map-data.rb",
"src/battle-map-spriteset.rb",
"src/battle-tbs-manager.rb",
"src/window-tactical.rb",
"src/scene-tactical-battle.rb",
"src/call-tbs.rb",
]
end
def harmony_build
final = File.new(Harmony::FINAL, "w+")
Harmony::TARGETS.each { |file|
src = File.open(file, "r+")
final.write(src.read + "\n")
src.close
}
final.close
end
harmony_build()
Added build.
module Harmony
# Build filename
FINAL = "build/final.rb"
# Source files
TARGETS = [
"src/config.rb",
"src/data-parser.rb",
"src/character-sprite.rb",
"src/panel-sprite.rb",
"src/panel-manager.rb",
"src/astar-algorithm.rb",
"src/battler-properties.rb",
"src/battle-prepare.rb",
"src/battle-map-data.rb",
"src/battle-map-spriteset.rb",
"src/battle-tbs-manager.rb",
"src/window-tactical.rb",
"src/scene-tactical-battle.rb",
"src/call-tbs.rb",
]
end
def harmony_build
final = File.new(Harmony::FINAL, "w+")
Harmony::TARGETS.each { |file|
src = File.open(file, "r+")
final.write(src.read + "\n")
src.close
}
final.close
end
harmony_build()
|
#!/usr/bin/env ruby -wKU
# encoding: utf-8
glibdir = "."
Dir.chdir glibdir
glibdir = Dir.pwd
$modular = true
Dir.chdir "#{glibdir}/supports"
version = nil
version_maj = 0
version_min = 0
version_sub = 0
version_mod = ''
revision = nil
load "build.rb"
puts "post-build..."
Dir.chdir "#{glibdir}"
if win32?
else
`rm -r "/Applications/Max5/Cycling '74/extensions/jcom.loader.mxo"`
`cp -r "../../Builds/MaxMSP/jcom.loader.mxo" "/Applications/Max5/Cycling '74/extensions/jcom.loader.mxo"`
`cp -r "./library/DeviceManagerLib/plugins/OSC.dylib" "/Applications/Max5/support/OSC.dylib"`
`cp -r "./library/DeviceManagerLib/plugins/Minuit.dylib" "/Applications/Max5/support/Minuit.dylib"`
`cp -r "./library/DeviceManagerLib/plugins/CopperLANPlugin.dylib" "/Applications/Max5/support/CopperLANPlugin.dylib"`
end
puts "done"
puts
Ensuring that default files gets copied into Max 5, adding copy instructions for Max 6, but these are commented out by default
#!/usr/bin/env ruby -wKU
# encoding: utf-8
glibdir = "."
Dir.chdir glibdir
glibdir = Dir.pwd
$modular = true
Dir.chdir "#{glibdir}/supports"
version = nil
version_maj = 0
version_min = 0
version_sub = 0
version_mod = ''
revision = nil
load "build.rb"
puts "post-build..."
Dir.chdir "#{glibdir}"
if win32?
else
# Copy into Max 5
`rm -r "/Applications/Max5/Cycling '74/extensions/jcom.loader.mxo"`
`cp -r "../../Builds/MaxMSP/jcom.loader.mxo" "/Applications/Max5/Cycling '74/extensions/jcom.loader.mxo"`
`cp -r "./library/DeviceManagerLib/plugins/OSC.dylib" "/Applications/Max5/support/OSC.dylib"`
`cp -r "./library/DeviceManagerLib/plugins/Minuit.dylib" "/Applications/Max5/support/Minuit.dylib"`
`cp -r "./library/DeviceManagerLib/plugins/CopperLANPlugin.dylib" "/Applications/Max5/support/CopperLANPlugin.dylib"`
# Copy default files into Max 5
`cp -r "Max/support/jcom.label.maxdefines" "/Applications/Max5/Cycling '74/default-definitions/jcom.label.maxdefines"`
`cp -r "Max/support/jcom.textslider.maxdefines" "/Applications/Max5/Cycling '74/default-definitions/jcom.textslider.maxdefines"`
`cp -r "Max/support/jcom.ui.maxdefines" "/Applications/Max5/Cycling '74/default-definitions/jcom.ui.maxdefines"`
`cp -r "Max/support/JamomaArarat.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaArarat.maxdefaults"`
`cp -r "Max/support/JamomaDark.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaDark.maxdefaults"`
`cp -r "Max/support/JamomaGraphite.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaGraphite.maxdefaults"`
`cp -r "Max/support/JamomaKulerBologna.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaKulerBologna.maxdefaults"`
`cp -r "Max/support/JamomaKulerQuietCry.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaKulerQuietCry.maxdefaults"`
`cp -r "Max/support/JamomaLight.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaLight.maxdefaults"`
`cp -r "Max/support/JamomaMax.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaMax.maxdefaults"`
`cp -r "Max/support/JamomaNoir.maxdefaults" "/Applications/Max5/Cycling '74/default-settings/JamomaNoir.maxdefaults"`
# Copy into Max 6 - uncomment this if you want it
#`rm -r "/Applications/Max6/Cycling '74/extensions/jcom.loader.mxo"`
# `cp -r "../../Builds/MaxMSP/jcom.loader.mxo" "/Applications/Max6/Cycling '74/extensions/jcom.loader.mxo"`
# `cp -r "./library/DeviceManagerLib/plugins/OSC.dylib" "/Applications/Max6/support/OSC.dylib"`
# `cp -r "./library/DeviceManagerLib/plugins/Minuit.dylib" "/Applications/Max6/support/Minuit.dylib"`
# `cp -r "./library/DeviceManagerLib/plugins/CopperLANPlugin.dylib" "/Applications/Max6/support/CopperLANPlugin.dylib"`
# Copy default files into Max 6 - uncomment this if you want it
# `cp -r "Max/support/jcom.label.maxdefines" "/Applications/Max6/Cycling '74/default-definitions/jcom.label.maxdefines"`
# `cp -r "Max/support/jcom.textslider.maxdefines" "/Applications/Max6/Cycling '74/default-definitions/jcom.textslider.maxdefines"`
# `cp -r "Max/support/jcom.ui.maxdefines" "/Applications/Max6/Cycling '74/default-definitions/jcom.ui.maxdefines"`
# `cp -r "Max/support/JamomaArarat.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaArarat.maxdefaults"`
# `cp -r "Max/support/JamomaDark.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaDark.maxdefaults"`
# `cp -r "Max/support/JamomaGraphite.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaGraphite.maxdefaults"`
# `cp -r "Max/support/JamomaKulerBologna.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaKulerBologna.maxdefaults"`
# `cp -r "Max/support/JamomaKulerQuietCry.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaKulerQuietCry.maxdefaults"`
# `cp -r "Max/support/JamomaLight.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaLight.maxdefaults"`
# `cp -r "Max/support/JamomaMax.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaMax.maxdefaults"`
# `cp -r "Max/support/JamomaNoir.maxdefaults" "/Applications/Max6/Cycling '74/default-settings/JamomaNoir.maxdefaults"`
end
puts "done"
puts
|
set :stage, :staging
set :branch, "develop"
server "ort-staging.linode.unep-wcmc.org", user: "wcmc", roles: %w{app web db}
set :domain, "ort-staging.linode.unep-wcmc.org"
set :server_name, "#{fetch(:application)}.#{fetch(:domain)}"
set :sudo_user, "wcmc"
set :app_port, "80"
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:
# server 'example.com', user: 'deploy', roles: %w{app db web}, my_property: :my_value
# server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'deploy', roles: %w{db}
# role-based syntax
# ==================
# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.
# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
deploy CITES staging from master
set :stage, :staging
set :branch, :master
server "ort-staging.linode.unep-wcmc.org", user: "wcmc", roles: %w{app web db}
set :domain, "ort-staging.linode.unep-wcmc.org"
set :server_name, "#{fetch(:application)}.#{fetch(:domain)}"
set :sudo_user, "wcmc"
set :app_port, "80"
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:
# server 'example.com', user: 'deploy', roles: %w{app db web}, my_property: :my_value
# server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'deploy', roles: %w{db}
# role-based syntax
# ==================
# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.
# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
|
# frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
config.active_job.queue_adapter = :delayed_job
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp", "caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# Listener stuff doesn't work properly without this.
Zeitwerk::Loader.eager_load_all
end
Turn on eager loading in development
# frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# If we don't eager load we get issues with namespaced modules not being found.
config.eager_load = true
config.active_job.queue_adapter = :delayed_job
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp", "caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# Listener stuff doesn't work properly without this.
Zeitwerk::Loader.eager_load_all
end
|
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Uncomment the following line if you're getting "A copy of XX has been removed from the module tree but is still active!" as it may help you:
# config.after_initialize { Dependencies.load_once_paths = Dependencies.load_once_paths.select { |path| (path =~ /app/).nil? } }
Update the code that reloads plugin app directories to more robust code
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Uncomment the following lines if you're getting
# "A copy of XX has been removed from the module tree but is still active!"
# or you want to develop a plugin and don't want to restart every time a change is made:
#config.after_initialize do
# ::ActiveSupport::Dependencies.load_once_paths = ::ActiveSupport::Dependencies.load_once_paths.select do |path|
# (path =~ /app/).nil?
# end
#end |
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# run rake js:build to build the optimized JS if set to true
# ENV['USE_OPTIMIZED_JS'] = true
# Really do care if the message wasn't sent.
config.action_mailer.raise_delivery_errors = true
config.to_prepare do
# Raise an exception on bad mass assignment. Helps us catch these bugs before
# they hit.
Canvas.protected_attribute_error = :raise
# Raise an exception on finder type mismatch or nil arguments. Helps us catch
# these bugs before they hit.
Canvas.dynamic_finder_nil_arguments_error = :raise
Canvas.dynamic_finder_type_cast_error = :raise
end
# initialize cache store
# this needs to happen in each environment config file, rather than a
# config/initializer/* file, to allow Rails' full initialization of the cache
# to take place, including middleware inserts and such.
config.cache_store = Canvas.cache_store_config
# eval <env>-local.rb if it exists
Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
# allow debugging only in development environment by default
require "ruby-debug"
fix typo in development.rb
Change-Id: Id7f4884bc2001aaa23068742608e4e8507a89632
Reviewed-on: https://gerrit.instructure.com/9180
Tested-by: Hudson <dfb64870173313a9a7b56f814c8e3b33e268497a@instructure.com>
Reviewed-by: Ryan Florence <2d8900489f91ac272fd9ce9d5789db6522668ca2@instructure.com>
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# run rake js:build to build the optimized JS if set to true
# ENV['USE_OPTIMIZED_JS'] = 'true'
# Really do care if the message wasn't sent.
config.action_mailer.raise_delivery_errors = true
config.to_prepare do
# Raise an exception on bad mass assignment. Helps us catch these bugs before
# they hit.
Canvas.protected_attribute_error = :raise
# Raise an exception on finder type mismatch or nil arguments. Helps us catch
# these bugs before they hit.
Canvas.dynamic_finder_nil_arguments_error = :raise
Canvas.dynamic_finder_type_cast_error = :raise
end
# initialize cache store
# this needs to happen in each environment config file, rather than a
# config/initializer/* file, to allow Rails' full initialization of the cache
# to take place, including middleware inserts and such.
config.cache_store = Canvas.cache_store_config
# eval <env>-local.rb if it exists
Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
# allow debugging only in development environment by default
require "ruby-debug"
|
Hummingbird::Application.configure do
routes.default_url_options = {host: 'localhost', port: 3000}
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Other mailer options
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :letter_opener
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.ember.variant = :development
# LiveReload
config.middleware.insert_after(ActionDispatch::Static, Rack::LiveReload)
# Caching
# Temporarily enable caching in development (COMMENT OUT WHEN DONE!)
#config.action_controller.perform_caching = true
#config.cache_store = :redis_store
config.react.variant = :development
config.react.addons = true
config.after_initialize do
Bullet.enable = true
Bullet.bullet_logger = true
# Bullet.growl = true
end
end
Remove left-over Bullet stuff.
Hummingbird::Application.configure do
routes.default_url_options = {host: 'localhost', port: 3000}
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Other mailer options
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :letter_opener
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.ember.variant = :development
# LiveReload
config.middleware.insert_after(ActionDispatch::Static, Rack::LiveReload)
# Caching
# Temporarily enable caching in development (COMMENT OUT WHEN DONE!)
#config.action_controller.perform_caching = true
#config.cache_store = :redis_store
config.react.variant = :development
config.react.addons = true
end
|
Rails.application.configure do
config.hosts << 'railsbump.test'
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
execute sucker punch jobs synchronously in development
require 'sucker_punch/testing/inline'
Rails.application.configure do
config.hosts << 'railsbump.test'
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
Add letter_opener config.
Generated by pah version 0.0.25
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Letter openner config
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
Update development configuration
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# Default url options when generating urls for action mailer
config.action_mailer.default_url_options = { host: 'localhost' }
# Set email delivery method to SMTP
config.action_mailer.delivery_method = :smtp
# Configure Gmail
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
user_name: '<your-gmail-username>',
password: '<your-gmail-password>',
authentication: 'plain',
enable_starttls_auto: true
}
end
|
# -*- encoding : utf-8 -*-
Otwartezabytki::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = false
# Use mailcatcher for debugging e-mails
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
config.action_mailer.default_url_options = { :host => "otwartezabytki.dev" }
end
don't use cache in development
# -*- encoding : utf-8 -*-
Otwartezabytki::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = false
# Use mailcatcher for debugging e-mails
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
config.action_mailer.default_url_options = { :host => "otwartezabytki.dev" }
config.cache_store = :null_store
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
solve unable to access asset in development mode, the error: Sprockets::Rails::Environment::NoDigestError (Assets should not be requested directly without their digests: Use the helpers in ActionView::Helpers to request logo.png):
sprockets-rails (3.0.0.beta1) lib/sprockets/rails/environment.rb:22:in serve'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = false
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# config.action_mailer.delivery_method = :sendmail
# config.action_mailer.perform_deliveries = true
## WORKS BELOW
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: 'briannealmock@gmail.com',
password: 'infinitiQX4$',
authentication: 'plain',
enable_starttls_auto: true }
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
Remove secure auth data
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# config.action_mailer.delivery_method = :sendmail
# config.action_mailer.perform_deliveries = true
## WORKS BELOW
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: ENV["GMAIL_USER"],
password: ENV["GMAIL_PASSWORD"],
authentication: 'plain',
enable_starttls_auto: true }
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
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
# Класс окна с реализацией всех возможностей, доступных при помощи Cigui.<br>
# Реализация выполнена для RGSS3.
#
class Win3
# X Coordinate of Window
attr_accessor :x
# Y Coordinate of Window
attr_accessor :y
# 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
# Create window
def initialize
@x,@y,@width,@height = 0, 0, 192, 64
@speed=0
@opacity, @back_opacity, @contents_opacity = 255, 255, 255
@z, @tone, @openness = 100, Rect.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)
# 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
# Класс, хранящий данные о цвете в формате 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
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 - окнами.
#
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
:select_window=>"(?:(?:#{VOCAB[:select]})+[\s]*(?:#{VOCAB[:window][:main]})+)|"+
"(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:select]})+)",
:select_by_index=>"(?:#{VOCAB[:window][:index]})+(?:#{VOCAB[:equal]}|[\s]*)+",
:select_by_label=>"(?:#{VOCAB[:window][:label]})+(?:#{VOCAB[:equal]}|[\s]*)+",
#~CIGUI branch
: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_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]*)+",
# 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_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=>"",
:window_close=>"",
}
#
class <<self
# Внутренний массив для вывода информации обо всех созданных окнах.<br>
# Открыт только для чтения.
#
attr_reader :windows
# Внутренний массив для вывода информации обо всех созданных спрайтах.<br>
# Открыт только для чтения.
#
attr_reader :sprites
# Требуется выполнить этот метод перед началом работы с CIGUI.<br>
# Инициализирует массив $do, если он еще не был создан. В этот массив пользователь подает
# команды для исполнения при следующем запуске метода #update.<br>
# Если даже массив $do был инициализирован ранее,
# то исполняет команду <i>cigui start</i> прежде всего.
# <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 и sprite.
#
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][:close]='close'
# # add 'window close' combination
# CMB[:window_close]="(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:close]})+)"
# # call method
# window_close? 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. Массив в строке должен быть помещен в квадратные скобки,
# а значения в нем должны разделяться точкой с запятой.<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
arr.size=4
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.
#
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
#__wlabel? string
end
# 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
begin
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
@windows.last.x = new_x
@windows.last.y = new_y
@windows.last.width = new_w
@windows.last.height = new_h
@last_action = @windows.last
@selection[:type]=:window
@selection[:index]=@windows.size-1
end
#rescue
# dunnolol
end
end #--------------------end of '__wcreate?'-------------------------
def __wdispose?(string)
matches=string.match(/#{CMB[:window_dispose]}/i)
# Only create
if matches
begin
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
end
@last_action = 'CIGUI disposed window'
end
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_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
# Change it
if @selection[:type]==:window
@windows[@selection[:index]].x = new_x
@windows[@selection[:index]].y = new_y
@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
@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?'-------------------------
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=2_4, Y=3_2',
'this window set label=something'
]
CIGUI.setup
CIGUI.update
puts CIGUI.last
end
Open/Close this window
- Added '__wopen?' method
- Added '__wclose?' method
- Updated commands in CMB for it
- Improved code for '__wcreate?'
- Start work under window select in '__wdispose?'
# = Руководство 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
# Класс окна с реализацией всех возможностей, доступных при помощи Cigui.<br>
# Реализация выполнена для RGSS3.
#
class Win3
# X Coordinate of Window
attr_accessor :x
# Y Coordinate of Window
attr_accessor :y
# 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
# Create window
def initialize
@x,@y,@width,@height = 0, 0, 192, 64
@speed=0
@opacity, @back_opacity, @contents_opacity = 255, 255, 255
@z, @tone, @openness = 100, Rect.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)
# 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
# Класс, хранящий данные о цвете в формате 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
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 - окнами.
#
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
:select_window=>"(?:(?:#{VOCAB[:select]})+[\s]*(?:#{VOCAB[:window][:main]})+)|"+
"(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:select]})+)",
:select_by_index=>"(?:#{VOCAB[:window][:index]})+(?:#{VOCAB[:equal]}|[\s]*)+",
:select_by_label=>"(?:#{VOCAB[:window][:label]})+(?:#{VOCAB[:equal]}|[\s]*)+",
#~CIGUI branch
: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_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]*)+",
# 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_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[:window][:main]})+[\s]*(?:#{VOCAB[:window][:open]}))|"+
"(?:(?:#{VOCAB[:window][:open]})+[\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> прежде всего.
# <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 и sprite.
#
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][:close]='close'
# # add 'window close' combination
# CMB[:window_close]="(?:(?:#{VOCAB[:window][:main]})+[\s]*(?:#{VOCAB[:window][:close]})+)"
# # call method
# window_close? 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. Массив в строке должен быть помещен в квадратные скобки,
# а значения в нем должны разделяться точкой с запятой.<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
arr.size=4
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.
#
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
# Set last action to inspect this window
@last_action = @windows.last
# 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]}/i)
# Здесь был какой-то собственный select window
# и я решил от него избавиться.
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)
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_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
# Change it
if @selection[:type]==:window
@windows[@selection[:index]].x = new_x
@windows[@selection[:index]].y = new_y
@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
@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',
'close this window'
]
CIGUI.setup
CIGUI.update
puts CIGUI.last
end |
BitcoinBank::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Uncomment this to test e-mails in development mode
config.action_mailer.delivery_method = :sendmail
# Comment this line if testing e-mails in development mode
# config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {
:host => "www.bitfication.com"
}
config.assets.debug = true
# Used to broadcast invoices public URLs
config.base_url = "http://bitfication.com:3000/"
end
Small adjustment on development environment...
BitcoinBank::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Uncomment this to test e-mails in development mode
config.action_mailer.delivery_method = :sendmail
# Comment this line if testing e-mails in development mode
# config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {
:host => "bitfication.com"
}
config.assets.debug = true
# Used to broadcast invoices public URLs
config.base_url = "http://bitfication.com:3000/"
end
|
# encoding: utf-8
proc { |p| $:.unshift(p) unless $:.any? { |lp| File.expand_path(lp) == p } }.call(File.expand_path('.', File.dirname(__FILE__)))
require 'helper'
require 'logger'
require 'stringio'
describe ApiHammer::RequestLogger do
let(:logio) { StringIO.new }
let(:logger) { Logger.new(logio) }
it 'logs' do
conn = Faraday.new do |f|
f.use ApiHammer::Faraday::RequestLogger, logger
f.use Faraday::Adapter::Rack, proc { |env| [200, {}, []] }
end
conn.get '/'
assert_match(/200/, logio.string)
lines = logio.string.split("\n")
assert_equal(2, lines.size)
assert lines.last =~ /INFO -- : /
json_bit = $'
JSON.parse json_bit # should not raise
end
{200 => :intense_green, 400 => :intense_yellow, 500 => :intense_red, 300 => :white}.each do |status, color|
it "colors by #{status} status" do
conn = Faraday.new do |f|
f.use ApiHammer::Faraday::RequestLogger, logger
f.use Faraday::Adapter::Rack, proc { |env| [status, {}, []] }
end
conn.get '/'
assert(logio.string.include?(Term::ANSIColor.send(color, status.to_s)))
end
end
it 'registers by name' do
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, proc { |env| [200, {}, []] }
end
conn.get '/'
assert_match(/200/, logio.string)
end
describe 'response body encoding' do
it 'deals with encoding specified properly by the content type' do
app = proc do |env|
[200, {'Content-Type' => 'text/plain; charset=utf-8'}, ["Jalapeños".force_encoding("ASCII-8BIT")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match(/Jalapeños/, logio.string)
end
it 'deals content type specifying no encoding' do
app = proc do |env|
[200, {'Content-Type' => 'text/plain; x=y'}, ["Jalapeños".force_encoding("ASCII-8BIT")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match(/Jalapeños/, logio.string)
end
it 'deals with no content type' do
app = proc do |env|
[200, {}, ["Jalapeños".force_encoding("ASCII-8BIT")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match(/Jalapeños/, logio.string)
end
it 'falls back to array of codepoints when encoding is improperly specified by the content type' do
app = proc do |env|
[200, {'Content-Type' => 'text/plain; charset=utf-8'}, ["xx" + [195].pack("C*")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match('[120,120,195]', logio.string)
end
it 'falls back to array of codepoints when encoding is not specified and not valid utf8' do
app = proc do |env|
[200, {}, ["xx" + [195].pack("C*")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match('[120,120,195]', logio.string)
end
end
describe 'logging body by content-type' do
{
'application/octet-stream' => false,
'image/png' => false,
'image/png; charset=what' => false,
'text/plain' => true,
'text/plain; charset=utf-8' => true,
}.each do |content_type, istext|
it "does #{istext ? '' : 'not'} log body for #{content_type}" do
app = proc do |env|
[200, {'Content-Type' => content_type}, ['data go here']]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert(logio.string.include?('data go here') == istext)
end
end
end
describe 'filtering' do
describe 'json response' do
it 'filters' do
app = proc { |env| [200, {'Content-Type' => 'application/json'}, ['{"pin": "foobar"}']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"{\"pin\": \"[FILTERED]\"}"))
end
it 'filters nested' do
app = proc { |env| [200, {'Content-Type' => 'application/json'}, ['{"object": {"pin": "foobar"}}']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"{\"object\": {\"pin\": \"[FILTERED]\"}}"))
end
it 'filters in array' do
app = proc { |env| [200, {'Content-Type' => 'application/json'}, ['[{"object": [{"pin": ["foobar"]}]}]']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"[{\"object\": [{\"pin\": \"[FILTERED]\"}]}]"))
end
end
describe 'json request' do
it 'filters a json request' do
app = proc { |env| [200, {}, []] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.post '/', '[{"object": [{"pin": ["foobar"]}]}]', {'Content-Type' => 'application/json'}
assert_includes(logio.string, %q("body":"[{\"object\": [{\"pin\": \"[FILTERED]\"}]}]"))
end
end
describe 'form encoded response' do
it 'filters' do
app = proc { |env| [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, ['pin=foobar']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"pin=[FILTERED]"))
end
it 'filters nested' do
app = proc { |env| [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, ['object[pin]=foobar']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"object[pin]=[FILTERED]"))
end
it 'filters in array' do
app = proc { |env| [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, ['object[][pin][]=foobar']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"object[][pin][]=[FILTERED]"))
end
end
describe 'form encoded request' do
it 'filters a json request' do
app = proc { |env| [200, {}, []] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.post '/', 'object[pin]=foobar', {'Content-Type' => 'application/x-www-form-urlencoded'}
assert_includes(logio.string, %q(object[pin]=[FILTERED]))
end
end
end
end
add non-filtered params to the params filtering tests to check against false positives
# encoding: utf-8
proc { |p| $:.unshift(p) unless $:.any? { |lp| File.expand_path(lp) == p } }.call(File.expand_path('.', File.dirname(__FILE__)))
require 'helper'
require 'logger'
require 'stringio'
describe ApiHammer::RequestLogger do
let(:logio) { StringIO.new }
let(:logger) { Logger.new(logio) }
it 'logs' do
conn = Faraday.new do |f|
f.use ApiHammer::Faraday::RequestLogger, logger
f.use Faraday::Adapter::Rack, proc { |env| [200, {}, []] }
end
conn.get '/'
assert_match(/200/, logio.string)
lines = logio.string.split("\n")
assert_equal(2, lines.size)
assert lines.last =~ /INFO -- : /
json_bit = $'
JSON.parse json_bit # should not raise
end
{200 => :intense_green, 400 => :intense_yellow, 500 => :intense_red, 300 => :white}.each do |status, color|
it "colors by #{status} status" do
conn = Faraday.new do |f|
f.use ApiHammer::Faraday::RequestLogger, logger
f.use Faraday::Adapter::Rack, proc { |env| [status, {}, []] }
end
conn.get '/'
assert(logio.string.include?(Term::ANSIColor.send(color, status.to_s)))
end
end
it 'registers by name' do
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, proc { |env| [200, {}, []] }
end
conn.get '/'
assert_match(/200/, logio.string)
end
describe 'response body encoding' do
it 'deals with encoding specified properly by the content type' do
app = proc do |env|
[200, {'Content-Type' => 'text/plain; charset=utf-8'}, ["Jalapeños".force_encoding("ASCII-8BIT")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match(/Jalapeños/, logio.string)
end
it 'deals content type specifying no encoding' do
app = proc do |env|
[200, {'Content-Type' => 'text/plain; x=y'}, ["Jalapeños".force_encoding("ASCII-8BIT")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match(/Jalapeños/, logio.string)
end
it 'deals with no content type' do
app = proc do |env|
[200, {}, ["Jalapeños".force_encoding("ASCII-8BIT")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match(/Jalapeños/, logio.string)
end
it 'falls back to array of codepoints when encoding is improperly specified by the content type' do
app = proc do |env|
[200, {'Content-Type' => 'text/plain; charset=utf-8'}, ["xx" + [195].pack("C*")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match('[120,120,195]', logio.string)
end
it 'falls back to array of codepoints when encoding is not specified and not valid utf8' do
app = proc do |env|
[200, {}, ["xx" + [195].pack("C*")]]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_match('[120,120,195]', logio.string)
end
end
describe 'logging body by content-type' do
{
'application/octet-stream' => false,
'image/png' => false,
'image/png; charset=what' => false,
'text/plain' => true,
'text/plain; charset=utf-8' => true,
}.each do |content_type, istext|
it "does #{istext ? '' : 'not'} log body for #{content_type}" do
app = proc do |env|
[200, {'Content-Type' => content_type}, ['data go here']]
end
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert(logio.string.include?('data go here') == istext)
end
end
end
describe 'filtering' do
describe 'json response' do
it 'filters' do
app = proc { |env| [200, {'Content-Type' => 'application/json'}, ['{"pin": "foobar", "bar": "baz"}']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"{\"pin\": \"[FILTERED]\", \"bar\": \"baz\"}"))
end
it 'filters nested' do
app = proc { |env| [200, {'Content-Type' => 'application/json'}, ['{"object": {"pin": "foobar"}, "bar": "baz"}']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"{\"object\": {\"pin\": \"[FILTERED]\"}, \"bar\": \"baz\"}"))
end
it 'filters in array' do
app = proc { |env| [200, {'Content-Type' => 'application/json'}, ['[{"object": [{"pin": ["foobar"]}], "bar": "baz"}]']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"[{\"object\": [{\"pin\": \"[FILTERED]\"}], \"bar\": \"baz\"}]"))
end
end
describe 'json request' do
it 'filters a json request' do
app = proc { |env| [200, {}, []] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.post '/', '[{"object": [{"pin": ["foobar"]}], "bar": "baz"}]', {'Content-Type' => 'application/json'}
assert_includes(logio.string, %q("body":"[{\"object\": [{\"pin\": \"[FILTERED]\"}], \"bar\": \"baz\"}]"))
end
end
describe 'form encoded response' do
it 'filters' do
app = proc { |env| [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, ['pin=foobar&bar=baz']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"pin=[FILTERED]&bar=baz"))
end
it 'filters nested' do
app = proc { |env| [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, ['object[pin]=foobar&bar=baz']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"object[pin]=[FILTERED]&bar=baz"))
end
it 'filters in array' do
app = proc { |env| [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, ['object[][pin][]=foobar&bar=baz']] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.get '/'
assert_includes(logio.string, %q("body":"object[][pin][]=[FILTERED]&bar=baz"))
end
end
describe 'form encoded request' do
it 'filters a json request' do
app = proc { |env| [200, {}, []] }
conn = Faraday.new do |f|
f.request :api_hammer_request_logger, logger, :filter_keys => 'pin'
f.use Faraday::Adapter::Rack, app
end
conn.post '/', 'object[pin]=foobar&bar=baz', {'Content-Type' => 'application/x-www-form-urlencoded'}
assert_includes(logio.string, %q(object[pin]=[FILTERED]&bar=baz))
end
end
end
end
|
Incense::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
rails dev environment: added ember dev mode
Incense::Application.configure do
config.ember.variant = :development #ember dev mode
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
|
require "test_helper"
class CreateSchemaTest < Capybara::Rails::TestCase
include Warden::Test::Helpers
after { Warden.test_reset! }
setup do
visit root_path
login_as users(:pablito), scope: :user
visit root_path
find('#user-menu').click
find_link('menu-new-schema').click
fill_in 'schema_name', :with => "Test"
page.execute_script("$(\"input[type=file]\").show()")
end
test "attempt to create a schema without an attached file" do
click_button "Crear Esquema"
assert_content page, "No se pudo crear el esquema"
end
test "attempt to create a schema with an invalid file" do
attach_file 'schema_spec_file', Rails.root.join('README.md')
click_button "Crear Esquema"
assert_content page, "Archivo no está en formato JSON o YAML:"
end
test "create a valid schema" do
attach_file 'schema_spec_file', Rails.root.join(
'test', 'files', 'test-schemas', 'schemaObject.json')
click_button "Crear Esquema"
assert_content page, "Nuevo Esquema creado correctamente"
end
end
Small refactor on create_schema_test
require "test_helper"
class CreateSchemaTest < Capybara::Rails::TestCase
include Warden::Test::Helpers
after { Warden.test_reset! }
setup do
visit root_path
login_as users(:pablito), scope: :user
visit root_path
find('#user-menu').click
find_link('menu-new-schema').click
fill_in 'schema_name', :with => "Test"
page.execute_script('$("input[type=file]").show()')
end
test "attempt to create a schema without an attached file" do
click_button "Crear Esquema"
assert_content page, "No se pudo crear el esquema"
end
test "attempt to create a schema with an invalid file" do
attach_file 'schema_spec_file', Rails.root.join('README.md')
click_button "Crear Esquema"
assert_content page, "Archivo no está en formato JSON o YAML:"
end
test "create a valid schema" do
attach_file 'schema_spec_file', Rails.root.join(
'test', 'files', 'test-schemas', 'schemaObject.json')
click_button "Crear Esquema"
assert_content page, "Nuevo Esquema creado correctamente"
end
end
|
Webapp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true # ActionMailer Config
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = true
# Send email in development mode.
config.action_mailer.perform_deliveries = false
end
basic SMTP mail settings
Webapp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true # ActionMailer Config
#
# SMTP / basic email setup
#
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# basic SMTP setup
config.action_mailer.smtp_settings = {
address: "musca.uberspace.de",
port: 587,
domain: "pellect.io",
authentication: "login",
user_name: "pelectio",
#password: ENV('SMTP_PASSWORD'),
password: "K0naBeach13",
enable_starttls_auto: true
}
# basic email settings
config.action_mailer.default_options = {
from: "robot@pellect.io",
reply_to: "no-reply@pellect.io"
}
# raise an error when something goes wrong with emails
config.action_mailer.raise_delivery_errors = true
# Send email in development mode.
config.action_mailer.perform_deliveries = true
end
|
I18n.available_locales = Noosfero.available_locales
Noosfero.default_locale = 'pt_BR'
FastGettext.locale = Noosfero.default_locale
FastGettext.default_locale = Noosfero.default_locale
I18n.locale = Noosfero.default_locale
I18n.default_locale = Noosfero.default_locale
if Rails.env.development?
ActionMailer::Base.delivery_method = :file
end
Change default language to es_ES
I18n.available_locales = Noosfero.available_locales
Noosfero.default_locale = 'es_ES'
FastGettext.locale = Noosfero.default_locale
FastGettext.default_locale = Noosfero.default_locale
I18n.locale = Noosfero.default_locale
I18n.default_locale = Noosfero.default_locale
|
SamsaWebsite::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
use mailcatcher on development
http://mailcatcher.me/
SamsaWebsite::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# mailcatcher http://mailcatcher.me/
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = true
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
config.public_file_server.enabled = true
config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.active_storage.service = :local
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Action Mailer settings
config.action_mailer.delivery_method = :letter_opener_web
# Configure default root URL for generating URLs to routes
config.action_mailer.default_url_options = {
host: 'localhost',
port: 3000
}
# Configure default root URL for email assets
config.action_mailer.asset_host = "http://" + ENV['APP_HOST']
Rails.application.routes.default_url_options = {
host: 'localhost',
port: 3000
}
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
Allow to override active_job adapter
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = true
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
config.public_file_server.enabled = true
config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.active_storage.service = :local
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Action Mailer settings
config.action_mailer.delivery_method = :letter_opener_web
# Configure default root URL for generating URLs to routes
config.action_mailer.default_url_options = {
host: 'localhost',
port: 3000
}
# Configure default root URL for email assets
config.action_mailer.asset_host = "http://" + ENV['APP_HOST']
Rails.application.routes.default_url_options = {
host: 'localhost',
port: 3000
}
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# This is useful to run rails in development with :async queue adapter
if ENV['RAILS_QUEUE_ADAPTER']
config.active_job.queue_adapter = ENV['RAILS_QUEUE_ADAPTER'].to_sym
end
end
|
#
# Copyright (C) 2015 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
Rails.configuration.to_prepare do
LiveEvents.logger = Rails.logger
LiveEvents.cache = Rails.cache
LiveEvents.statsd = InstStatsd::Statsd
LiveEvents.max_queue_size = -> { Setting.get('live_events_max_queue_size', 1000).to_i }
LiveEvents.settings = -> {
plugin_settings = Canvas::Plugin.find(:live_events)&.settings
if plugin_settings && Canvas::Plugin.value_to_boolean(plugin_settings['use_consul'])
Canvas::DynamicSettings.find('live-events', default_ttl: 2.hours)
else
plugin_settings
end
}
end
Increase live events max queue size
closes PLAT-4551
Test Plan:
- n/a
Change-Id: I6a82092fcddf5f382443193f0e5d73eb8913c6d4
Reviewed-on: https://gerrit.instructure.com/198003
Tested-by: Jenkins
Reviewed-by: Weston Dransfield <e9203059795dc94e28a8831c65eb7869e818825e@instructure.com>
QA-Review: Weston Dransfield <e9203059795dc94e28a8831c65eb7869e818825e@instructure.com>
Product-Review: Marc Phillips <b810f855174e0bc032432310b0808df2cf714fbc@instructure.com>
#
# Copyright (C) 2015 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
Rails.configuration.to_prepare do
LiveEvents.logger = Rails.logger
LiveEvents.cache = Rails.cache
LiveEvents.statsd = InstStatsd::Statsd
LiveEvents.max_queue_size = -> { Setting.get('live_events_max_queue_size', 5000).to_i }
LiveEvents.settings = -> {
plugin_settings = Canvas::Plugin.find(:live_events)&.settings
if plugin_settings && Canvas::Plugin.value_to_boolean(plugin_settings['use_consul'])
Canvas::DynamicSettings.find('live-events', default_ttl: 2.hours)
else
plugin_settings
end
}
end
|
Thread.new do
system("rackup private_pub.ru -s thin -E production -o 0.0.0.0 -p 8080")
end
add more verbose private_pub startup command
Thread.new do
system("RAILS_ENV=production bundle exec rackup private_pub.ru -s thin -E production -p 9292")
end
|
# encoding: UTF-8
require_relative '../../lib/rails_admin_extensions/rails_admin_change_state.rb'
require_relative '../../lib/rails_admin_extensions/rails_admin_new.rb'
require_relative '../../lib/rails_admin_extensions/rails_admin_delete.rb'
RailsAdmin.config do |config|
### Popular gems integration
## == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
## == Auth ==
# config.authorize_with do |req|
# redirect_to main_app.root_path unless current_user.try(:admin?)
# if req.action_name == 'statistics' && current_user.role != 'superuser'
# redirect_to dashboard_path
# end
# end
config.authorize_with :cancan, Ability
config.current_user_method(&:current_user)
# config.excluded_models = ['AgeFilter', 'FederalState',
# 'OrganizationConnection', 'Filter']
## == PaperTrail ==
config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
config.included_models = %w(
Organization Website Location FederalState Offer Opening
Category Email UpdateRequest LanguageFilter User Contact
Tag Definition Note Area SearchLocation ContactPerson
Subscription Section NextStep SolutionCategory
LogicVersion SplitBase City TargetAudienceFiltersOffer
)
config.actions do
dashboard # mandatory
index # mandatory
new do
except ['User', 'FederalState', 'Section']
end
export
bulk_delete do
except ['User', 'FederalState', 'Section']
end
show
edit do
except ['Section']
end
delete do
except ['User', 'FederalState', 'Section']
end
show_in_app do
only ['Offer', 'Organization']
end
clone do
except ['Section', 'City', 'TargetAudienceFiltersOffer']
end
# nested_set do
# only ['Category']
# end
nestable do
only ['Category', 'SolutionCategory']
end
change_state
## With an audit adapter, you can add:
history_index
history_show
end
config.model 'Organization' do
list do
field :offers_count
field :name
field :aasm_state
field :creator do
formatted_value do
Creator::Twin.new(bindings[:object]).creator
end
end
field :locations_count
field :created_by
sort_by :offers_count
end
weight(-6)
field :name
field :description do
css_class 'js-count-character'
end
field :notes
field :locations
field :legal_form
field :charitable
field :accredited_institution
field :founded
field :umbrella_filters do
label 'Umbrellas'
help do
'Erforderlich.'
end
end
field :slug do
read_only true
end
field :websites
field :contact_people
field :mailings do
help do
'Dieses Feld nutzt ausschließlich Comms!'
end
end
field :aasm_state do
read_only true
help false
end
# Hidden fields
edit do
field :created_by, :hidden do
visible do
bindings[:object].new_record?
end
default_value do
bindings[:view]._current_user.id
end
end
end
show do
field :offers
field :locations
field :created_by
field :approved_by
field :translation_links do
formatted_value do
en = bindings[:object].translations.where(locale: :en).first
ar = bindings[:object].translations.where(locale: :ar).first
fa = bindings[:object].translations.where(locale: :fa).first
output_string = ''
output_string += if en
"<a href='/organization_translations/#{en.id}/edit'>Englisch</a><br/>"
else
'Englisch (wird noch erstellt)<br/>'
end
output_string += if ar
"<a href='/organization_translations/#{ar.id}/edit'>Arabisch</a><br/>"
else
'Arabisch (wird noch erstellt)<br/>'
end
output_string += if fa
"<a href='/organization_translations/#{fa.id}/edit'>Farsi</a><br/>"
else
'Farsi (wird noch erstellt)<br/>'
end
output_string.html_safe
end
end
end
clone_config do
custom_method :partial_dup
end
export do
field :id
end
end
config.label_methods << :url
config.model 'Website' do
field :host
field :url
field :unreachable_count do
read_only true
end
show do
field :offers
field :organizations
end
end
config.label_methods << :display_name
config.model 'Location' do
list do
field :name
field :organization
field :zip
field :federal_state
field :street
field :city
field :display_name
end
weight(-5)
field :organization
field :name
field :street
field :addition
field :in_germany do
help do
'Für Adressen außerhalb von Deutschland entfernen.'
end
end
field :zip do
help do
'Für Adressen außerhalb von Deutschland optional - ansonsten Länge von 5.'
end
end
field :city
field :federal_state do
inline_add false
inline_edit false
help do
'Für Adressen außerhalb von Deutschland optional - ansonsten Pflicht.'
end
end
field :hq
field :visible do
help do
'Obacht: nur dann entfernen, wenn die Adresse ÜBERALL im Frontend
versteckt werden soll!'
end
end
field :latitude do
read_only true
end
field :longitude do
read_only true
end
show do
field :offers
field :display_name
end
export do
field :id
end
clone_config do
custom_method :partial_dup
end
object_label_method :display_name
end
config.model 'City' do
weight 1
list do
field :id do
sort_reverse false
end
field :name
end
show do
field :name
field :organizations
end
field :name
field :locations do
visible false
end
field :offers do
visible false
end
field :organizations do
visible false
end
end
config.model 'FederalState' do
weight 2
list do
field :id do
sort_reverse false
end
field :name
end
end
config.model 'SplitBase' do
weight(-4)
field(:id) { read_only true }
field :title do
help do
'Erforderlich. Anbieterwording. Direkt von der Anbieterseite kopieren.'
end
end
field :clarat_addition do
help { 'Optional. Auszufüllen bei überschneidenden Titeln.' }
end
field :organization
field :solution_category
field :comments
list do
field :offers
end
show do
field :offers
field :display_name
end
object_label_method :display_name
end
config.model 'Offer' do
weight(-4)
list do
field :name
field :section
field :aasm_state
field :creator do
formatted_value do
Creator::Twin.new(bindings[:object]).creator
end
end
field :expires_at
field :logic_version
field :location
field :approved_at
field :organizations do
searchable :name
end
field :created_by
end
field :section
field :split_base
field :all_inclusive
field :name do
css_class 'js-category-suggestions__trigger'
end
field :description do
css_class 'js-count-character'
end
field :notes
field :next_steps do
css_class 'js-next-steps-offers'
end
field :old_next_steps do
read_only false # set to true once deprecated
end
field :code_word
field :contact_people
field :hide_contact_people do
help do
"Versteckt alle nicht-SPoC Kontaktpersonen in der Angebotsübersicht."
end
end
field :encounter
field :slug do
read_only true
end
field :location
field :area
field :organizations do
help do
'Required. Only approved organizations.'
end
end
field :categories do
label 'Problem categories'
inline_add false
css_class 'js-category-suggestions'
end
field :solution_category do
inline_add false
inline_edit false
end
field :treatment_type
field :trait_filters
field :language_filters do
inline_add false
end
# field :target_audience_filters do
# help do
# 'Richtet sich das Angebot direkt an das Kind, oder an Erwachsene wie
# z.B. die Eltern, einen Nachbarn oder einen Lotsen'
# end
# end
field :target_audience_filters_offers do
visible do
!bindings[:object].new_record?
end
help do
'Richtet sich das Angebot direkt an das Kind, oder an Erwachsene wie
z.B. die Eltern, einen Nachbarn oder einen Lotsen'
end
end
# field :residency_status
# field :participant_structure
# field :gender_first_part_of_stamp
# field :gender_second_part_of_stamp
# field :age_from
# field :age_to
# field :age_visible
field :openings
field :opening_specification do
help do
'Bitte achtet auf eine einheitliche Ausdrucksweise.'
end
end
field :websites
field :tags do
inverse_of :offers
end
field :starts_at do
help do
'Optional. Nur für saisonale Angebote ausfüllen!'
end
end
field :expires_at
field :logic_version
field :aasm_state do
read_only true
help false
end
# Hidden fields
edit do
field :created_by, :hidden do
visible do
bindings[:object].new_record?
end
default_value do
bindings[:view]._current_user.id
end
end
end
show do
field :created_at do
strftime_format "%d. %B %Y"
end
field :created_by
field :completed_at do
strftime_format "%d. %B %Y"
end
field :completed_by
field :approved_at do
strftime_format "%d. %B %Y"
end
field :approved_by
field :translation_links do
formatted_value do
en = bindings[:object].translations.where(locale: :en).first
ar = bindings[:object].translations.where(locale: :ar).first
fa = bindings[:object].translations.where(locale: :fa).first
output_string = ''
output_string += if en
"<a href='/offer_translations/#{en.id}/edit'>Englisch</a><br/>"
else
'Englisch (wird noch erstellt)<br/>'
end
output_string += if ar
"<a href='/offer_translations/#{ar.id}/edit'>Arabisch</a><br/>"
else
'Arabisch (wird noch erstellt)<br/>'
end
output_string += if fa
"<a href='/offer_translations/#{fa.id}/edit'>Farsi</a><br/>"
else
'Farsi (wird noch erstellt)<br/>'
end
output_string.html_safe
end
end
end
clone_config do
custom_method :partial_dup
end
export do
field :id
end
end
config.model 'TargetAudienceFiltersOffer' do
weight 3
field(:id) { read_only true }
field(:offer_id) { read_only true }
field :target_audience_filter
field :residency_status
field :gender_first_part_of_stamp
field :gender_second_part_of_stamp
field :addition
field :age_from
field :age_to
field :age_visible
field(:stamp_de) { read_only true }
field(:stamp_en) { read_only true }
list do
sort_by :id
field :offer_id
field :target_audience_filter
end
edit do
field :offer_id do
read_only do
!bindings[:object].new_record?
end
end
end
# queryable false
# filterable false
object_label_method :name
end
config.model 'ContactPerson' do
object_label_method :display_name
list do
field :id
field :first_name
field :last_name
field :organization
field :offers
field :email_address
field :operational_name
field :local_number_1
field :local_number_2
end
show do
field :gender
field :academic_title
field :position
field :first_name
field :last_name
field :operational_name
field :responsibility
field :area_code_1
field :local_number_1
field :area_code_2
field :local_number_2
field :fax_area_code
field :fax_number
field :street
field :zip_and_city
field :email
field :organization
field :offers
end
field :gender
field :academic_title
field :position do
help do
'Bitte nur für Orga-Kontakte auswählen! Dann aber verpflichtend.'
end
end
field :first_name
field :last_name
field :operational_name do
help do
'Falls es sich nicht um einen persönlichen Ansprechpartner handelt,'\
" hier z.B. 'Zentrale' eintragen."
end
end
field :responsibility do
help do
"Z.b. 'Zuständig für alle Anfragen von Menschen deren Nachname mit den
Buchstaben A-M anfangen'"
end
end
field :area_code_1
field :local_number_1
field :area_code_2
field :local_number_2
field :fax_area_code
field :fax_number
field :street do
help do
"Ausschließlich bei Angeboten mit dem Encounter 'Brief' verwenden."
end
end
field :zip_and_city do
help do
"Ausschließlich bei Angeboten mit dem Encounter 'Brief' verwenden."
end
end
field :email
field :organization
field :offers do
visible false
end
field :spoc do
help do
"Single Point of Contact / Zentrale Anlaufstelle."
end
end
export do
field :id
end
clone_config do
custom_method :partial_dup
end
end
config.model 'Opening' do
field :day do
help do
'Required. Wenn weder "Open" noch "Close" angegeben werden, bedeutet
das an diesem Tag "nach Absprache".'
end
end
field :open do
help do
'Required if "Close" given.'
end
end
field :close do
help do
'Required if "Open" given.'
end
end
field :name do
visible false
end
list do
sort_by :sort_value
field :sort_value do
sort_reverse false
visible false
end
end
end
config.model 'Category' do
weight(-3)
field :name_de
field :keywords_de
field :sections
field :parent
field :sort_order
field :visible
field :name_en
field :keywords_en
field :name_ar
field :keywords_ar
field :name_fa
field :keywords_fa
field :name_tr
field :name_pl
field :name_ru
field :name_fr
field(:id) { read_only true }
object_label_method :name_with_world_suffix_and_optional_asterisk
list do
sort_by :name_de
end
show do
field :offers
field :icon
end
# nested_set(max_depth: 5)
nestable_tree(max_depth: 5)
end
config.model 'NextStep' do
field :text_de
field :text_en
field :text_ar
field :text_fa
field :text_tr
field :text_pl
field :text_ru
field :text_fr
field(:id) { read_only true }
object_label_method :text_de
end
config.model 'SolutionCategory' do
weight(-2)
field :name
field :parent
field(:id) { read_only true }
list do
sort_by :name
end
show do
field :offers
end
nestable_tree(max_depth: 5)
end
config.model 'Definition' do
weight(-4)
field :key
field :explanation
object_label_method :key
end
config.model 'Email' do
weight(-3)
field :address
field :aasm_state do
read_only true
help false
end
list do
field :contact_people
end
show do
field :contact_people
end
object_label_method :address
end
config.model 'Note' do
list do
field :text
field :topic
field :user
field :created_at
field :notable
field :referencable
end
edit do
field :notable
field :text
field :topic
field :referencable
field :user_id, :hidden do
default_value do
bindings[:view]._current_user.id
end
end
end
nested do
field :notable do
visible false
end
field :text do
read_only do
!bindings[:object].new_record?
end
end
field :topic do
read_only do
!bindings[:object].new_record?
end
end
field :referencable do
read_only do
!bindings[:object].new_record?
end
end
end
update do
field :id do
read_only true
end
field :text do
read_only true
end
field :topic do
read_only true
end
field :user do
read_only true
end
field :notable do
read_only true
end
field :user_id do
read_only true
visible false
end
field :referencable
end
end
config.model 'TraitFilter' do
field :id
field :name
field :identifier
end
config.model 'LanguageFilter' do
field :id
field :name
field :identifier
end
config.model 'TargetAudienceFilter' do
field :id
field :name
field :identifier
end
config.model 'Section' do
weight 3
field :id
field :name
field :identifier
end
config.model 'User' do
weight 1
list do
field :id
field :name
field :email
field :role
field :created_at
field :updated_at
end
edit do
field :name do
read_only do
bindings[:object] != bindings[:view].current_user
end
end
field :email do
read_only do
bindings[:object] != bindings[:view].current_user
end
end
field :password do
visible do
bindings[:object] == bindings[:view].current_user
end
end
end
end
config.model 'Tag' do
weight 1
field :name_de
field :keywords_de
field :name_en
field :keywords_en
field :name_ar
field :keywords_ar
field :name_fa
field :keywords_fa
field :name_tr
field :name_pl
field :name_ru
object_label_method :name_de
end
config.model 'Area' do
weight 1
field :id
field :name
field :minlat
field :maxlat
field :minlong
field :maxlong
end
config.model 'Contact' do
weight 2
end
config.model 'Subscription' do
weight 2
end
config.model 'UpdateRequest' do
weight 2
end
config.model 'ContactPersonOffer' do
weight 3
end
config.model 'SearchLocation' do
weight 3
field :query do
read_only true
end
field :latitude do
read_only true
end
field :longitude do
read_only true
end
end
config.model 'LogicVersion' do
weight 3
field :name do
read_only true
end
field :version do
read_only true
end
field :description
end
end
Reorder fields for offer edit
# encoding: UTF-8
require_relative '../../lib/rails_admin_extensions/rails_admin_change_state.rb'
require_relative '../../lib/rails_admin_extensions/rails_admin_new.rb'
require_relative '../../lib/rails_admin_extensions/rails_admin_delete.rb'
RailsAdmin.config do |config|
### Popular gems integration
## == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
## == Auth ==
# config.authorize_with do |req|
# redirect_to main_app.root_path unless current_user.try(:admin?)
# if req.action_name == 'statistics' && current_user.role != 'superuser'
# redirect_to dashboard_path
# end
# end
config.authorize_with :cancan, Ability
config.current_user_method(&:current_user)
# config.excluded_models = ['AgeFilter', 'FederalState',
# 'OrganizationConnection', 'Filter']
## == PaperTrail ==
config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
config.included_models = %w(
Organization Website Location FederalState Offer Opening
Category Email UpdateRequest LanguageFilter User Contact
Tag Definition Note Area SearchLocation ContactPerson
Subscription Section NextStep SolutionCategory
LogicVersion SplitBase City TargetAudienceFiltersOffer
)
config.actions do
dashboard # mandatory
index # mandatory
new do
except ['User', 'FederalState', 'Section']
end
export
bulk_delete do
except ['User', 'FederalState', 'Section']
end
show
edit do
except ['Section']
end
delete do
except ['User', 'FederalState', 'Section']
end
show_in_app do
only ['Offer', 'Organization']
end
clone do
except ['Section', 'City', 'TargetAudienceFiltersOffer']
end
# nested_set do
# only ['Category']
# end
nestable do
only ['Category', 'SolutionCategory']
end
change_state
## With an audit adapter, you can add:
history_index
history_show
end
config.model 'Organization' do
list do
field :offers_count
field :name
field :aasm_state
field :creator do
formatted_value do
Creator::Twin.new(bindings[:object]).creator
end
end
field :locations_count
field :created_by
sort_by :offers_count
end
weight(-6)
field :name
field :description do
css_class 'js-count-character'
end
field :notes
field :locations
field :legal_form
field :charitable
field :accredited_institution
field :founded
field :umbrella_filters do
label 'Umbrellas'
help do
'Erforderlich.'
end
end
field :slug do
read_only true
end
field :websites
field :contact_people
field :mailings do
help do
'Dieses Feld nutzt ausschließlich Comms!'
end
end
field :aasm_state do
read_only true
help false
end
# Hidden fields
edit do
field :created_by, :hidden do
visible do
bindings[:object].new_record?
end
default_value do
bindings[:view]._current_user.id
end
end
end
show do
field :offers
field :locations
field :created_by
field :approved_by
field :translation_links do
formatted_value do
en = bindings[:object].translations.where(locale: :en).first
ar = bindings[:object].translations.where(locale: :ar).first
fa = bindings[:object].translations.where(locale: :fa).first
output_string = ''
output_string += if en
"<a href='/organization_translations/#{en.id}/edit'>Englisch</a><br/>"
else
'Englisch (wird noch erstellt)<br/>'
end
output_string += if ar
"<a href='/organization_translations/#{ar.id}/edit'>Arabisch</a><br/>"
else
'Arabisch (wird noch erstellt)<br/>'
end
output_string += if fa
"<a href='/organization_translations/#{fa.id}/edit'>Farsi</a><br/>"
else
'Farsi (wird noch erstellt)<br/>'
end
output_string.html_safe
end
end
end
clone_config do
custom_method :partial_dup
end
export do
field :id
end
end
config.label_methods << :url
config.model 'Website' do
field :host
field :url
field :unreachable_count do
read_only true
end
show do
field :offers
field :organizations
end
end
config.label_methods << :display_name
config.model 'Location' do
list do
field :name
field :organization
field :zip
field :federal_state
field :street
field :city
field :display_name
end
weight(-5)
field :organization
field :name
field :street
field :addition
field :in_germany do
help do
'Für Adressen außerhalb von Deutschland entfernen.'
end
end
field :zip do
help do
'Für Adressen außerhalb von Deutschland optional - ansonsten Länge von 5.'
end
end
field :city
field :federal_state do
inline_add false
inline_edit false
help do
'Für Adressen außerhalb von Deutschland optional - ansonsten Pflicht.'
end
end
field :hq
field :visible do
help do
'Obacht: nur dann entfernen, wenn die Adresse ÜBERALL im Frontend
versteckt werden soll!'
end
end
field :latitude do
read_only true
end
field :longitude do
read_only true
end
show do
field :offers
field :display_name
end
export do
field :id
end
clone_config do
custom_method :partial_dup
end
object_label_method :display_name
end
config.model 'City' do
weight 1
list do
field :id do
sort_reverse false
end
field :name
end
show do
field :name
field :organizations
end
field :name
field :locations do
visible false
end
field :offers do
visible false
end
field :organizations do
visible false
end
end
config.model 'FederalState' do
weight 2
list do
field :id do
sort_reverse false
end
field :name
end
end
config.model 'SplitBase' do
weight(-4)
field(:id) { read_only true }
field :title do
help do
'Erforderlich. Anbieterwording. Direkt von der Anbieterseite kopieren.'
end
end
field :clarat_addition do
help { 'Optional. Auszufüllen bei überschneidenden Titeln.' }
end
field :organization
field :solution_category
field :comments
list do
field :offers
end
show do
field :offers
field :display_name
end
object_label_method :display_name
end
config.model 'Offer' do
weight(-4)
list do
field :name
field :section
field :aasm_state
field :creator do
formatted_value do
Creator::Twin.new(bindings[:object]).creator
end
end
field :expires_at
field :logic_version
field :location
field :approved_at
field :organizations do
searchable :name
end
field :created_by
end
field :section
field :split_base
field :all_inclusive
field :name do
css_class 'js-category-suggestions__trigger'
end
field :description do
css_class 'js-count-character'
end
field :notes
field :next_steps do
css_class 'js-next-steps-offers'
end
field :old_next_steps do
read_only false # set to true once deprecated
end
field :code_word
field :contact_people
field :hide_contact_people do
help do
"Versteckt alle nicht-SPoC Kontaktpersonen in der Angebotsübersicht."
end
end
field :encounter
field :slug do
read_only true
end
field :location
field :area
field :organizations do
help do
'Required. Only approved organizations.'
end
end
field :categories do
label 'Problem categories'
inline_add false
css_class 'js-category-suggestions'
end
field :tags do
inverse_of :offers
end
field :solution_category do
inline_add false
inline_edit false
end
field :treatment_type
field :trait_filters
field :language_filters do
inline_add false
end
# field :target_audience_filters do
# help do
# 'Richtet sich das Angebot direkt an das Kind, oder an Erwachsene wie
# z.B. die Eltern, einen Nachbarn oder einen Lotsen'
# end
# end
field :target_audience_filters_offers do
visible do
!bindings[:object].new_record?
end
help do
'Richtet sich das Angebot direkt an das Kind, oder an Erwachsene wie
z.B. die Eltern, einen Nachbarn oder einen Lotsen'
end
end
# field :residency_status
# field :participant_structure
# field :gender_first_part_of_stamp
# field :gender_second_part_of_stamp
# field :age_from
# field :age_to
# field :age_visible
field :openings
field :opening_specification do
help do
'Bitte achtet auf eine einheitliche Ausdrucksweise.'
end
end
field :websites
field :starts_at do
help do
'Optional. Nur für saisonale Angebote ausfüllen!'
end
end
field :expires_at
field :logic_version
field :aasm_state do
read_only true
help false
end
# Hidden fields
edit do
field :created_by, :hidden do
visible do
bindings[:object].new_record?
end
default_value do
bindings[:view]._current_user.id
end
end
end
show do
field :created_at do
strftime_format "%d. %B %Y"
end
field :created_by
field :completed_at do
strftime_format "%d. %B %Y"
end
field :completed_by
field :approved_at do
strftime_format "%d. %B %Y"
end
field :approved_by
field :translation_links do
formatted_value do
en = bindings[:object].translations.where(locale: :en).first
ar = bindings[:object].translations.where(locale: :ar).first
fa = bindings[:object].translations.where(locale: :fa).first
output_string = ''
output_string += if en
"<a href='/offer_translations/#{en.id}/edit'>Englisch</a><br/>"
else
'Englisch (wird noch erstellt)<br/>'
end
output_string += if ar
"<a href='/offer_translations/#{ar.id}/edit'>Arabisch</a><br/>"
else
'Arabisch (wird noch erstellt)<br/>'
end
output_string += if fa
"<a href='/offer_translations/#{fa.id}/edit'>Farsi</a><br/>"
else
'Farsi (wird noch erstellt)<br/>'
end
output_string.html_safe
end
end
end
clone_config do
custom_method :partial_dup
end
export do
field :id
end
end
config.model 'TargetAudienceFiltersOffer' do
weight 3
field(:id) { read_only true }
field(:offer_id) { read_only true }
field :target_audience_filter
field :residency_status
field :gender_first_part_of_stamp
field :gender_second_part_of_stamp
field :addition
field :age_from
field :age_to
field :age_visible
field(:stamp_de) { read_only true }
field(:stamp_en) { read_only true }
list do
sort_by :id
field :offer_id
field :target_audience_filter
end
edit do
field :offer_id do
read_only do
!bindings[:object].new_record?
end
end
end
# queryable false
# filterable false
object_label_method :name
end
config.model 'ContactPerson' do
object_label_method :display_name
list do
field :id
field :first_name
field :last_name
field :organization
field :offers
field :email_address
field :operational_name
field :local_number_1
field :local_number_2
end
show do
field :gender
field :academic_title
field :position
field :first_name
field :last_name
field :operational_name
field :responsibility
field :area_code_1
field :local_number_1
field :area_code_2
field :local_number_2
field :fax_area_code
field :fax_number
field :street
field :zip_and_city
field :email
field :organization
field :offers
end
field :gender
field :academic_title
field :position do
help do
'Bitte nur für Orga-Kontakte auswählen! Dann aber verpflichtend.'
end
end
field :first_name
field :last_name
field :operational_name do
help do
'Falls es sich nicht um einen persönlichen Ansprechpartner handelt,'\
" hier z.B. 'Zentrale' eintragen."
end
end
field :responsibility do
help do
"Z.b. 'Zuständig für alle Anfragen von Menschen deren Nachname mit den
Buchstaben A-M anfangen'"
end
end
field :area_code_1
field :local_number_1
field :area_code_2
field :local_number_2
field :fax_area_code
field :fax_number
field :street do
help do
"Ausschließlich bei Angeboten mit dem Encounter 'Brief' verwenden."
end
end
field :zip_and_city do
help do
"Ausschließlich bei Angeboten mit dem Encounter 'Brief' verwenden."
end
end
field :email
field :organization
field :offers do
visible false
end
field :spoc do
help do
"Single Point of Contact / Zentrale Anlaufstelle."
end
end
export do
field :id
end
clone_config do
custom_method :partial_dup
end
end
config.model 'Opening' do
field :day do
help do
'Required. Wenn weder "Open" noch "Close" angegeben werden, bedeutet
das an diesem Tag "nach Absprache".'
end
end
field :open do
help do
'Required if "Close" given.'
end
end
field :close do
help do
'Required if "Open" given.'
end
end
field :name do
visible false
end
list do
sort_by :sort_value
field :sort_value do
sort_reverse false
visible false
end
end
end
config.model 'Category' do
weight(-3)
field :name_de
field :keywords_de
field :sections
field :parent
field :sort_order
field :visible
field :name_en
field :keywords_en
field :name_ar
field :keywords_ar
field :name_fa
field :keywords_fa
field :name_tr
field :name_pl
field :name_ru
field :name_fr
field(:id) { read_only true }
object_label_method :name_with_world_suffix_and_optional_asterisk
list do
sort_by :name_de
end
show do
field :offers
field :icon
end
# nested_set(max_depth: 5)
nestable_tree(max_depth: 5)
end
config.model 'NextStep' do
field :text_de
field :text_en
field :text_ar
field :text_fa
field :text_tr
field :text_pl
field :text_ru
field :text_fr
field(:id) { read_only true }
object_label_method :text_de
end
config.model 'SolutionCategory' do
weight(-2)
field :name
field :parent
field(:id) { read_only true }
list do
sort_by :name
end
show do
field :offers
end
nestable_tree(max_depth: 5)
end
config.model 'Definition' do
weight(-4)
field :key
field :explanation
object_label_method :key
end
config.model 'Email' do
weight(-3)
field :address
field :aasm_state do
read_only true
help false
end
list do
field :contact_people
end
show do
field :contact_people
end
object_label_method :address
end
config.model 'Note' do
list do
field :text
field :topic
field :user
field :created_at
field :notable
field :referencable
end
edit do
field :notable
field :text
field :topic
field :referencable
field :user_id, :hidden do
default_value do
bindings[:view]._current_user.id
end
end
end
nested do
field :notable do
visible false
end
field :text do
read_only do
!bindings[:object].new_record?
end
end
field :topic do
read_only do
!bindings[:object].new_record?
end
end
field :referencable do
read_only do
!bindings[:object].new_record?
end
end
end
update do
field :id do
read_only true
end
field :text do
read_only true
end
field :topic do
read_only true
end
field :user do
read_only true
end
field :notable do
read_only true
end
field :user_id do
read_only true
visible false
end
field :referencable
end
end
config.model 'TraitFilter' do
field :id
field :name
field :identifier
end
config.model 'LanguageFilter' do
field :id
field :name
field :identifier
end
config.model 'TargetAudienceFilter' do
field :id
field :name
field :identifier
end
config.model 'Section' do
weight 3
field :id
field :name
field :identifier
end
config.model 'User' do
weight 1
list do
field :id
field :name
field :email
field :role
field :created_at
field :updated_at
end
edit do
field :name do
read_only do
bindings[:object] != bindings[:view].current_user
end
end
field :email do
read_only do
bindings[:object] != bindings[:view].current_user
end
end
field :password do
visible do
bindings[:object] == bindings[:view].current_user
end
end
end
end
config.model 'Tag' do
weight 1
field :name_de
field :keywords_de
field :name_en
field :keywords_en
field :name_ar
field :keywords_ar
field :name_fa
field :keywords_fa
field :name_tr
field :name_pl
field :name_ru
object_label_method :name_de
end
config.model 'Area' do
weight 1
field :id
field :name
field :minlat
field :maxlat
field :minlong
field :maxlong
end
config.model 'Contact' do
weight 2
end
config.model 'Subscription' do
weight 2
end
config.model 'UpdateRequest' do
weight 2
end
config.model 'ContactPersonOffer' do
weight 3
end
config.model 'SearchLocation' do
weight 3
field :query do
read_only true
end
field :latitude do
read_only true
end
field :longitude do
read_only true
end
end
config.model 'LogicVersion' do
weight 3
field :name do
read_only true
end
field :version do
read_only true
end
field :description
end
end
|
require 'rubygems'
require 'fileutils'
require 'yaml'
require 'erb'
APPLICATION = "'RITES Investigations'"
puts "\nInitial setup of #{APPLICATION} Rails application ...\n"
JRUBY = defined? RUBY_ENGINE && RUBY_ENGINE == 'jruby'
RAILS_ROOT = File.expand_path(File.dirname(File.dirname(__FILE__)))
APP_DIR_NAME = File.basename(RAILS_ROOT)
# Add the unpacked gems in vendor/gems to the $LOAD_PATH
Dir["#{RAILS_ROOT}/vendor/gems/**"].each do |dir|
$LOAD_PATH << File.expand_path(File.directory?(lib = "#{dir}/lib") ? lib : dir)
end
require 'uuidtools'
require 'highline/import'
def jruby_system_command
JRUBY ? "jruby -S" : ""
end
def gem_install_command_strings(missing_gems)
command = JRUBY ? " jruby -S gem install " : " sudo ruby gem install "
command + missing_gems.collect {|g| "#{g[0]} -v'#{g[1]}'"}.join(' ') + "\n"
end
def rails_file_path(*args)
File.join([RAILS_ROOT] + args)
end
def rails_file_exists?(*args)
File.exists?(rails_file_path(args))
end
@db_config_path = rails_file_path(%w{config database.yml})
@db_config_sample_path = rails_file_path(%w{config database.sample.yml})
@settings_config_path = rails_file_path(%w{config settings.yml})
@settings_config_sample_path = rails_file_path(%w{config settings.sample.yml})
@rinet_data_config_path = rails_file_path(%w{config rinet_data.yml})
@rinet_data_config_sample_path = rails_file_path(%w{config rinet_data.sample.yml})
@mailer_config_path = rails_file_path(%w{config mailer.yml})
@mailer_config_sample_path = rails_file_path(%w{config mailer.sample.yml})
@db_config_sample = YAML::load(IO.read(@db_config_sample_path))
@settings_config_sample = YAML::load(IO.read(@settings_config_sample_path))
@rinet_data_sample_config = YAML::load(IO.read(@rinet_data_config_sample_path))
@mailer_config_sample = YAML::load(IO.read(@mailer_config_sample_path))
@new_database_yml_created = false
@new_settings_yml_created = false
@new_rinet_data_yml_created = false
@new_mailer_yml_created = false
def copy_file(source, destination)
puts <<HEREDOC
copying: #{source}
to: #{destination}
HEREDOC
FileUtils.cp(source, destination)
end
@missing_gems = []
# These gems need to be installed with the Ruby VM for the web application
if JRUBY
@gems_needed_at_start = [
['rake', '>=0.8.7'],
['activerecord-jdbcmysql-adapter', '>=0.9.2'],
['jruby-openssl', '>=0.5.2']
]
else
@gems_needed_at_start = [['mysql', '>= 2.7']]
end
@gems_needed_at_start.each do |gem_name_and_version|
begin
gem gem_name_and_version[0], gem_name_and_version[1]
rescue Gem::LoadError
@missing_gems << gem_name_and_version
end
begin
require gem_name_and_version[0]
rescue LoadError
end
end
if @missing_gems.length > 0
message = "\n\n*** Please install the following gems: (#{@missing_gems.join(', ')}) and run config/setup.rb again.\n"
message << "\n#{gem_install_command_strings(@missing_gems)}\n"
raise message
end
# returns true if @db_name_prefix on entry == @db_name_prefix on exit
# false otherwise
def confirm_database_name_prefix_user_password
original_db_name_prefix = @db_name_prefix
puts <<HEREDOC
The default prefix for specifying the database names will be: #{@db_name_prefix}.
You can specify a different prefix for the database names:
HEREDOC
@db_name_prefix = ask(" database name prefix: ") { |q| q.default = @db_name_prefix }
if @db_name_prefix == original_db_name_prefix
@db_user = ask(" database username: ") { |q| q.default = 'root' }
@db_password = ask(" database password: ") { |q| q.default = 'password' }
true
else
false
end
end
def create_new_database_yml
raise "the instance variable @db_name_prefix must be set before calling create_new_database_yml" unless @db_name_prefix
@db_config = @db_config_sample
%w{development test staging production}.each do |env|
@db_config[env]['database'] = "#{@db_name_prefix}_#{env}"
@db_config[env]['username'] = @db_user
@db_config[env]['password'] = @db_password
end
%w{itsi ccportal}.each do |external_db|
@db_config[external_db]['username'] = @db_user
@db_config[external_db]['password'] = @db_password
end
puts <<HEREDOC
creating: #{@db_config_path}
from template: #{@db_config_sample_path}
using database name prefix: #{@db_name_prefix}
HEREDOC
File.open(@db_config_path, 'w') {|f| f.write @db_config.to_yaml }
end
def create_new_settings_yml
@settings_config = @settings_config_sample
puts <<HEREDOC
creating: #{@settings_config_path}
from template: #{@settings_config_sample_path}
HEREDOC
File.open(@settings_config_path, 'w') {|f| f.write @settings_config.to_yaml }
end
def create_new_mailer_yml
@mailer_config = @mailer_config_sample
puts <<HEREDOC
creating: #{@mailer_config_path}
from template: #{@mailer_config_sample_path}
HEREDOC
File.open(@mailer_config_path, 'w') {|f| f.write @mailer_config.to_yaml }
end
def create_new_rinet_data_yml
@rinet_data_config = @rinet_data_sample_config
puts <<HEREDOC
creating: #{@rinet_data_config_path}
from template: #{@rinet_data_config_sample_path}
HEREDOC
File.open(@rinet_data_config_path, 'w') {|f| f.write @rinet_data_config.to_yaml }
end
#
# check for git submodules
#
def check_for_git_submodules
git_modules_path = File.join(rails_file_path, '.gitmodules')
if File.exists?(git_modules_path)
git_modules = File.read(git_modules_path)
git_submodule_paths = git_modules.grep(/path = .*/) { |path| path[/path = (.*)/, 1] }
unless git_submodule_paths.all? { |path| File.exists?(path) }
puts <<HEREDOC
Initializing git submodules ...
HEREDOC
`git submodule init`
`git submodule update`
end
end
end
#
# check for config/database.yml
#
def check_for_config_database_yml
unless File.exists?(@db_config_path)
puts <<HEREDOC
The Rails database configuration file does not yet exist.
HEREDOC
@db_name_prefix = APP_DIR_NAME.gsub(/\W/, '_')
confirm_database_name_prefix_user_password
create_new_database_yml
@new_database_yml_created = true
end
end
#
# check for config/settings.yml
#
def check_for_config_settings_yml
unless File.exists?(@settings_config_path)
puts <<HEREDOC
The Rails application settings file does not yet exist.
HEREDOC
create_new_settings_yml
else
@settings_config = YAML::load(IO.read(@settings_config_path))
puts <<HEREDOC
The Rails application settings file exists, lookking for possible updates ...
HEREDOC
%w{development staging production}.each do |env|
puts "\nchecking environment: #{env}\n"
unless @settings_config[env]['states_and_provinces']
puts <<HEREDOC
The states_and_provinces parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_sample_config[env]['states_and_provinces'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['states_and_provinces'] = @settings_sample_config[env]['states_and_provinces']
end
unless @settings_config[env]['active_grades']
puts <<HEREDOC
The active_grades parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_sample_config[env]['active_grades'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['active_grades'] = @settings_sample_config[env]['active_grades']
end
unless @settings_config[env]['active_school_levels']
puts <<HEREDOC
The active_school_levels parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_sample_config[env]['active_school_levels'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['active_school_levels'] = @settings_sample_config[env]['active_school_levels']
end
unless @settings_config[env]['default_admin_user']
puts <<HEREDOC
Collecting default_admin settings into one hash, :default_admin_user in the #{env} section of settings.yml
HEREDOC
default_admin_user = {}
original_keys = %w{admin_email admin_login admin_first_name admin_last_name}
new_keys = %w{email login first_name last_name}
original_keys.zip(new_keys).each do |key_pair|
default_admin_user[key_pair[1]] = @settings_config[env].delete(key_pair[0])
end
@settings_config[env]['default_admin_user'] = default_admin_user
end
unless @settings_config[env]['default_maven_jnlp']
puts <<HEREDOC
Collecting default_maven_jnlp settings into one hash, :default_maven_jnlp in the #{env} section of settings.yml
HEREDOC
default_maven_jnlp = {}
original_keys = %w{default_maven_jnlp_server default_maven_jnlp_family default_maven_jnlp_version}
new_keys = %w{server family version}
original_keys.zip(new_keys).each do |key_pair|
default_maven_jnlp[key_pair[1]] = @settings_config[env].delete(key_pair[0])
end
@settings_config[env]['default_maven_jnlp'] = default_maven_jnlp
end
unless @settings_config[env]['valid_sakai_instances']
puts <<HEREDOC
The valid_sakai_instances parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_sample_config[env]['valid_sakai_instances'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['valid_sakai_instances'] = @settings_sample_config[env]['valid_sakai_instances']
end
end
end
end
#
# check for config/mailer.yml
#
def check_for_config_mailer_yml
unless File.exists?(@mailer_config_path)
puts <<HEREDOC
The Rails mailer configuration file does not yet exist.
HEREDOC
create_new_mailer_yml
end
end
#
# check for config/rinet_data.yml
#
def check_for_config_rinet_data_yml
unless File.exists?(@rinet_data_config_path)
puts <<HEREDOC
The RITES RINET CSV import configuration file does not yet exist.
HEREDOC
create_new_rinet_data_yml
@new_rinet_data_yml_created = true
end
end
#
# check for log/development.log
#
def check_for_log_development_log
@dev_log_path = rails_file_path(%w{log development.log})
unless File.exists?(@dev_log_path)
puts <<HEREDOC
The Rails development log:
#{@dev_log_path} does not yet exist.
#{@dev_log_path} created and permission set to 666
HEREDOC
FileUtils.mkdir(rails_file_path("log")) unless File.exists?(rails_file_path("log"))
FileUtils.touch(@dev_log_path)
FileUtils.chmod(0666, @dev_log_path)
end
end
#
# check for config/initializers/site_keys.rb
#
def check_for_config_initializers_site_keys_rb
site_keys_path = rails_file_path(%w{config initializers site_keys.rb})
unless File.exists?(site_keys_path)
puts <<HEREDOC
The Rails site keys authentication tokens file does not yet exist:
new #{site_keys_path} created.
If you have copied a production database from another app instance you will
need to have the same site keys authentication tokens in order for the existing
User passwords to work.
If you have ssh access to the production deploy site you can install a copy
with this capistrano task:
cap production db:copy_remote_site_keys
HEREDOC
site_key = UUIDTools::UUID.timestamp_create.to_s
site_keys_rb = <<HEREDOC
REST_AUTH_SITE_KEY = '#{site_key}'
REST_AUTH_DIGEST_STRETCHES = 10
HEREDOC
File.open(site_keys_path, 'w') {|f| f.write site_keys_rb }
end
end
#
# update config/database.yml
#
def update_config_database_yml
@db_config = YAML::load(IO.read(@db_config_path))
@db_name_prefix = @db_config['development']['database'][/(.*)_development/, 1]
puts <<HEREDOC
----------------------------------------
Updating the Rails database configuration file: config/database.yml
Specify values for the mysql database name, username and password for the
development staging and production environments.
Here are the current settings in config/database.yml:
#{@db_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
create_new_database_yml unless @new_database_yml_created || confirm_database_name_prefix_user_password
%w{development test production}.each do |env|
puts "\nSetting parameters for the #{env} database:\n\n"
@db_config[env]['database'] = ask(" database name: ") { |q| q.default = @db_config[env]['database'] }
@db_config[env]['username'] = ask(" username: ") { |q| q.default = @db_config[env]['username'] }
@db_config[env]['password'] = ask(" password: ") { |q| q.default = @db_config[env]['password'] }
@db_config[env]['adaptor'] = "<% if RUBY_PLATFORM =~ /java/ %>jdbcmysql<% else %>mysql<% end %>"
end
puts <<HEREDOC
If you have access to a ITSI database for importing ITSI Activities into RITES
specify the values for the mysql database name, host, username, password, and asset_url.
HEREDOC
puts "\nSetting parameters for the ITSI database:\n\n"
@db_config['itsi']['database'] = ask(" database name: ") { |q| q.default = @db_config['itsi']['database'] }
@db_config['itsi']['host'] = ask(" host: ") { |q| q.default = @db_config['itsi']['host'] }
@db_config['itsi']['username'] = ask(" username: ") { |q| q.default = @db_config['itsi']['username'] }
@db_config['itsi']['password'] = ask(" password: ") { |q| q.default = @db_config['itsi']['password'] }
@db_config['itsi']['asset_url'] = ask(" asset url: ") { |q| q.default = @db_config['itsi']['asset_url'] }
@db_config['itsi']['adaptor'] = "<% if RUBY_PLATFORM =~ /java/ %>jdbcmysql<% else %>mysql<% end %>"
puts <<HEREDOC
If you have access to a CCPortal database that indexes ITSI Activities into sequenced Units
specify the values for the mysql database name, host, username, password.
HEREDOC
puts "\nSetting parameters for the CCPortal database:\n\n"
@db_config['ccportal']['database'] = ask(" database name: ") { |q| q.default = @db_config['ccportal']['database'] }
@db_config['ccportal']['host'] = ask(" host: ") { |q| q.default = @db_config['ccportal']['host'] }
@db_config['ccportal']['username'] = ask(" username: ") { |q| q.default = @db_config['ccportal']['username'] }
@db_config['ccportal']['password'] = ask(" password: ") { |q| q.default = @db_config['ccportal']['password'] }
@db_config['ccportal']['adaptor'] = "<% if RUBY_PLATFORM =~ /java/ %>jdbcmysql<% else %>mysql<% end %>"
puts <<HEREDOC
Here is the updated database configuration:
#{@db_config.to_yaml}
HEREDOC
if agree("OK to save to config/database.yml? (y/n): ")
File.open(@db_config_path, 'w') {|f| f.write @db_config.to_yaml }
end
end
end
#
# update config/rinet_data.yml
#
def update_config_rinet_data_yml
@rinet_data_config = YAML::load(IO.read(@rinet_data_config_path))
puts <<HEREDOC
----------------------------------------
Updating the RINET CSV Account import configuration file: config/rinet_data.yml
Specify values for the host, username and password for the RINET SFTP
site to download Sakai account data in CSV format.
Here are the current settings in config/rinet_data.yml:
#{@rinet_data_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
create_new_rinet_data_yml unless @new_rinet_data_yml_created
%w{development test staging production}.each do |env|
puts "\nSetting parameters for the #{env} rinet_data:\n"
@rinet_data_config[env]['host'] = ask(" RINET host: ") { |q| q.default = @rinet_data_config[env]['host'] }
@rinet_data_config[env]['username'] = ask(" RINET username: ") { |q| q.default = @rinet_data_config[env]['username'] }
@rinet_data_config[env]['password'] = ask(" RINET password: ") { |q| q.default = @rinet_data_config[env]['password'] }
puts
end
puts <<HEREDOC
Here is the updated rinet_data configuration:
#{@rinet_data_config.to_yaml}
HEREDOC
if agree("OK to save to config/rinet_data.yml? (y/n): ")
File.open(@rinet_data_config_path, 'w') {|f| f.write @rinet_data_config.to_yaml }
end
end
end
def get_include_otrunk_examples_settings(env)
include_otrunk_examples = @settings_config[env]['include_otrunk_examples']
puts <<HEREDOC
Processing and importing of otrunk-examples can be enabled or disabled.
It is currently #{include_otrunk_examples ? 'disabled' : 'enabled' }.
HEREDOC
@settings_config[env]['include_otrunk_examples'] = agree("Include otrunk-examples? (y/n) ") { |q| q.default = (include_otrunk_examples ? 'y' : 'n') }
end
def get_states_and_provinces_settings(env)
states_and_provinces = (@settings_config[env]['states_and_provinces'] || []).join(' ')
puts <<HEREDOC
Detailed data are imported for the following US schools and district:
#{states_and_provinces}
List state or province abbreviations for the locations you want imported.
Use two-character capital letter abreviations and delimit multiple items with spaces.
HEREDOC
states_and_provinces = @settings_config[env]['states_and_provinces'].join(' ')
states_and_provinces = ask(" states_and_provinces: ") { |q| q.default = states_and_provinces }
@settings_config[env]['states_and_provinces'] = states_and_provinces.split
end
def get_active_grades_settings(env)
active_grades = (@settings_config[env]['active_grades'] || []).join(' ')
puts <<HEREDOC
The following is a list of the active grade:
#{active_grades}
List active grades for this application instance.
Use any of the following:
K 1 2 3 4 5 6 7 8 9 10 11 12
and delimit multiple active grades with a space character.
HEREDOC
active_grades = ask(" active_grades: ") { |q| q.default = active_grades }
@settings_config[env]['active_grades'] = active_grades.split
end
def get_active_school_levels(env)
active_school_levels = (@settings_config[env]['active_school_levels'] || []).join(' ')
puts <<HEREDOC
The following is a list of the active school levels:
#{active_school_levels}
List active school levels for this application instance.
Use any of the following:
1 2 3 4
and delimit multiple active school levels with a space character.
School level. The following codes are used for active school levels:
1 = Primary (low grade = PK through 03; high grade = PK through 08)
2 = Middle (low grade = 04 through 07; high grade = 04 through 09)
3 = High (low grade = 07 through 12; high grade = 12 only
4 = Other (any other configuration not falling within the above three categories, including ungraded)
HEREDOC
active_school_levels = ask(" active_school_levels: ") { |q| q.default = active_school_levels }
@settings_config[env]['active_school_levels'] = active_school_levels.split
end
def get_valid_sakai_instances(env)
puts <<HEREDOC
Specify the sakai server urls from which it is ok to receive linktool requests.
Delimit multiple items with spaces.
HEREDOC
sakai_instances = @settings_config[env]['valid_sakai_instances'].join(' ')
sakai_instances = ask(" valid_sakai_instances: ") { |q| q.default = sakai_instances }
@settings_config[env]['valid_sakai_instances'] = sakai_instances.split
end
def get_maven_jnlp_settings(env)
puts <<HEREDOC
Specify the maven_jnlp server used for providing jnlps and jars dor running Java OTrunk applications.
HEREDOC
maven_jnlp_server = @settings_config[env]['maven_jnlp_servers'][0]
maven_jnlp_server[:host] = ask(" host: ") { |q| q.default = maven_jnlp_server[:host] }
maven_jnlp_server[:path] = ask(" path: ") { |q| q.default = maven_jnlp_server[:path] }
maven_jnlp_server[:name] = ask(" name: ") { |q| q.default = maven_jnlp_server[:name] }
@settings_config[env]['maven_jnlp_servers'][0] = maven_jnlp_server
@settings_config[env]['default_maven_jnlp_server'] = maven_jnlp_server[:name]
@settings_config[env]['default_maven_jnlp_family'] = ask(" default_maven_jnlp_family: ") { |q| q.default = @settings_config[env]['default_maven_jnlp_family'] }
maven_jnlp_families = (@settings_config[env]['maven_jnlp_families'] || []).join(' ')
puts <<HEREDOC
The following is a list of the active maven_jnlp_families:
#{maven_jnlp_families}
Specify which maven_jnlp_families to include. Enter nothing to include all
the maven_jnlp_families. Delimit multiple items with spaces.
HEREDOC
maven_jnlp_families = ask(" active_school_levels: ") { |q| q.default = maven_jnlp_families }
@settings_config[env]['maven_jnlp_families'] = maven_jnlp_families.split
puts <<HEREDOC
Specify the default_jnlp_version to use:
HEREDOC
@settings_config[env]['default_jnlp_version'] = ask(" default_jnlp_version: ") { |q| q.default = @settings_config[env]['default_jnlp_version'] }
end
#
# update config/settings.yml
#
def update_config_settings_yml
puts <<HEREDOC
----------------------------------------
Updating the application settings configuration file: config/settings.yml
Specify general application settings values: site url, site name, and admin name, email, login
for the development staging and production environments.
If you are doing development locally you may want to use one database for development and production.
Some of the importing scripts run much faster in production mode.
HEREDOC
puts <<HEREDOC
Here are the current settings in config/settings.yml:
#{@settings_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
%w{development staging production}.each do |env|
puts "\n#{env}:\n"
@settings_config[env]['site_url'] = ask(" site url: ") { |q| q.default = @settings_config[env]['site_url'] }
@settings_config[env]['site_name'] = ask(" site_name: ") { |q| q.default = @settings_config[env]['site_name'] }
@settings_config[env]['admin_email'] = ask(" admin_email: ") { |q| q.default = @settings_config[env]['admin_email'] }
@settings_config[env]['admin_login'] = ask(" admin_login: ") { |q| q.default = @settings_config[env]['admin_login'] }
@settings_config[env]['admin_first_name'] = ask(" admin_first_name: ") { |q| q.default = @settings_config[env]['admin_first_name'] }
@settings_config[env]['admin_last_name'] = ask(" admin_last_name: ") { |q| q.default = @settings_config[env]['admin_last_name'] }
#
# site_district and site_school
#
puts <<HEREDOC
The site district is a virtual district that contains the site school.
Any full member can become part of the site school and district.
HEREDOC
@settings_config[env]['site_district'] = ask(" site_district: ") { |q| q.default = @settings_config[env]['site_district'] }
@settings_config[env]['site_school'] = ask(" site_school: ") { |q| q.default = @settings_config[env]['site_school'] }
#
# ---- states_and_provinces ----
#
get_states_and_provinces_settings(env)
#
# ---- active_grades ----
#
get_active_grades_settings(env)
#
# ---- valid_sakai_instances ----
#
get_active_school_levels(env)
#
# ---- valid_sakai_instances ----
#
get_valid_sakai_instances(env)
#
# ---- enable_default_users ----
#
puts <<HEREDOC
A number of default users are created that are good for testing but insecure for
production deployments. Setting this value to true will enable the default users
setting it to false will disable the default_users for this envioronment.
HEREDOC
default_users = @settings_config[env]['enable_default_users'].to_s
default_users = ask(" enable_default_users: ", ['true', 'false']) { |q| q.default = default_users }
@settings_config[env]['enable_default_users'] = eval(default_users)
#
# ---- maven_jnlp ----
#
get_maven_jnlp_settings(env)
end # each env
end
puts <<HEREDOC
Here are the updated application settings:
#{@settings_config.to_yaml}
HEREDOC
if agree("OK to save to config/settings.yml? (y/n): ")
File.open(@settings_config_path, 'w') {|f| f.write @settings_config.to_yaml }
end
end
#
# update config/mailer.yml
#
def update_config_mailer_yml
@mailer_config = YAML::load(IO.read(@mailer_config_path))
delivery_types = [:test, :smtp, :sendmail]
deliv_types = delivery_types.collect { |deliv| deliv.to_s }.join(' | ')
authentication_types = [:plain, :login, :cram_md5]
auth_types = authentication_types.collect { |auth| auth.to_s }.join(' | ')
puts @mailer_config_sample_config
puts <<HEREDOC
----------------------------------------
Updating the Rails mailer configuration file: config/mailer.yml
You will need to specify values for the SMTP mail server this #{APPLICATION} instance will
use to send outgoing mail. In addition you need to specify the hostname of this specific
#{APPLICATION} instance.
The SMTP parameters are used to send user account activation emails to new users and the
hostname of the #{APPLICATION} is used as part of account activation url rendered into the
body of the email.
You will need to specify a mail delivery method: (#{deliv_types})
the hostname of the #{APPLICATION} without the protocol: (example: #{@mailer_config_sample[:host]})
If you do not have a working SMTP server select the test deliver method instead of the
smtp delivery method. The activivation emails will appear in #{@dev_log_path}. You can
easily see then as the are generated with this command:
tail -f -n 100 #{@dev_log_path}
You will also need to specify:
the hostname of the #{APPLICATION} application without the protocol: (example: #{@mailer_config_sample[:host]})
and a series of SMTP server values:
host name of the remote mail server: (example: #{@mailer_config_sample[:smtp][:address]}))
port the SMTP server runs on (most run on port 25)
SMTP helo domain
authentication method for sending mail: (#{auth_types})
username (only applies to the :login and :cram-md5 athentication methods)
password (only applies to the :login and :cram-md5 athentication methods)
Here are the current settings in config/mailer.yml:
#{@mailer_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
say("\nChoose mail delivery type: #{deliv_types}:\n\n")
@mailer_config[:delivery_type] = ask(" delivery type: ", delivery_types) { |q|
q.default = "test"
}
@mailer_config[:host] = ask(" #{APPLICATION} hostname: ") { |q| q.default = @mailer_config[:host] }
@mailer_config[:smtp][:address] = ask(" SMTP address: ") { |q|
q.default = @mailer_config[:smtp][:address]
}
@mailer_config[:smtp][:port] = ask(" SMTP port: ", Integer) { |q|
q.default = @mailer_config[:smtp][:port]
q.in = 25..65535
}
@mailer_config[:smtp][:domain] = ask(" SMTP domain: ") { |q|
q.default = @mailer_config[:smtp][:domain]
}
say("\nChoose SMTP authentication type: #{auth_types}:\n\n")
@mailer_config[:smtp][:authentication] = ask(" SMTP auth type: ", authentication_types) { |q|
q.default = "login"
}
@mailer_config[:smtp][:user_name] = ask(" SMTP username: ") { |q|
q.default = @mailer_config[:smtp][:user_name]
}
@mailer_config[:smtp][:password] = ask(" SMTP password: ") { |q|
q.default = @mailer_config[:smtp][:password]
}
end
puts <<HEREDOC
Here is the new mailer configuration:
#{@mailer_config.to_yaml}
HEREDOC
if agree("OK to save to config/mailer.yml? (y/n): ")
File.open(@mailer_config_path, 'w') {|f| f.write @mailer_config.to_yaml }
end
end
# *****************************************************
puts <<HEREDOC
This setup program will help you configure a new #{APPLICATION} instance.
HEREDOC
check_for_git_submodules
check_for_config_database_yml
check_for_config_settings_yml
check_for_config_rinet_data_yml
check_for_config_mailer_yml
check_for_log_development_log
check_for_config_initializers_site_keys_rb
update_config_database_yml
update_config_settings_yml
update_config_rinet_data_yml
update_config_mailer_yml
puts <<HEREDOC
Finished configuring application settings.
********************************************************************
*** If you are also setting up an application from scratch and ***
*** need to create or recreate the resources in the database ***
*** follow the steps below: ***
********************************************************************
MRI Ruby:
rake gems:install
RAILS_ENV=production rake db:migrate:reset
RAILS_ENV=production rake rigse:setup:new_rites_app
JRuby:
jruby -S rake gems:install
RAILS_ENV=production jruby -S rake db:migrate:reset
RAILS_ENV=production jruby -S rake rigse:setup:new_rites_app
These scripts will take about 5-30 minutes to run and are much faster if you are both running
Rails in production mode and using JRuby. If you are using separate databases for development and
production and want to run these tasks to populate a development database I recommend temporarily
identifying the development database as production for the purpose of generating these data.
HEREDOC
setup.rb creates more test and cucumber settings
If the cucumber ENV settings don't exist run:
ruby config/setup
to update settings.yml and database.yml with
require 'rubygems'
require 'fileutils'
require 'yaml'
require 'erb'
APPLICATION = "'RITES Investigations'"
puts "\nInitial setup of #{APPLICATION} Rails application ...\n"
JRUBY = defined? RUBY_ENGINE && RUBY_ENGINE == 'jruby'
RAILS_ROOT = File.expand_path(File.dirname(File.dirname(__FILE__)))
APP_DIR_NAME = File.basename(RAILS_ROOT)
# Add the unpacked gems in vendor/gems to the $LOAD_PATH
Dir["#{RAILS_ROOT}/vendor/gems/**"].each do |dir|
$LOAD_PATH << File.expand_path(File.directory?(lib = "#{dir}/lib") ? lib : dir)
end
require 'uuidtools'
require 'highline/import'
def jruby_system_command
JRUBY ? "jruby -S" : ""
end
def gem_install_command_strings(missing_gems)
command = JRUBY ? " jruby -S gem install " : " sudo ruby gem install "
command + missing_gems.collect {|g| "#{g[0]} -v'#{g[1]}'"}.join(' ') + "\n"
end
def rails_file_path(*args)
File.join([RAILS_ROOT] + args)
end
def rails_file_exists?(*args)
File.exists?(rails_file_path(args))
end
@db_config_path = rails_file_path(%w{config database.yml})
@db_config_sample_path = rails_file_path(%w{config database.sample.yml})
@settings_config_path = rails_file_path(%w{config settings.yml})
@settings_config_sample_path = rails_file_path(%w{config settings.sample.yml})
@rinet_data_config_path = rails_file_path(%w{config rinet_data.yml})
@rinet_data_config_sample_path = rails_file_path(%w{config rinet_data.sample.yml})
@mailer_config_path = rails_file_path(%w{config mailer.yml})
@mailer_config_sample_path = rails_file_path(%w{config mailer.sample.yml})
@db_config_sample = YAML::load_file(@db_config_sample_path)
@settings_config_sample = YAML::load_file(@settings_config_sample_path)
@rinet_data_config_sample = YAML::load_file(@rinet_data_config_sample_path)
@mailer_config_sample = YAML::load_file(@mailer_config_sample_path)
@new_database_yml_created = false
@new_settings_yml_created = false
@new_rinet_data_yml_created = false
@new_mailer_yml_created = false
def copy_file(source, destination)
puts <<HEREDOC
copying: #{source}
to: #{destination}
HEREDOC
FileUtils.cp(source, destination)
end
@missing_gems = []
# These gems need to be installed with the Ruby VM for the web application
if JRUBY
@gems_needed_at_start = [
['rake', '>=0.8.7'],
['activerecord-jdbcmysql-adapter', '>=0.9.2'],
['jruby-openssl', '>=0.5.2']
]
else
@gems_needed_at_start = [['mysql', '>= 2.7']]
end
@gems_needed_at_start.each do |gem_name_and_version|
begin
gem gem_name_and_version[0], gem_name_and_version[1]
rescue Gem::LoadError
@missing_gems << gem_name_and_version
end
begin
require gem_name_and_version[0]
rescue LoadError
end
end
if @missing_gems.length > 0
message = "\n\n*** Please install the following gems: (#{@missing_gems.join(', ')}) and run config/setup.rb again.\n"
message << "\n#{gem_install_command_strings(@missing_gems)}\n"
raise message
end
# returns true if @db_name_prefix on entry == @db_name_prefix on exit
# false otherwise
def confirm_database_name_prefix_user_password
original_db_name_prefix = @db_name_prefix
puts <<HEREDOC
The default prefix for specifying the database names will be: #{@db_name_prefix}.
You can specify a different prefix for the database names:
HEREDOC
@db_name_prefix = ask(" database name prefix: ") { |q| q.default = @db_name_prefix }
if @db_name_prefix == original_db_name_prefix
@db_user = ask(" database username: ") { |q| q.default = 'root' }
@db_password = ask(" database password: ") { |q| q.default = 'password' }
true
else
false
end
end
def create_new_database_yml
raise "the instance variable @db_name_prefix must be set before calling create_new_database_yml" unless @db_name_prefix
@db_config = @db_config_sample
%w{development test staging production}.each do |env|
@db_config[env]['database'] = "#{@db_name_prefix}_#{env}"
@db_config[env]['username'] = @db_user
@db_config[env]['password'] = @db_password
end
%w{itsi ccportal}.each do |external_db|
@db_config[external_db]['username'] = @db_user
@db_config[external_db]['password'] = @db_password
end
puts <<HEREDOC
creating: #{@db_config_path}
from template: #{@db_config_sample_path}
using database name prefix: #{@db_name_prefix}
HEREDOC
File.open(@db_config_path, 'w') {|f| f.write @db_config.to_yaml }
end
def create_new_settings_yml
@settings_config = @settings_config_sample
puts <<HEREDOC
creating: #{@settings_config_path}
from template: #{@settings_config_sample_path}
HEREDOC
File.open(@settings_config_path, 'w') {|f| f.write @settings_config.to_yaml }
end
def create_new_mailer_yml
@mailer_config = @mailer_config_sample
puts <<HEREDOC
creating: #{@mailer_config_path}
from template: #{@mailer_config_sample_path}
HEREDOC
File.open(@mailer_config_path, 'w') {|f| f.write @mailer_config.to_yaml }
end
def create_new_rinet_data_yml
@rinet_data_config = @rinet_data_config_sample
puts <<HEREDOC
creating: #{@rinet_data_config_path}
from template: #{@rinet_data_config_sample_path}
HEREDOC
File.open(@rinet_data_config_path, 'w') {|f| f.write @rinet_data_config.to_yaml }
end
#
# check for git submodules
#
def check_for_git_submodules
git_modules_path = File.join(rails_file_path, '.gitmodules')
if File.exists?(git_modules_path)
git_modules = File.read(git_modules_path)
git_submodule_paths = git_modules.grep(/path = .*/) { |path| path[/path = (.*)/, 1] }
unless git_submodule_paths.all? { |path| File.exists?(path) }
puts <<HEREDOC
Initializing git submodules ...
HEREDOC
`git submodule init`
`git submodule update`
end
end
end
#
# check for config/database.yml
#
def check_for_config_database_yml
unless File.exists?(@db_config_path)
puts <<HEREDOC
The Rails database configuration file does not yet exist.
HEREDOC
@db_name_prefix = APP_DIR_NAME.gsub(/\W/, '_')
confirm_database_name_prefix_user_password
create_new_database_yml
@new_database_yml_created = true
end
end
#
# check for config/settings.yml
#
def check_for_config_settings_yml
unless File.exists?(@settings_config_path)
puts <<HEREDOC
The Rails application settings file does not yet exist.
HEREDOC
create_new_settings_yml
else
@settings_config = YAML::load_file(@settings_config_path)
puts <<HEREDOC
The Rails application settings file exists, looking for possible updates ...
HEREDOC
%w{development test cucumber staging production}.each do |env|
puts "\nchecking environment: #{env}\n"
unless @settings_config[env]
puts <<HEREDOC
The '#{env}' section of settings.yml does not yet exist, copying all of: #{env} from settings.sample.yml
HEREDOC
@settings_config[env] = @settings_config_sample[env]
else
unless @settings_config[env]['states_and_provinces']
puts <<HEREDOC
The states_and_provinces parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_config_sample[env]['states_and_provinces'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['states_and_provinces'] = @settings_config_sample[env]['states_and_provinces']
end
unless @settings_config[env]['active_grades']
puts <<HEREDOC
The active_grades parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_config_sample[env]['active_grades'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['active_grades'] = @settings_config_sample[env]['active_grades']
end
unless @settings_config[env]['active_school_levels']
puts <<HEREDOC
The active_school_levels parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_config_sample[env]['active_school_levels'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['active_school_levels'] = @settings_config_sample[env]['active_school_levels']
end
unless @settings_config[env]['default_admin_user']
puts <<HEREDOC
Collecting default_admin settings into one hash, :default_admin_user in the #{env} section of settings.yml
HEREDOC
default_admin_user = {}
original_keys = %w{admin_email admin_login admin_first_name admin_last_name}
new_keys = %w{email login first_name last_name}
original_keys.zip(new_keys).each do |key_pair|
default_admin_user[key_pair[1]] = @settings_config[env].delete(key_pair[0])
end
@settings_config[env]['default_admin_user'] = default_admin_user
end
unless @settings_config[env]['default_maven_jnlp']
puts <<HEREDOC
Collecting default_maven_jnlp settings into one hash, :default_maven_jnlp in the #{env} section of settings.yml
HEREDOC
default_maven_jnlp = {}
original_keys = %w{default_maven_jnlp_server default_maven_jnlp_family default_maven_jnlp_version}
new_keys = %w{server family version}
original_keys.zip(new_keys).each do |key_pair|
default_maven_jnlp[key_pair[1]] = @settings_config[env].delete(key_pair[0])
end
@settings_config[env]['default_maven_jnlp'] = default_maven_jnlp
end
unless @settings_config[env]['valid_sakai_instances']
puts <<HEREDOC
The valid_sakai_instances parameter does not yet exist in the #{env} section of settings.yml
Copying the values in the sample: #{@settings_config_sample[env]['valid_sakai_instances'].join(', ')} into settings.yml.
HEREDOC
@settings_config[env]['valid_sakai_instances'] = @settings_config_sample[env]['valid_sakai_instances']
end
end
end
end
end
#
# check for config/mailer.yml
#
def check_for_config_mailer_yml
unless File.exists?(@mailer_config_path)
puts <<HEREDOC
The Rails mailer configuration file does not yet exist.
HEREDOC
create_new_mailer_yml
end
end
#
# check for config/rinet_data.yml
#
def check_for_config_rinet_data_yml
unless File.exists?(@rinet_data_config_path)
puts <<HEREDOC
The RITES RINET CSV import configuration file does not yet exist.
HEREDOC
create_new_rinet_data_yml
@new_rinet_data_yml_created = true
end
end
#
# check for log/development.log
#
def check_for_log_development_log
@dev_log_path = rails_file_path(%w{log development.log})
unless File.exists?(@dev_log_path)
puts <<HEREDOC
The Rails development log:
#{@dev_log_path} does not yet exist.
#{@dev_log_path} created and permission set to 666
HEREDOC
FileUtils.mkdir(rails_file_path("log")) unless File.exists?(rails_file_path("log"))
FileUtils.touch(@dev_log_path)
FileUtils.chmod(0666, @dev_log_path)
end
end
#
# check for config/initializers/site_keys.rb
#
def check_for_config_initializers_site_keys_rb
site_keys_path = rails_file_path(%w{config initializers site_keys.rb})
unless File.exists?(site_keys_path)
puts <<HEREDOC
The Rails site keys authentication tokens file does not yet exist:
new #{site_keys_path} created.
If you have copied a production database from another app instance you will
need to have the same site keys authentication tokens in order for the existing
User passwords to work.
If you have ssh access to the production deploy site you can install a copy
with this capistrano task:
cap production db:copy_remote_site_keys
HEREDOC
site_key = UUIDTools::UUID.timestamp_create.to_s
site_keys_rb = <<HEREDOC
REST_AUTH_SITE_KEY = '#{site_key}'
REST_AUTH_DIGEST_STRETCHES = 10
HEREDOC
File.open(site_keys_path, 'w') {|f| f.write site_keys_rb }
end
end
#
# update config/database.yml
#
def update_config_database_yml
@db_config = YAML::load_file(@db_config_path)
@db_name_prefix = @db_config['development']['database'][/(.*)_development/, 1]
unless @db_config['cucumber']
puts "\ndding cucumber env (copy of test) to default database ...\n"
@db_config['cucumber'] = @db_config['test']
File.open(@db_config_path, 'w') {|f| f.write @db_config.to_yaml }
end
puts <<HEREDOC
----------------------------------------
Updating the Rails database configuration file: config/database.yml
Specify values for the mysql database name, username and password for the
development staging and production environments.
Here are the current settings in config/database.yml:
#{@db_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
create_new_database_yml unless @new_database_yml_created || confirm_database_name_prefix_user_password
%w{development test production}.each do |env|
puts "\nSetting parameters for the #{env} database:\n\n"
@db_config[env]['database'] = ask(" database name: ") { |q| q.default = @db_config[env]['database'] }
@db_config[env]['username'] = ask(" username: ") { |q| q.default = @db_config[env]['username'] }
@db_config[env]['password'] = ask(" password: ") { |q| q.default = @db_config[env]['password'] }
@db_config[env]['adaptor'] = "<% if RUBY_PLATFORM =~ /java/ %>jdbcmysql<% else %>mysql<% end %>"
end
@db_config['cucumber'] = @db_config['test']
puts <<HEREDOC
If you have access to a ITSI database for importing ITSI Activities into RITES
specify the values for the mysql database name, host, username, password, and asset_url.
HEREDOC
puts "\nSetting parameters for the ITSI database:\n\n"
@db_config['itsi']['database'] = ask(" database name: ") { |q| q.default = @db_config['itsi']['database'] }
@db_config['itsi']['host'] = ask(" host: ") { |q| q.default = @db_config['itsi']['host'] }
@db_config['itsi']['username'] = ask(" username: ") { |q| q.default = @db_config['itsi']['username'] }
@db_config['itsi']['password'] = ask(" password: ") { |q| q.default = @db_config['itsi']['password'] }
@db_config['itsi']['asset_url'] = ask(" asset url: ") { |q| q.default = @db_config['itsi']['asset_url'] }
@db_config['itsi']['adaptor'] = "<% if RUBY_PLATFORM =~ /java/ %>jdbcmysql<% else %>mysql<% end %>"
puts <<HEREDOC
If you have access to a CCPortal database that indexes ITSI Activities into sequenced Units
specify the values for the mysql database name, host, username, password.
HEREDOC
puts "\nSetting parameters for the CCPortal database:\n\n"
@db_config['ccportal']['database'] = ask(" database name: ") { |q| q.default = @db_config['ccportal']['database'] }
@db_config['ccportal']['host'] = ask(" host: ") { |q| q.default = @db_config['ccportal']['host'] }
@db_config['ccportal']['username'] = ask(" username: ") { |q| q.default = @db_config['ccportal']['username'] }
@db_config['ccportal']['password'] = ask(" password: ") { |q| q.default = @db_config['ccportal']['password'] }
@db_config['ccportal']['adaptor'] = "<% if RUBY_PLATFORM =~ /java/ %>jdbcmysql<% else %>mysql<% end %>"
puts <<HEREDOC
Here is the updated database configuration:
#{@db_config.to_yaml}
HEREDOC
if agree("OK to save to config/database.yml? (y/n): ")
File.open(@db_config_path, 'w') {|f| f.write @db_config.to_yaml }
end
end
end
#
# update config/rinet_data.yml
#
def update_config_rinet_data_yml
@rinet_data_config = YAML::load_file(@rinet_data_config_path)
puts <<HEREDOC
----------------------------------------
Updating the RINET CSV Account import configuration file: config/rinet_data.yml
Specify values for the host, username and password for the RINET SFTP
site to download Sakai account data in CSV format.
Here are the current settings in config/rinet_data.yml:
#{@rinet_data_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
create_new_rinet_data_yml unless @new_rinet_data_yml_created
%w{development test staging production}.each do |env|
puts "\nSetting parameters for the #{env} rinet_data:\n"
@rinet_data_config[env]['host'] = ask(" RINET host: ") { |q| q.default = @rinet_data_config[env]['host'] }
@rinet_data_config[env]['username'] = ask(" RINET username: ") { |q| q.default = @rinet_data_config[env]['username'] }
@rinet_data_config[env]['password'] = ask(" RINET password: ") { |q| q.default = @rinet_data_config[env]['password'] }
puts
end
puts <<HEREDOC
Here is the updated rinet_data configuration:
#{@rinet_data_config.to_yaml}
HEREDOC
if agree("OK to save to config/rinet_data.yml? (y/n): ")
File.open(@rinet_data_config_path, 'w') {|f| f.write @rinet_data_config.to_yaml }
end
end
end
def get_include_otrunk_examples_settings(env)
include_otrunk_examples = @settings_config[env]['include_otrunk_examples']
puts <<HEREDOC
Processing and importing of otrunk-examples can be enabled or disabled.
It is currently #{include_otrunk_examples ? 'disabled' : 'enabled' }.
HEREDOC
@settings_config[env]['include_otrunk_examples'] = agree("Include otrunk-examples? (y/n) ") { |q| q.default = (include_otrunk_examples ? 'y' : 'n') }
end
def get_states_and_provinces_settings(env)
states_and_provinces = (@settings_config[env]['states_and_provinces'] || []).join(' ')
puts <<HEREDOC
Detailed data are imported for the following US schools and district:
#{states_and_provinces}
List state or province abbreviations for the locations you want imported.
Use two-character capital letter abreviations and delimit multiple items with spaces.
HEREDOC
states_and_provinces = @settings_config[env]['states_and_provinces'].join(' ')
states_and_provinces = ask(" states_and_provinces: ") { |q| q.default = states_and_provinces }
@settings_config[env]['states_and_provinces'] = states_and_provinces.split
end
def get_active_grades_settings(env)
active_grades = (@settings_config[env]['active_grades'] || []).join(' ')
puts <<HEREDOC
The following is a list of the active grade:
#{active_grades}
List active grades for this application instance.
Use any of the following:
K 1 2 3 4 5 6 7 8 9 10 11 12
and delimit multiple active grades with a space character.
HEREDOC
active_grades = ask(" active_grades: ") { |q| q.default = active_grades }
@settings_config[env]['active_grades'] = active_grades.split
end
def get_active_school_levels(env)
active_school_levels = (@settings_config[env]['active_school_levels'] || []).join(' ')
puts <<HEREDOC
The following is a list of the active school levels:
#{active_school_levels}
List active school levels for this application instance.
Use any of the following:
1 2 3 4
and delimit multiple active school levels with a space character.
School level. The following codes are used for active school levels:
1 = Primary (low grade = PK through 03; high grade = PK through 08)
2 = Middle (low grade = 04 through 07; high grade = 04 through 09)
3 = High (low grade = 07 through 12; high grade = 12 only
4 = Other (any other configuration not falling within the above three categories, including ungraded)
HEREDOC
active_school_levels = ask(" active_school_levels: ") { |q| q.default = active_school_levels }
@settings_config[env]['active_school_levels'] = active_school_levels.split
end
def get_valid_sakai_instances(env)
puts <<HEREDOC
Specify the sakai server urls from which it is ok to receive linktool requests.
Delimit multiple items with spaces.
HEREDOC
sakai_instances = @settings_config[env]['valid_sakai_instances'].join(' ')
sakai_instances = ask(" valid_sakai_instances: ") { |q| q.default = sakai_instances }
@settings_config[env]['valid_sakai_instances'] = sakai_instances.split
end
def get_maven_jnlp_settings(env)
puts <<HEREDOC
Specify the maven_jnlp server used for providing jnlps and jars dor running Java OTrunk applications.
HEREDOC
maven_jnlp_server = @settings_config[env]['maven_jnlp_servers'][0]
maven_jnlp_server[:host] = ask(" host: ") { |q| q.default = maven_jnlp_server[:host] }
maven_jnlp_server[:path] = ask(" path: ") { |q| q.default = maven_jnlp_server[:path] }
maven_jnlp_server[:name] = ask(" name: ") { |q| q.default = maven_jnlp_server[:name] }
@settings_config[env]['maven_jnlp_servers'][0] = maven_jnlp_server
@settings_config[env]['default_maven_jnlp_server'] = maven_jnlp_server[:name]
@settings_config[env]['default_maven_jnlp_family'] = ask(" default_maven_jnlp_family: ") { |q| q.default = @settings_config[env]['default_maven_jnlp_family'] }
maven_jnlp_families = (@settings_config[env]['maven_jnlp_families'] || []).join(' ')
puts <<HEREDOC
The following is a list of the active maven_jnlp_families:
#{maven_jnlp_families}
Specify which maven_jnlp_families to include. Enter nothing to include all
the maven_jnlp_families. Delimit multiple items with spaces.
HEREDOC
maven_jnlp_families = ask(" active_school_levels: ") { |q| q.default = maven_jnlp_families }
@settings_config[env]['maven_jnlp_families'] = maven_jnlp_families.split
puts <<HEREDOC
Specify the default_jnlp_version to use:
HEREDOC
@settings_config[env]['default_jnlp_version'] = ask(" default_jnlp_version: ") { |q| q.default = @settings_config[env]['default_jnlp_version'] }
end
#
# update config/settings.yml
#
def update_config_settings_yml
puts <<HEREDOC
----------------------------------------
Updating the application settings configuration file: config/settings.yml
Specify general application settings values: site url, site name, and admin name, email, login
for the development staging and production environments.
If you are doing development locally you may want to use one database for development and production.
Some of the importing scripts run much faster in production mode.
HEREDOC
puts <<HEREDOC
Here are the current settings in config/settings.yml:
#{@settings_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
%w{development staging production}.each do |env|
puts "\n#{env}:\n"
@settings_config[env]['site_url'] = ask(" site url: ") { |q| q.default = @settings_config[env]['site_url'] }
@settings_config[env]['site_name'] = ask(" site_name: ") { |q| q.default = @settings_config[env]['site_name'] }
@settings_config[env]['admin_email'] = ask(" admin_email: ") { |q| q.default = @settings_config[env]['admin_email'] }
@settings_config[env]['admin_login'] = ask(" admin_login: ") { |q| q.default = @settings_config[env]['admin_login'] }
@settings_config[env]['admin_first_name'] = ask(" admin_first_name: ") { |q| q.default = @settings_config[env]['admin_first_name'] }
@settings_config[env]['admin_last_name'] = ask(" admin_last_name: ") { |q| q.default = @settings_config[env]['admin_last_name'] }
#
# site_district and site_school
#
puts <<HEREDOC
The site district is a virtual district that contains the site school.
Any full member can become part of the site school and district.
HEREDOC
@settings_config[env]['site_district'] = ask(" site_district: ") { |q| q.default = @settings_config[env]['site_district'] }
@settings_config[env]['site_school'] = ask(" site_school: ") { |q| q.default = @settings_config[env]['site_school'] }
#
# ---- states_and_provinces ----
#
get_states_and_provinces_settings(env)
#
# ---- active_grades ----
#
get_active_grades_settings(env)
#
# ---- valid_sakai_instances ----
#
get_active_school_levels(env)
#
# ---- valid_sakai_instances ----
#
get_valid_sakai_instances(env)
#
# ---- enable_default_users ----
#
puts <<HEREDOC
A number of default users are created that are good for testing but insecure for
production deployments. Setting this value to true will enable the default users
setting it to false will disable the default_users for this envioronment.
HEREDOC
default_users = @settings_config[env]['enable_default_users'].to_s
default_users = ask(" enable_default_users: ", ['true', 'false']) { |q| q.default = default_users }
@settings_config[env]['enable_default_users'] = eval(default_users)
#
# ---- maven_jnlp ----
#
get_maven_jnlp_settings(env)
end # each env
end
puts <<HEREDOC
Here are the updated application settings:
#{@settings_config.to_yaml}
HEREDOC
if agree("OK to save to config/settings.yml? (y/n): ")
File.open(@settings_config_path, 'w') {|f| f.write @settings_config.to_yaml }
end
end
#
# update config/mailer.yml
#
def update_config_mailer_yml
@mailer_config = YAML::load_file(@mailer_config_path)
delivery_types = [:test, :smtp, :sendmail]
deliv_types = delivery_types.collect { |deliv| deliv.to_s }.join(' | ')
authentication_types = [:plain, :login, :cram_md5]
auth_types = authentication_types.collect { |auth| auth.to_s }.join(' | ')
puts @mailer_config_sample_config
puts <<HEREDOC
----------------------------------------
Updating the Rails mailer configuration file: config/mailer.yml
You will need to specify values for the SMTP mail server this #{APPLICATION} instance will
use to send outgoing mail. In addition you need to specify the hostname of this specific
#{APPLICATION} instance.
The SMTP parameters are used to send user account activation emails to new users and the
hostname of the #{APPLICATION} is used as part of account activation url rendered into the
body of the email.
You will need to specify a mail delivery method: (#{deliv_types})
the hostname of the #{APPLICATION} without the protocol: (example: #{@mailer_config_sample[:host]})
If you do not have a working SMTP server select the test deliver method instead of the
smtp delivery method. The activivation emails will appear in #{@dev_log_path}. You can
easily see then as the are generated with this command:
tail -f -n 100 #{@dev_log_path}
You will also need to specify:
the hostname of the #{APPLICATION} application without the protocol: (example: #{@mailer_config_sample[:host]})
and a series of SMTP server values:
host name of the remote mail server: (example: #{@mailer_config_sample[:smtp][:address]}))
port the SMTP server runs on (most run on port 25)
SMTP helo domain
authentication method for sending mail: (#{auth_types})
username (only applies to the :login and :cram-md5 athentication methods)
password (only applies to the :login and :cram-md5 athentication methods)
Here are the current settings in config/mailer.yml:
#{@mailer_config.to_yaml}
HEREDOC
unless agree("Accept defaults? (y/n) ")
say("\nChoose mail delivery type: #{deliv_types}:\n\n")
@mailer_config[:delivery_type] = ask(" delivery type: ", delivery_types) { |q|
q.default = "test"
}
@mailer_config[:host] = ask(" #{APPLICATION} hostname: ") { |q| q.default = @mailer_config[:host] }
@mailer_config[:smtp][:address] = ask(" SMTP address: ") { |q|
q.default = @mailer_config[:smtp][:address]
}
@mailer_config[:smtp][:port] = ask(" SMTP port: ", Integer) { |q|
q.default = @mailer_config[:smtp][:port]
q.in = 25..65535
}
@mailer_config[:smtp][:domain] = ask(" SMTP domain: ") { |q|
q.default = @mailer_config[:smtp][:domain]
}
say("\nChoose SMTP authentication type: #{auth_types}:\n\n")
@mailer_config[:smtp][:authentication] = ask(" SMTP auth type: ", authentication_types) { |q|
q.default = "login"
}
@mailer_config[:smtp][:user_name] = ask(" SMTP username: ") { |q|
q.default = @mailer_config[:smtp][:user_name]
}
@mailer_config[:smtp][:password] = ask(" SMTP password: ") { |q|
q.default = @mailer_config[:smtp][:password]
}
end
puts <<HEREDOC
Here is the new mailer configuration:
#{@mailer_config.to_yaml}
HEREDOC
if agree("OK to save to config/mailer.yml? (y/n): ")
File.open(@mailer_config_path, 'w') {|f| f.write @mailer_config.to_yaml }
end
end
# *****************************************************
puts <<HEREDOC
This setup program will help you configure a new #{APPLICATION} instance.
HEREDOC
check_for_git_submodules
check_for_config_database_yml
check_for_config_settings_yml
check_for_config_rinet_data_yml
check_for_config_mailer_yml
check_for_log_development_log
check_for_config_initializers_site_keys_rb
update_config_database_yml
update_config_settings_yml
update_config_rinet_data_yml
update_config_mailer_yml
puts <<HEREDOC
Finished configuring application settings.
********************************************************************
*** If you are also setting up an application from scratch and ***
*** need to create or recreate the resources in the database ***
*** follow the steps below: ***
********************************************************************
MRI Ruby:
rake gems:install
RAILS_ENV=production rake db:migrate:reset
RAILS_ENV=production rake rigse:setup:new_rites_app
JRuby:
jruby -S rake gems:install
RAILS_ENV=production jruby -S rake db:migrate:reset
RAILS_ENV=production jruby -S rake rigse:setup:new_rites_app
These scripts will take about 5-30 minutes to run and are much faster if you are both running
Rails in production mode and using JRuby. If you are using separate databases for development and
production and want to run these tasks to populate a development database I recommend temporarily
identifying the development database as production for the purpose of generating these data.
HEREDOC |
require 'test_helper'
class FacebookCanvas::MiddlewareTest < ActionDispatch::IntegrationTest
test 'convert post to get request' do
post '/foo/index'
assert_response :success
end
test 'do not convert post' do
post '/foo/create', { "utf8" => "utf" }
assert_response :success
end
test 'do not convert xhr requests' do
xhr :post, '/foo/create'
assert_response :success
end
end
Rename integration test class to avoid future name clashes
require 'test_helper'
class FacebookCanvas::IntegrationMiddlewareTest < ActionDispatch::IntegrationTest
test 'convert post to get request' do
post '/foo/index'
assert_response :success
end
test 'do not convert post' do
post '/foo/create', { "utf8" => "utf" }
assert_response :success
end
test 'do not convert xhr requests' do
xhr :post, '/foo/create'
assert_response :success
end
end
|
require Rails.root.join('lib', 'rails_admin', 'send_reset_password_email.rb')
require Rails.root.join('lib', 'rails_admin', 'export_project.rb')
require Rails.root.join('lib', 'rails_admin', 'yaml_field.rb')
RailsAdmin::Config::Actions.register(RailsAdmin::Config::Actions::SendResetPasswordEmail)
RailsAdmin::Config::Actions.register(RailsAdmin::Config::Actions::ExportProject)
RailsAdmin::Config::Actions.register(RailsAdmin::Config::Fields::Types::Yaml)
RailsAdmin.config do |config|
### Popular gems integration
config.parent_controller = 'ApplicationController'
## == Devise ==
config.authenticate_with(&:authenticated?)
config.current_user_method(&:current_api_user)
# == Cancan ==
config.authorize_with :cancan, AdminAbility
## == Pundit ==
# config.authorize_with :pundit
## == PaperTrail ==
# config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
## == Gravatar integration ==
## To disable Gravatar integration in Navigation Bar set to false
# config.show_gravatar true
config.actions do
dashboard do
# https://github.com/sferik/rails_admin/wiki/Dashboard-action#disabling-record-count-bars
statistics false
end
index # mandatory
new
export
bulk_delete
show
edit
delete
send_reset_password_email
export_project do
only ['Project']
end
## With an audit adapter, you can add:
# history_index
# history_show
end
config.main_app_name = ['Check']
config.included_models = ['Account', 'Annotation', 'ApiKey', 'Bot', 'Bounce', 'Claim', 'Comment', 'Contact', 'Embed', 'Flag', 'Link', 'Media', 'Project', 'ProjectMedia', 'ProjectSource', 'Source', 'Status', 'Tag', 'Team', 'TeamUser', 'User', 'BotUser']
config.navigation_static_links = {
'API Explorer' => '/api',
'GraphiQL' => '/graphiql',
'Web Client' => CONFIG['checkdesk_client']
}
config.navigation_static_label = 'External Tools'
def annotation_config(type, specific_data = [])
list do
field :annotation_type
field :annotated do
pretty_value do
path = bindings[:view].show_path(model_name: bindings[:object].annotated_type, id: bindings[:object].annotated_id)
bindings[:view].tag(:a, href: path) << "#{bindings[:object].annotated_type} ##{bindings[:object].annotated_id}"
end
end
field :annotator do
pretty_value do
path = bindings[:view].show_path(model_name: bindings[:object].annotator_type, id: bindings[:object].annotator_id)
bindings[:view].tag(:a, href: path) << "#{bindings[:object].annotator_type} ##{bindings[:object].annotator_id}"
end
end
end
edit do
field :annotation_type do
read_only true
help ''
end
field :annotated_type, :enum do
enum do
type.classify.constantize.annotated_types
end
end
field :annotated_id
field :annotator_type
field :annotator_id
specific_data.each do |field_name|
field field_name
end
field :entities
end
show do
specific_data.each do |field|
configure field do
visible true
end
end
exclude_fields :data
end
end
def media_config
edit do
field :type, :enum do
enum do
Media.types
end
end
include_all_fields
end
end
def render_settings(field_type)
partial "form_settings_#{field_type}"
hide do
bindings[:object].new_record?
end
end
config.model 'ApiKey' do
list do
field :access_token
field :expire_at
end
create do
field :expire_at do
strftime_format "%Y-%m-%d"
end
end
edit do
field :expire_at do
strftime_format "%Y-%m-%d"
end
end
end
config.model 'Comment' do
annotation_config('comment', [:text])
parent Annotation
end
config.model 'Embed' do
annotation_config('embed', [:title, :description, :embed, :username, :published_at])
parent Annotation
end
config.model 'Flag' do
annotation_config('flag', [:flag])
parent Annotation
edit do
field :flag, :enum do
enum do
Flag.flag_types
end
end
end
end
config.model 'Media' do
media_config
end
config.model 'Link' do
media_config
end
config.model 'Claim' do
media_config
end
config.model 'Status' do
annotation_config('status', [:status])
parent Annotation
edit do
field :status, :enum do
enum do
annotated, context = bindings[:object].get_annotated_and_context
Status.possible_values(annotated, context)[:statuses].collect { |s| s[:id]}
end
end
end
create do
field :status do
hide
end
end
end
config.model 'Tag' do
annotation_config('tag', [:tag, :full_tag])
parent Annotation
end
config.model 'Project' do
object_label_method do
:admin_label
end
list do
field :title
field :description
field :team
field :archived
field :settings do
label 'Link to authorize Bridge to publish translations automatically'
formatted_value do
project = bindings[:object]
token = project.token
host = CONFIG['checkdesk_base_url']
%w(twitter facebook).collect do |p|
dest = "#{host}/api/admin/project/#{project.id}/add_publisher/#{p}?token=#{token}"
link = "#{host}/api/users/auth/#{p}?destination=#{dest}"
bindings[:view].link_to(p.capitalize, link)
end.join(' | ').html_safe
end
end
end
show do
configure :get_viber_token do
label 'Viber token'
end
configure :get_slack_notifications_enabled do
label 'Enable Slack notifications'
end
configure :get_slack_channel do
label 'Slack #channel'
end
configure :get_languages, :json do
label 'Languages'
end
end
edit do
field :title
field :description
field :team do
end
field :archived
field :lead_image
field :user
field :slack_notifications_enabled, :boolean do
label 'Enable Slack notifications'
formatted_value{ bindings[:object].get_slack_notifications_enabled }
help ''
hide do
bindings[:object].new_record?
end
end
field :viber_token do
label 'Viber token'
formatted_value{ bindings[:object].get_viber_token }
help ''
hide do
bindings[:object].new_record?
end
end
field :slack_channel do
label 'Slack default #channel'
formatted_value{ bindings[:object].get_slack_channel }
help 'The Slack channel to which Check should send notifications about events that occur in this project.'
render_settings('field')
end
field :languages, :yaml do
label 'Languages'
help "A list of the project's preferred languages for machine translation (e.g. ['ar', 'fr'])."
end
end
end
config.model 'Team' do
list do
field :name
field :description
field :slug
field :private
field :archived
end
show do
configure :get_media_verification_statuses, :json do
label 'Media verification statuses'
end
configure :get_source_verification_statuses, :json do
label 'Source verification statuses'
end
configure :get_keep_enabled do
label 'Enable Keep archiving'
end
configure :get_slack_notifications_enabled do
label 'Enable Slack notifications'
end
configure :get_slack_webhook do
label 'Slack webhook'
end
configure :get_slack_channel do
label 'Slack default #channel'
end
configure :get_checklist, :json do
label 'Checklist'
end
configure :get_suggested_tags do
label 'Suggested tags'
end
end
edit do
field :name
field :description
field :logo
field :slug
field :private
field :archived
field :media_verification_statuses, :yaml do
label 'Media verification statuses'
render_settings('text')
help "A list of custom verification statuses for reports that match your team's journalistic guidelines."
end
field :source_verification_statuses, :yaml do
label 'Source verification statuses'
help "A list of custom verification statuses for sources that match your team's journalistic guidelines."
render_settings('text')
end
field :keep_enabled, :boolean do
label 'Enable Keep archiving'
formatted_value{ bindings[:object].get_keep_enabled }
help ''
hide do
bindings[:object].new_record?
end
end
field :slack_notifications_enabled, :boolean do
label 'Enable Slack notifications'
formatted_value{ bindings[:object].get_slack_notifications_enabled }
help ''
hide do
bindings[:object].new_record?
end
end
field :slack_webhook do
label 'Slack webhook'
formatted_value{ bindings[:object].get_slack_webhook }
help "A <a href='https://my.slack.com/services/new/incoming-webhook/' target='_blank'>webhook supplied by Slack</a> and that Check uses to send notifications about events that occur in your team.".html_safe
render_settings('field')
end
field :slack_channel do
label 'Slack default #channel'
formatted_value{ bindings[:object].get_slack_channel }
help "The Slack channel to which Check should send notifications about events that occur in your team."
render_settings('field')
end
field :checklist, :yaml do
label 'Checklist'
help "A list of tasks that should be automatically created every time a new report is added to a project in your team."
render_settings('text')
end
field :suggested_tags do
label 'Suggested tags'
formatted_value { bindings[:object].get_suggested_tags }
help "A list of common tags to be used with reports and sources in your team."
render_settings('field')
end
end
end
config.model 'TeamUser' do
list do
field :team
field :user
field :role
field :status
end
edit do
field :team
field :user
field :role, :enum do
enum do
TeamUser.role_types
end
end
field :status, :enum do
enum do
TeamUser.status_types
end
end
end
end
config.model 'User' do
list do
field :name
field :login
field :provider
field :email
field :is_admin do
visible do
bindings[:view]._current_user.is_admin?
end
end
end
show do
configure :get_languages, :json do
label 'Languages'
end
end
edit do
field :name
field :login
field :provider do
visible do
bindings[:view]._current_user.is_admin? && bindings[:object].email.blank?
end
end
field :password do
visible do
bindings[:view]._current_user.is_admin? && bindings[:object].provider.blank?
end
formatted_value do
''
end
end
field :email
field :profile_image
field :image
field :current_team_id
field :is_admin do
visible do
bindings[:view]._current_user.is_admin?
end
end
field :languages, :yaml do
label 'Languages'
render_settings('text')
help "A list of the user's preferred languages (e.g. for translation)."
end
end
end
config.model 'BotUser' do
label 'Bot User'
label_plural 'Bot Users'
list do
field :name
field :login
field :api_key
end
show do
field :name
field :login
field :api_key
end
edit do
field :name
field :login
field :profile_image
field :image
field :api_key
end
end
end
Ticket #6269: Configure the team fields that team owners can manage
Team owners can manage only these fields:
- Media verification statuses
- Source verification statuses
- Checklists
- Enable Slack notifications
- Slack webhook
- Slack default #channel
require Rails.root.join('lib', 'rails_admin', 'send_reset_password_email.rb')
require Rails.root.join('lib', 'rails_admin', 'export_project.rb')
require Rails.root.join('lib', 'rails_admin', 'yaml_field.rb')
RailsAdmin::Config::Actions.register(RailsAdmin::Config::Actions::SendResetPasswordEmail)
RailsAdmin::Config::Actions.register(RailsAdmin::Config::Actions::ExportProject)
RailsAdmin::Config::Actions.register(RailsAdmin::Config::Fields::Types::Yaml)
RailsAdmin.config do |config|
### Popular gems integration
config.parent_controller = 'ApplicationController'
## == Devise ==
config.authenticate_with(&:authenticated?)
config.current_user_method(&:current_api_user)
# == Cancan ==
config.authorize_with :cancan, AdminAbility
## == Pundit ==
# config.authorize_with :pundit
## == PaperTrail ==
# config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
## == Gravatar integration ==
## To disable Gravatar integration in Navigation Bar set to false
# config.show_gravatar true
config.actions do
dashboard do
# https://github.com/sferik/rails_admin/wiki/Dashboard-action#disabling-record-count-bars
statistics false
end
index # mandatory
new
export
bulk_delete
show
edit
delete
send_reset_password_email
export_project do
only ['Project']
end
## With an audit adapter, you can add:
# history_index
# history_show
end
config.main_app_name = ['Check']
config.included_models = ['Account', 'Annotation', 'ApiKey', 'Bot', 'Bounce', 'Claim', 'Comment', 'Contact', 'Embed', 'Flag', 'Link', 'Media', 'Project', 'ProjectMedia', 'ProjectSource', 'Source', 'Status', 'Tag', 'Team', 'TeamUser', 'User', 'BotUser']
config.navigation_static_links = {
'API Explorer' => '/api',
'GraphiQL' => '/graphiql',
'Web Client' => CONFIG['checkdesk_client']
}
config.navigation_static_label = 'External Tools'
def annotation_config(type, specific_data = [])
list do
field :annotation_type
field :annotated do
pretty_value do
path = bindings[:view].show_path(model_name: bindings[:object].annotated_type, id: bindings[:object].annotated_id)
bindings[:view].tag(:a, href: path) << "#{bindings[:object].annotated_type} ##{bindings[:object].annotated_id}"
end
end
field :annotator do
pretty_value do
path = bindings[:view].show_path(model_name: bindings[:object].annotator_type, id: bindings[:object].annotator_id)
bindings[:view].tag(:a, href: path) << "#{bindings[:object].annotator_type} ##{bindings[:object].annotator_id}"
end
end
end
edit do
field :annotation_type do
read_only true
help ''
end
field :annotated_type, :enum do
enum do
type.classify.constantize.annotated_types
end
end
field :annotated_id
field :annotator_type
field :annotator_id
specific_data.each do |field_name|
field field_name
end
field :entities
end
show do
specific_data.each do |field|
configure field do
visible true
end
end
exclude_fields :data
end
end
def media_config
edit do
field :type, :enum do
enum do
Media.types
end
end
include_all_fields
end
end
def render_settings(field_type)
partial "form_settings_#{field_type}"
hide do
bindings[:object].new_record?
end
end
def visible_only_for_admin
visible do
bindings[:view]._current_user.is_admin?
end
end
config.model 'ApiKey' do
list do
field :access_token
field :expire_at
end
create do
field :expire_at do
strftime_format "%Y-%m-%d"
end
end
edit do
field :expire_at do
strftime_format "%Y-%m-%d"
end
end
end
config.model 'Comment' do
annotation_config('comment', [:text])
parent Annotation
end
config.model 'Embed' do
annotation_config('embed', [:title, :description, :embed, :username, :published_at])
parent Annotation
end
config.model 'Flag' do
annotation_config('flag', [:flag])
parent Annotation
edit do
field :flag, :enum do
enum do
Flag.flag_types
end
end
end
end
config.model 'Media' do
media_config
end
config.model 'Link' do
media_config
end
config.model 'Claim' do
media_config
end
config.model 'Status' do
annotation_config('status', [:status])
parent Annotation
edit do
field :status, :enum do
enum do
annotated, context = bindings[:object].get_annotated_and_context
Status.possible_values(annotated, context)[:statuses].collect { |s| s[:id]}
end
end
end
create do
field :status do
hide
end
end
end
config.model 'Tag' do
annotation_config('tag', [:tag, :full_tag])
parent Annotation
end
config.model 'Project' do
object_label_method do
:admin_label
end
list do
field :title
field :description
field :team
field :archived
field :settings do
label 'Link to authorize Bridge to publish translations automatically'
formatted_value do
project = bindings[:object]
token = project.token
host = CONFIG['checkdesk_base_url']
%w(twitter facebook).collect do |p|
dest = "#{host}/api/admin/project/#{project.id}/add_publisher/#{p}?token=#{token}"
link = "#{host}/api/users/auth/#{p}?destination=#{dest}"
bindings[:view].link_to(p.capitalize, link)
end.join(' | ').html_safe
end
end
end
show do
configure :get_viber_token do
label 'Viber token'
end
configure :get_slack_notifications_enabled do
label 'Enable Slack notifications'
end
configure :get_slack_channel do
label 'Slack #channel'
end
configure :get_languages, :json do
label 'Languages'
end
end
edit do
field :title
field :description
field :team do
end
field :archived
field :lead_image
field :user
field :slack_notifications_enabled, :boolean do
label 'Enable Slack notifications'
formatted_value{ bindings[:object].get_slack_notifications_enabled }
help ''
hide do
bindings[:object].new_record?
end
end
field :viber_token do
label 'Viber token'
formatted_value{ bindings[:object].get_viber_token }
help ''
hide do
bindings[:object].new_record?
end
end
field :slack_channel do
label 'Slack default #channel'
formatted_value{ bindings[:object].get_slack_channel }
help 'The Slack channel to which Check should send notifications about events that occur in this project.'
render_settings('field')
end
field :languages, :yaml do
label 'Languages'
help "A list of the project's preferred languages for machine translation (e.g. ['ar', 'fr'])."
end
end
end
config.model 'Team' do
list do
field :name
field :description
field :slug
field :private do
visible_only_for_admin
end
field :archived do
visible_only_for_admin
end
end
show do
configure :get_media_verification_statuses, :json do
label 'Media verification statuses'
end
configure :get_source_verification_statuses, :json do
label 'Source verification statuses'
end
configure :get_keep_enabled do
label 'Enable Keep archiving'
visible_only_for_admin
end
configure :get_slack_notifications_enabled do
label 'Enable Slack notifications'
end
configure :get_slack_webhook do
label 'Slack webhook'
end
configure :get_slack_channel do
label 'Slack default #channel'
end
configure :get_checklist, :json do
label 'Checklist'
end
configure :get_suggested_tags do
label 'Suggested tags'
visible_only_for_admin
end
configure :private do
visible_only_for_admin
end
configure :projects do
visible_only_for_admin
end
configure :accounts do
visible_only_for_admin
end
configure :team_users do
visible_only_for_admin
end
configure :users do
visible_only_for_admin
end
configure :sources do
visible_only_for_admin
end
configure :settings do
hide
end
end
edit do
field :name do
read_only true
help ''
end
field :description do
visible_only_for_admin
end
field :logo do
visible_only_for_admin
end
field :slug do
read_only true
help ''
end
field :private do
visible_only_for_admin
end
field :archived do
visible_only_for_admin
end
field :media_verification_statuses, :yaml do
label 'Media verification statuses'
render_settings('text')
help "A list of custom verification statuses for reports that match your team's journalistic guidelines."
end
field :source_verification_statuses, :yaml do
label 'Source verification statuses'
help "A list of custom verification statuses for sources that match your team's journalistic guidelines."
render_settings('text')
end
field :keep_enabled, :boolean do
label 'Enable Keep archiving'
formatted_value{ bindings[:object].get_keep_enabled }
help ''
hide do
bindings[:object].new_record?
end
visible_only_for_admin
end
field :slack_notifications_enabled, :boolean do
label 'Enable Slack notifications'
formatted_value{ bindings[:object].get_slack_notifications_enabled }
help ''
hide do
bindings[:object].new_record?
end
end
field :slack_webhook do
label 'Slack webhook'
formatted_value{ bindings[:object].get_slack_webhook }
help "A <a href='https://my.slack.com/services/new/incoming-webhook/' target='_blank'>webhook supplied by Slack</a> and that Check uses to send notifications about events that occur in your team.".html_safe
render_settings('field')
end
field :slack_channel do
label 'Slack default #channel'
formatted_value{ bindings[:object].get_slack_channel }
help "The Slack channel to which Check should send notifications about events that occur in your team."
render_settings('field')
end
field :checklist, :yaml do
label 'Checklist'
help "A list of tasks that should be automatically created every time a new report is added to a project in your team."
render_settings('text')
end
field :suggested_tags do
label 'Suggested tags'
formatted_value { bindings[:object].get_suggested_tags }
help "A list of common tags to be used with reports and sources in your team."
render_settings('field')
visible_only_for_admin
end
end
end
config.model 'TeamUser' do
list do
field :team
field :user
field :role
field :status
end
edit do
field :team
field :user
field :role, :enum do
enum do
TeamUser.role_types
end
end
field :status, :enum do
enum do
TeamUser.status_types
end
end
end
end
config.model 'User' do
list do
field :name
field :login
field :provider
field :email
field :is_admin do
visible do
bindings[:view]._current_user.is_admin?
end
end
end
show do
configure :get_languages, :json do
label 'Languages'
end
end
edit do
field :name
field :login
field :provider do
visible do
bindings[:view]._current_user.is_admin? && bindings[:object].email.blank?
end
end
field :password do
visible do
bindings[:view]._current_user.is_admin? && bindings[:object].provider.blank?
end
formatted_value do
''
end
end
field :email
field :profile_image
field :image
field :current_team_id
field :is_admin do
visible do
bindings[:view]._current_user.is_admin?
end
end
field :languages, :yaml do
label 'Languages'
render_settings('text')
help "A list of the user's preferred languages (e.g. for translation)."
end
end
end
config.model 'BotUser' do
label 'Bot User'
label_plural 'Bot Users'
list do
field :name
field :login
field :api_key
end
show do
field :name
field :login
field :api_key
end
edit do
field :name
field :login
field :profile_image
field :image
field :api_key
end
end
end
|
require 'test_helper'
module Tire
class PercolatorIntegrationTest < Test::Unit::TestCase
include Test::Integration
context "Percolator" do
setup do
@index = Tire.index('percolator-test')
@index.create
end
teardown { @index.delete }
context "when registering a query" do
should "register query as a Hash" do
query = { :query => { :query_string => { :query => 'warning' } } }
assert @index.register_percolator_query('alert', query)
sleep 0.1
percolator = Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/alert")
assert percolator
end
should "register query as block" do
assert @index.register_percolator_query('alert') { string 'warning' }
sleep 0.1
percolator = Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/alert")
assert percolator
end
end
context "when percolating a document" do
setup do
@index.register_percolator_query('alert') { string 'warning' }
@index.register_percolator_query('gantz') { string '"y u no match"' }
@index.register_percolator_query('weather', :tags => ['weather']) { string 'severe' }
sleep 0.1
end
should "return an empty array when no query matches" do
matches = @index.percolate :message => 'Situation normal'
assert_equal [], matches
end
should "return an array of matching query names" do
matches = @index.percolate :message => 'Severe weather warning'
assert_equal ['alert','weather'], matches.sort
end
should "return an array of matching query names for specific percolated queries" do
matches = @index.percolate(:message => 'Severe weather warning') { term :tags, 'weather' }
assert_equal ['weather'], matches
end
end
context "when storing document and percolating it" do
setup do
@index.register_percolator_query('alert') { string 'warning' }
@index.register_percolator_query('gantz') { string '"y u no match"' }
@index.register_percolator_query('weather', :tags => ['weather']) { string 'severe' }
sleep 0.1
end
should "return an empty array when no query matches" do
response = @index.store :message => 'Situation normal', :percolate => true
assert_equal [], response['matches']
end
should "return an array of matching query names" do
response = @index.store :message => 'Severe weather warning', :percolate => true
assert_equal ['alert','weather'], response['matches'].sort
end
should "return an array of matching query names for specific percolated queries" do
response = @index.store :message => 'Severe weather warning', :percolate => 'tags:weather'
assert_equal ['weather'], response['matches']
end
end
end
end
end
[FIX] Fixed remaining registered queries in percolator integration tests
require 'test_helper'
module Tire
class PercolatorIntegrationTest < Test::Unit::TestCase
include Test::Integration
context "Percolator" do
setup do
delete_registered_queries
@index = Tire.index('percolator-test')
@index.create
end
teardown do
delete_registered_queries
@index.delete
end
context "when registering a query" do
should "register query as a Hash" do
query = { :query => { :query_string => { :query => 'warning' } } }
assert @index.register_percolator_query('alert', query)
Tire.index('_percolator').refresh; sleep 0.1
percolator = Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/alert")
assert percolator
end
should "register query as block" do
assert @index.register_percolator_query('alert') { string 'warning' }
Tire.index('_percolator').refresh; sleep 0.1
percolator = Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/alert")
assert percolator
end
end
context "when percolating a document" do
setup do
@index.register_percolator_query('alert') { string 'warning' }
@index.register_percolator_query('gantz') { string '"y u no match"' }
@index.register_percolator_query('weather', :tags => ['weather']) { string 'severe' }
Tire.index('_percolator').refresh; sleep 0.1
end
should "return an empty array when no query matches" do
matches = @index.percolate :message => 'Situation normal'
assert_equal [], matches
end
should "return an array of matching query names" do
matches = @index.percolate :message => 'Severe weather warning'
assert_equal ['alert','weather'], matches.sort
end
should "return an array of matching query names for specific percolated queries" do
matches = @index.percolate(:message => 'Severe weather warning') { term :tags, 'weather' }
assert_equal ['weather'], matches
end
end
context "when storing document and percolating it" do
setup do
@index.register_percolator_query('alert') { string 'warning' }
@index.register_percolator_query('gantz') { string '"y u no match"' }
@index.register_percolator_query('weather', :tags => ['weather']) { string 'severe' }
Tire.index('_percolator').refresh; sleep 0.1
end
should "return an empty array when no query matches" do
response = @index.store :message => 'Situation normal', :percolate => true
assert_equal [], response['matches']
end
should "return an array of matching query names" do
response = @index.store :message => 'Severe weather warning', :percolate => true
assert_equal ['alert','weather'], response['matches'].sort
end
should "return an array of matching query names for specific percolated queries" do
response = @index.store :message => 'Severe weather warning', :percolate => 'tags:weather'
assert_equal ['weather'], response['matches']
end
end
end
private
def delete_registered_queries
Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/alert") rescue nil
Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/gantz") rescue nil
Configuration.client.get("#{Configuration.url}/_percolator/percolator-test/weather") rescue nil
end
end
end
|
#ActiveModelSerializers.config.adapter = :json
added roots back (#98)
ActiveModelSerializers.config.adapter = :json
|
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Wrappers are used by the form builder to generate a
# complete input. You can remove any component from the
# wrapper, change the order or even add your own to the
# stack. The options given below are used to wrap the
# whole input.
config.wrappers :default, :class => :input,
:hint_class => :field_with_hint, :error_class => :field_with_errors do |b|
## Extensions enabled by default
# Any of these extensions can be disabled for a
# given input by passing: `f.input EXTENSION_NAME => false`.
# You can make any of these extensions optional by
# renaming `b.use` to `b.optional`.
# Determines whether to use HTML5 (:email, :url, ...)
# and required attributes
b.use :html5
# Calculates placeholders automatically from I18n
# You can also pass a string as f.input :placeholder => "Placeholder"
b.use :placeholder
## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => :lookup`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable the lookup for any of those
# extensions by default, you can change `b.optional` to `b.use`.
# Calculates maxlength from length validations for string inputs
b.optional :maxlength
# Calculates pattern from format validations for string inputs
b.optional :pattern
# Calculates min and max from length validations for numeric inputs
b.optional :min_max
# Calculates readonly automatically from readonly attributes
b.optional :readonly
## Inputs
b.use :label_input
b.use :hint, :wrap_with => { :tag => :span, :class => :hint }
b.use :error, :wrap_with => { :tag => :span, :class => :error }
end
config.wrappers :table, :tag => 'span', :class => 'control-group', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.wrapper :tag => 'div', :class => 'controls' do |ba|
ba.use :input
ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
end
config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |ba|
ba.use :input
ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
end
config.wrappers :prepend, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-prepend' do |prepend|
prepend.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
config.wrappers :inline, :tag => 'span', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :input
b.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
config.wrappers :append, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-append' do |append|
append.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
# Wrappers for forms and inputs using the Twitter Bootstrap toolkit.
# Check the Bootstrap docs (http://twitter.github.com/bootstrap)
# to learn about the different styles for forms and inputs,
# buttons and other elements.
config.default_wrapper = :bootstrap
# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
# :inline => input + label
# :nested => label > input
config.boolean_style = :nested
# Default class for buttons
config.button_class = 'btn'
# Method used to tidy up errors.
# config.error_method = :first
# Default tag used for error notification helper.
config.error_notification_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'alert alert-error'
# ID to add for error notification helper.
# config.error_notification_id = nil
# Series of attempts to detect a default label method for collection.
# config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attempts to detect a default value method for collection.
# config.collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
# config.collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
# config.collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to :span. Please note that when using :boolean_style = :nested,
# SimpleForm will force this option to be a label.
# config.item_wrapper_tag = :span
# You can define a class to use in all item wrappers. Defaulting to none.
# config.item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
# config.label_text = lambda { |label, required| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
config.label_class = 'control-label'
# You can define the class to use on all forms. Default is simple_form.
config.form_class = 'form-horizontal'
# You can define which elements should obtain additional classes
# config.generate_additional_classes_for = [:wrapper, :label, :input]
# Whether attributes are required by default (or not). Default is true.
# config.required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
# Default is enabled.
config.browser_validations = false
# Collection of methods to detect if a file type was given.
# config.file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value.
# config.input_mappings = { /count/ => :integer }
# Default priority for time_zone inputs.
# config.time_zone_priority = nil
# Default priority for country inputs.
# config.country_priority = nil
# Default size for text inputs.
# config.default_input_size = 50
# When false, do not use translations for labels.
# config.translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
# config.inputs_discovery = true
# Cache SimpleForm inputs discovery
# config.cache_discovery = !Rails.env.development?
end
feat(ui): support validation messages in inline form fields
The inline form field definition for simple_form did not support
validation notifications.
This patch adapts the inline fields for validation notifications using
bootstrap.
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Wrappers are used by the form builder to generate a
# complete input. You can remove any component from the
# wrapper, change the order or even add your own to the
# stack. The options given below are used to wrap the
# whole input.
config.wrappers :default, :class => :input,
:hint_class => :field_with_hint, :error_class => :field_with_errors do |b|
## Extensions enabled by default
# Any of these extensions can be disabled for a
# given input by passing: `f.input EXTENSION_NAME => false`.
# You can make any of these extensions optional by
# renaming `b.use` to `b.optional`.
# Determines whether to use HTML5 (:email, :url, ...)
# and required attributes
b.use :html5
# Calculates placeholders automatically from I18n
# You can also pass a string as f.input :placeholder => "Placeholder"
b.use :placeholder
## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => :lookup`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable the lookup for any of those
# extensions by default, you can change `b.optional` to `b.use`.
# Calculates maxlength from length validations for string inputs
b.optional :maxlength
# Calculates pattern from format validations for string inputs
b.optional :pattern
# Calculates min and max from length validations for numeric inputs
b.optional :min_max
# Calculates readonly automatically from readonly attributes
b.optional :readonly
## Inputs
b.use :label_input
b.use :hint, :wrap_with => { :tag => :span, :class => :hint }
b.use :error, :wrap_with => { :tag => :span, :class => :error }
end
config.wrappers :table, :tag => 'span', :class => 'control-group', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.wrapper :tag => 'div', :class => 'controls' do |ba|
ba.use :input
ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
end
config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |ba|
ba.use :input
ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
end
config.wrappers :prepend, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-prepend' do |prepend|
prepend.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-inline' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-block' }
end
end
config.wrappers :inline, :tag => 'span', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :input
b.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
b.use :error, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
config.wrappers :append, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-append' do |append|
append.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
# Wrappers for forms and inputs using the Twitter Bootstrap toolkit.
# Check the Bootstrap docs (http://twitter.github.com/bootstrap)
# to learn about the different styles for forms and inputs,
# buttons and other elements.
config.default_wrapper = :bootstrap
# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
# :inline => input + label
# :nested => label > input
config.boolean_style = :nested
# Default class for buttons
config.button_class = 'btn'
# Method used to tidy up errors.
# config.error_method = :first
# Default tag used for error notification helper.
config.error_notification_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'alert alert-error'
# ID to add for error notification helper.
# config.error_notification_id = nil
# Series of attempts to detect a default label method for collection.
# config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attempts to detect a default value method for collection.
# config.collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
# config.collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
# config.collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to :span. Please note that when using :boolean_style = :nested,
# SimpleForm will force this option to be a label.
# config.item_wrapper_tag = :span
# You can define a class to use in all item wrappers. Defaulting to none.
# config.item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
# config.label_text = lambda { |label, required| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
config.label_class = 'control-label'
# You can define the class to use on all forms. Default is simple_form.
config.form_class = 'form-horizontal'
# You can define which elements should obtain additional classes
# config.generate_additional_classes_for = [:wrapper, :label, :input]
# Whether attributes are required by default (or not). Default is true.
# config.required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
# Default is enabled.
config.browser_validations = false
# Collection of methods to detect if a file type was given.
# config.file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value.
# config.input_mappings = { /count/ => :integer }
# Default priority for time_zone inputs.
# config.time_zone_priority = nil
# Default priority for country inputs.
# config.country_priority = nil
# Default size for text inputs.
# config.default_input_size = 50
# When false, do not use translations for labels.
# config.translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
# config.inputs_discovery = true
# Cache SimpleForm inputs discovery
# config.cache_discovery = !Rails.env.development?
end
|
$:.unshift 'lib'
$:.unshift '../caruby/lib'
require "test/unit"
require 'caruby'
class JavaTest < Test::Unit::TestCase
def test_ruby_to_java_date_conversion
rdt = DateTime.now
jdt = Java::JavaUtil::Date.from_ruby_date(rdt)
assert(CaRuby::Resource.value_equal?(rdt, jdt.to_ruby_date), 'Ruby->Java->Ruby date conversion not idempotent')
end
def test_java_to_ruby_date_conversion
cal = Java::JavaUtil::Calendar.instance
verify_java_to_ruby_date_conversion(cal.time)
# roll back to a a different DST setting
if cal.timeZone.useDaylightTime then
verify_java_to_ruby_date_conversion(flip_DST(cal))
end
end
def flip_DST(cal)
isdt = cal.timeZone.inDaylightTime(cal.time)
11.times do
cal.roll(Java::JavaUtil::Calendar::MONTH, false)
return cal.time if cal.timeZone.inDaylightTime(cal.time) != isdt
end
end
def test_to_ruby
assert_same(Java::JavaUtil::BitSet, Class.to_ruby(java.util.BitSet.java_class), "Java => Ruby class incorrect")
end
def test_list_delete_if
list = Java::JavaUtil::ArrayList.new << 1 << 2
assert_same(list, list.delete_if { |n| n == 2 })
assert_equal([1], list.to_a, "Java ArrayList delete_if incorrect")
end
def test_set_delete_if
list = Java::JavaUtil::HashSet.new << 1 << 2
assert_same(list, list.delete_if { |n| n == 2 })
assert_equal([1], list.to_a, "Java HashSet delete_if incorrect")
end
def test_list_clear
list = Java::JavaUtil::ArrayList.new
assert(list.empty?, "Cleared ArrayList not empty")
assert_same(list, list.clear, "ArrayList clear result incorrect")
end
def test_set_clear
set = Java::JavaUtil::HashSet.new
assert(set.empty?, "Cleared HashSet not empty")
assert_same(set, set.clear, "HashSet clear result incorrect")
end
def test_set_merge
set = Java::JavaUtil::HashSet.new << 1
other = Java::JavaUtil::HashSet.new << 2
assert_same(set, set.merge(other), "HashSet merge result incorrect")
assert(set.include?(2), "HashSet merge not updated")
assert_same(set, set.clear, "HashSet clear result incorrect")
end
private
def verify_java_to_ruby_date_conversion(jdate)
rdt = jdate.to_ruby_date
actual = Java::JavaUtil::Date.from_ruby_date(rdt)
assert_equal(jdate.to_s, actual.to_s, 'Java->Ruby->Java date conversion not idempotent')
assert_equal(jdate.to_ruby_date, rdt, 'Java->Ruby date reconversion not equal')
end
end
Test zero date.
$:.unshift 'lib'
$:.unshift '../caruby/lib'
require "test/unit"
require 'caruby'
class JavaTest < Test::Unit::TestCase
def test_ruby_to_java_date_conversion
rdt = DateTime.now
jdt = Java::JavaUtil::Date.from_ruby_date(rdt)
assert(CaRuby::Resource.value_equal?(rdt, jdt.to_ruby_date), 'Ruby->Java->Ruby date conversion not idempotent')
end
def test_java_to_ruby_date_conversion
cal = Java::JavaUtil::Calendar.instance
verify_java_to_ruby_date_conversion(cal.time)
# roll back to a a different DST setting
if cal.timeZone.useDaylightTime then
verify_java_to_ruby_date_conversion(flip_DST(cal))
end
end
def test_zero_date
jdt = Java::JavaUtil::Date.new(0)
verify_java_to_ruby_date_conversion(jdt)
end
def flip_DST(cal)
isdt = cal.timeZone.inDaylightTime(cal.time)
11.times do
cal.roll(Java::JavaUtil::Calendar::MONTH, false)
return cal.time if cal.timeZone.inDaylightTime(cal.time) != isdt
end
end
def test_to_ruby
assert_same(Java::JavaUtil::BitSet, Class.to_ruby(java.util.BitSet.java_class), "Java => Ruby class incorrect")
end
def test_list_delete_if
list = Java::JavaUtil::ArrayList.new << 1 << 2
assert_same(list, list.delete_if { |n| n == 2 })
assert_equal([1], list.to_a, "Java ArrayList delete_if incorrect")
end
def test_set_delete_if
list = Java::JavaUtil::HashSet.new << 1 << 2
assert_same(list, list.delete_if { |n| n == 2 })
assert_equal([1], list.to_a, "Java HashSet delete_if incorrect")
end
def test_list_clear
list = Java::JavaUtil::ArrayList.new
assert(list.empty?, "Cleared ArrayList not empty")
assert_same(list, list.clear, "ArrayList clear result incorrect")
end
def test_set_clear
set = Java::JavaUtil::HashSet.new
assert(set.empty?, "Cleared HashSet not empty")
assert_same(set, set.clear, "HashSet clear result incorrect")
end
def test_set_merge
set = Java::JavaUtil::HashSet.new << 1
other = Java::JavaUtil::HashSet.new << 2
assert_same(set, set.merge(other), "HashSet merge result incorrect")
assert(set.include?(2), "HashSet merge not updated")
assert_same(set, set.clear, "HashSet clear result incorrect")
end
private
def verify_java_to_ruby_date_conversion(jdate)
rdt = jdate.to_ruby_date
actual = Java::JavaUtil::Date.from_ruby_date(rdt)
assert_equal(jdate.to_s, actual.to_s, 'Java->Ruby->Java date conversion not idempotent')
assert_equal(jdate.to_ruby_date, rdt, 'Java->Ruby date reconversion not equal')
end
end |
refs #44 Sets up hosts initializer for Volontari.at.
module Volontariat
HOSTS = { development: 'http://localhost:3001', production: 'http://volontari.at'}
end |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ruby_svg_image_generator/version'
Gem::Specification.new do |spec|
spec.name = "ruby_svg_image_generator"
spec.version = RubySvgImageGenerator::VERSION
spec.authors = ["santiriera626" , "camumino", "franx0"]
spec.email = ["santiriera626@gmail.com", "camumino@gmail.com", "francisco.moya.martinez@gmail.com"]
spec.summary = "%q{TODO: Write a short summary, because Rubygems requires one.}"
spec.description = "%q{TODO: Write a longer description or delete this line"
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency 'rspec', "~> 3.4.0"
spec.add_dependency "ruby_matrix_to_svg", "~> 0.0.1"
end
redo fix gemspec error to build travis
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ruby_svg_image_generator/version'
Gem::Specification.new do |spec|
spec.name = "ruby_svg_image_generator"
spec.version = RubySvgImageGenerator::VERSION
spec.authors = ["santiriera626" , "camumino", "franx0"]
spec.email = ["santiriera626@gmail.com", "camumino@gmail.com", "francisco.moya.martinez@gmail.com"]
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency 'rspec', "~> 3.4.0"
spec.add_dependency "ruby_matrix_to_svg", "~> 0.0.1"
end
|
#
# Cookbook Name:: jenkins-master
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
include_recipe "jenkins::master"
jenkins_plugin 'build-flow-plugin' do
notifies :restart, 'service[jenkins]', :immediately
end
jenkins_plugin 'buildgraph-view' do
notifies :restart, 'service[jenkins]', :immediately
end
jenkins_password_credentials 'root' do
description 'Nimbus Default'
password 'passw0rd'
end
jenkins_ssh_slave 'chef-managed-slave' do
description 'This slave is managed by Chef'
remote_fs '/share/executor'
labels ['executor', 'nimbus', 'chef']
host '9.114.194.75'
user 'jenkins'
credentials 'root'
end
include_recipe "jenkins-job-builder"
cookbook_file "/usr/local/share/jenkins_jobs/sample-jobs.yaml" do
source "sample-jobs.yaml"
end
cookbook_file "/usr/local/share/jenkins_jobs/job-deploy.yaml" do
source "job-deploy.yaml"
end
build_jenkins_job do
job_config "/usr/local/share/jenkins_jobs/"
end
create /usr/local/share/jenkins_jobs/
#
# Cookbook Name:: jenkins-master
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
include_recipe "jenkins::master"
jenkins_plugin 'build-flow-plugin' do
notifies :restart, 'service[jenkins]', :immediately
end
jenkins_plugin 'buildgraph-view' do
notifies :restart, 'service[jenkins]', :immediately
end
jenkins_password_credentials 'root' do
description 'Nimbus Default'
password 'passw0rd'
end
jenkins_ssh_slave 'chef-managed-slave' do
description 'This slave is managed by Chef'
remote_fs '/share/executor'
labels ['executor', 'nimbus', 'chef']
host '9.114.194.75'
user 'jenkins'
credentials 'root'
end
include_recipe "jenkins-job-builder"
directory "/usr/local/share/jenkins_jobs/" do
owner "root"
group "root"
mode 0755
action :create
end
cookbook_file "/usr/local/share/jenkins_jobs/sample-jobs.yaml" do
source "sample-jobs.yaml"
end
cookbook_file "/usr/local/share/jenkins_jobs/job-deploy.yaml" do
source "job-deploy.yaml"
end
build_jenkins_job do
job_config "/usr/local/share/jenkins_jobs/"
end |
#
# Cookbook Name:: rs_user_policy
# Recipe:: install
#
# Copyright 2013, Ryan J. Geyer
#
# 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.
rightscale_marker :begin
chef_gem "rs_user_policy"
directory node["rs_user_policy"]["home"] do
recursive true
end
directory node["rs_user_policy"]["user_assignments_dir"] do
recursive true
end
directory node["rs_user_policy"]["audits_dir"] do
recursive true
end
directory node["rs_user_policy"]["log_dir"] do
recursive true
end
ruby_block "Create the initial user_assignment file if (#{node["rs_user_policy"]["user_assignments_dir"]}) is empty" do
block do
if Dir["#{node["rs_user_policy"]["user_assignments_dir"]}/*"].empty?
::File.open(::File.join(node["rs_user_policy"]["user_assignments_dir"], "user_assignments.json"), "w") do |file|
file.write(node["rs_user_policy"]["user_assignments"]["json"])
end
end
end
end
rightscale_marker :end
Install the gem in ever possible place
#
# Cookbook Name:: rs_user_policy
# Recipe:: install
#
# Copyright 2013, Ryan J. Geyer
#
# 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.
rightscale_marker :begin
# Cover our bases by installing it in the Chef/RightScale sandbox, as
# well as for the system
chef_gem "rs_user_policy"
gem "rs_user_policy"
directory node["rs_user_policy"]["home"] do
recursive true
end
directory node["rs_user_policy"]["user_assignments_dir"] do
recursive true
end
directory node["rs_user_policy"]["audits_dir"] do
recursive true
end
directory node["rs_user_policy"]["log_dir"] do
recursive true
end
ruby_block "Create the initial user_assignment file if (#{node["rs_user_policy"]["user_assignments_dir"]}) is empty" do
block do
if Dir["#{node["rs_user_policy"]["user_assignments_dir"]}/*"].empty?
::File.open(::File.join(node["rs_user_policy"]["user_assignments_dir"], "user_assignments.json"), "w") do |file|
file.write(node["rs_user_policy"]["user_assignments"]["json"])
end
end
end
end
rightscale_marker :end |
require 'test_helper'
class RidgepoleRake::CommandTest < Minitest::Test
def setup
RidgepoleRake.instance_variable_set(:@config, nil)
end
def test_command_with_apply_action
action = :apply
config = RidgepoleRake.config
exp = 'bundle exec ridgepole --apply --file db/schemas/Schemafile --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config).command
end
def test_command_with_export_action
action = :export
config = RidgepoleRake.config
exp = 'bundle exec ridgepole --export --output db/schemas.dump/Schemafile --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config).command
end
def test_command_with_diff_action
action = :diff
config = RidgepoleRake.config
exp = 'bundle exec ridgepole --diff config/database.yml db/schemas/Schemafile --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config).command
end
end
Add test for `--merge`
require 'test_helper'
class RidgepoleRake::CommandTest < Minitest::Test
def setup
RidgepoleRake.instance_variable_set(:@config, nil)
end
def test_command_with_apply_action
action = :apply
config = RidgepoleRake.config
exp = 'bundle exec ridgepole --apply --file db/schemas/Schemafile --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config).command
end
def test_command_with_export_action
action = :export
config = RidgepoleRake.config
exp = 'bundle exec ridgepole --export --output db/schemas.dump/Schemafile --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config).command
end
def test_command_with_diff_action
action = :diff
config = RidgepoleRake.config
exp = 'bundle exec ridgepole --diff config/database.yml db/schemas/Schemafile --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config).command
end
def test_command_with_merge_action
action = :merge
config = RidgepoleRake.config
options = { table_or_patch: 'patch_file.rb' }
exp = 'bundle exec ridgepole --merge --file patch_file.rb --env development --config config/database.yml'
assert_equal exp, RidgepoleRake::Command.new(action, config, options).command
end
end
|
Pod::Spec.new do |s|
s.name = "mParticle-iOS-SDK"
s.version = "5.1.3"
s.summary = "mParticle iOS SDK."
s.description = <<-DESC
Your job is to build an awesome app experience that consumers love. You also need several tools and services to make data-driven decisions.
Like most app owners, you end up implementing and maintaining numerous SDKs ranging from analytics, attribution, push notification, remarketing,
monetization, etc. But embedding multiple 3rd party libraries creates a number of unintended consequences and hidden costs. From not being
able to move as fast as you want, to bloating and destabilizing your app, to losing control and ownership of your 1st party data.
mParticle solves all these problems with one lightweight SDK. Implement new partners without changing code or waiting for app store approval.
Improve stability and security within your app. We enable our clients to spend more time innovating and less time integrating.
DESC
s.homepage = "http://www.mparticle.com"
s.license = { :type => 'Apache', :file => 'LICENSE'}
s.author = { "mParticle" => "support@mparticle.com" }
s.source = { :git => "https://github.com/mParticle/mParticle-iOS-SDK.git", :tag => s.version.to_s }
s.documentation_url = "http://docs.mparticle.com"
s.docset_url = "https://static.mparticle.com/sdk/ios/com.mparticle.mParticle-SDK.docset/Contents/Resources/Documents/index.html"
s.social_media_url = "https://twitter.com/mparticles"
s.requires_arc = true
s.platform = :ios, '7.0'
s.default_subspecs = 'mParticle', 'CrashReporter', 'Adjust', 'Appboy', 'BranchMetrics', 'comScore', 'Flurry', 'Kahuna', 'Kochava', 'Localytics'
s.subspec 'Core-SDK' do |ss|
ss.public_header_files = 'Pod/Classes/mParticle.h', 'Pod/Classes/MPEnums.h', 'Pod/Classes/MPUserSegments.h', \
'Pod/Classes/Event/MPEvent.h', 'Pod/Classes/Ecommerce/MPCommerce.h', 'Pod/Classes/Ecommerce/MPCommerceEvent.h', \
'Pod/Classes/Ecommerce/MPCart.h', 'Pod/Classes/Ecommerce/MPProduct.h', 'Pod/Classes/Ecommerce/MPPromotion.h', \
'Pod/Classes/Ecommerce/MPTransactionAttributes.h', 'Pod/Classes/Ecommerce/MPBags.h'
ss.source_files = 'Pod/Classes/**/*'
ss.platform = :ios, '7.0'
ss.frameworks = 'Accounts', 'CoreGraphics', 'CoreLocation', 'CoreTelephony', 'Foundation', 'Security', 'Social', 'SystemConfiguration', 'UIKit'
ss.weak_framework = 'AdSupport', 'iAd'
ss.libraries = 'c++', 'sqlite3', 'z'
end
s.subspec 'Adjust' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Adjust', '~> 4.3'
ss.prefix_header_contents = "#define MP_KIT_ADJUST 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Appboy' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Appboy-iOS-SDK', '~> 2.16'
ss.prefix_header_contents = "#define MP_KIT_APPBOY 1"
ss.platform = :ios, '7.0'
end
s.subspec 'BranchMetrics' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Branch', '0.11.6'
ss.prefix_header_contents = "#define MP_KIT_BRANCHMETRICS 1"
ss.platform = :ios, '7.0'
end
s.subspec 'comScore' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'comScore-iOS-SDK', '~> 3.1502.26'
ss.prefix_header_contents = "#define MP_KIT_COMSCORE 1"
ss.platform = :ios, '7.0'
ss.frameworks = 'AVFoundation', 'CoreMedia', 'MediaPlayer'
end
s.subspec 'Crittercism' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'CrittercismSDK', '5.4.0'
ss.prefix_header_contents = "#define MP_KIT_CRITTERCISM 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Flurry' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Flurry-iOS-SDK/FlurrySDK'
ss.prefix_header_contents = "#define MP_KIT_FLURRY 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Kahuna' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'KahunaSDK', '1.0.571'
ss.prefix_header_contents = "#define MP_KIT_KAHUNA 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Kochava' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Kochava'
ss.prefix_header_contents = "#define MP_KIT_KOCHAVA 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Localytics' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Localytics', '~> 3.5'
ss.prefix_header_contents = "#define MP_KIT_LOCALYTICS 1"
ss.platform = :ios, '7.0'
end
s.subspec 'mParticle' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.prefix_header_contents = "#define MP_KIT_MPARTICLE 1"
ss.platform = :ios, '7.0'
end
s.subspec 'CrashReporter' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'mParticle-CrashReporter', '~> 1.2'
ss.prefix_header_contents = "#define MP_CRASH_REPORTER 1"
ss.platform = :ios, '7.0'
end
end
Update Appboy subspec
Pod::Spec.new do |s|
s.name = "mParticle-iOS-SDK"
s.version = "5.1.3"
s.summary = "mParticle iOS SDK."
s.description = <<-DESC
Your job is to build an awesome app experience that consumers love. You also need several tools and services to make data-driven decisions.
Like most app owners, you end up implementing and maintaining numerous SDKs ranging from analytics, attribution, push notification, remarketing,
monetization, etc. But embedding multiple 3rd party libraries creates a number of unintended consequences and hidden costs. From not being
able to move as fast as you want, to bloating and destabilizing your app, to losing control and ownership of your 1st party data.
mParticle solves all these problems with one lightweight SDK. Implement new partners without changing code or waiting for app store approval.
Improve stability and security within your app. We enable our clients to spend more time innovating and less time integrating.
DESC
s.homepage = "http://www.mparticle.com"
s.license = { :type => 'Apache', :file => 'LICENSE'}
s.author = { "mParticle" => "support@mparticle.com" }
s.source = { :git => "https://github.com/mParticle/mParticle-iOS-SDK.git", :tag => s.version.to_s }
s.documentation_url = "http://docs.mparticle.com"
s.docset_url = "https://static.mparticle.com/sdk/ios/com.mparticle.mParticle-SDK.docset/Contents/Resources/Documents/index.html"
s.social_media_url = "https://twitter.com/mparticles"
s.requires_arc = true
s.platform = :ios, '7.0'
s.default_subspecs = 'mParticle', 'CrashReporter', 'Adjust', 'Appboy', 'BranchMetrics', 'comScore', 'Flurry', 'Kahuna', 'Kochava', 'Localytics'
s.subspec 'Core-SDK' do |ss|
ss.public_header_files = 'Pod/Classes/mParticle.h', 'Pod/Classes/MPEnums.h', 'Pod/Classes/MPUserSegments.h', \
'Pod/Classes/Event/MPEvent.h', 'Pod/Classes/Ecommerce/MPCommerce.h', 'Pod/Classes/Ecommerce/MPCommerceEvent.h', \
'Pod/Classes/Ecommerce/MPCart.h', 'Pod/Classes/Ecommerce/MPProduct.h', 'Pod/Classes/Ecommerce/MPPromotion.h', \
'Pod/Classes/Ecommerce/MPTransactionAttributes.h', 'Pod/Classes/Ecommerce/MPBags.h'
ss.source_files = 'Pod/Classes/**/*'
ss.platform = :ios, '7.0'
ss.frameworks = 'Accounts', 'CoreGraphics', 'CoreLocation', 'CoreTelephony', 'Foundation', 'Security', 'Social', 'SystemConfiguration', 'UIKit'
ss.weak_framework = 'AdSupport', 'iAd'
ss.libraries = 'c++', 'sqlite3', 'z'
end
s.subspec 'Adjust' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Adjust', '~> 4.3'
ss.prefix_header_contents = "#define MP_KIT_ADJUST 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Appboy' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Appboy-iOS-SDK', '~> 2.17'
ss.prefix_header_contents = "#define MP_KIT_APPBOY 1"
ss.platform = :ios, '7.0'
end
s.subspec 'BranchMetrics' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Branch', '0.11.6'
ss.prefix_header_contents = "#define MP_KIT_BRANCHMETRICS 1"
ss.platform = :ios, '7.0'
end
s.subspec 'comScore' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'comScore-iOS-SDK', '~> 3.1502.26'
ss.prefix_header_contents = "#define MP_KIT_COMSCORE 1"
ss.platform = :ios, '7.0'
ss.frameworks = 'AVFoundation', 'CoreMedia', 'MediaPlayer'
end
s.subspec 'Crittercism' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'CrittercismSDK', '5.4.0'
ss.prefix_header_contents = "#define MP_KIT_CRITTERCISM 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Flurry' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Flurry-iOS-SDK/FlurrySDK'
ss.prefix_header_contents = "#define MP_KIT_FLURRY 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Kahuna' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'KahunaSDK', '1.0.571'
ss.prefix_header_contents = "#define MP_KIT_KAHUNA 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Kochava' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Kochava'
ss.prefix_header_contents = "#define MP_KIT_KOCHAVA 1"
ss.platform = :ios, '7.0'
end
s.subspec 'Localytics' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'Localytics', '~> 3.5'
ss.prefix_header_contents = "#define MP_KIT_LOCALYTICS 1"
ss.platform = :ios, '7.0'
end
s.subspec 'mParticle' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.prefix_header_contents = "#define MP_KIT_MPARTICLE 1"
ss.platform = :ios, '7.0'
end
s.subspec 'CrashReporter' do |ss|
ss.dependency 'mParticle-iOS-SDK/Core-SDK'
ss.dependency 'mParticle-iOS-SDK/mParticle'
ss.dependency 'mParticle-CrashReporter', '~> 1.2'
ss.prefix_header_contents = "#define MP_CRASH_REPORTER 1"
ss.platform = :ios, '7.0'
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'deterministic/version'
Gem::Specification.new do |spec|
spec.name = "deterministic"
spec.version = Deterministic::VERSION
spec.authors = ["Piotr Zolnierek"]
spec.email = ["pz@anixe.pl"]
spec.description = %q{A gem providing failsafe flow}
spec.summary = %q{see above}
spec.homepage = "http://github.com/pzol/deterministic"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", ">= 3"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-bundler"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "simplecov"
end
refact: Add required ruby version
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'deterministic/version'
Gem::Specification.new do |spec|
spec.name = "deterministic"
spec.version = Deterministic::VERSION
spec.authors = ["Piotr Zolnierek"]
spec.email = ["pz@anixe.pl"]
spec.description = %q{A gem providing failsafe flow}
spec.summary = %q{see above}
spec.homepage = "http://github.com/pzol/deterministic"
spec.license = "MIT"
spec.required_ruby_version = '>=1.9.3'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", ">= 3"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-bundler"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "simplecov"
end
|
require_relative 'test_case'
require 'rtest/assertion_errors'
require 'rtest/test'
module Rtest
class AssertionErrorTest < TestCase
def setup
self.assertion = Assertion.new
end
attr_accessor :assertion
def test_error
assert_instance_of Assertion, assertion.error
end
def test_location
result = FailingTest.new.run
assertion = result.failure
exp_location = %r(.*/rtest/test/rtest/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "F", assertion.result_code
end
def test_result_label
assert_equal "Failure", assertion.result_label
end
end
class EmptyTest < TestCase
def setup
self.assertion = Empty.new
end
attr_accessor :assertion
def test_error
assert_instance_of Empty, assertion.error
end
def test_location
result = FailingTest.new(:test_empty).run
assertion = result.failure
exp_location = %r(.*/rtest/test/rtest/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "_", assertion.result_code
end
def test_result_label
assert_equal "_Empty", assertion.result_label
end
end
class SkipTest < TestCase
def setup
self.assertion = Skip.new
end
attr_accessor :assertion
def test_error
assert_instance_of Skip, assertion.error
end
def test_location
result = SkippedTest.new.run
assertion = result.failure
exp_location = %r(.*/rtest/test/rtest/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "S", assertion.result_code
end
def test_result_label
assert_equal "Skipped", assertion.result_label
end
end
end
Admit defeat
require_relative 'test_case'
require 'rtest/assertion_errors'
require 'rtest/test'
module Rtest
class AssertionErrorTest < TestCase
def setup
self.assertion = Assertion.new
end
attr_accessor :assertion
def test_error
assert_instance_of Assertion, assertion.error
end
def test_location
result = FailingTest.new.run
assertion = result.failure
exp_location = %r(.*/rtest/test/rtest/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "F", assertion.result_code
end
def test_result_label
assert_equal "Failure", assertion.result_label
end
end
class EmptyTest < TestCase
def setup
self.assertion = Empty.new
end
attr_accessor :assertion
def test_error
assert_instance_of Empty, assertion.error
end
def test_location
result = FailingTest.new(:test_empty).run
assertion = result.failure
exp_location = %r(.*/rtest/test/rtest/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_location_handles_unnamed_classes
skip "I'm broken and need to be fixed"
result = Class.new(Test) {
def test_empty
end
}.new(:test_empty).run
assert result.failure.location
end
def test_result_code
assert_equal "_", assertion.result_code
end
def test_result_label
assert_equal "_Empty", assertion.result_label
end
end
class SkipTest < TestCase
def setup
self.assertion = Skip.new
end
attr_accessor :assertion
def test_error
assert_instance_of Skip, assertion.error
end
def test_location
result = SkippedTest.new.run
assertion = result.failure
exp_location = %r(.*/rtest/test/rtest/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "S", assertion.result_code
end
def test_result_label
assert_equal "Skipped", assertion.result_label
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'devise_zxcvbn/version'
Gem::Specification.new do |spec|
spec.name = "devise_zxcvbn"
spec.version = DeviseZxcvbn::VERSION
spec.authors = ["Bit Zesty"]
spec.email = ["info@bitzesty.com"]
spec.description = %q{This gems works with devise to provide backend password strength checking via zxcvbn-js to reject weak passwords }
spec.summary = %q{Devise plugin to reject weak passwords}
spec.homepage = "https://github.com/bitzesty/devise_zxcvbn"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "activemodel"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rspec_junit_formatter"
spec.add_runtime_dependency "devise"
spec.add_runtime_dependency("zxcvbn-js", "~> 4.2.0")
end
Update `zxcvbn-js` dependency version
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'devise_zxcvbn/version'
Gem::Specification.new do |spec|
spec.name = "devise_zxcvbn"
spec.version = DeviseZxcvbn::VERSION
spec.authors = ["Bit Zesty"]
spec.email = ["info@bitzesty.com"]
spec.description = %q{This gems works with devise to provide backend password strength checking via zxcvbn-js to reject weak passwords }
spec.summary = %q{Devise plugin to reject weak passwords}
spec.homepage = "https://github.com/bitzesty/devise_zxcvbn"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "activemodel"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rspec_junit_formatter"
spec.add_runtime_dependency "devise"
spec.add_runtime_dependency("zxcvbn-js", "~> 4.4.1")
end
|
name 'netuitive-agent'
maintainer 'Netuitive, Inc'
homepage 'http://www.netuitive.com'
# Defaults to C:/netuitive on Windows
# and /opt/netuitive on all other platforms
install_dir "#{default_root}/#{name}"
build_version '0.7.7-RC5'
build_iteration 1
# Creates required build directories
dependency 'preparation'
# netuitive diamond agent
dependency 'netuitive-diamond'
# netuitive statsd
dependency 'netuitive-statsd'
# netuitive event handler
dependency 'netuitive-event-handler'
# Version manifest file
dependency 'version-manifest'
exclude '**/.git'
exclude '**/bundler/git'
exclude '**/.gitkeep'
# main config
config_file "#{install_dir}/conf/netuitive-agent.conf"
# default collector configs
config_file "#{install_dir}/conf/collectors/CassandraJolokiaCollector.conf"
config_file "#{install_dir}/conf/collectors/ConsulCollector.conf"
config_file "#{install_dir}/conf/collectors/DNSLookupCheckCollector.conf"
config_file "#{install_dir}/conf/collectors/ElasticSearchCollector.conf"
config_file "#{install_dir}/conf/collectors/FlumeCollector.conf"
config_file "#{install_dir}/conf/collectors/HeartbeatCollector.conf"
config_file "#{install_dir}/conf/collectors/HttpCodeCollector.conf"
config_file "#{install_dir}/conf/collectors/HttpCollector.conf"
config_file "#{install_dir}/conf/collectors/HttpdCollector.conf"
config_file "#{install_dir}/conf/collectors/JolokiaCollector.conf"
config_file "#{install_dir}/conf/collectors/KafkaCollector.conf"
config_file "#{install_dir}/conf/collectors/KafkaConsumerLagCollector.conf"
config_file "#{install_dir}/conf/collectors/KafkaJolokiaCollector.conf"
config_file "#{install_dir}/conf/collectors/MongoDBCollector.conf"
config_file "#{install_dir}/conf/collectors/MySQLCollector.conf"
config_file "#{install_dir}/conf/collectors/NginxCollector.conf"
config_file "#{install_dir}/conf/collectors/PortCheckCollector.conf"
config_file "#{install_dir}/conf/collectors/PostgresqlCollector.conf"
config_file "#{install_dir}/conf/collectors/PowerDNSCollector.conf"
config_file "#{install_dir}/conf/collectors/ProcessCheckCollector.conf"
config_file "#{install_dir}/conf/collectors/ProcessResourcesCollector.conf"
config_file "#{install_dir}/conf/collectors/PuppetDBCollector.conf"
config_file "#{install_dir}/conf/collectors/RabbitMQCollector.conf"
config_file "#{install_dir}/conf/collectors/RedisCollector.conf"
config_file "#{install_dir}/conf/collectors/SNMPCollector.conf"
config_file "#{install_dir}/conf/collectors/SNMPInterfaceCollector.conf"
config_file "#{install_dir}/conf/collectors/SolrCollector.conf"
config_file "#{install_dir}/conf/collectors/TCPCollector.conf"
config_file "#{install_dir}/conf/collectors/UserScriptsCollector.conf"
Version bump to v0.7.7-RC6
name 'netuitive-agent'
maintainer 'Netuitive, Inc'
homepage 'http://www.netuitive.com'
# Defaults to C:/netuitive on Windows
# and /opt/netuitive on all other platforms
install_dir "#{default_root}/#{name}"
build_version '0.7.7-RC6'
build_iteration 1
# Creates required build directories
dependency 'preparation'
# netuitive diamond agent
dependency 'netuitive-diamond'
# netuitive statsd
dependency 'netuitive-statsd'
# netuitive event handler
dependency 'netuitive-event-handler'
# Version manifest file
dependency 'version-manifest'
exclude '**/.git'
exclude '**/bundler/git'
exclude '**/.gitkeep'
# main config
config_file "#{install_dir}/conf/netuitive-agent.conf"
# default collector configs
config_file "#{install_dir}/conf/collectors/CassandraJolokiaCollector.conf"
config_file "#{install_dir}/conf/collectors/ConsulCollector.conf"
config_file "#{install_dir}/conf/collectors/DNSLookupCheckCollector.conf"
config_file "#{install_dir}/conf/collectors/ElasticSearchCollector.conf"
config_file "#{install_dir}/conf/collectors/FlumeCollector.conf"
config_file "#{install_dir}/conf/collectors/HeartbeatCollector.conf"
config_file "#{install_dir}/conf/collectors/HttpCodeCollector.conf"
config_file "#{install_dir}/conf/collectors/HttpCollector.conf"
config_file "#{install_dir}/conf/collectors/HttpdCollector.conf"
config_file "#{install_dir}/conf/collectors/JolokiaCollector.conf"
config_file "#{install_dir}/conf/collectors/KafkaCollector.conf"
config_file "#{install_dir}/conf/collectors/KafkaConsumerLagCollector.conf"
config_file "#{install_dir}/conf/collectors/KafkaJolokiaCollector.conf"
config_file "#{install_dir}/conf/collectors/MongoDBCollector.conf"
config_file "#{install_dir}/conf/collectors/MySQLCollector.conf"
config_file "#{install_dir}/conf/collectors/NginxCollector.conf"
config_file "#{install_dir}/conf/collectors/PortCheckCollector.conf"
config_file "#{install_dir}/conf/collectors/PostgresqlCollector.conf"
config_file "#{install_dir}/conf/collectors/PowerDNSCollector.conf"
config_file "#{install_dir}/conf/collectors/ProcessCheckCollector.conf"
config_file "#{install_dir}/conf/collectors/ProcessResourcesCollector.conf"
config_file "#{install_dir}/conf/collectors/PuppetDBCollector.conf"
config_file "#{install_dir}/conf/collectors/RabbitMQCollector.conf"
config_file "#{install_dir}/conf/collectors/RedisCollector.conf"
config_file "#{install_dir}/conf/collectors/SNMPCollector.conf"
config_file "#{install_dir}/conf/collectors/SNMPInterfaceCollector.conf"
config_file "#{install_dir}/conf/collectors/SolrCollector.conf"
config_file "#{install_dir}/conf/collectors/TCPCollector.conf"
config_file "#{install_dir}/conf/collectors/UserScriptsCollector.conf"
|
require_relative 'handler_init'
describe "Handler" do
it "Handles" do
handler = EventStore::Messaging::Controls::Handler::HandlesHandledMessage.new
message = EventStore::Messaging::Controls::Message::HandledMessage.new
handler.handle message
assert(message.handler? "HandlesHandledMessage")
end
end
Test description is clarified
require_relative 'handler_init'
describe "Handle Message" do
it "Handles" do
handler = EventStore::Messaging::Controls::Handler::HandlesHandledMessage.new
message = EventStore::Messaging::Controls::Message::HandledMessage.new
handler.handle message
assert(message.handler? "HandlesHandledMessage")
end
end
|
#
# Copyright 2016-2022 GitLab 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.
#
name 'gitlab-exporter'
default_version '11.17.1'
license 'MIT'
license_file 'LICENSE'
skip_transitive_dependency_licensing true
dependency 'ruby'
dependency 'postgresql'
build do
patch source: 'add-license-file.patch'
env = with_standard_compiler_flags(with_embedded_path)
gem "install gitlab-exporter --no-document --version #{version}", env: env
end
Update gitlab-org/gitlab-exporter to 11.18.0
Bump gitlab-org/gitlab-exporter from 11.17.1 to 11.18.0
Changelog: changed
Signed-off-by: Robert Marshall <0465b3b4f3ae0103ad50d09ff86a3523700a2979@gitlab.com>
#
# Copyright 2016-2022 GitLab 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.
#
name 'gitlab-exporter'
default_version '11.18.0'
license 'MIT'
license_file 'LICENSE'
skip_transitive_dependency_licensing true
dependency 'ruby'
dependency 'postgresql'
build do
patch source: 'add-license-file.patch'
env = with_standard_compiler_flags(with_embedded_path)
gem "install gitlab-exporter --no-document --version #{version}", env: env
end
|
require 'application_system_test_case'
class IncidentsIndexTest < ApplicationSystemTestCase
def assert_incident_for(driver_name)
assert_selector 'table.incidents td', text: driver_name
end
def assert_no_incident_for(driver_name)
assert_no_selector 'table.incidents td', text: driver_name
end
test 'visiting the index as staff shows incidents in the current month' do
when_current_user_is :staff
Timecop.freeze Date.new(2017, 5, 15) do
incident_for 'Shera Hessel', occurred_at: 1.month.ago
incident_for 'Trudie Borer', occurred_at: Date.today
incident_for 'Nona Strosin', occurred_at: 1.month.since
visit incidents_url
end
assert_selector 'h1', text: 'Incidents'
assert_selector 'h2', text: 'Monday, May 1 — Wednesday, May 31'
assert_selector 'a.switch button', text: 'View single week'
assert_incident_for 'Trudie Borer'
assert_no_incident_for 'Shera Hessel'
assert_no_incident_for 'Nona Strosin'
end
test 'moving to the previous month shows incidents in that month' do
when_current_user_is :staff
Timecop.freeze Date.new(2017, 5, 15) do
incident_for 'Nanci Kuvalis', occurred_at: 1.month.ago
incident_for 'Kathie Ledner', occurred_at: Date.today
visit incidents_url
end
assert_selector 'table.incidents td', text: 'Kathie Ledner'
click_button 'Previous month'
assert_selector 'h2', text: 'Saturday, April 1 — Sunday, April 30'
assert_incident_for 'Nanci Kuvalis'
end
test 'switching from month to week goes to the first week in the month' do
when_current_user_is :staff
Timecop.freeze Date.new(2017, 5, 15) do
incident_for 'Malorie Gulgowski', occurred_at: 2.weeks.ago
incident_for 'Marcelina Okuneva', occurred_at: Date.today
visit incidents_url
end
click_button 'View single week'
assert_selector 'h2', text: 'Sunday, April 30 — Saturday, May 6'
assert_incident_for 'Malorie Gulgowski'
assert_no_incident_for 'Marclinea Okuneva'
end
test "visiting the index as a driver shows all of the driver's incidents" do
driver = create :user, :driver, name: 'Alfred Bergnaum'
when_current_user_is driver
incident_for driver
incident_for 'Evelyn Parisian'
incident_for 'Eusebia Farrell'
visit incidents_url
assert_selector 'h1', text: 'Your Incidents'
assert_incident_for 'Alfred Bergnaum'
assert_no_incident_for 'Evelyn Parisian'
assert_no_incident_for 'Eusebia Farrell'
end
end
Test moving from week to month
require 'application_system_test_case'
class IncidentsIndexTest < ApplicationSystemTestCase
def assert_incident_for(driver_name)
assert_selector 'table.incidents td', text: driver_name
end
def assert_no_incident_for(driver_name)
assert_no_selector 'table.incidents td', text: driver_name
end
test 'visiting the index as staff shows incidents in the current month' do
when_current_user_is :staff
Timecop.freeze Date.new(2017, 5, 15) do
incident_for 'Shera Hessel', occurred_at: 1.month.ago
incident_for 'Trudie Borer', occurred_at: Date.today
incident_for 'Nona Strosin', occurred_at: 1.month.since
visit incidents_url
end
assert_selector 'h1', text: 'Incidents'
assert_selector 'h2', text: 'Monday, May 1 — Wednesday, May 31'
assert_selector 'a.switch button', text: 'View single week'
assert_incident_for 'Trudie Borer'
assert_no_incident_for 'Shera Hessel'
assert_no_incident_for 'Nona Strosin'
end
test 'moving to the previous month shows incidents in that month' do
when_current_user_is :staff
Timecop.freeze Date.new(2017, 5, 15) do
incident_for 'Nanci Kuvalis', occurred_at: 1.month.ago
incident_for 'Kathie Ledner', occurred_at: Date.today
visit incidents_url
end
assert_selector 'table.incidents td', text: 'Kathie Ledner'
click_button 'Previous month'
assert_selector 'h2', text: 'Saturday, April 1 — Sunday, April 30'
assert_incident_for 'Nanci Kuvalis'
end
test 'switching from month to week goes to the first week in the month' do
when_current_user_is :staff
Timecop.freeze Date.new(2017, 5, 15) do
incident_for 'Malorie Gulgowski', occurred_at: 2.weeks.ago
incident_for 'Marcelina Okuneva', occurred_at: Date.today
visit incidents_url
end
click_button 'View single week'
assert_selector 'h2', text: 'Sunday, April 30 — Saturday, May 6'
assert_incident_for 'Malorie Gulgowski'
assert_no_incident_for 'Marclinea Okuneva'
end
test 'switching from mid-month week to month works as expected' do
when_current_user_is :staff
visit incidents_url(mode: 'week', start_date: '2017-05-07')
assert_selector 'h2', text: 'Sunday, May 7 — Saturday, May 13'
click_button 'View for whole month'
assert_selector 'h2', text: 'Monday, May 1 — Wednesday, May 31'
end
test "visiting the index as a driver shows all of the driver's incidents" do
driver = create :user, :driver, name: 'Alfred Bergnaum'
when_current_user_is driver
incident_for driver
incident_for 'Evelyn Parisian'
incident_for 'Eusebia Farrell'
visit incidents_url
assert_selector 'h1', text: 'Your Incidents'
assert_incident_for 'Alfred Bergnaum'
assert_no_incident_for 'Evelyn Parisian'
assert_no_incident_for 'Eusebia Farrell'
end
end
|
Add test cases for OCF::PhysicalContainer::Zipruby
# coding: utf-8
require_relative 'helper'
require 'epub/ocf/physical_container'
class TestOCFPhysicalContainer < Test::Unit::TestCase
def setup
@path = 'OPS/nav.xhtml'
@content = File.read(File.join('test/fixtures/book', @path))
end
class TestZipruby < self
def setup
super
@container_path = 'test/fixtures/book.epub'
@container = EPUB::OCF::PhysicalContainer::Zipruby.new(@container_path)
end
def test_class_method_open
EPUB::OCF::PhysicalContainer::Zipruby.open @container_path do |container|
assert_instance_of EPUB::OCF::PhysicalContainer::Zipruby, container
assert_equal @content, container.read(@path).force_encoding('UTF-8')
assert_equal File.read('test/fixtures/book/OPS/日本語.xhtml'), container.read('OPS/日本語.xhtml').force_encoding('UTF-8')
end
end
def test_class_method_read
assert_equal @content, EPUB::OCF::PhysicalContainer::Zipruby.read(@container_path, @path).force_encoding('UTF-8')
end
def test_open_yields_over_container_with_opened_archive
@container.open do |container|
assert_instance_of EPUB::OCF::PhysicalContainer::Zipruby, container
end
end
def test_container_in_open_block_can_readable
@container.open do |container|
assert_equal @content, container.read(@path).force_encoding('UTF-8')
end
end
def test_read
assert_equal @content, @container.read(@path).force_encoding('UTF-8')
end
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper.rb'))
class AllowActionOnceTest < ActiveSupport::TestCase
test "should flunk" do
flunk
end
end
Removed unused test
|
# frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'discourse_api/version'
Gem::Specification.new do |spec|
spec.name = 'discourse_api'
spec.version = DiscourseApi::VERSION
spec.authors = ['Sam Saffron', 'John Paul Ashenfelter', 'Michael Herold', 'Blake Erickson']
spec.email = ['sam.saffron@gmail.com', 'john@ashenfelter.com', 'michael.j.herold@gmail.com', 'o.blakeerickson@gmail.com']
spec.description = 'Discourse API'
spec.summary = 'Allows access to the Discourse API'
spec.homepage = 'http://github.com/discourse/discourse_api'
spec.license = 'MIT'
spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'faraday', '~> 0.9'
spec.add_dependency 'faraday_middleware', '~> 0.10'
spec.add_dependency 'rack', '>= 1.6'
spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'guard', '~> 2.14'
spec.add_development_dependency 'guard-rspec', '~> 4.7'
spec.add_development_dependency 'rake', '~> 11.1'
spec.add_development_dependency 'rb-inotify', '~> 0.9'
spec.add_development_dependency 'rspec', '~> 3.4'
spec.add_development_dependency 'rubocop', '~> 0.69'
spec.add_development_dependency 'simplecov', '~> 0.11'
spec.add_development_dependency 'webmock', '~> 2.0'
spec.add_development_dependency 'rubocop-discourse', '~> 1.0'
spec.add_development_dependency 'rubocop-rspec', '~> 1.0'
spec.required_ruby_version = '>= 2.2.3'
end
FIX: Don't use an old version of rubocop-discourse
Looks like rubocop-discourse 2 was released a couple of months ago, but
we never updated it here causing CI to break. This change removes the
version constraint because we also aren't specifying a version in the
discourse/discourse gemfile.
# frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'discourse_api/version'
Gem::Specification.new do |spec|
spec.name = 'discourse_api'
spec.version = DiscourseApi::VERSION
spec.authors = ['Sam Saffron', 'John Paul Ashenfelter', 'Michael Herold', 'Blake Erickson']
spec.email = ['sam.saffron@gmail.com', 'john@ashenfelter.com', 'michael.j.herold@gmail.com', 'o.blakeerickson@gmail.com']
spec.description = 'Discourse API'
spec.summary = 'Allows access to the Discourse API'
spec.homepage = 'http://github.com/discourse/discourse_api'
spec.license = 'MIT'
spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'faraday', '~> 0.9'
spec.add_dependency 'faraday_middleware', '~> 0.10'
spec.add_dependency 'rack', '>= 1.6'
spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'guard', '~> 2.14'
spec.add_development_dependency 'guard-rspec', '~> 4.7'
spec.add_development_dependency 'rake', '~> 11.1'
spec.add_development_dependency 'rb-inotify', '~> 0.9'
spec.add_development_dependency 'rspec', '~> 3.4'
spec.add_development_dependency 'rubocop', '~> 0.69'
spec.add_development_dependency 'simplecov', '~> 0.11'
spec.add_development_dependency 'webmock', '~> 2.0'
spec.add_development_dependency 'rubocop-discourse'
spec.add_development_dependency 'rubocop-rspec'
spec.required_ruby_version = '>= 2.2.3'
end
|
# -*- encoding: utf-8 -*-
require File.dirname(__FILE__) + "/lib/unibits/version"
Gem::Specification.new do |gem|
gem.name = "unibits"
gem.version = Unibits::VERSION
gem.summary = "Visualizes Unicode encodings."
gem.description = "Visualizes Unicode encodings in the terminal. Supports UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE, US-ASCII, and ASCII-8BIT. Comes as CLI command and as Ruby Kernel method."
gem.authors = ["Jan Lelis"]
gem.email = ["mail@janlelis.de"]
gem.homepage = "https://github.com/janlelis/unibits"
gem.license = "MIT"
gem.files = Dir["{**/}{.*,*}"].select{ |path| File.file?(path) && path !~ /^(pkg|screenshots)/ }
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.add_dependency 'paint', '>= 0.9', '< 3.0'
gem.add_dependency 'unicode-display_width', '~> 1.1'
gem.add_dependency 'characteristics', '~> 0.3.0'
gem.add_dependency 'rationalist', '~> 2.0'
gem.required_ruby_version = "~> 2.0"
end
Update gemspec description
# -*- encoding: utf-8 -*-
require File.dirname(__FILE__) + "/lib/unibits/version"
Gem::Specification.new do |gem|
gem.name = "unibits"
gem.version = Unibits::VERSION
gem.summary = "Visualizes encodings."
gem.description = "Visualizes encodings in the terminal. Supports UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE, US-ASCII, ASCII-8BIT, and most of Rubies single-byte encodings. Comes as CLI command and as Ruby Kernel method."
gem.authors = ["Jan Lelis"]
gem.email = ["mail@janlelis.de"]
gem.homepage = "https://github.com/janlelis/unibits"
gem.license = "MIT"
gem.files = Dir["{**/}{.*,*}"].select{ |path| File.file?(path) && path !~ /^(pkg|screenshots)/ }
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.add_dependency 'paint', '>= 0.9', '< 3.0'
gem.add_dependency 'unicode-display_width', '~> 1.1'
gem.add_dependency 'characteristics', '~> 0.3.0'
gem.add_dependency 'rationalist', '~> 2.0'
gem.required_ruby_version = "~> 2.0"
end
|
#!/usr/bin/ruby
require 'pry'
require "#{File.expand_path(File.dirname(__FILE__))}/../config/environment"
Pry.start
get the correct ruby
#!/usr/bin/env ruby
require 'pry'
require "#{File.expand_path(File.dirname(__FILE__))}/../config/environment"
Pry.start
|
#!/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:{}, timeout:5)
$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=timeout
client.receive_timeout=timeout
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, timeout:5)
$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, timeout:timeout
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"]
shorts = []
if (not quote.nil?) and quote.downcase == "bts"
response_json = chain_command command:"blockchain_market_list_shorts", params:[base.upcase]
shorts = response_json["result"]
end
#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
Time.parse(e["expiration"]+' +0000') > Time.now and
e["market_index"]["order_price"]["ratio"].to_f < feed_price
#feed_price > e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision
}.sort_by {|e| (e["type"] == "ask_order" and e["market_index"]["order_price"]["ratio"].to_f) or
(e["type"] == "cover_order" and e["market_index"]["order_price"]["ratio"] >= feed_price and
feed_price * 0.9) or
(e["type"] == "cover_order" and feed_price)
}.first(max_orders)
#puts ob[0].concat(shorts)
bids = ob[0].concat(shorts).sort_by {|e|
begin
(e["type"] == "bid_order" and e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision) or
(e["type"] == "short_order" and ( e["state"]["limit_price"].nil? ? feed_price :
[ e["state"]["limit_price"]["ratio"].to_f*quote_precision/base_precision, feed_price ].min ) )
rescue
puts e
end
}.reverse.first(max_orders)
#asks_new=Hash[*asks.map["price","volume"]]
asks_new=[]
bids_new=[]
bids.each do |e|
item = {
"price"=> ( (e["type"] == "bid_order" and e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision) or
(e["type"] == "short_order" and ( e["state"]["limit_price"].nil? ? feed_price :
[ e["state"]["limit_price"]["ratio"].to_f*quote_precision/base_precision, feed_price ].min ) )
),
"volume"=>e["state"]["balance"].to_f/base_precision
}
if e["type"] == "bid_order"
item["volume"] /= item["price"]
elsif e["type"] == "short_order"
item["volume"] /= 2
end
bids_new.push item
end
asks.each do |e|
item = {
"price"=> ((e["type"] == "ask_order" and e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision) or
(e["type"] == "cover_order" and e["market_index"]["order_price"]["ratio"] >= feed_price and
( (bids.empty? or feed_price * 0.9 < bids[0]["price"]) ?
feed_price * 0.9 : bids[0]["price"] + 0.000001 ) ) or # hack price to not match
(e["type"] == "cover_order" and feed_price)
),
"volume"=>e["state"]["balance"].to_f/quote_precision
}
#item["volume"] /= item["price"]
asks_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:nil)
account = my_chain_config["account"] if account.nil?
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 (account:nil, quote:"bts", base:"cny", type:"all")
ret = {
"source"=>"chain",
"base"=>base,
"quote"=>quote,
"asks"=>[],
"bids"=>[],
"shorts"=>[],
"covers"=>[]
}
account = my_chain_config["account"] if account.nil?
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)
need_short = ("all" == type or "short" == type)
need_cover = ("all" == type or "cover" == type)
asks_new=[]
bids_new=[]
shorts_new=[]
covers_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
elsif "short_order" == order_type and need_short
order_volume = e[1]["state"]["balance"].to_f / quote_precision
order_limit_price = e[1]["state"]["limit_price"]["ratio"].to_f * quote_precision / base_precision
order_price = e[1]["market_index"]["order_price"]["ratio"].to_f
order_owner = e[1]["market_index"]["owner"]
item = {"id"=>e[0], "price"=>order_price, "interest"=>order_price, "limit_price"=>order_limit_price,
"volume"=>order_volume, "owner"=>order_owner}
shorts_new.push item
elsif "cover_order" == order_type and need_cover
order_volume = e[1]["state"]["balance"].to_f / base_precision
order_interest = e[1]["interest_rate"]["ratio"].to_f * quote_precision / base_precision
order_owner = e[1]["market_index"]["owner"]
item = {"id"=>e[0], "price"=>order_price, "interest"=>order_interest, "margin_price"=>order_price,
"volume"=>order_volume, "owner"=>order_owner}
covers_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
ret["shorts"]=shorts_new
ret["covers"]=covers_new
return ret
end
def chain_list_shorts (base:"cny")
ret = []
response_json = chain_command command:"blockchain_market_list_shorts", params:[base.upcase]
orders = response_json["result"]
#puts orders
if orders.nil? or orders.empty?
return ret
end
response_json = chain_command command:"blockchain_get_asset", params:[base.upcase]
base_precision = response_json["result"]["precision"]
order_list = []
orders.each { |o|
price_js = o["state"]["limit_price"]
price_limit = 0
if not price_js.nil?
price_limit = (BigDecimal.new(price_js["ratio"]) * 10000.0 / base_precision).to_f
end
interest = (BigDecimal.new(o["interest_rate"]["ratio"]) * 100.0).to_f
interest_s = o["interest_rate"]["ratio"]
bts_balance = o["collateral"]/100000.0
owner = o["market_index"]["owner"]
order_list.push ({"bts_balance"=>bts_balance, "price_limit"=>price_limit, "interest"=>interest,
"owner"=>owner, "interest_s"=>interest_s})
}
ret = order_list
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 (account:nil, 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"] if account.nil?
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
def chain_short (account:nil, volume:nil, quote:"bts", interest:0.0, base:"cny", price_limit:"0")
$LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } }
if volume.nil?
return nil
end
account = my_chain_config["account"] if account.nil?
#wallet_market_submit_short <from_account_name> <short_collateral> <collateral_symbol> <interest_rate> <quote_symbol> [short_price_limit]
response_json = chain_command command:"wallet_market_submit_short", params:[account, volume, quote.upcase, interest, base.upcase, price_limit]
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_cover (account:nil, volume:0, base:"cny", id:nil)
$LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } }
if id.nil?
return nil
end
account = my_chain_config["account"] if account.nil?
#wallet_market_submit_short <from_account_name> <short_collateral> <collateral_symbol> <interest_rate> <quote_symbol> [short_price_limit]
response_json = chain_command command:"wallet_market_cover", params:[account, volume, base.upcase, id]
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]
puts "command=" + ARGV[0]
if ARGV[1]
args = ARGV.clone
args.shift
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
if result["error"]
puts JSON.pretty_generate result
printf "ERROR.code=%s\nERROR.message=\n%s\nERROR.detail=\n%s\n", result["error"]["code"], result["error"]["message"], result["error"]["detail"]
puts
elsif String === result["result"]
puts "result="
printf result["result"]
puts
else
puts JSON.pretty_generate result
end
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
fix short volume bug in chain_fetch; tweak default timeout in chain_command and chain_post
#!/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:{}, timeout:55)
$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=timeout
client.receive_timeout=timeout
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, timeout:55)
$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, timeout:timeout
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"]
shorts = []
if (not quote.nil?) and quote.downcase == "bts"
response_json = chain_command command:"blockchain_market_list_shorts", params:[base.upcase]
shorts = response_json["result"]
end
#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
Time.parse(e["expiration"]+' +0000') > Time.now and
e["market_index"]["order_price"]["ratio"].to_f < feed_price
#feed_price > e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision
}.sort_by {|e| (e["type"] == "ask_order" and e["market_index"]["order_price"]["ratio"].to_f) or
(e["type"] == "cover_order" and e["market_index"]["order_price"]["ratio"] >= feed_price and
feed_price * 0.9) or
(e["type"] == "cover_order" and feed_price)
}.first(max_orders)
#puts ob[0].concat(shorts)
bids = ob[0].concat(shorts).sort_by {|e|
begin
(e["type"] == "bid_order" and e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision) or
(e["type"] == "short_order" and ( e["state"]["limit_price"].nil? ? feed_price :
[ e["state"]["limit_price"]["ratio"].to_f*quote_precision/base_precision, feed_price ].min ) )
rescue
puts e
end
}.reverse.first(max_orders)
#asks_new=Hash[*asks.map["price","volume"]]
asks_new=[]
bids_new=[]
bids.each do |e|
item = {
"price"=> ( (e["type"] == "bid_order" and e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision) or
(e["type"] == "short_order" and ( e["state"]["limit_price"].nil? ? feed_price :
[ e["state"]["limit_price"]["ratio"].to_f*quote_precision/base_precision, feed_price ].min ) )
),
"volume"=>( e["type"] == "bid_order" ? e["state"]["balance"].to_f/base_precision : e["state"]["balance"].to_f/quote_precision)
}
if e["type"] == "bid_order"
item["volume"] /= item["price"]
elsif e["type"] == "short_order"
item["volume"] /= 2
end
bids_new.push item
end
asks.each do |e|
item = {
"price"=> ((e["type"] == "ask_order" and e["market_index"]["order_price"]["ratio"].to_f*quote_precision/base_precision) or
(e["type"] == "cover_order" and e["market_index"]["order_price"]["ratio"] >= feed_price and
( (bids.empty? or feed_price * 0.9 < bids[0]["price"]) ?
feed_price * 0.9 : bids[0]["price"] + 0.000001 ) ) or # hack price to not match
(e["type"] == "cover_order" and feed_price)
),
"volume"=>e["state"]["balance"].to_f/quote_precision
}
#item["volume"] /= item["price"]
asks_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:nil)
account = my_chain_config["account"] if account.nil?
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 (account:nil, quote:"bts", base:"cny", type:"all")
ret = {
"source"=>"chain",
"base"=>base,
"quote"=>quote,
"asks"=>[],
"bids"=>[],
"shorts"=>[],
"covers"=>[]
}
account = my_chain_config["account"] if account.nil?
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)
need_short = ("all" == type or "short" == type)
need_cover = ("all" == type or "cover" == type)
asks_new=[]
bids_new=[]
shorts_new=[]
covers_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
elsif "short_order" == order_type and need_short
order_volume = e[1]["state"]["balance"].to_f / quote_precision
order_limit_price = e[1]["state"]["limit_price"]["ratio"].to_f * quote_precision / base_precision
order_price = e[1]["market_index"]["order_price"]["ratio"].to_f
order_owner = e[1]["market_index"]["owner"]
item = {"id"=>e[0], "price"=>order_price, "interest"=>order_price, "limit_price"=>order_limit_price,
"volume"=>order_volume, "owner"=>order_owner}
shorts_new.push item
elsif "cover_order" == order_type and need_cover
order_volume = e[1]["state"]["balance"].to_f / base_precision
order_interest = e[1]["interest_rate"]["ratio"].to_f * quote_precision / base_precision
order_owner = e[1]["market_index"]["owner"]
item = {"id"=>e[0], "price"=>order_price, "interest"=>order_interest, "margin_price"=>order_price,
"volume"=>order_volume, "owner"=>order_owner}
covers_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
ret["shorts"]=shorts_new
ret["covers"]=covers_new
return ret
end
def chain_list_shorts (base:"cny")
ret = []
response_json = chain_command command:"blockchain_market_list_shorts", params:[base.upcase]
orders = response_json["result"]
#puts orders
if orders.nil? or orders.empty?
return ret
end
response_json = chain_command command:"blockchain_get_asset", params:[base.upcase]
base_precision = response_json["result"]["precision"]
order_list = []
orders.each { |o|
price_js = o["state"]["limit_price"]
price_limit = 0
if not price_js.nil?
price_limit = (BigDecimal.new(price_js["ratio"]) * 10000.0 / base_precision).to_f
end
interest = (BigDecimal.new(o["interest_rate"]["ratio"]) * 100.0).to_f
interest_s = o["interest_rate"]["ratio"]
bts_balance = o["collateral"]/100000.0
owner = o["market_index"]["owner"]
order_list.push ({"bts_balance"=>bts_balance, "price_limit"=>price_limit, "interest"=>interest,
"owner"=>owner, "interest_s"=>interest_s})
}
ret = order_list
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 (account:nil, 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"] if account.nil?
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
def chain_short (account:nil, volume:nil, quote:"bts", interest:0.0, base:"cny", price_limit:"0")
$LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } }
if volume.nil?
return nil
end
account = my_chain_config["account"] if account.nil?
#wallet_market_submit_short <from_account_name> <short_collateral> <collateral_symbol> <interest_rate> <quote_symbol> [short_price_limit]
response_json = chain_command command:"wallet_market_submit_short", params:[account, volume, quote.upcase, interest, base.upcase, price_limit]
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_cover (account:nil, volume:0, base:"cny", id:nil)
$LOG.info (method(__method__).name) { {"parameters"=>method(__method__).parameters.map { |arg| "#{arg[1]} = #{eval arg[1].to_s}" }.join(', ') } }
if id.nil?
return nil
end
account = my_chain_config["account"] if account.nil?
#wallet_market_submit_short <from_account_name> <short_collateral> <collateral_symbol> <interest_rate> <quote_symbol> [short_price_limit]
response_json = chain_command command:"wallet_market_cover", params:[account, volume, base.upcase, id]
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]
puts "command=" + ARGV[0]
if ARGV[1]
args = ARGV.clone
args.shift
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
if result["error"]
puts JSON.pretty_generate result
printf "ERROR.code=%s\nERROR.message=\n%s\nERROR.detail=\n%s\n", result["error"]["code"], result["error"]["message"], result["error"]["detail"]
puts
elsif String === result["result"]
puts "result="
printf result["result"]
puts
else
puts JSON.pretty_generate result
end
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
|
class Chirp < Formula
include Language::Python::Virtualenv
desc "Programs amateur radios"
homepage "http://chirp.danplanet.com/projects/chirp/wiki/Home"
url "http://trac.chirp.danplanet.com/chirp_daily/daily-20170714/chirp-daily-20170714.tar.gz"
sha256 "9ebd201acda7abe826da190f2ab122beb70acb07636fe2dae1a0b80b58d5f4dd"
depends_on "gtk-mac-integration"
depends_on "libxml2" => "with-python"
depends_on "py2cairo"
depends_on "pygtk"
depends_on "python@2"
resource "pyserial" do
url "https://files.pythonhosted.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz"
sha256 "1eecfe4022240f2eab5af8d414f0504e072ee68377ba63d3b6fe6e66c26f66d1"
end
def install
inreplace "setup.py", "darwin", "noop"
inreplace "chirp/ui/mainapp.py", "reporting.check_for_updates(updates_callback)", "pass"
virtualenv_install_with_resources
ln_s bin/"chirpw", bin/"chirp"
end
end
chirp 20180316
class Chirp < Formula
include Language::Python::Virtualenv
desc "Programs amateur radios"
homepage "http://chirp.danplanet.com/projects/chirp/wiki/Home"
url "https://trac.chirp.danplanet.com/chirp_daily/daily-20180316/chirp-daily-20180316.tar.gz"
sha256 "33b7c5ebb6aeae750eb8c7638f86777e5888d26bfc576b8b0bf239d491ceec6f"
depends_on "gtk-mac-integration"
depends_on "libxml2" => "with-python"
depends_on "py2cairo"
depends_on "pygtk"
depends_on "python@2"
resource "pyserial" do
url "https://files.pythonhosted.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz"
sha256 "1eecfe4022240f2eab5af8d414f0504e072ee68377ba63d3b6fe6e66c26f66d1"
end
def install
inreplace "setup.py", "darwin", "noop"
inreplace "chirp/ui/mainapp.py", "reporting.check_for_updates(updates_callback)", "pass"
virtualenv_install_with_resources
ln_s bin/"chirpw", bin/"chirp"
end
end
|
Update Version to v0.0.7
|
#!/usr/bin/env ruby
# Copyright 2014 Square 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.
# To remove all Gem dependencies for the setup script, the Colored gem is
# included here wholesale. For authorship, etc.: https://github.com/defunkt/colored
module Colored
extend self
COLORS = {
'black' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
}
EXTRAS = {
'clear' => 0,
'bold' => 1,
'underline' => 4,
'reversed' => 7
}
COLORS.each do |color, value|
define_method(color) do
colorize(self, :foreground => color)
end
define_method("on_#{color}") do
colorize(self, :background => color)
end
COLORS.each do |highlight, value|
next if color == highlight
define_method("#{color}_on_#{highlight}") do
colorize(self, :foreground => color, :background => highlight)
end
end
end
EXTRAS.each do |extra, value|
next if extra == 'clear'
define_method(extra) do
colorize(self, :extra => extra)
end
end
define_method(:to_eol) do
tmp = sub(/^(\e\[[\[\e0-9;m]+m)/, "\\1\e[2K")
if tmp == self
return "\e[2K" << self
end
tmp
end
def colorize(string, options = {})
colored = [color(options[:foreground]), color("on_#{options[:background]}"), extra(options[:extra])].compact * ''
colored << string
colored << extra(:clear)
end
def colors
@@colors ||= COLORS.keys.sort
end
def extra(extra_name)
extra_name = extra_name.to_s
"\e[#{EXTRAS[extra_name]}m" if EXTRAS[extra_name]
end
def color(color_name)
background = color_name.to_s =~ /on_/
color_name = color_name.to_s.sub('on_', '')
return unless color_name && COLORS[color_name]
"\e[#{COLORS[color_name] + (background ? 10 : 0)}m"
end
end unless Object.const_defined? :Colored
String.send(:include, Colored)
############################## BEGIN SETUP SCRIPT ##############################
def bool(str) 'YyTt1'.include? str[0, 1] end
def say(*strs) puts strs.join(' ') end
def prompt(message, default_yes=true)
y = default_yes ? 'Y' : 'y'
n = default_yes ? 'n' : 'N'
say message.green.bold, "[#{y}/#{n}]".green
answer = gets.strip
if answer.empty?
answer = default_yes
else
answer = bool(answer)
end
return answer
end
def prompt_or_quit(*args) exit unless prompt(*args) end
def run(*command)
args = ["Running".cyan]
args += command.map { |s| s.cyan.bold }
args << "...".cyan
say *args
stdout, stderr, status = Open3.capture3(*command)
unless status.success?
say "Command exited unsuccessfully:".red.bold, status.inspect.red
puts
say "stdout".underline.bold
puts stdout
puts
say "stderr".underline.bold
puts stderr
exit 1
end
stdout
end
def run_ignore(*command)
args = ["Running".cyan]
args += command.map { |s| s.cyan.bold }
args << "... (failure OK)".cyan
say *args
system *command
end
def query(question, default=nil)
output = ''
begin
if default
say question.green.bold, "[#{default.empty? ? 'blank' : default}]".green
else
say question.green.bold
end
output = gets.strip
output = default if default && output.empty?
end while output.empty? && default != ''
output == '' ? nil : output
end
def choose(question, choices, default=nil)
output = nil
until choices.include?(output)
if default
say question.green.bold, "(#{choices.join('/')})".green, "[#{default}]".green
else
say question.green.bold, "(#{choices.join('/')})".green
end
output = gets.strip.downcase
output = default if default && output == ''
output = choices.detect { |c| c.downcase =~ /^#{Regexp.escape output}/ }
end
return output
end
if RUBY_VERSION < '1.9.2'
say "You need Ruby 1.9.2 or newer to use Squash.".red.bold
say "Please re-run this script under a newer version of Ruby.".magenta
exit 1
end
if RUBY_PLATFORM == 'java'
say "This setup script must be run on MRI 1.9.2 or newer.".red.bold
say "You can run Squash itself on JRuby, but this script must be run on MRI."
say "See http://jira.codehaus.org/browse/JRUBY-6409 for the reason why."
exit 1
end
say "Welcome! Let's set up your Squash installation.".bold
puts "I'll ask you some questions to help configure Squash for your needs.",
"Remember to read the README.md file to familiarize yourself with the Squash",
"codebase, as there's a strong likelihood you'll need to make other tweaks",
"to fully support your particular environment."
puts
puts "If something's not right, you can abort this script at any time; it's",
"resumable. Simply rerun it when you are ready."
say
say "Checking the basic environment..."
if File.absolute_path(Dir.getwd) != File.absolute_path(File.dirname(__FILE__))
say "You are not running this script from the Rails project's root directory.".red.bold
say "Please cd into the project root and re-run this script.".magenta
exit 1
end
step = File.read('/tmp/squash_install_progress').to_i rescue 0
if step == 0 && !`git status --porcelain`.empty?
say "You have a dirty working directory.".red.bold
puts "It's #{"highly".bold} recommended to run this script on a clean working",
"directory. In the event you get some answers wrong, or change your mind",
"later, it will be easy to see what files the script changed, and update",
"them accordingly."
prompt_or_quit "Continue?", false
end
say "Checking for required software..."
require 'open3'
require 'yaml'
require 'fileutils'
require 'securerandom'
if `which psql`.empty?
say "You need PostgreSQL version 9.0 or newer to use Squash.".red.bold
say "Please install PostgreSQL and re-run this script.".magenta
exit 1
end
unless `psql -V` =~ /^psql \(PostgreSQL\) (\d{2,}|9)\./
say "You need PostgreSQL version 9.0 or newer to use Squash.".red.bold
say "Please upgrade PostgreSQL and re-run this script.".magenta
exit 1
end
if `which bundle`.empty?
say "You need Bundler to use Squash.".red.bold
say "Please run", "gem install bundler".bold, "and re-run this script.".magenta
exit 1
end
say
say "We will now install gems if you are ready (in the correct gemset, etc.)."
prompt_or_quit "Are you ready to install required gems?"
run 'bundle', 'install'
if step < 1
say
say "Now let's configure production hostname and URL settings.".bold
puts "If you don't know what URL your production instance will have, just make",
"something up. You can always change it later."
hostname = query("What hostname will your production instance have (e.g., squash.mycompany.com)?")
https = prompt("Will your production instance be using HTTPS?", hostname)
email_domain = query("What is the domain portion of your organization's email addresses?", hostname)
sender = query("What sender should Squash emails use?", "squash@#{email_domain}")
mail_strategy = choose("How will Squash send email?", %w(localhost smtp))
if mail_strategy == 'smtp'
smtp_domain = email_domain
smtp_host = query("What's the hostname of your SMTP server?")
smtp_port = query("What's the port of your SMTP server?", '25')
smtp_auth = choose("What's the authentication for your SMTP server?", %w(none plain ntlm))
unless smtp_auth == 'none'
smtp_username = query("What's the username for your SMTP server?")
smtp_password = query("What's the password for your SMTP server?")
end
smtp_ssl = prompt("Do you want to skip SSL verification?")
end
smtp_settings = {
'address' => smtp_host,
'port' => smtp_port,
'domain' => smtp_domain,
'user_name' => smtp_username,
'password' => smtp_password,
'authentication' => smtp_auth,
'enable_starttls_auto' => smtp_ssl
}
say "Updating config/environments/common/mailer.yml..."
File.open('config/environments/common/mailer.yml', 'w') do |f|
f.puts({
'from' => sender,
'domain' => email_domain,
'strategy' => mail_strategy,
'smtp_settings' => smtp_settings
}.to_yaml)
end
say "Updating config/environments/production/mailer.yml..."
File.open('config/environments/production/mailer.yml', 'w') do |f|
f.puts({
'default_url_options' => {
'host' => hostname,
'protocol' => https ? 'https' : 'http'
}
}.to_yaml)
end
unless https
say "Updating config/environments/production.rb..."
prod_config = File.read('config/environments/production.rb')
prod_config.sub! 'config.force_ssl = true', 'config.force_ssl = false'
prod_config.sub! 'config.middleware.insert_before ::ActionDispatch::SSL, Ping',
'config.middleware.insert_before ::Rack::Runtime, Ping'
File.open('config/environments/production.rb', 'w') do |f|
f.puts prod_config
end
end
url = query("What URL will production Squash be available at?", "http#{'s' if https}://#{hostname}")
say "Updating config/environments/production/javascript_dogfood.yml..."
File.open('config/environments/production/javascript_dogfood.yml', 'w') do |f|
f.puts({'APIHost' => url}.to_yaml)
end
say "Updating config/environments/production/dogfood.yml..."
dogfood = YAML.load_file('config/environments/production/dogfood.yml')
File.open('config/environments/production/dogfood.yml', 'w') do |f|
f.puts dogfood.merge('api_host' => url).to_yaml
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '1' }
end
if step < 2
say
say "Now we'll cover authentication.".bold
auth = choose("How will users authenticate to Squash?", %w(password LDAP))
if auth == 'LDAP'
ldap_host = query("What's the hostname of your LDAP server?")
ldap_ssl = prompt("Is your LDAP service using SSL?")
ldap_port = query("What port is your LDAP service running on?", ldap_ssl ? '636' : '389').to_i
tree_base = query("Under what tree base can the user records be found in LDAP?")
search_key = query("What search key should I use to locate a user by username under that tree?", 'uid')
bind_dn = query("Will you be using a different DN to bind to the LDAP server? If so, enter it now.", '')
bind_pw = query("What is the password for #{bind_dn}?") if bind_dn
say "Updating config/environments/common/authentication.yml..."
File.open('config/environments/common/authentication.yml', 'w') do |f|
f.puts({
'strategy' => 'ldap',
'ldap' => {
'host' => ldap_host,
'port' => ldap_port,
'ssl' => ldap_ssl,
'tree_base' => tree_base,
'search_key' => search_key,
'bind_dn' => bind_dn,
'bind_password' => bind_pw
}
}.to_yaml)
end
elsif auth == 'password'
say "Updating config/environments/common/authentication.yml..."
File.open('config/environments/common/authentication.yml', 'w') do |f|
f.puts({
'strategy' => 'password',
'registration_enabled' => true,
'password' => {
'salt' => SecureRandom.base64
}
}.to_yaml)
end
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '2' }
end
if step < 3
say
say "Let's set up your database now.".bold
say "If you don't know the answer to a question, give a best guess. You can always",
"change your database.yml file later."
dev_host = query("What is the hostname of the development PostgreSQL server?", 'localhost')
dev_user = query("What PostgreSQL user will Squash use in development?", 'squash')
dev_pw = query("What is #{dev_user}@#{dev_host}'s password?", '')
dev_local = dev_host.nil? || dev_host == 'localhost' || dev_host == '0.0.0.0' || dev_host == '127.0.0.1'
dev_db = query("What is the name of your PostgreSQL development database?#{" (It doesn't have to exist yet.)" if dev_local}", 'squash_development')
test_host = query("What is the hostname of the test PostgreSQL server?", 'localhost')
test_user = query("What PostgreSQL user will Squash use in test?", dev_user)
test_pw = query("What is #{test_user}@#{test_host}'s password?", '')
test_db = query("What is the name of your PostgreSQL test database?", 'squash_test')
prod_host = query("What is the hostname of the production PostgreSQL server?", 'localhost')
prod_user = query("What PostgreSQL user will Squash use in production?", dev_user)
prod_pw = query("What is #{prod_user}@#{prod_host}'s password?", '')
prod_db = query("What is the name of your PostgreSQL production database?", 'squash_production')
say "Updating config/database.yml..."
File.open('config/database.yml', 'w') do |f|
common = {
'adapter' => 'postgresql', # temporarily for the rake db:migrate calls
'encoding' => 'utf8'
}
f.puts({
'development' => common.merge(
'host' => dev_host,
'username' => dev_user,
'password' => dev_pw,
'database' => dev_db
),
'test' => common.merge(
'host' => test_host,
'username' => test_user,
'password' => test_pw,
'database' => test_db
),
'production' => common.merge(
'host' => prod_host,
'username' => prod_user,
'password' => prod_pw,
'database' => prod_db,
'pool' => 30
)
}.to_yaml)
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '3' }
end
if step < 4
db_config = YAML.load_file('config/database.yml')
dev_host = db_config['development']['host']
dev_user = db_config['development']['username']
dev_db = db_config['development']['database']
dev_local = (dev_host.nil? || dev_host == 'localhost' || dev_host == '0.0.0.0' || dev_host == '127.0.0.1')
test_host = db_config['test']['host']
test_user = db_config['test']['username']
test_db = db_config['test']['database']
test_local = (test_host.nil? || test_host == 'localhost' || test_host == '0.0.0.0' || test_host == '127.0.0.1')
run_ignore 'createuser', '-DSR', 'squash' if dev_local
dbs = `psql -ltA | awk -F'|' '{ print $1 }'`.split(/\n/)
if dev_local
unless dbs.include?(dev_db)
prompt_or_quit "Ready to create the development database?"
run "createdb", '-O', dev_user, dev_db
end
end
prompt_or_quit "Ready to migrate the development database?"
run 'rake', 'db:migrate'
if test_local
unless dbs.include?(test_db)
prompt_or_quit "Ready to create the test database?"
run "createdb", '-O', test_user, test_db
end
end
prompt_or_quit "Ready to migrate the test database?"
run 'env', 'RAILS_ENV=test', 'rake', 'db:migrate'
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '4' }
end
if step < 5
say "Generating session secret..."
secret = SecureRandom.hex
contents = File.read('config/initializers/secret_token.rb')
File.open('config/initializers/secret_token.rb', 'w') do |f|
f.puts contents.sub('_SECRET_', secret)
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '5' }
end
say
say "All done!".green.bold, "You should now be able to run".green,
"rails server.".green.bold, "Some notes:".green
puts
say "* If you want Squash to monitor itself for errors in production, edit".yellow
say " ", "config/environments/production/dogfood.yml".bold.yellow, "and set".yellow, "disabled".bold.yellow, "to".yellow
say " ", "false.".bold.yellow, "When you deploy Squash to production, create a project for itself".yellow
say " and copy the generated API key to this file.".yellow
puts
say "* Test that all specs pass by running".yellow, 'rspec spec.'.bold.yellow
puts
puts "* You can delete this setup script now if you wish.".yellow
FileUtils.rm '/tmp/squash_install_progress'
Fixes invalid option of localhost for mail strategy
#!/usr/bin/env ruby
# Copyright 2014 Square 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.
# To remove all Gem dependencies for the setup script, the Colored gem is
# included here wholesale. For authorship, etc.: https://github.com/defunkt/colored
module Colored
extend self
COLORS = {
'black' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
}
EXTRAS = {
'clear' => 0,
'bold' => 1,
'underline' => 4,
'reversed' => 7
}
COLORS.each do |color, value|
define_method(color) do
colorize(self, :foreground => color)
end
define_method("on_#{color}") do
colorize(self, :background => color)
end
COLORS.each do |highlight, value|
next if color == highlight
define_method("#{color}_on_#{highlight}") do
colorize(self, :foreground => color, :background => highlight)
end
end
end
EXTRAS.each do |extra, value|
next if extra == 'clear'
define_method(extra) do
colorize(self, :extra => extra)
end
end
define_method(:to_eol) do
tmp = sub(/^(\e\[[\[\e0-9;m]+m)/, "\\1\e[2K")
if tmp == self
return "\e[2K" << self
end
tmp
end
def colorize(string, options = {})
colored = [color(options[:foreground]), color("on_#{options[:background]}"), extra(options[:extra])].compact * ''
colored << string
colored << extra(:clear)
end
def colors
@@colors ||= COLORS.keys.sort
end
def extra(extra_name)
extra_name = extra_name.to_s
"\e[#{EXTRAS[extra_name]}m" if EXTRAS[extra_name]
end
def color(color_name)
background = color_name.to_s =~ /on_/
color_name = color_name.to_s.sub('on_', '')
return unless color_name && COLORS[color_name]
"\e[#{COLORS[color_name] + (background ? 10 : 0)}m"
end
end unless Object.const_defined? :Colored
String.send(:include, Colored)
############################## BEGIN SETUP SCRIPT ##############################
def bool(str) 'YyTt1'.include? str[0, 1] end
def say(*strs) puts strs.join(' ') end
def prompt(message, default_yes=true)
y = default_yes ? 'Y' : 'y'
n = default_yes ? 'n' : 'N'
say message.green.bold, "[#{y}/#{n}]".green
answer = gets.strip
if answer.empty?
answer = default_yes
else
answer = bool(answer)
end
return answer
end
def prompt_or_quit(*args) exit unless prompt(*args) end
def run(*command)
args = ["Running".cyan]
args += command.map { |s| s.cyan.bold }
args << "...".cyan
say *args
stdout, stderr, status = Open3.capture3(*command)
unless status.success?
say "Command exited unsuccessfully:".red.bold, status.inspect.red
puts
say "stdout".underline.bold
puts stdout
puts
say "stderr".underline.bold
puts stderr
exit 1
end
stdout
end
def run_ignore(*command)
args = ["Running".cyan]
args += command.map { |s| s.cyan.bold }
args << "... (failure OK)".cyan
say *args
system *command
end
def query(question, default=nil)
output = ''
begin
if default
say question.green.bold, "[#{default.empty? ? 'blank' : default}]".green
else
say question.green.bold
end
output = gets.strip
output = default if default && output.empty?
end while output.empty? && default != ''
output == '' ? nil : output
end
def choose(question, choices, default=nil)
output = nil
until choices.include?(output)
if default
say question.green.bold, "(#{choices.join('/')})".green, "[#{default}]".green
else
say question.green.bold, "(#{choices.join('/')})".green
end
output = gets.strip.downcase
output = default if default && output == ''
output = choices.detect { |c| c.downcase =~ /^#{Regexp.escape output}/ }
end
return output
end
if RUBY_VERSION < '1.9.2'
say "You need Ruby 1.9.2 or newer to use Squash.".red.bold
say "Please re-run this script under a newer version of Ruby.".magenta
exit 1
end
if RUBY_PLATFORM == 'java'
say "This setup script must be run on MRI 1.9.2 or newer.".red.bold
say "You can run Squash itself on JRuby, but this script must be run on MRI."
say "See http://jira.codehaus.org/browse/JRUBY-6409 for the reason why."
exit 1
end
say "Welcome! Let's set up your Squash installation.".bold
puts "I'll ask you some questions to help configure Squash for your needs.",
"Remember to read the README.md file to familiarize yourself with the Squash",
"codebase, as there's a strong likelihood you'll need to make other tweaks",
"to fully support your particular environment."
puts
puts "If something's not right, you can abort this script at any time; it's",
"resumable. Simply rerun it when you are ready."
say
say "Checking the basic environment..."
if File.absolute_path(Dir.getwd) != File.absolute_path(File.dirname(__FILE__))
say "You are not running this script from the Rails project's root directory.".red.bold
say "Please cd into the project root and re-run this script.".magenta
exit 1
end
step = File.read('/tmp/squash_install_progress').to_i rescue 0
if step == 0 && !`git status --porcelain`.empty?
say "You have a dirty working directory.".red.bold
puts "It's #{"highly".bold} recommended to run this script on a clean working",
"directory. In the event you get some answers wrong, or change your mind",
"later, it will be easy to see what files the script changed, and update",
"them accordingly."
prompt_or_quit "Continue?", false
end
say "Checking for required software..."
require 'open3'
require 'yaml'
require 'fileutils'
require 'securerandom'
if `which psql`.empty?
say "You need PostgreSQL version 9.0 or newer to use Squash.".red.bold
say "Please install PostgreSQL and re-run this script.".magenta
exit 1
end
unless `psql -V` =~ /^psql \(PostgreSQL\) (\d{2,}|9)\./
say "You need PostgreSQL version 9.0 or newer to use Squash.".red.bold
say "Please upgrade PostgreSQL and re-run this script.".magenta
exit 1
end
if `which bundle`.empty?
say "You need Bundler to use Squash.".red.bold
say "Please run", "gem install bundler".bold, "and re-run this script.".magenta
exit 1
end
say
say "We will now install gems if you are ready (in the correct gemset, etc.)."
prompt_or_quit "Are you ready to install required gems?"
run 'bundle', 'install'
if step < 1
say
say "Now let's configure production hostname and URL settings.".bold
puts "If you don't know what URL your production instance will have, just make",
"something up. You can always change it later."
hostname = query("What hostname will your production instance have (e.g., squash.mycompany.com)?")
https = prompt("Will your production instance be using HTTPS?", hostname)
email_domain = query("What is the domain portion of your organization's email addresses?", hostname)
sender = query("What sender should Squash emails use?", "squash@#{email_domain}")
mail_strategy = choose("How will Squash send email?", %w(sendmail smtp))
if mail_strategy == 'smtp'
smtp_domain = email_domain
smtp_host = query("What's the hostname of your SMTP server?")
smtp_port = query("What's the port of your SMTP server?", '25')
smtp_auth = choose("What's the authentication for your SMTP server?", %w(none plain ntlm))
unless smtp_auth == 'none'
smtp_username = query("What's the username for your SMTP server?")
smtp_password = query("What's the password for your SMTP server?")
end
smtp_ssl = prompt("Do you want to skip SSL verification?")
end
smtp_settings = {
'address' => smtp_host,
'port' => smtp_port,
'domain' => smtp_domain,
'user_name' => smtp_username,
'password' => smtp_password,
'authentication' => smtp_auth,
'enable_starttls_auto' => smtp_ssl
}
say "Updating config/environments/common/mailer.yml..."
File.open('config/environments/common/mailer.yml', 'w') do |f|
f.puts({
'from' => sender,
'domain' => email_domain,
'strategy' => mail_strategy,
'smtp_settings' => smtp_settings
}.to_yaml)
end
say "Updating config/environments/production/mailer.yml..."
File.open('config/environments/production/mailer.yml', 'w') do |f|
f.puts({
'default_url_options' => {
'host' => hostname,
'protocol' => https ? 'https' : 'http'
}
}.to_yaml)
end
unless https
say "Updating config/environments/production.rb..."
prod_config = File.read('config/environments/production.rb')
prod_config.sub! 'config.force_ssl = true', 'config.force_ssl = false'
prod_config.sub! 'config.middleware.insert_before ::ActionDispatch::SSL, Ping',
'config.middleware.insert_before ::Rack::Runtime, Ping'
File.open('config/environments/production.rb', 'w') do |f|
f.puts prod_config
end
end
url = query("What URL will production Squash be available at?", "http#{'s' if https}://#{hostname}")
say "Updating config/environments/production/javascript_dogfood.yml..."
File.open('config/environments/production/javascript_dogfood.yml', 'w') do |f|
f.puts({'APIHost' => url}.to_yaml)
end
say "Updating config/environments/production/dogfood.yml..."
dogfood = YAML.load_file('config/environments/production/dogfood.yml')
File.open('config/environments/production/dogfood.yml', 'w') do |f|
f.puts dogfood.merge('api_host' => url).to_yaml
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '1' }
end
if step < 2
say
say "Now we'll cover authentication.".bold
auth = choose("How will users authenticate to Squash?", %w(password LDAP))
if auth == 'LDAP'
ldap_host = query("What's the hostname of your LDAP server?")
ldap_ssl = prompt("Is your LDAP service using SSL?")
ldap_port = query("What port is your LDAP service running on?", ldap_ssl ? '636' : '389').to_i
tree_base = query("Under what tree base can the user records be found in LDAP?")
search_key = query("What search key should I use to locate a user by username under that tree?", 'uid')
bind_dn = query("Will you be using a different DN to bind to the LDAP server? If so, enter it now.", '')
bind_pw = query("What is the password for #{bind_dn}?") if bind_dn
say "Updating config/environments/common/authentication.yml..."
File.open('config/environments/common/authentication.yml', 'w') do |f|
f.puts({
'strategy' => 'ldap',
'ldap' => {
'host' => ldap_host,
'port' => ldap_port,
'ssl' => ldap_ssl,
'tree_base' => tree_base,
'search_key' => search_key,
'bind_dn' => bind_dn,
'bind_password' => bind_pw
}
}.to_yaml)
end
elsif auth == 'password'
say "Updating config/environments/common/authentication.yml..."
File.open('config/environments/common/authentication.yml', 'w') do |f|
f.puts({
'strategy' => 'password',
'registration_enabled' => true,
'password' => {
'salt' => SecureRandom.base64
}
}.to_yaml)
end
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '2' }
end
if step < 3
say
say "Let's set up your database now.".bold
say "If you don't know the answer to a question, give a best guess. You can always",
"change your database.yml file later."
dev_host = query("What is the hostname of the development PostgreSQL server?", 'localhost')
dev_user = query("What PostgreSQL user will Squash use in development?", 'squash')
dev_pw = query("What is #{dev_user}@#{dev_host}'s password?", '')
dev_local = dev_host.nil? || dev_host == 'localhost' || dev_host == '0.0.0.0' || dev_host == '127.0.0.1'
dev_db = query("What is the name of your PostgreSQL development database?#{" (It doesn't have to exist yet.)" if dev_local}", 'squash_development')
test_host = query("What is the hostname of the test PostgreSQL server?", 'localhost')
test_user = query("What PostgreSQL user will Squash use in test?", dev_user)
test_pw = query("What is #{test_user}@#{test_host}'s password?", '')
test_db = query("What is the name of your PostgreSQL test database?", 'squash_test')
prod_host = query("What is the hostname of the production PostgreSQL server?", 'localhost')
prod_user = query("What PostgreSQL user will Squash use in production?", dev_user)
prod_pw = query("What is #{prod_user}@#{prod_host}'s password?", '')
prod_db = query("What is the name of your PostgreSQL production database?", 'squash_production')
say "Updating config/database.yml..."
File.open('config/database.yml', 'w') do |f|
common = {
'adapter' => 'postgresql', # temporarily for the rake db:migrate calls
'encoding' => 'utf8'
}
f.puts({
'development' => common.merge(
'host' => dev_host,
'username' => dev_user,
'password' => dev_pw,
'database' => dev_db
),
'test' => common.merge(
'host' => test_host,
'username' => test_user,
'password' => test_pw,
'database' => test_db
),
'production' => common.merge(
'host' => prod_host,
'username' => prod_user,
'password' => prod_pw,
'database' => prod_db,
'pool' => 30
)
}.to_yaml)
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '3' }
end
if step < 4
db_config = YAML.load_file('config/database.yml')
dev_host = db_config['development']['host']
dev_user = db_config['development']['username']
dev_db = db_config['development']['database']
dev_local = (dev_host.nil? || dev_host == 'localhost' || dev_host == '0.0.0.0' || dev_host == '127.0.0.1')
test_host = db_config['test']['host']
test_user = db_config['test']['username']
test_db = db_config['test']['database']
test_local = (test_host.nil? || test_host == 'localhost' || test_host == '0.0.0.0' || test_host == '127.0.0.1')
run_ignore 'createuser', '-DSR', 'squash' if dev_local
dbs = `psql -ltA | awk -F'|' '{ print $1 }'`.split(/\n/)
if dev_local
unless dbs.include?(dev_db)
prompt_or_quit "Ready to create the development database?"
run "createdb", '-O', dev_user, dev_db
end
end
prompt_or_quit "Ready to migrate the development database?"
run 'rake', 'db:migrate'
if test_local
unless dbs.include?(test_db)
prompt_or_quit "Ready to create the test database?"
run "createdb", '-O', test_user, test_db
end
end
prompt_or_quit "Ready to migrate the test database?"
run 'env', 'RAILS_ENV=test', 'rake', 'db:migrate'
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '4' }
end
if step < 5
say "Generating session secret..."
secret = SecureRandom.hex
contents = File.read('config/initializers/secret_token.rb')
File.open('config/initializers/secret_token.rb', 'w') do |f|
f.puts contents.sub('_SECRET_', secret)
end
File.open('/tmp/squash_install_progress', 'w') { |f| f.puts '5' }
end
say
say "All done!".green.bold, "You should now be able to run".green,
"rails server.".green.bold, "Some notes:".green
puts
say "* If you want Squash to monitor itself for errors in production, edit".yellow
say " ", "config/environments/production/dogfood.yml".bold.yellow, "and set".yellow, "disabled".bold.yellow, "to".yellow
say " ", "false.".bold.yellow, "When you deploy Squash to production, create a project for itself".yellow
say " and copy the generated API key to this file.".yellow
puts
say "* Test that all specs pass by running".yellow, 'rspec spec.'.bold.yellow
puts
puts "* You can delete this setup script now if you wish.".yellow
FileUtils.rm '/tmp/squash_install_progress'
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'remarkovable'
spec.version = '0.3'
spec.authors = ['Jake Worth']
spec.email = ['jake@jakeworth.com']
spec.summary = 'Markov chains for all.'
spec.description = 'A gem that produces Markov chain output from any text.'
spec.homepage = 'https://rubygems.org/gems/remarkovable'
spec.license = 'MIT'
spec.files = ['lib/remarkovable.rb']
spec.test_files = %w(test/test_speak.rb test/test_markov_model.rb)
spec.require_paths = ['lib']
end
Point to github here
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'remarkovable'
spec.version = '0.3'
spec.authors = ['Jake Worth']
spec.email = ['jake@jakeworth.com']
spec.summary = 'Markov chains for all.'
spec.description = 'A gem that produces Markov chain output from any text.'
spec.homepage = 'https://github.com/jwworth/remarkovable'
spec.license = 'MIT'
spec.files = ['lib/remarkovable.rb']
spec.test_files = %w(test/test_speak.rb test/test_markov_model.rb)
spec.require_paths = ['lib']
end
|
# This file is part of Metasm, the Ruby assembly manipulation suite
# Copyright (C) 2006-2009 Yoann GUILLOT
#
# Licence is LGPL, see LICENCE in the top-level directory
# this file compliments disassemble.rb, adding misc user-friendly methods
module Metasm
class InstructionBlock
# adds an address to the from_normal/from_subfuncret list
def add_from(addr, type=:normal)
send "add_from_#{type}", addr
end
def add_from_normal(addr)
@from_normal ||= []
@from_normal |= [addr]
end
def add_from_subfuncret(addr)
@from_subfuncret ||= []
@from_subfuncret |= [addr]
end
def add_from_indirect(addr)
@from_indirect ||= []
@from_indirect |= [addr]
end
# iterates over every from address, yields [address, type in [:normal, :subfuncret, :indirect]]
def each_from
each_from_normal { |a| yield a, :normal }
each_from_subfuncret { |a| yield a, :subfuncret }
each_from_indirect { |a| yield a, :indirect }
end
def each_from_normal(&b)
@from_normal.each(&b) if from_normal
end
def each_from_subfuncret(&b)
@from_subfuncret.each(&b) if from_subfuncret
end
def each_from_indirect(&b)
@from_indirect.each(&b) if from_indirect
end
def add_to(addr, type=:normal)
send "add_to_#{type}", addr
end
def add_to_normal(addr)
@to_normal ||= []
@to_normal |= [addr]
end
def add_to_subfuncret(addr)
@to_subfuncret ||= []
@to_subfuncret |= [addr]
end
def add_to_indirect(addr)
@to_indirect ||= []
@to_indirect |= [addr]
end
def each_to
each_to_normal { |a| yield a, :normal }
each_to_subfuncret { |a| yield a, :subfuncret }
each_to_indirect { |a| yield a, :indirect }
end
def each_to_normal(&b)
@to_normal.each(&b) if to_normal
end
def each_to_subfuncret(&b)
@to_subfuncret.each(&b) if to_subfuncret
end
def each_to_indirect(&b)
@to_indirect.each(&b) if to_indirect
end
# yields all from that are from the same function
def each_from_samefunc(dasm, &b)
return if dasm.function[address]
@from_subfuncret.each(&b) if from_subfuncret
@from_normal.each(&b) if from_normal
end
# yields all from that are not in the same subfunction as this block
def each_from_otherfunc(dasm, &b)
@from_normal.each(&b) if from_normal and dasm.function[address]
@from_subfuncret.each(&b) if from_subfuncret and dasm.function[address]
@from_indirect.each(&b) if from_indirect
end
# yields all to that are in the same subfunction as this block
def each_to_samefunc(dasm)
each_to { |to, type|
next if type != :normal and type != :subfuncret
to = dasm.normalize(to)
yield to if not dasm.function[to]
}
end
# yields all to that are not in the same subfunction as this block
def each_to_otherfunc(dasm)
each_to { |to, type|
to = dasm.normalize(to)
yield to if type == :indirect or dasm.function[to] or not dasm.decoded[to]
}
end
# returns the array used in each_from_samefunc
def from_samefunc(dasm)
ary = []
each_from_samefunc(dasm) { |a| ary << a }
ary
end
def from_otherfunc(dasm)
ary = []
each_from_otherfunc(dasm) { |a| ary << a }
ary
end
def to_samefunc(dasm)
ary = []
each_to_samefunc(dasm) { |a| ary << a }
ary
end
def to_otherfunc(dasm)
ary = []
each_to_otherfunc(dasm) { |a| ary << a }
ary
end
end
class DecodedInstruction
# checks if this instruction is the first of its IBlock
def block_head?
self == @block.list.first
end
end
class CPU
# compat alias, for scripts using older version of metasm
def get_backtrace_binding(di) backtrace_binding(di) end
end
class Disassembler
# access the default value for @@backtrace_maxblocks for newly created Disassemblers
def self.backtrace_maxblocks ; @@backtrace_maxblocks ; end
def self.backtrace_maxblocks=(b) ; @@backtrace_maxblocks = b ; end
# adds a commentary at the given address
# comments are found in the array @comment: {addr => [list of strings]}
def add_comment(addr, cmt)
@comment[addr] ||= []
@comment[addr] |= [cmt]
end
# returns the 1st element of #get_section_at (ie the edata at a given address) or nil
def get_edata_at(*a)
if s = get_section_at(*a)
s[0]
end
end
# returns the DecodedInstruction at addr if it exists
def di_at(addr)
di = @decoded[addr] || @decoded[normalize(addr)] if addr
di if di.kind_of? DecodedInstruction
end
# returns the InstructionBlock containing the address at addr
def block_at(addr)
di = di_at(addr)
di.block if di
end
# returns the DecodedFunction at addr if it exists
def function_at(addr)
f = @function[addr] || @function[normalize(addr)] if addr
f if f.kind_of? DecodedFunction
end
# returns the DecodedInstruction covering addr
# returns one at starting nearest addr if multiple are available (overlapping instrs)
def di_including(addr)
return if not addr
addr = normalize(addr)
if off = (0...16).find { |o| @decoded[addr-o].kind_of? DecodedInstruction and @decoded[addr-o].bin_length > o }
@decoded[addr-off]
end
end
# returns the InstructionBlock containing the byte at addr
# returns the one of di_including() on multiple matches (overlapping instrs)
def block_including(addr)
di = di_including(addr)
di.block if di
end
# returns the DecodedFunction including this byte
# return the one of find_function_start() if multiple are possible (block shared by multiple funcs)
def function_including(addr)
return if not di = di_including(addr)
function_at(find_function_start(di.address))
end
# yields every InstructionBlock
# returns the list of IBlocks
def each_instructionblock(&b)
ret = []
@decoded.each { |addr, di|
next if not di.kind_of? DecodedInstruction or not di.block_head?
ret << di.block
b.call(di.block) if b
}
ret
end
alias instructionblocks each_instructionblock
# return a backtrace_binding reversed (akin to code emulation) (but not really)
def get_fwdemu_binding(di, pc=nil)
@cpu.get_fwdemu_binding(di, pc)
end
# reads len raw bytes from the mmaped address space
def read_raw_data(addr, len)
if e = get_section_at(addr)
e[0].read(len)
end
end
# read an int of arbitrary type (:u8, :i32, ...)
def decode_int(addr, type)
type = "u#{type*8}".to_sym if type.kind_of? Integer
if e = get_section_at(addr)
e[0].decode_imm(type, @cpu.endianness)
end
end
# read a byte at address addr
def decode_byte(addr)
decode_int(addr, :u8)
end
# read a dword at address addr
# the dword is cpu-sized (eg 32 or 64bits)
def decode_dword(addr)
decode_int(addr, @cpu.size/8)
end
# read a zero-terminated string from addr
# if no terminal 0 is found, return nil
def decode_strz(addr, maxsz=4096)
if e = get_section_at(addr)
str = e[0].read(maxsz).to_s
return if not len = str.index(?\0)
str[0, len]
end
end
# read a zero-terminated wide string from addr
# return nil if no terminal found
def decode_wstrz(addr, maxsz=4096)
if e = get_section_at(addr)
str = e[0].read(maxsz).to_s
return if not len = str.unpack('v*').index(0)
str[0, 2*len]
end
end
# disassembles one instruction at address
# returns nil if no instruction can be decoded there
# does not update any internal state of the disassembler, nor reuse the @decoded cache
def disassemble_instruction(addr)
if e = get_section_at(addr)
@cpu.decode_instruction(e[0], normalize(addr))
end
end
# disassemble addr as if the code flow came from from_addr
def disassemble_from(addr, from_addr)
from_addr = from_addr.address if from_addr.kind_of? DecodedInstruction
from_addr = normalize(from_addr)
if b = block_at(from_addr)
b.add_to_normal(addr)
end
@addrs_todo << [addr, from_addr]
disassemble
end
# returns the label associated to an addr, or nil if none exist
def get_label_at(addr)
e = get_edata_at(addr, false)
e.inv_export[e.ptr] if e
end
# sets the label for the specified address
# returns nil if the address is not mapped
# memcheck is passed to get_section_at to validate that the address is mapped
# keep existing label if 'overwrite' is false
def set_label_at(addr, name, memcheck=true, overwrite=true)
addr = Expression[addr].reduce
e, b = get_section_at(addr, memcheck)
if not e
elsif not l = e.inv_export[e.ptr] or (!overwrite and l != name)
l = @program.new_label(name)
e.add_export l, e.ptr
@label_alias_cache = nil
@old_prog_binding[l] = @prog_binding[l] = b + e.ptr
elsif l != name
l = rename_label l, @program.new_label(name)
end
l
end
# remove a label at address addr
def del_label_at(addr, name=get_label_at(addr))
ed = get_edata_at(addr)
if ed and ed.inv_export[ed.ptr]
ed.del_export name, ed.ptr
@label_alias_cache = nil
end
each_xref(addr) { |xr|
next if not xr.origin or not o = @decoded[xr.origin] or not o.kind_of? Renderable
o.each_expr { |e|
next unless e.kind_of?(Expression)
e.lexpr = addr if e.lexpr == name
e.rexpr = addr if e.rexpr == name
}
}
@old_prog_binding.delete name
@prog_binding.delete name
end
# changes a label to another, updates referring instructions etc
# returns the new label
# the new label must be program-uniq (see @program.new_label)
def rename_label(old, new)
return new if old == new
raise "label #{new.inspect} exists" if @prog_binding[new]
each_xref(normalize(old)) { |x|
next if not di = @decoded[x.origin]
@cpu.replace_instr_arg_immediate(di.instruction, old, new)
di.comment.to_a.each { |c| c.gsub!(old, new) }
}
e = get_edata_at(old, false)
if e
e.add_export new, e.export.delete(old), true
end
raise "cant rename nonexisting label #{old}" if not @prog_binding[old]
@label_alias_cache = nil
@old_prog_binding[new] = @prog_binding[new] = @prog_binding.delete(old)
@addrs_todo.each { |at|
case at[0]
when old; at[0] = new
when Expression; at[0] = at[0].bind(old => new)
end
}
if @inv_section_reloc[old]
@inv_section_reloc[old].each { |b, e_, o, r|
(0..16).each { |off|
if di = @decoded[Expression[b]+o-off] and di.bin_length > off
@cpu.replace_instr_arg_immediate(di.instruction, old, new)
end
}
r.target = r.target.bind(old => new)
}
@inv_section_reloc[new] = @inv_section_reloc.delete(old)
end
if c_parser and @c_parser.toplevel.symbol[old]
@c_parser.toplevel.symbol[new] = @c_parser.toplevel.symbol.delete(old)
@c_parser.toplevel.symbol[new].name = new
end
new
end
# finds the start of a function from the address of an instruction
def find_function_start(addr)
addr = addr.address if addr.kind_of? DecodedInstruction
todo = [addr]
done = []
while a = todo.pop
a = normalize(a)
di = @decoded[a]
next if done.include? a or not di.kind_of? DecodedInstruction
done << a
a = di.block.address
break a if @function[a]
l = []
di.block.each_from_samefunc(self) { |f| l << f }
break a if l.empty?
todo.concat l
end
end
# iterates over the blocks of a function, yields each func block address
# returns the graph of blocks (block address => [list of samefunc blocks])
def each_function_block(addr, incl_subfuncs = false, find_func_start = true)
addr = @function.index(addr) if addr.kind_of? DecodedFunction
addr = addr.address if addr.kind_of? DecodedInstruction
addr = find_function_start(addr) if not @function[addr] and find_func_start
todo = [addr]
ret = {}
while a = todo.pop
next if not di = di_at(a)
a = di.block.address
next if ret[a]
ret[a] = []
yield a if block_given?
di.block.each_to_samefunc(self) { |f| ret[a] << f ; todo << f }
di.block.each_to_otherfunc(self) { |f| ret[a] << f ; todo << f } if incl_subfuncs
end
ret
end
alias function_blocks each_function_block
# returns a graph of function calls
# for each func passed as arg (default: all), update the 'ret' hash
# associating func => [list of direct subfuncs called]
def function_graph(funcs = @function.keys + @entrypoints.to_a, ret={})
funcs = funcs.map { |f| normalize(f) }.uniq.find_all { |f| @decoded[f] }
funcs.each { |f|
next if ret[f]
ret[f] = []
each_function_block(f) { |b|
@decoded[b].block.each_to_otherfunc(self) { |sf|
ret[f] |= [sf]
}
}
}
ret
end
# return the graph of function => subfunction list
# recurses from an entrypoint
def function_graph_from(addr)
addr = normalize(addr)
addr = find_function_start(addr) || addr
ret = {}
osz = ret.length-1
while ret.length != osz
osz = ret.length
function_graph(ret.values.flatten + [addr], ret)
end
ret
end
# return the graph of function => subfunction list
# for which a (sub-sub)function includes addr
def function_graph_to(addr)
addr = normalize(addr)
addr = find_function_start(addr) || addr
full = function_graph
ret = {}
todo = [addr]
done = []
while a = todo.pop
next if done.include? a
done << a
full.each { |f, sf|
next if not sf.include? a
ret[f] ||= []
ret[f] |= [a]
todo << f
}
end
ret
end
# returns info on sections, from @program if supported
# returns an array of [name, addr, length, info]
def section_info
if @program.respond_to? :section_info
@program.section_info
else
list = []
@sections.each { |k, v|
list << [get_label_at(k), normalize(k), v.length, nil]
}
list
end
end
# transform an address into a file offset
def addr_to_fileoff(addr)
addr = normalize(addr)
@program.addr_to_fileoff(addr)
end
# transform a file offset into an address
def fileoff_to_addr(foff)
@program.fileoff_to_addr(foff)
end
# remove the decodedinstruction from..to, replace them by the new Instructions in 'by'
# this updates the block list structure, old di will still be visible in @decoded, except from original block (those are deleted)
# if from..to spans multiple blocks
# to.block is splitted after to
# all path from from are replaced by a single link to after 'to', be careful !
# (eg a->b->... & a->c ; from in a, to in c => a->b is lost)
# all instructions are stuffed in the first block
# paths are only walked using from/to_normal
# 'by' may be empty
# returns the block containing the new instrs (nil if empty)
def replace_instrs(from, to, by, patch_by=false)
raise 'bad from' if not fdi = di_at(from) or not fdi.block.list.index(fdi)
raise 'bad to' if not tdi = di_at(to) or not tdi.block.list.index(tdi)
# create DecodedInstruction from Instructions in 'by' if needed
split_block(fdi.block, fdi.address)
split_block(tdi.block, tdi.block.list[tdi.block.list.index(tdi)+1].address) if tdi != tdi.block.list.last
fb = fdi.block
tb = tdi.block
# generate DecodedInstr from Instrs
# try to keep the bin_length of original block
wantlen = tdi.address + tdi.bin_length - fb.address
wantlen -= by.grep(DecodedInstruction).inject(0) { |len, di| len + di.bin_length }
ldi = by.last
ldi = DecodedInstruction.new(ldi) if ldi.kind_of? Instruction
nb_i = by.grep(Instruction).length
wantlen = nb_i if wantlen < 0 or (ldi and ldi.opcode.props[:setip])
if patch_by
by.map! { |di|
if di.kind_of? Instruction
di = DecodedInstruction.new(di)
wantlen -= di.bin_length = wantlen / by.grep(Instruction).length
nb_i -= 1
end
di
}
else
by = by.map { |di|
if di.kind_of? Instruction
di = DecodedInstruction.new(di)
wantlen -= (di.bin_length = wantlen / nb_i)
nb_i -= 1
end
di
}
end
#puts " ** patch next_addr to #{Expression[tb.list.last.next_addr]}" if not by.empty? and by.last.opcode.props[:saveip]
by.last.next_addr = tb.list.last.next_addr if not by.empty? and by.last.opcode.props[:saveip]
fb.list.each { |di| @decoded.delete di.address }
fb.list.clear
tb.list.each { |di| @decoded.delete di.address }
tb.list.clear
by.each { |di| fb.add_di di }
by.each_with_index { |di, i|
if odi = di_at(di.address)
# collision, hopefully with another deobfuscation run ?
if by[i..-1].all? { |mydi| mydi.to_s == @decoded[mydi.address].to_s }
puts "replace_instrs: merge at #{di}" if $DEBUG
by[i..-1] = by[i..-1].map { |xdi| @decoded[xdi.address] }
by[i..-1].each { fb.list.pop }
split_block(odi.block, odi.address)
tb.to_normal = [di.address]
(odi.block.from_normal ||= []) << to
odi.block.from_normal.uniq!
break
else
#raise "replace_instrs: collision #{di} vs #{odi}"
puts "replace_instrs: collision #{di} vs #{odi}" if $VERBOSE
while @decoded[di.address].kind_of? DecodedInstruction # find free space.. raise ?
di.address += 1 # XXX use floats ?
di.bin_length -= 1
end
end
end
@decoded[di.address] = di
}
@addrs_done.delete_if { |ad| normalize(ad[0]) == tb.address or ad[1] == tb.address }
@addrs_done.delete_if { |ad| normalize(ad[0]) == fb.address or ad[1] == fb.address } if by.empty? and tb.address != fb.address
# update to_normal/from_normal
fb.to_normal = tb.to_normal
fb.to_normal.to_a.each { |newto|
# other paths may already point to newto, we must only update the relevant entry
if ndi = di_at(newto) and idx = ndi.block.from_normal.to_a.index(to)
if by.empty?
ndi.block.from_normal[idx,1] = fb.from_normal.to_a
else
ndi.block.from_normal[idx] = fb.list.last.address
end
end
}
fb.to_subfuncret = tb.to_subfuncret
fb.to_subfuncret.to_a.each { |newto|
if ndi = di_at(newto) and idx = ndi.block.from_subfuncret.to_a.index(to)
if by.empty?
ndi.block.from_subfuncret[idx,1] = fb.from_subfuncret.to_a
else
ndi.block.from_subfuncret[idx] = fb.list.last.address
end
end
}
if by.empty?
tb.to_subfuncret = nil if tb.to_subfuncret == []
tolist = tb.to_subfuncret || tb.to_normal.to_a
if lfrom = get_label_at(fb.address) and tolist.length == 1
lto = auto_label_at(tolist.first)
each_xref(fb.address, :x) { |x|
next if not di = @decoded[x.origin]
@cpu.replace_instr_arg_immediate(di.instruction, lfrom, lto)
di.comment.to_a.each { |c| c.gsub!(lfrom, lto) }
}
end
fb.from_normal.to_a.each { |newfrom|
if ndi = di_at(newfrom) and idx = ndi.block.to_normal.to_a.index(from)
ndi.block.to_normal[idx..idx] = tolist
end
}
fb.from_subfuncret.to_a.each { |newfrom|
if ndi = di_at(newfrom) and idx = ndi.block.to_subfuncret.to_a.index(from)
ndi.block.to_subfuncret[idx..idx] = tolist
end
}
else
# merge with adjacent blocks
merge_blocks(fb, fb.to_normal.first) if fb.to_normal.to_a.length == 1 and di_at(fb.to_normal.first)
merge_blocks(fb.from_normal.first, fb) if fb.from_normal.to_a.length == 1 and di_at(fb.from_normal.first)
end
fb if not by.empty?
end
# undefine a sequence of decodedinstructions from an address
# stops at first non-linear branch
# removes @decoded, @comments, @xrefs, @addrs_done
# does not update @prog_binding (does not undefine labels)
def undefine_from(addr)
return if not di_at(addr)
@comment.delete addr if @function.delete addr
split_block(addr)
addrs = []
while di = di_at(addr)
di.block.list.each { |ddi| addrs << ddi.address }
break if di.block.to_subfuncret.to_a != [] or di.block.to_normal.to_a.length != 1
addr = di.block.to_normal.first
break if ndi = di_at(addr) and ndi.block.from_normal.to_a.length != 1
end
addrs.each { |a| @decoded.delete a }
@xrefs.delete_if { |a, x|
if not x.kind_of? Array
true if x and addrs.include? x.origin
else
x.delete_if { |xx| addrs.include? xx.origin }
true if x.empty?
end
}
@addrs_done.delete_if { |ad| !(addrs & [normalize(ad[0]), normalize(ad[1])]).empty? }
end
# merge two instruction blocks if they form a simple chain and are adjacent
# returns true if merged
def merge_blocks(b1, b2, allow_nonadjacent = false)
if b1 and not b1.kind_of? InstructionBlock
return if not b1 = block_at(b1)
end
if b2 and not b2.kind_of? InstructionBlock
return if not b2 = block_at(b2)
end
if b1 and b2 and (allow_nonadjacent or b1.list.last.next_addr == b2.address) and
b1.to_normal.to_a == [b2.address] and b2.from_normal.to_a.length == 1 and # that handles delay_slot
b1.to_subfuncret.to_a == [] and b2.from_subfuncret.to_a == [] and
b1.to_indirect.to_a == [] and b2.from_indirect.to_a == []
b2.list.each { |di| b1.add_di di }
b1.to_normal = b2.to_normal
b2.list.clear
@addrs_done.delete_if { |ad| normalize(ad[0]) == b2.address }
true
end
end
# computes the binding of a code sequence
# just a forwarder to CPU#code_binding
def code_binding(*a)
@cpu.code_binding(self, *a)
end
# returns an array of instructions/label that, once parsed and assembled, should
# give something equivalent to the code accessible from the (list of) entrypoints given
# from the @decoded dasm graph
# assume all jump targets have a matching label in @prog_binding
# may add inconditionnal jumps in the listing to preserve the code flow
def flatten_graph(entry, include_subfunc=true)
ret = []
entry = [entry] if not entry.kind_of? Array
todo = entry.map { |a| normalize(a) }
done = []
inv_binding = @prog_binding.invert
while addr = todo.pop
next if done.include? addr or not di_at(addr)
done << addr
b = @decoded[addr].block
ret << Label.new(inv_binding[addr]) if inv_binding[addr]
ret.concat b.list.map { |di| di.instruction }
b.each_to_otherfunc(self) { |to|
to = normalize to
todo.unshift to if include_subfunc
}
b.each_to_samefunc(self) { |to|
to = normalize to
todo << to
}
if not di = b.list[-1-@cpu.delay_slot] or not di.opcode.props[:stopexec] or di.opcode.props[:saveip]
to = b.list.last.next_addr
if todo.include? to
if done.include? to or not di_at(to)
if not to_l = inv_binding[to]
to_l = auto_label_at(to, 'loc')
if done.include? to and idx = ret.index(@decoded[to].block.list.first.instruction)
ret.insert(idx, Label.new(to_l))
end
end
ret << @cpu.instr_uncond_jump_to(to_l)
else
todo << to # ensure it's next in the listing
end
end
end
end
ret
end
# returns a demangled C++ name
def demangle_cppname(name)
case name[0]
when ?? # MSVC
name = name[1..-1]
demangle_msvc(name[1..-1]) if name[0] == ??
when ?_
name = name.sub(/_GLOBAL__[ID]_/, '')
demangle_gcc(name[2..-1][/\S*/]) if name[0, 2] == '_Z'
end
end
# from wgcc-2.2.2/undecorate.cpp
# TODO
def demangle_msvc(name)
op = name[0, 1]
op = name[0, 2] if op == '_'
if op = {
'2' => "new", '3' => "delete", '4' => "=", '5' => ">>", '6' => "<<", '7' => "!", '8' => "==", '9' => "!=",
'A' => "[]", 'C' => "->", 'D' => "*", 'E' => "++", 'F' => "--", 'G' => "-", 'H' => "+", 'I' => "&",
'J' => "->*", 'K' => "/", 'L' => "%", 'M' => "<", 'N' => "<=", 'O' => ">", 'P' => ">=", 'Q' => ",",
'R' => "()", 'S' => "~", 'T' => "^", 'U' => "|", 'V' => "&&", 'W' => "||", 'X' => "*=", 'Y' => "+=",
'Z' => "-=", '_0' => "/=", '_1' => "%=", '_2' => ">>=", '_3' => "<<=", '_4' => "&=", '_5' => "|=", '_6' => "^=",
'_7' => "`vftable'", '_8' => "`vbtable'", '_9' => "`vcall'", '_A' => "`typeof'", '_B' => "`local static guard'",
'_C' => "`string'", '_D' => "`vbase destructor'", '_E' => "`vector deleting destructor'", '_F' => "`default constructor closure'",
'_G' => "`scalar deleting destructor'", '_H' => "`vector constructor iterator'", '_I' => "`vector destructor iterator'",
'_J' => "`vector vbase constructor iterator'", '_K' => "`virtual displacement map'", '_L' => "`eh vector constructor iterator'",
'_M' => "`eh vector destructor iterator'", '_N' => "`eh vector vbase constructor iterator'", '_O' => "`copy constructor closure'",
'_S' => "`local vftable'", '_T' => "`local vftable constructor closure'", '_U' => "new[]", '_V' => "delete[]",
'_X' => "`placement delete closure'", '_Y' => "`placement delete[] closure'"}[op]
op[0] == ?` ? op[1..-2] : "op_#{op}"
end
end
# from http://www.codesourcery.com/public/cxx-abi/abi.html
def demangle_gcc(name)
subs = []
ret = ''
decode_tok = lambda {
name ||= ''
case name[0]
when nil
ret = nil
when ?N
name = name[1..-1]
decode_tok[]
until name[0] == ?E
break if not ret
ret << '::'
decode_tok[]
end
name = name[1..-1]
when ?I
name = name[1..-1]
ret = ret[0..-3] if ret[-2, 2] == '::'
ret << '<'
decode_tok[]
until name[0] == ?E
break if not ret
ret << ', '
decode_tok[]
end
ret << ' ' if ret and ret[-1] == ?>
ret << '>' if ret
name = name[1..-1]
when ?T
case name[1]
when ?T; ret << 'vtti('
when ?V; ret << 'vtable('
when ?I; ret << 'typeinfo('
when ?S; ret << 'typename('
else ret = nil
end
name = name[2..-1].to_s
decode_tok[] if ret
ret << ')' if ret
name = name[1..-1] if name[0] == ?E
when ?C
name = name[2..-1]
base = ret[/([^:]*)(<.*|::)?$/, 1]
ret << base
when ?D
name = name[2..-1]
base = ret[/([^:]*)(<.*|::)?$/, 1]
ret << '~' << base
when ?0..?9
nr = name[/^[0-9]+/]
name = name[nr.length..-1].to_s
ret << name[0, nr.to_i]
name = name[nr.to_i..-1]
subs << ret[/[\w:]*$/]
when ?S
name = name[1..-1]
case name[0]
when ?_, ?0..?9, ?A..?Z
case name[0]
when ?_; idx = 0 ; name = name[1..-1]
when ?0..?9; idx = name[0, 1].unpack('C')[0] - 0x30 + 1 ; name = name[2..-1]
when ?A..?Z; idx = name[0, 1].unpack('C')[0] - 0x41 + 11 ; name = name[2..-1]
end
if not subs[idx]
ret = nil
else
ret << subs[idx]
end
when ?t
ret << 'std::'
name = name[1..-1]
decode_tok[]
else
std = { ?a => 'std::allocator',
?b => 'std::basic_string',
?s => 'std::string', # 'std::basic_string < char, std::char_traits<char>, std::allocator<char> >',
?i => 'std::istream', # 'std::basic_istream<char, std::char_traits<char> >',
?o => 'std::ostream', # 'std::basic_ostream<char, std::char_traits<char> >',
?d => 'std::iostream', # 'std::basic_iostream<char, std::char_traits<char> >'
}[name[0]]
if not std
ret = nil
else
ret << std
end
name = name[1..-1]
end
when ?P, ?R, ?r, ?V, ?K
attr = { ?P => '*', ?R => '&', ?r => ' restrict', ?V => ' volatile', ?K => ' const' }[name[0]]
name = name[1..-1]
rl = ret.length
decode_tok[]
if ret
ret << attr
subs << ret[rl..-1]
end
else
if ret =~ /[(<]/ and ty = {
?v => 'void', ?w => 'wchar_t', ?b => 'bool', ?c => 'char', ?a => 'signed char',
?h => 'unsigned char', ?s => 'short', ?t => 'unsigned short', ?i => 'int',
?j => 'unsigned int', ?l => 'long', ?m => 'unsigned long', ?x => '__int64',
?y => 'unsigned __int64', ?n => '__int128', ?o => 'unsigned __int128', ?f => 'float',
?d => 'double', ?e => 'long double', ?g => '__float128', ?z => '...'
}[name[0]]
name = name[1..-1]
ret << ty
else
fu = name[0, 2]
name = name[2..-1]
if op = {
'nw' => ' new', 'na' => ' new[]', 'dl' => ' delete', 'da' => ' delete[]',
'ps' => '+', 'ng' => '-', 'ad' => '&', 'de' => '*', 'co' => '~', 'pl' => '+',
'mi' => '-', 'ml' => '*', 'dv' => '/', 'rm' => '%', 'an' => '&', 'or' => '|',
'eo' => '^', 'aS' => '=', 'pL' => '+=', 'mI' => '-=', 'mL' => '*=', 'dV' => '/=',
'rM' => '%=', 'aN' => '&=', 'oR' => '|=', 'eO' => '^=', 'ls' => '<<', 'rs' => '>>',
'lS' => '<<=', 'rS' => '>>=', 'eq' => '==', 'ne' => '!=', 'lt' => '<', 'gt' => '>',
'le' => '<=', 'ge' => '>=', 'nt' => '!', 'aa' => '&&', 'oo' => '||', 'pp' => '++',
'mm' => '--', 'cm' => ',', 'pm' => '->*', 'pt' => '->', 'cl' => '()', 'ix' => '[]',
'qu' => '?', 'st' => ' sizeof', 'sz' => ' sizeof', 'at' => ' alignof', 'az' => ' alignof'
}[fu]
ret << "operator#{op}"
elsif fu == 'cv'
ret << "cast<"
decode_tok[]
ret << ">" if ret
else
ret = nil
end
end
end
name ||= ''
}
decode_tok[]
subs.pop
if ret and name != ''
ret << '('
decode_tok[]
while ret and name != ''
ret << ', '
decode_tok[]
end
ret << ')' if ret
end
ret
end
# scans all the sections raw for a given regexp
# return/yields all the addresses matching
# if yield returns nil/false, do not include the addr in the final result
# sections are scanned MB by MB, so this should work (slowly) on 4GB sections (eg debugger VM)
# with addr_start/length, symbol-based section are skipped
def pattern_scan(pat, addr_start=nil, length=nil, chunksz=nil, margin=nil, &b)
chunksz ||= 4*1024*1024 # scan 4MB at a time
margin ||= 65536 # add this much bytes at each chunk to find /pat/ over chunk boundaries
pat = Regexp.new(Regexp.escape(pat)) if pat.kind_of? ::String
found = []
@sections.each { |sec_addr, e|
if addr_start
length ||= 0x1000_0000
begin
if sec_addr < addr_start
next if sec_addr+e.length <= addr_start
e = e[addr_start-sec_addr, e.length]
sec_addr = addr_start
end
if sec_addr+e.length > addr_start+length
next if sec_addr > addr_start+length
e = e[0, sec_addr+e.length-(addr_start+length)]
end
rescue
puts $!, $!.message, $!.backtrace if $DEBUG
# catch arithmetic error with symbol-based section
next
end
end
e.pattern_scan(pat, chunksz, margin) { |eo|
match_addr = sec_addr + eo
found << match_addr if not b or b.call(match_addr)
false
}
}
found
end
# returns/yields [addr, string] found using pattern_scan /[\x20-\x7e]/
def strings_scan(minlen=6, &b)
ret = []
nexto = 0
pattern_scan(/[\x20-\x7e]{#{minlen},}/m, nil, 1024) { |o|
if o - nexto > 0
next unless e = get_edata_at(o)
str = e.data[e.ptr, 1024][/[\x20-\x7e]{#{minlen},}/m]
ret << [o, str] if not b or b.call(o, str)
nexto = o + str.length
end
}
ret
end
# exports the addr => symbol map (see load_map)
def save_map
@prog_binding.map { |l, o|
type = di_at(o) ? 'c' : 'd' # XXX
o = o.to_s(16).rjust(8, '0') if o.kind_of? ::Integer
"#{o} #{type} #{l}"
}
end
# loads a map file (addr => symbol)
# off is an optionnal offset to add to every address found (for eg rebased binaries)
# understands:
# standard map files (eg linux-kernel.map: <addr> <type> <name>, e.g. 'c01001ba t setup_idt')
# ida map files (<sectionidx>:<sectionoffset> <name>)
# arg is either the map itself or the filename of the map (if it contains no newline)
def load_map(str, off=0)
str = File.read(str) rescue nil if not str.index("\n")
sks = @sections.keys.sort
seen = {}
str.each_line { |l|
case l.strip
when /^([0-9A-F]+)\s+(\w+)\s+(\w+)/i # kernel.map style
addr = $1.to_i(16)+off
set_label_at(addr, $3, false, !seen[addr])
seen[addr] = true
when /^([0-9A-F]+):([0-9A-F]+)\s+([a-z_]\w+)/i # IDA style
# we do not have section load order, let's just hope that the addresses are sorted (and sortable..)
# could check the 1st part of the file, with section sizes, but it is not very convenient
# the regexp is so that we skip the 1st part with section descriptions
# in the file, section 1 is the 1st section ; we have an additionnal section (exe header) which fixes the 0-index
# XXX this is PE-specific, TODO fix it for ELF (ida references sections, we reference segments...)
addr = sks[$1.to_i(16)] + $2.to_i(16) + off
set_label_at(addr, $3, false, !seen[addr])
seen[addr] = true
end
}
end
# saves the dasm state in a file
def save_file(file)
tmpfile = file + '.tmp'
File.open(tmpfile, 'wb') { |fd| save_io(fd) }
File.rename tmpfile, file
end
# saves the dasm state to an IO
def save_io(fd)
fd.puts 'Metasm.dasm'
if @program.filename and not @program.kind_of?(Shellcode)
t = @program.filename.to_s
fd.puts "binarypath #{t.length}", t
else
t = "#{@cpu.class.name.sub(/.*::/, '')} #{@cpu.size} #{@cpu.endianness}"
fd.puts "cpu #{t.length}", t
# XXX will be reloaded as a Shellcode with this CPU, but it may be a custom EXE
# do not output binarypath, we'll be loaded as a Shellcode, 'section' will suffice
end
@sections.each { |a, e|
# forget edata exports/relocs
# dump at most 16Mo per section
t = "#{Expression[a]} #{e.length}\n" +
[e.data[0, 2**24].to_str].pack('m*')
fd.puts "section #{t.length}", t
}
t = save_map.join("\n")
fd.puts "map #{t.length}", t
t = @decoded.map { |a, d|
next if not d.kind_of? DecodedInstruction
"#{Expression[a]},#{d.bin_length} #{d.instruction}#{" ; #{d.comment.join(' ')}" if d.comment}"
}.compact.sort.join("\n")
fd.puts "decoded #{t.length}", t
t = @comment.map { |a, c|
c.map { |l| l.chomp }.join("\n").split("\n").map { |lc| "#{Expression[a]} #{lc.chomp}" }
}.join("\n")
fd.puts "comment #{t.length}", t
bl = @decoded.values.map { |d|
d.block if d.kind_of? DecodedInstruction and d.block_head?
}.compact
t = bl.map { |b|
[Expression[b.address],
b.list.map { |d| Expression[d.address] }.join(','),
b.to_normal.to_a.map { |t_| Expression[t_] }.join(','),
b.to_subfuncret.to_a.map { |t_| Expression[t_] }.join(','),
b.to_indirect.to_a.map { |t_| Expression[t_] }.join(','),
b.from_normal.to_a.map { |t_| Expression[t_] }.join(','),
b.from_subfuncret.to_a.map { |t_| Expression[t_] }.join(','),
b.from_indirect.to_a.map { |t_| Expression[t_] }.join(','),
].join(';')
}.sort.join("\n")
fd.puts "blocks #{t.length}", t
t = @function.map { |a, f|
next if not @decoded[a]
[a, *f.return_address.to_a].map { |e| Expression[e] }.join(',')
}.compact.sort.join("\n")
# TODO binding ?
fd.puts "funcs #{t.length}", t
t = @xrefs.map { |a, x|
a = ':default' if a == :default
a = ':unknown' if a == Expression::Unknown
# XXX origin
case x
when nil
when Xref
[Expression[a], x.type, x.len, (Expression[x.origin] if x.origin)].join(',')
when Array
x.map { |x_| [Expression[a], x_.type, x_.len, (Expression[x_.origin] if x_.origin)].join(',') }
end
}.compact.join("\n")
fd.puts "xrefs #{t.length}", t
t = @c_parser.to_s
fd.puts "c #{t.length}", t
#t = bl.map { |b| b.backtracked_for }
#fd.puts "trace #{t.length}" , t
end
# loads a disassembler from a saved file
def self.load(str, &b)
d = new(nil, nil)
d.load(str, &b)
d
end
# loads the dasm state from a savefile content
# will yield unknown segments / binarypath notfound
def load(str)
raise 'Not a metasm save file' if str[0, 12].chomp != 'Metasm.dasm'
off = 12
pp = Preprocessor.new
app = AsmPreprocessor.new
while off < str.length
i = str.index("\n", off) || str.length
type, len = str[off..i].chomp.split
off = i+1
data = str[off, len.to_i]
off += len.to_i
case type
when nil, ''
when 'binarypath'
data = yield(type, data) if not File.exist? data and block_given?
reinitialize AutoExe.decode_file(data)
@program.disassembler = self
@program.init_disassembler
when 'cpu'
cpuname, size, endianness = data.split
cpu = Metasm.const_get(cpuname)
raise 'invalid cpu' if not cpu < CPU
cpu = cpu.new
cpu.size = size.to_i
cpu.endianness = endianness.to_sym
reinitialize Shellcode.new(cpu)
@program.disassembler = self
@program.init_disassembler
@sections.delete(0) # rm empty section at 0, other real 'section' follow
when 'section'
info = data[0, data.index("\n") || data.length]
data = data[info.length, data.length]
pp.feed!(info)
addr = Expression.parse(pp).reduce
len = Expression.parse(pp).reduce
edata = EncodedData.new(data.unpack('m*').first, :virtsize => len)
add_section(addr, edata)
when 'map'
load_map data
when 'decoded'
data.each_line { |l|
begin
next if l !~ /^([^,]*),(\d*) ([^;]*)(?:; (.*))?/
a, len, instr, cmt = $1, $2, $3, $4
a = Expression.parse(pp.feed!(a)).reduce
instr = @cpu.parse_instruction(app.feed!(instr))
di = DecodedInstruction.new(instr, a)
di.bin_length = len.to_i
di.add_comment cmt if cmt
@decoded[a] = di
rescue
puts "load: bad di #{l.inspect}" if $VERBOSE
end
}
when 'blocks'
data.each_line { |l|
bla = l.chomp.split(';').map { |sl| sl.split(',') }
begin
a = Expression.parse(pp.feed!(bla.shift[0])).reduce
b = InstructionBlock.new(a, get_section_at(a).to_a[0])
bla.shift.each { |e|
a = Expression.parse(pp.feed!(e)).reduce
b.add_di(@decoded[a])
}
bla.zip([:to_normal, :to_subfuncret, :to_indirect, :from_normal, :from_subfuncret, :from_indirect]).each { |l_, s|
b.send("#{s}=", l_.map { |e| Expression.parse(pp.feed!(e)).reduce }) if not l_.empty?
}
rescue
puts "load: bad block #{l.inspect}" if $VERBOSE
end
}
when 'funcs'
data.each_line { |l|
begin
a, *r = l.split(',').map { |e| Expression.parse(pp.feed!(e)).reduce }
@function[a] = DecodedFunction.new
@function[a].return_address = r if not r.empty?
@function[a].finalized = true
# TODO
rescue
puts "load: bad function #{l.inspect} #$!" if $VERBOSE
end
}
when 'comment'
data.each_line { |l|
begin
a, c = l.split(' ', 2)
a = Expression.parse(pp.feed!(a)).reduce
@comment[a] ||= []
@comment[a] |= [c]
rescue
puts "load: bad comment #{l.inspect} #$!" if $VERBOSE
end
}
when 'c'
begin
# TODO parse_invalid_c, split per function, whatever
parse_c('')
@c_parser.allow_bad_c = true
parse_c(data, 'savefile#c')
rescue
puts "load: bad C: #$!", $!.backtrace if $VERBOSE
end
@c_parser.readtok until @c_parser.eos? if @c_parser
when 'xrefs'
data.each_line { |l|
begin
a, t, len, o = l.chomp.split(',')
case a
when ':default'; a = :default
when ':unknown'; a = Expression::Unknown
else a = Expression.parse(pp.feed!(a)).reduce
end
t = (t.empty? ? nil : t.to_sym)
len = (len != '' ? len.to_i : nil)
o = (o.to_s != '' ? Expression.parse(pp.feed!(o)).reduce : nil) # :default/:unknown ?
add_xref(a, Xref.new(t, o, len))
rescue
puts "load: bad xref #{l.inspect} #$!" if $VERBOSE
end
}
#when 'trace'
else
if block_given?
yield(type, data)
else
puts "load: unsupported section #{type.inspect}" if $VERBOSE
end
end
end
end
# change the base address of the loaded binary
# better done early (before disassembling anything)
# returns the delta
def rebase(newaddr)
rebase_delta(newaddr - @sections.keys.min)
end
def rebase_delta(delta)
fix = lambda { |a|
case a
when Array
a.map! { |e| fix[e] }
when Hash
tmp = {}
a.each { |k, v| tmp[fix[k]] = v }
a.replace tmp
when Integer
a += delta
when BacktraceTrace
a.origin = fix[a.origin]
a.address = fix[a.address]
end
a
}
fix[@sections]
fix[@decoded]
fix[@xrefs]
fix[@function]
fix[@addrs_todo]
fix[@addrs_done]
fix[@comment]
@prog_binding.each_key { |k| @prog_binding[k] = fix[@prog_binding[k]] }
@old_prog_binding.each_key { |k| @old_prog_binding[k] = fix[@old_prog_binding[k]] }
@label_alias_cache = nil
@decoded.values.grep(DecodedInstruction).each { |di|
if di.block_head?
b = di.block
b.address += delta
fix[b.to_normal]
fix[b.to_subfuncret]
fix[b.to_indirect]
fix[b.from_normal]
fix[b.from_subfuncret]
fix[b.from_indirect]
fix[b.backtracked_for]
end
di.address = fix[di.address]
di.next_addr = fix[di.next_addr]
}
@function.each_value { |f|
f.return_address = fix[f.return_address]
fix[f.backtracked_for]
}
@xrefs.values.flatten.compact.each { |x| x.origin = fix[x.origin] }
delta
end
# dataflow method
# walks a function, starting at addr
# follows the usage of registers, computing the evolution from the value they had at start_addr
# whenever an instruction references the register (or anything derived from it),
# yield [di, used_register, reg_value, trace_state] where reg_value is the Expression holding the value of
# the register wrt the initial value at start_addr, and trace_state the value of all registers (reg_value
# not yet applied)
# reg_value may be nil if used_register is not modified by the function (eg call [eax])
# the yield return value is propagated, unless it is nil/false
# init_state is a hash { :reg => initial value }
def trace_function_register(start_addr, init_state)
function_walk(start_addr, init_state) { |args|
trace_state = args.last
case args.first
when :di
di = args[2]
update = {}
get_fwdemu_binding(di).each { |r, v|
if v.kind_of?(Expression) and v.externals.find { |e| trace_state[e] }
# XXX may mix old (from trace) and current (from v) registers
newv = v.bind(trace_state)
update[r] = yield(di, r, newv, trace_state)
elsif r.kind_of?(ExpressionType) and rr = r.externals.find { |e| trace_state[e] }
# reg dereferenced in a write (eg mov [esp], 42)
next if update.has_key?(rr) # already yielded
if yield(di, rr, trace_state[rr], trace_state) == false
update[rr] = false
end
elsif trace_state[r]
# started on mov reg, foo
next if di.address == start_addr
update[r] = false
end
}
# directly walk the instruction argument list for registers not appearing in the binding
@cpu.instr_args_memoryptr(di).each { |ind|
b = @cpu.instr_args_memoryptr_getbase(ind)
if b and b = b.symbolic and not update.has_key?(b)
yield(di, b, nil, trace_state)
end
}
@cpu.instr_args_regs(di).each { |r|
r = r.symbolic
if not update.has_key?(r)
yield(di, r, nil, trace_state)
end
}
update.each { |r, v|
trace_state = trace_state.dup
if v
# cannot follow non-registers, or we would have to emulate every single
# instruction (try following [esp+4] across a __stdcall..)
trace_state[r] = v if r.kind_of?(::Symbol)
else
trace_state.delete r
end
}
when :subfunc
faddr = args[1]
f = @function[faddr]
f = @function[f.backtrace_binding[:thunk]] if f and f.backtrace_binding[:thunk]
if f
binding = f.backtrace_binding
if binding.empty?
backtrace_update_function_binding(faddr)
binding = f.backtrace_binding
end
# XXX fwdemu_binding ?
binding.each { |r, v|
if v.externals.find { |e| trace_state[e] }
if r.kind_of?(::Symbol)
trace_state = trace_state.dup
trace_state[r] = Expression[v.bind(trace_state)].reduce
end
elsif trace_state[r]
trace_state = trace_state.dup
trace_state.delete r
end
}
end
when :merge
# when merging paths, keep the smallest common state subset
# XXX may have unexplored froms
conflicts = args[2]
trace_state = trace_state.dup
conflicts.each { |addr, st|
trace_state.delete_if { |k, v| st[k] != v }
}
end
trace_state = false if trace_state.empty?
trace_state
}
end
# define a register as a pointer to a structure
# rename all [reg+off] as [reg+struct.member] in current function
# also trace assignments of pointer members
def trace_update_reg_structptr(addr, reg, structname, structoff=0)
sname = soff = ctx = nil
expr_to_sname = lambda { |expr|
if not expr.kind_of?(Expression) or expr.op != :+
sname = nil
next
end
sname = expr.lexpr || expr.rexpr
soff = (expr.lexpr ? expr.rexpr : 0)
if soff.kind_of?(Expression)
# ignore index in ptr array
if soff.op == :* and soff.lexpr == @cpu.size/8
soff = 0
elsif soff.rexpr.kind_of?(Expression) and soff.rexpr.op == :* and soff.rexpr.lexpr == @cpu.size/8
soff = soff.lexpr
elsif soff.lexpr.kind_of?(Expression) and soff.lexpr.op == :* and soff.lexpr.lexpr == @cpu.size/8
soff = soff.rexpr
end
elsif soff.kind_of?(::Symbol)
# array with 1 byte elements / pre-scaled idx?
if not ctx[soff]
soff = 0
end
end
}
lastdi = nil
trace_function_register(addr, reg => Expression[structname, :+, structoff]) { |di, r, val, trace|
next if r.to_s =~ /flag/ # XXX maybe too ia32-specific?
ctx = trace
@cpu.instr_args_memoryptr(di).each { |ind|
# find the structure dereference in di
b = @cpu.instr_args_memoryptr_getbase(ind)
b = b.symbolic if b
next unless trace[b]
imm = @cpu.instr_args_memoryptr_getoffset(ind) || 0
# check expr has the form 'traced_struct_reg + off'
expr_to_sname[trace[b] + imm] # Expr#+ calls Expr#reduce
next unless sname.kind_of?(::String) and soff.kind_of?(::Integer)
next if not st = c_parser.toplevel.struct[sname] or not st.kind_of?(C::Union)
# ignore lea esi, [esi+0]
next if soff == 0 and not di.backtrace_binding.find { |k, v| v-k != 0 }
# TODO if trace[b] offset != 0, we had a lea reg, [struct+substruct_off], tweak str accordingly
# resolve struct + off into struct.membername
str = st.name.dup
mb = st.expand_member_offset(c_parser, soff, str)
# patch di
imm = imm.rexpr if imm.kind_of?(Expression) and not imm.lexpr and imm.rexpr.kind_of?(ExpressionString)
imm = imm.expr if imm.kind_of?(ExpressionString)
@cpu.instr_args_memoryptr_setoffset(ind, ExpressionString.new(imm, str, :structoff))
# check if the type is an enum/bitfield, patch instruction immediates
trace_update_reg_structptr_arg_enum(di, ind, mb, str) if mb
} if lastdi != di.address
lastdi = di.address
next Expression[structname, :+, structoff] if di.address == addr and r == reg
# check if we need to trace 'r' further
val = val.reduce_rec if val.kind_of?(Expression)
val = Expression[val] if val.kind_of?(::String)
case val
when Expression
# only trace trivial structptr+off expressions
expr_to_sname[val]
if sname.kind_of?(::String) and soff.kind_of?(::Integer)
Expression[sname, :+, soff]
end
when Indirection
# di is mov reg, [ptr+struct.offset]
# check if the target member is a pointer to a struct, if so, trace it
expr_to_sname[val.pointer.reduce]
next unless sname.kind_of?(::String) and soff.kind_of?(::Integer)
if st = c_parser.toplevel.struct[sname] and st.kind_of?(C::Union)
pt = st.expand_member_offset(c_parser, soff, '')
pt = pt.untypedef if pt
if pt.kind_of?(C::Pointer)
tt = pt.type.untypedef
stars = ''
while tt.kind_of?(C::Pointer)
stars << '*'
tt = tt.type.untypedef
end
if tt.kind_of?(C::Union) and tt.name
Expression[tt.name + stars]
end
end
elsif soff == 0 and sname[-1] == ?*
# XXX pointer to pointer to struct
# full C type support would be better, but harder to fit in an Expr
Expression[sname[0...-1]]
end
# in other cases, stop trace
end
}
end
# found a special member of a struct, check if we can apply
# bitfield/enum name to other constants in the di
def trace_update_reg_structptr_arg_enum(di, ind, mb, str)
if ename = mb.has_attribute_var('enum') and enum = c_parser.toplevel.struct[ename] and enum.kind_of?(C::Enum)
# handle enums: struct moo { int __attribute__((enum(bla))) fld; };
doit = lambda { |_di|
if num = _di.instruction.args.grep(Expression).first and num_i = num.reduce and num_i.kind_of?(::Integer)
# handle enum values on tagged structs
if enum.members and name = enum.members.index(num_i)
num.lexpr = nil
num.op = :+
num.rexpr = ExpressionString.new(Expression[num_i], name, :enum)
_di.add_comment "enum::#{ename}" if _di.address != di.address
end
end
}
doit[di]
# mov eax, [ptr+struct.enumfield] => trace eax
if reg = @cpu.instr_args_regs(di).find { |r| v = di.backtrace_binding[r.symbolic] and (v - ind.symbolic) == 0 }
reg = reg.symbolic
trace_function_register(di.address, reg => Expression[0]) { |_di, r, val, trace|
next if r != reg and val != Expression[reg]
doit[_di]
val
}
end
elsif mb.untypedef.kind_of?(C::Struct)
# handle bitfields
byte_off = 0
if str =~ /\+(\d+)$/
# test byte [bitfield+1], 0x1 => test dword [bitfield], 0x100
# XXX little-endian only
byte_off = $1.to_i
str[/\+\d+$/] = ''
end
cmt = str.split('.')[-2, 2].join('.') if str.count('.') > 1
doit = lambda { |_di, add|
if num = _di.instruction.args.grep(Expression).first and num_i = num.reduce and num_i.kind_of?(::Integer)
# TODO handle ~num_i
num_left = num_i << add
s_or = []
mb.untypedef.members.each { |mm|
if bo = mb.bitoffsetof(c_parser, mm)
boff, blen = bo
if mm.name && blen == 1 && ((num_left >> boff) & 1) > 0
s_or << mm.name
num_left &= ~(1 << boff)
end
end
}
if s_or.first
if num_left != 0
s_or << ('0x%X' % num_left)
end
s = s_or.join('|')
num.lexpr = nil
num.op = :+
num.rexpr = ExpressionString.new(Expression[num_i], s, :bitfield)
_di.add_comment cmt if _di.address != di.address
end
end
}
doit[di, byte_off*8]
if reg = @cpu.instr_args_regs(di).find { |r| v = di.backtrace_binding[r.symbolic] and (v - ind.symbolic) == 0 }
reg = reg.symbolic
trace_function_register(di.address, reg => Expression[0]) { |_di, r, val, trace|
if r.kind_of?(Expression) and r.op == :&
if r.lexpr == reg
# test al, 42
doit[_di, byte_off*8]
elsif r.lexpr.kind_of?(Expression) and r.lexpr.op == :>> and r.lexpr.lexpr == reg
# test ah, 42
doit[_di, byte_off*8+r.lexpr.rexpr]
end
end
next if r != reg and val != Expression[reg]
doit[_di, byte_off*8]
_di.address == di.address && r == reg ? Expression[0] : val
}
end
end
end
# change Expression display mode for current object o to display integers as char constants
def toggle_expr_char(o)
return if not o.kind_of?(Renderable)
tochars = lambda { |v|
if v.kind_of?(::Integer)
a = []
vv = v.abs
a << (vv & 0xff)
vv >>= 8
while vv > 0
a << (vv & 0xff)
vv >>= 8
end
if a.all? { |b| b < 0x7f }
s = a.pack('C*').inspect.gsub("'") { '\\\'' }[1...-1]
ExpressionString.new(v, (v > 0 ? "'#{s}'" : "-'#{s}'"), :char)
end
end
}
o.each_expr { |e|
if e.kind_of?(Expression)
if nr = tochars[e.rexpr]
e.rexpr = nr
elsif e.rexpr.kind_of?(ExpressionString) and e.rexpr.type == :char
e.rexpr = e.rexpr.expr
end
if nl = tochars[e.lexpr]
e.lexpr = nl
elsif e.lexpr.kind_of?(ExpressionString) and e.lexpr.type == :char
e.lexpr = e.lexpr.expr
end
end
}
end
def toggle_expr_dec(o)
return if not o.kind_of?(Renderable)
o.each_expr { |e|
if e.kind_of?(Expression)
if e.rexpr.kind_of?(::Integer)
e.rexpr = ExpressionString.new(Expression[e.rexpr], e.rexpr.to_s, :decimal)
elsif e.rexpr.kind_of?(ExpressionString) and e.rexpr.type == :decimal
e.rexpr = e.rexpr.reduce
end
if e.lexpr.kind_of?(::Integer)
e.lexpr = ExpressionString.new(Expression[e.lexpr], e.lexpr.to_s, :decimal)
elsif e.lexpr.kind_of?(ExpressionString) and e.lexpr.type == :decimal
e.lexpr = e.lexpr.reduce
end
end
}
end
# patch Expressions in current object to include label names when available
# XXX should we also create labels ?
def toggle_expr_offset(o)
return if not o.kind_of? Renderable
o.each_expr { |e|
next unless e.kind_of?(Expression)
if n = @prog_binding[e.lexpr]
e.lexpr = n
elsif e.lexpr.kind_of? ::Integer and n = get_label_at(e.lexpr)
add_xref(normalize(e.lexpr), Xref.new(:addr, o.address)) if o.respond_to? :address
e.lexpr = n
end
if n = @prog_binding[e.rexpr]
e.rexpr = n
elsif e.rexpr.kind_of? ::Integer and n = get_label_at(e.rexpr)
add_xref(normalize(e.rexpr), Xref.new(:addr, o.address)) if o.respond_to? :address
e.rexpr = n
end
}
end
# toggle all ExpressionStrings
def toggle_expr_str(o)
return if not o.kind_of?(Renderable)
o.each_expr { |e|
next unless e.kind_of?(ExpressionString)
e.hide_str = !e.hide_str
}
end
# call this function on a function entrypoint if the function is in fact a __noreturn
# will cut the to_subfuncret of callers
def fix_noreturn(o)
each_xref(o, :x) { |a|
a = normalize(a.origin)
next if not di = di_at(a) or not di.opcode.props[:saveip]
# XXX should check if caller also becomes __noreturn
di.block.each_to_subfuncret { |to|
next if not tdi = di_at(to) or not tdi.block.from_subfuncret
tdi.block.from_subfuncret.delete_if { |aa| normalize(aa) == di.address }
tdi.block.from_subfuncret = nil if tdi.block.from_subfuncret.empty?
}
di.block.to_subfuncret = nil
}
end
# find the addresses of calls calling the address, handles thunks
def call_sites(funcaddr)
find_call_site = proc { |a|
until not di = di_at(a)
if di.opcode.props[:saveip]
cs = di.address
break
end
if di.block.from_subfuncret.to_a.first
while di.block.from_subfuncret.to_a.length == 1
a = di.block.from_subfuncret[0]
break if not di_at(a)
a = @decoded[a].block.list.first.address
di = @decoded[a]
end
end
break if di.block.from_subfuncret.to_a.first
break if di.block.from_normal.to_a.length != 1
a = di.block.from_normal.first
end
cs
}
ret = []
each_xref(normalize(funcaddr), :x) { |a|
ret << find_call_site[a.origin]
}
ret.compact.uniq
end
# loads a disassembler plugin script
# this is simply a ruby script instance_eval() in the disassembler
# the filename argument is autocompleted with '.rb' suffix, and also
# searched for in the Metasmdir/samples/dasm-plugins subdirectory if not found in cwd
def load_plugin(plugin_filename)
if not File.exist?(plugin_filename)
if File.exist?(plugin_filename+'.rb')
plugin_filename += '.rb'
elsif defined? Metasmdir
# try autocomplete
pf = File.join(Metasmdir, 'samples', 'dasm-plugins', plugin_filename)
if File.exist? pf
plugin_filename = pf
elsif File.exist? pf + '.rb'
plugin_filename = pf + '.rb'
end
end
end
instance_eval File.read(plugin_filename)
end
# same as load_plugin, but hides the @gui attribute while loading, preventing the plugin do popup stuff
# this is useful when you want to load a plugin from another plugin to enhance the plugin's functionnality
# XXX this also prevents setting up kbd_callbacks etc..
def load_plugin_nogui(plugin_filename)
oldgui = gui
@gui = nil
load_plugin(plugin_filename)
ensure
@gui = oldgui
end
# compose two code/instruction's backtrace_binding
# assumes bd1 is followed by bd2 in the code flow
# eg inc edi + push edi =>
# { Ind[:esp, 4] => Expr[:edi + 1], :esp => Expr[:esp - 4], :edi => Expr[:edi + 1] }
# XXX if bd1 writes to memory with a pointer that is reused in bd2, this function has to
# revert the change made by bd2, which only works with simple ptr addition now
# XXX unhandled situations may be resolved using :unknown, or by returning incorrect values
def compose_bt_binding(bd1, bd2)
if bd1.kind_of? DecodedInstruction
bd1 = bd1.backtrace_binding ||= cpu.get_backtrace_binding(bd1)
end
if bd2.kind_of? DecodedInstruction
bd2 = bd2.backtrace_binding ||= cpu.get_backtrace_binding(bd2)
end
reduce = lambda { |e| Expression[Expression[e].reduce] }
bd = {}
bd2.each { |k, v|
bd[k] = reduce[v.bind(bd1)]
}
# for each pointer appearing in keys of bd1, we must infer from bd2 what final
# pointers should appear in bd
# eg 'mov [eax], 0 mov ebx, eax' => { [eax] <- 0, [ebx] <- 0, ebx <- eax }
bd1.each { |k, v|
if k.kind_of? Indirection
done = false
k.pointer.externals.each { |e|
# XXX this will break on nontrivial pointers or bd2
bd2.each { |k2, v2|
# we dont want to invert computation of flag_zero/carry etc (booh)
next if k2.to_s =~ /flag/
# discard indirection etc, result would be too complex / not useful
next if not Expression[v2].expr_externals.include? e
done = true
# try to reverse the computation made upon 'e'
# only simple addition handled here
ptr = reduce[k.pointer.bind(e => Expression[[k2, :-, v2], :+, e])]
# if bd2 does not rewrite e, duplicate the original pointer
if not bd2[e]
bd[k] ||= reduce[v]
# here we should not see 'e' in ptr anymore
ptr = Expression::Unknown if ptr.externals.include? e
else
# cant check if add reversion was successful..
end
bd[Indirection[reduce[ptr], k.len]] ||= reduce[v]
}
}
bd[k] ||= reduce[v] if not done
else
bd[k] ||= reduce[v]
end
}
bd
end
def gui_hilight_word_regexp(word)
@cpu.gui_hilight_word_regexp(word)
end
# return a C::AllocCStruct from c_parser
# TODO handle program.class::Header.to_c_struct
def decode_c_struct(structname, addr)
if c_parser and edata = get_edata_at(addr)
c_parser.decode_c_struct(structname, edata.data, edata.ptr)
end
end
def decode_c_ary(structname, addr, len)
if c_parser and edata = get_edata_at(addr)
c_parser.decode_c_ary(structname, len, edata.data, edata.ptr)
end
end
# find the function containing addr, and find & rename stack vars in it
def name_local_vars(addr)
if @cpu.respond_to?(:name_local_vars) and faddr = find_function_start(addr)
@function[faddr] ||= DecodedFunction.new # XXX
@cpu.name_local_vars(self, faddr)
end
end
end
end
dasm: fix merge_block wrt calls
# This file is part of Metasm, the Ruby assembly manipulation suite
# Copyright (C) 2006-2009 Yoann GUILLOT
#
# Licence is LGPL, see LICENCE in the top-level directory
# this file compliments disassemble.rb, adding misc user-friendly methods
module Metasm
class InstructionBlock
# adds an address to the from_normal/from_subfuncret list
def add_from(addr, type=:normal)
send "add_from_#{type}", addr
end
def add_from_normal(addr)
@from_normal ||= []
@from_normal |= [addr]
end
def add_from_subfuncret(addr)
@from_subfuncret ||= []
@from_subfuncret |= [addr]
end
def add_from_indirect(addr)
@from_indirect ||= []
@from_indirect |= [addr]
end
# iterates over every from address, yields [address, type in [:normal, :subfuncret, :indirect]]
def each_from
each_from_normal { |a| yield a, :normal }
each_from_subfuncret { |a| yield a, :subfuncret }
each_from_indirect { |a| yield a, :indirect }
end
def each_from_normal(&b)
@from_normal.each(&b) if from_normal
end
def each_from_subfuncret(&b)
@from_subfuncret.each(&b) if from_subfuncret
end
def each_from_indirect(&b)
@from_indirect.each(&b) if from_indirect
end
def add_to(addr, type=:normal)
send "add_to_#{type}", addr
end
def add_to_normal(addr)
@to_normal ||= []
@to_normal |= [addr]
end
def add_to_subfuncret(addr)
@to_subfuncret ||= []
@to_subfuncret |= [addr]
end
def add_to_indirect(addr)
@to_indirect ||= []
@to_indirect |= [addr]
end
def each_to
each_to_normal { |a| yield a, :normal }
each_to_subfuncret { |a| yield a, :subfuncret }
each_to_indirect { |a| yield a, :indirect }
end
def each_to_normal(&b)
@to_normal.each(&b) if to_normal
end
def each_to_subfuncret(&b)
@to_subfuncret.each(&b) if to_subfuncret
end
def each_to_indirect(&b)
@to_indirect.each(&b) if to_indirect
end
# yields all from that are from the same function
def each_from_samefunc(dasm, &b)
return if dasm.function[address]
@from_subfuncret.each(&b) if from_subfuncret
@from_normal.each(&b) if from_normal
end
# yields all from that are not in the same subfunction as this block
def each_from_otherfunc(dasm, &b)
@from_normal.each(&b) if from_normal and dasm.function[address]
@from_subfuncret.each(&b) if from_subfuncret and dasm.function[address]
@from_indirect.each(&b) if from_indirect
end
# yields all to that are in the same subfunction as this block
def each_to_samefunc(dasm)
each_to { |to, type|
next if type != :normal and type != :subfuncret
to = dasm.normalize(to)
yield to if not dasm.function[to]
}
end
# yields all to that are not in the same subfunction as this block
def each_to_otherfunc(dasm)
each_to { |to, type|
to = dasm.normalize(to)
yield to if type == :indirect or dasm.function[to] or not dasm.decoded[to]
}
end
# returns the array used in each_from_samefunc
def from_samefunc(dasm)
ary = []
each_from_samefunc(dasm) { |a| ary << a }
ary
end
def from_otherfunc(dasm)
ary = []
each_from_otherfunc(dasm) { |a| ary << a }
ary
end
def to_samefunc(dasm)
ary = []
each_to_samefunc(dasm) { |a| ary << a }
ary
end
def to_otherfunc(dasm)
ary = []
each_to_otherfunc(dasm) { |a| ary << a }
ary
end
end
class DecodedInstruction
# checks if this instruction is the first of its IBlock
def block_head?
self == @block.list.first
end
end
class CPU
# compat alias, for scripts using older version of metasm
def get_backtrace_binding(di) backtrace_binding(di) end
end
class Disassembler
# access the default value for @@backtrace_maxblocks for newly created Disassemblers
def self.backtrace_maxblocks ; @@backtrace_maxblocks ; end
def self.backtrace_maxblocks=(b) ; @@backtrace_maxblocks = b ; end
# adds a commentary at the given address
# comments are found in the array @comment: {addr => [list of strings]}
def add_comment(addr, cmt)
@comment[addr] ||= []
@comment[addr] |= [cmt]
end
# returns the 1st element of #get_section_at (ie the edata at a given address) or nil
def get_edata_at(*a)
if s = get_section_at(*a)
s[0]
end
end
# returns the DecodedInstruction at addr if it exists
def di_at(addr)
di = @decoded[addr] || @decoded[normalize(addr)] if addr
di if di.kind_of? DecodedInstruction
end
# returns the InstructionBlock containing the address at addr
def block_at(addr)
di = di_at(addr)
di.block if di
end
# returns the DecodedFunction at addr if it exists
def function_at(addr)
f = @function[addr] || @function[normalize(addr)] if addr
f if f.kind_of? DecodedFunction
end
# returns the DecodedInstruction covering addr
# returns one at starting nearest addr if multiple are available (overlapping instrs)
def di_including(addr)
return if not addr
addr = normalize(addr)
if off = (0...16).find { |o| @decoded[addr-o].kind_of? DecodedInstruction and @decoded[addr-o].bin_length > o }
@decoded[addr-off]
end
end
# returns the InstructionBlock containing the byte at addr
# returns the one of di_including() on multiple matches (overlapping instrs)
def block_including(addr)
di = di_including(addr)
di.block if di
end
# returns the DecodedFunction including this byte
# return the one of find_function_start() if multiple are possible (block shared by multiple funcs)
def function_including(addr)
return if not di = di_including(addr)
function_at(find_function_start(di.address))
end
# yields every InstructionBlock
# returns the list of IBlocks
def each_instructionblock(&b)
ret = []
@decoded.each { |addr, di|
next if not di.kind_of? DecodedInstruction or not di.block_head?
ret << di.block
b.call(di.block) if b
}
ret
end
alias instructionblocks each_instructionblock
# return a backtrace_binding reversed (akin to code emulation) (but not really)
def get_fwdemu_binding(di, pc=nil)
@cpu.get_fwdemu_binding(di, pc)
end
# reads len raw bytes from the mmaped address space
def read_raw_data(addr, len)
if e = get_section_at(addr)
e[0].read(len)
end
end
# read an int of arbitrary type (:u8, :i32, ...)
def decode_int(addr, type)
type = "u#{type*8}".to_sym if type.kind_of? Integer
if e = get_section_at(addr)
e[0].decode_imm(type, @cpu.endianness)
end
end
# read a byte at address addr
def decode_byte(addr)
decode_int(addr, :u8)
end
# read a dword at address addr
# the dword is cpu-sized (eg 32 or 64bits)
def decode_dword(addr)
decode_int(addr, @cpu.size/8)
end
# read a zero-terminated string from addr
# if no terminal 0 is found, return nil
def decode_strz(addr, maxsz=4096)
if e = get_section_at(addr)
str = e[0].read(maxsz).to_s
return if not len = str.index(?\0)
str[0, len]
end
end
# read a zero-terminated wide string from addr
# return nil if no terminal found
def decode_wstrz(addr, maxsz=4096)
if e = get_section_at(addr)
str = e[0].read(maxsz).to_s
return if not len = str.unpack('v*').index(0)
str[0, 2*len]
end
end
# disassembles one instruction at address
# returns nil if no instruction can be decoded there
# does not update any internal state of the disassembler, nor reuse the @decoded cache
def disassemble_instruction(addr)
if e = get_section_at(addr)
@cpu.decode_instruction(e[0], normalize(addr))
end
end
# disassemble addr as if the code flow came from from_addr
def disassemble_from(addr, from_addr)
from_addr = from_addr.address if from_addr.kind_of? DecodedInstruction
from_addr = normalize(from_addr)
if b = block_at(from_addr)
b.add_to_normal(addr)
end
@addrs_todo << [addr, from_addr]
disassemble
end
# returns the label associated to an addr, or nil if none exist
def get_label_at(addr)
e = get_edata_at(addr, false)
e.inv_export[e.ptr] if e
end
# sets the label for the specified address
# returns nil if the address is not mapped
# memcheck is passed to get_section_at to validate that the address is mapped
# keep existing label if 'overwrite' is false
def set_label_at(addr, name, memcheck=true, overwrite=true)
addr = Expression[addr].reduce
e, b = get_section_at(addr, memcheck)
if not e
elsif not l = e.inv_export[e.ptr] or (!overwrite and l != name)
l = @program.new_label(name)
e.add_export l, e.ptr
@label_alias_cache = nil
@old_prog_binding[l] = @prog_binding[l] = b + e.ptr
elsif l != name
l = rename_label l, @program.new_label(name)
end
l
end
# remove a label at address addr
def del_label_at(addr, name=get_label_at(addr))
ed = get_edata_at(addr)
if ed and ed.inv_export[ed.ptr]
ed.del_export name, ed.ptr
@label_alias_cache = nil
end
each_xref(addr) { |xr|
next if not xr.origin or not o = @decoded[xr.origin] or not o.kind_of? Renderable
o.each_expr { |e|
next unless e.kind_of?(Expression)
e.lexpr = addr if e.lexpr == name
e.rexpr = addr if e.rexpr == name
}
}
@old_prog_binding.delete name
@prog_binding.delete name
end
# changes a label to another, updates referring instructions etc
# returns the new label
# the new label must be program-uniq (see @program.new_label)
def rename_label(old, new)
return new if old == new
raise "label #{new.inspect} exists" if @prog_binding[new]
each_xref(normalize(old)) { |x|
next if not di = @decoded[x.origin]
@cpu.replace_instr_arg_immediate(di.instruction, old, new)
di.comment.to_a.each { |c| c.gsub!(old, new) }
}
e = get_edata_at(old, false)
if e
e.add_export new, e.export.delete(old), true
end
raise "cant rename nonexisting label #{old}" if not @prog_binding[old]
@label_alias_cache = nil
@old_prog_binding[new] = @prog_binding[new] = @prog_binding.delete(old)
@addrs_todo.each { |at|
case at[0]
when old; at[0] = new
when Expression; at[0] = at[0].bind(old => new)
end
}
if @inv_section_reloc[old]
@inv_section_reloc[old].each { |b, e_, o, r|
(0..16).each { |off|
if di = @decoded[Expression[b]+o-off] and di.bin_length > off
@cpu.replace_instr_arg_immediate(di.instruction, old, new)
end
}
r.target = r.target.bind(old => new)
}
@inv_section_reloc[new] = @inv_section_reloc.delete(old)
end
if c_parser and @c_parser.toplevel.symbol[old]
@c_parser.toplevel.symbol[new] = @c_parser.toplevel.symbol.delete(old)
@c_parser.toplevel.symbol[new].name = new
end
new
end
# finds the start of a function from the address of an instruction
def find_function_start(addr)
addr = addr.address if addr.kind_of? DecodedInstruction
todo = [addr]
done = []
while a = todo.pop
a = normalize(a)
di = @decoded[a]
next if done.include? a or not di.kind_of? DecodedInstruction
done << a
a = di.block.address
break a if @function[a]
l = []
di.block.each_from_samefunc(self) { |f| l << f }
break a if l.empty?
todo.concat l
end
end
# iterates over the blocks of a function, yields each func block address
# returns the graph of blocks (block address => [list of samefunc blocks])
def each_function_block(addr, incl_subfuncs = false, find_func_start = true)
addr = @function.index(addr) if addr.kind_of? DecodedFunction
addr = addr.address if addr.kind_of? DecodedInstruction
addr = find_function_start(addr) if not @function[addr] and find_func_start
todo = [addr]
ret = {}
while a = todo.pop
next if not di = di_at(a)
a = di.block.address
next if ret[a]
ret[a] = []
yield a if block_given?
di.block.each_to_samefunc(self) { |f| ret[a] << f ; todo << f }
di.block.each_to_otherfunc(self) { |f| ret[a] << f ; todo << f } if incl_subfuncs
end
ret
end
alias function_blocks each_function_block
# returns a graph of function calls
# for each func passed as arg (default: all), update the 'ret' hash
# associating func => [list of direct subfuncs called]
def function_graph(funcs = @function.keys + @entrypoints.to_a, ret={})
funcs = funcs.map { |f| normalize(f) }.uniq.find_all { |f| @decoded[f] }
funcs.each { |f|
next if ret[f]
ret[f] = []
each_function_block(f) { |b|
@decoded[b].block.each_to_otherfunc(self) { |sf|
ret[f] |= [sf]
}
}
}
ret
end
# return the graph of function => subfunction list
# recurses from an entrypoint
def function_graph_from(addr)
addr = normalize(addr)
addr = find_function_start(addr) || addr
ret = {}
osz = ret.length-1
while ret.length != osz
osz = ret.length
function_graph(ret.values.flatten + [addr], ret)
end
ret
end
# return the graph of function => subfunction list
# for which a (sub-sub)function includes addr
def function_graph_to(addr)
addr = normalize(addr)
addr = find_function_start(addr) || addr
full = function_graph
ret = {}
todo = [addr]
done = []
while a = todo.pop
next if done.include? a
done << a
full.each { |f, sf|
next if not sf.include? a
ret[f] ||= []
ret[f] |= [a]
todo << f
}
end
ret
end
# returns info on sections, from @program if supported
# returns an array of [name, addr, length, info]
def section_info
if @program.respond_to? :section_info
@program.section_info
else
list = []
@sections.each { |k, v|
list << [get_label_at(k), normalize(k), v.length, nil]
}
list
end
end
# transform an address into a file offset
def addr_to_fileoff(addr)
addr = normalize(addr)
@program.addr_to_fileoff(addr)
end
# transform a file offset into an address
def fileoff_to_addr(foff)
@program.fileoff_to_addr(foff)
end
# remove the decodedinstruction from..to, replace them by the new Instructions in 'by'
# this updates the block list structure, old di will still be visible in @decoded, except from original block (those are deleted)
# if from..to spans multiple blocks
# to.block is splitted after to
# all path from from are replaced by a single link to after 'to', be careful !
# (eg a->b->... & a->c ; from in a, to in c => a->b is lost)
# all instructions are stuffed in the first block
# paths are only walked using from/to_normal
# 'by' may be empty
# returns the block containing the new instrs (nil if empty)
def replace_instrs(from, to, by, patch_by=false)
raise 'bad from' if not fdi = di_at(from) or not fdi.block.list.index(fdi)
raise 'bad to' if not tdi = di_at(to) or not tdi.block.list.index(tdi)
# create DecodedInstruction from Instructions in 'by' if needed
split_block(fdi.block, fdi.address)
split_block(tdi.block, tdi.block.list[tdi.block.list.index(tdi)+1].address) if tdi != tdi.block.list.last
fb = fdi.block
tb = tdi.block
# generate DecodedInstr from Instrs
# try to keep the bin_length of original block
wantlen = tdi.address + tdi.bin_length - fb.address
wantlen -= by.grep(DecodedInstruction).inject(0) { |len, di| len + di.bin_length }
ldi = by.last
ldi = DecodedInstruction.new(ldi) if ldi.kind_of? Instruction
nb_i = by.grep(Instruction).length
wantlen = nb_i if wantlen < 0 or (ldi and ldi.opcode.props[:setip])
if patch_by
by.map! { |di|
if di.kind_of? Instruction
di = DecodedInstruction.new(di)
wantlen -= di.bin_length = wantlen / by.grep(Instruction).length
nb_i -= 1
end
di
}
else
by = by.map { |di|
if di.kind_of? Instruction
di = DecodedInstruction.new(di)
wantlen -= (di.bin_length = wantlen / nb_i)
nb_i -= 1
end
di
}
end
#puts " ** patch next_addr to #{Expression[tb.list.last.next_addr]}" if not by.empty? and by.last.opcode.props[:saveip]
by.last.next_addr = tb.list.last.next_addr if not by.empty? and by.last.opcode.props[:saveip]
fb.list.each { |di| @decoded.delete di.address }
fb.list.clear
tb.list.each { |di| @decoded.delete di.address }
tb.list.clear
by.each { |di| fb.add_di di }
by.each_with_index { |di, i|
if odi = di_at(di.address)
# collision, hopefully with another deobfuscation run ?
if by[i..-1].all? { |mydi| mydi.to_s == @decoded[mydi.address].to_s }
puts "replace_instrs: merge at #{di}" if $DEBUG
by[i..-1] = by[i..-1].map { |xdi| @decoded[xdi.address] }
by[i..-1].each { fb.list.pop }
split_block(odi.block, odi.address)
tb.to_normal = [di.address]
(odi.block.from_normal ||= []) << to
odi.block.from_normal.uniq!
break
else
#raise "replace_instrs: collision #{di} vs #{odi}"
puts "replace_instrs: collision #{di} vs #{odi}" if $VERBOSE
while @decoded[di.address].kind_of? DecodedInstruction # find free space.. raise ?
di.address += 1 # XXX use floats ?
di.bin_length -= 1
end
end
end
@decoded[di.address] = di
}
@addrs_done.delete_if { |ad| normalize(ad[0]) == tb.address or ad[1] == tb.address }
@addrs_done.delete_if { |ad| normalize(ad[0]) == fb.address or ad[1] == fb.address } if by.empty? and tb.address != fb.address
# update to_normal/from_normal
fb.to_normal = tb.to_normal
fb.to_normal.to_a.each { |newto|
# other paths may already point to newto, we must only update the relevant entry
if ndi = di_at(newto) and idx = ndi.block.from_normal.to_a.index(to)
if by.empty?
ndi.block.from_normal[idx,1] = fb.from_normal.to_a
else
ndi.block.from_normal[idx] = fb.list.last.address
end
end
}
fb.to_subfuncret = tb.to_subfuncret
fb.to_subfuncret.to_a.each { |newto|
if ndi = di_at(newto) and idx = ndi.block.from_subfuncret.to_a.index(to)
if by.empty?
ndi.block.from_subfuncret[idx,1] = fb.from_subfuncret.to_a
else
ndi.block.from_subfuncret[idx] = fb.list.last.address
end
end
}
if by.empty?
tb.to_subfuncret = nil if tb.to_subfuncret == []
tolist = tb.to_subfuncret || tb.to_normal.to_a
if lfrom = get_label_at(fb.address) and tolist.length == 1
lto = auto_label_at(tolist.first)
each_xref(fb.address, :x) { |x|
next if not di = @decoded[x.origin]
@cpu.replace_instr_arg_immediate(di.instruction, lfrom, lto)
di.comment.to_a.each { |c| c.gsub!(lfrom, lto) }
}
end
fb.from_normal.to_a.each { |newfrom|
if ndi = di_at(newfrom) and idx = ndi.block.to_normal.to_a.index(from)
ndi.block.to_normal[idx..idx] = tolist
end
}
fb.from_subfuncret.to_a.each { |newfrom|
if ndi = di_at(newfrom) and idx = ndi.block.to_subfuncret.to_a.index(from)
ndi.block.to_subfuncret[idx..idx] = tolist
end
}
else
# merge with adjacent blocks
merge_blocks(fb, fb.to_normal.first) if fb.to_normal.to_a.length == 1 and di_at(fb.to_normal.first)
merge_blocks(fb.from_normal.first, fb) if fb.from_normal.to_a.length == 1 and di_at(fb.from_normal.first)
end
fb if not by.empty?
end
# undefine a sequence of decodedinstructions from an address
# stops at first non-linear branch
# removes @decoded, @comments, @xrefs, @addrs_done
# does not update @prog_binding (does not undefine labels)
def undefine_from(addr)
return if not di_at(addr)
@comment.delete addr if @function.delete addr
split_block(addr)
addrs = []
while di = di_at(addr)
di.block.list.each { |ddi| addrs << ddi.address }
break if di.block.to_subfuncret.to_a != [] or di.block.to_normal.to_a.length != 1
addr = di.block.to_normal.first
break if ndi = di_at(addr) and ndi.block.from_normal.to_a.length != 1
end
addrs.each { |a| @decoded.delete a }
@xrefs.delete_if { |a, x|
if not x.kind_of? Array
true if x and addrs.include? x.origin
else
x.delete_if { |xx| addrs.include? xx.origin }
true if x.empty?
end
}
@addrs_done.delete_if { |ad| !(addrs & [normalize(ad[0]), normalize(ad[1])]).empty? }
end
# merge two instruction blocks if they form a simple chain and are adjacent
# returns true if merged
def merge_blocks(b1, b2, allow_nonadjacent = false)
if b1 and not b1.kind_of? InstructionBlock
return if not b1 = block_at(b1)
end
if b2 and not b2.kind_of? InstructionBlock
return if not b2 = block_at(b2)
end
if b1 and b2 and (allow_nonadjacent or b1.list.last.next_addr == b2.address) and
b1.to_normal.to_a == [b2.address] and b2.from_normal.to_a.length == 1 and # that handles delay_slot
b1.to_subfuncret.to_a == [] and b2.from_subfuncret.to_a == [] and
b1.to_indirect.to_a == [] and b2.from_indirect.to_a == []
b2.list.each { |di| b1.add_di di }
b1.to_normal = b2.to_normal
b1.to_subfuncret = b2.to_subfuncret
b1.to_indirect = b2.to_indirect
b2.list.clear
@addrs_done.delete_if { |ad| normalize(ad[0]) == b2.address }
true
end
end
# computes the binding of a code sequence
# just a forwarder to CPU#code_binding
def code_binding(*a)
@cpu.code_binding(self, *a)
end
# returns an array of instructions/label that, once parsed and assembled, should
# give something equivalent to the code accessible from the (list of) entrypoints given
# from the @decoded dasm graph
# assume all jump targets have a matching label in @prog_binding
# may add inconditionnal jumps in the listing to preserve the code flow
def flatten_graph(entry, include_subfunc=true)
ret = []
entry = [entry] if not entry.kind_of? Array
todo = entry.map { |a| normalize(a) }
done = []
inv_binding = @prog_binding.invert
while addr = todo.pop
next if done.include? addr or not di_at(addr)
done << addr
b = @decoded[addr].block
ret << Label.new(inv_binding[addr]) if inv_binding[addr]
ret.concat b.list.map { |di| di.instruction }
b.each_to_otherfunc(self) { |to|
to = normalize to
todo.unshift to if include_subfunc
}
b.each_to_samefunc(self) { |to|
to = normalize to
todo << to
}
if not di = b.list[-1-@cpu.delay_slot] or not di.opcode.props[:stopexec] or di.opcode.props[:saveip]
to = b.list.last.next_addr
if todo.include? to
if done.include? to or not di_at(to)
if not to_l = inv_binding[to]
to_l = auto_label_at(to, 'loc')
if done.include? to and idx = ret.index(@decoded[to].block.list.first.instruction)
ret.insert(idx, Label.new(to_l))
end
end
ret << @cpu.instr_uncond_jump_to(to_l)
else
todo << to # ensure it's next in the listing
end
end
end
end
ret
end
# returns a demangled C++ name
def demangle_cppname(name)
case name[0]
when ?? # MSVC
name = name[1..-1]
demangle_msvc(name[1..-1]) if name[0] == ??
when ?_
name = name.sub(/_GLOBAL__[ID]_/, '')
demangle_gcc(name[2..-1][/\S*/]) if name[0, 2] == '_Z'
end
end
# from wgcc-2.2.2/undecorate.cpp
# TODO
def demangle_msvc(name)
op = name[0, 1]
op = name[0, 2] if op == '_'
if op = {
'2' => "new", '3' => "delete", '4' => "=", '5' => ">>", '6' => "<<", '7' => "!", '8' => "==", '9' => "!=",
'A' => "[]", 'C' => "->", 'D' => "*", 'E' => "++", 'F' => "--", 'G' => "-", 'H' => "+", 'I' => "&",
'J' => "->*", 'K' => "/", 'L' => "%", 'M' => "<", 'N' => "<=", 'O' => ">", 'P' => ">=", 'Q' => ",",
'R' => "()", 'S' => "~", 'T' => "^", 'U' => "|", 'V' => "&&", 'W' => "||", 'X' => "*=", 'Y' => "+=",
'Z' => "-=", '_0' => "/=", '_1' => "%=", '_2' => ">>=", '_3' => "<<=", '_4' => "&=", '_5' => "|=", '_6' => "^=",
'_7' => "`vftable'", '_8' => "`vbtable'", '_9' => "`vcall'", '_A' => "`typeof'", '_B' => "`local static guard'",
'_C' => "`string'", '_D' => "`vbase destructor'", '_E' => "`vector deleting destructor'", '_F' => "`default constructor closure'",
'_G' => "`scalar deleting destructor'", '_H' => "`vector constructor iterator'", '_I' => "`vector destructor iterator'",
'_J' => "`vector vbase constructor iterator'", '_K' => "`virtual displacement map'", '_L' => "`eh vector constructor iterator'",
'_M' => "`eh vector destructor iterator'", '_N' => "`eh vector vbase constructor iterator'", '_O' => "`copy constructor closure'",
'_S' => "`local vftable'", '_T' => "`local vftable constructor closure'", '_U' => "new[]", '_V' => "delete[]",
'_X' => "`placement delete closure'", '_Y' => "`placement delete[] closure'"}[op]
op[0] == ?` ? op[1..-2] : "op_#{op}"
end
end
# from http://www.codesourcery.com/public/cxx-abi/abi.html
def demangle_gcc(name)
subs = []
ret = ''
decode_tok = lambda {
name ||= ''
case name[0]
when nil
ret = nil
when ?N
name = name[1..-1]
decode_tok[]
until name[0] == ?E
break if not ret
ret << '::'
decode_tok[]
end
name = name[1..-1]
when ?I
name = name[1..-1]
ret = ret[0..-3] if ret[-2, 2] == '::'
ret << '<'
decode_tok[]
until name[0] == ?E
break if not ret
ret << ', '
decode_tok[]
end
ret << ' ' if ret and ret[-1] == ?>
ret << '>' if ret
name = name[1..-1]
when ?T
case name[1]
when ?T; ret << 'vtti('
when ?V; ret << 'vtable('
when ?I; ret << 'typeinfo('
when ?S; ret << 'typename('
else ret = nil
end
name = name[2..-1].to_s
decode_tok[] if ret
ret << ')' if ret
name = name[1..-1] if name[0] == ?E
when ?C
name = name[2..-1]
base = ret[/([^:]*)(<.*|::)?$/, 1]
ret << base
when ?D
name = name[2..-1]
base = ret[/([^:]*)(<.*|::)?$/, 1]
ret << '~' << base
when ?0..?9
nr = name[/^[0-9]+/]
name = name[nr.length..-1].to_s
ret << name[0, nr.to_i]
name = name[nr.to_i..-1]
subs << ret[/[\w:]*$/]
when ?S
name = name[1..-1]
case name[0]
when ?_, ?0..?9, ?A..?Z
case name[0]
when ?_; idx = 0 ; name = name[1..-1]
when ?0..?9; idx = name[0, 1].unpack('C')[0] - 0x30 + 1 ; name = name[2..-1]
when ?A..?Z; idx = name[0, 1].unpack('C')[0] - 0x41 + 11 ; name = name[2..-1]
end
if not subs[idx]
ret = nil
else
ret << subs[idx]
end
when ?t
ret << 'std::'
name = name[1..-1]
decode_tok[]
else
std = { ?a => 'std::allocator',
?b => 'std::basic_string',
?s => 'std::string', # 'std::basic_string < char, std::char_traits<char>, std::allocator<char> >',
?i => 'std::istream', # 'std::basic_istream<char, std::char_traits<char> >',
?o => 'std::ostream', # 'std::basic_ostream<char, std::char_traits<char> >',
?d => 'std::iostream', # 'std::basic_iostream<char, std::char_traits<char> >'
}[name[0]]
if not std
ret = nil
else
ret << std
end
name = name[1..-1]
end
when ?P, ?R, ?r, ?V, ?K
attr = { ?P => '*', ?R => '&', ?r => ' restrict', ?V => ' volatile', ?K => ' const' }[name[0]]
name = name[1..-1]
rl = ret.length
decode_tok[]
if ret
ret << attr
subs << ret[rl..-1]
end
else
if ret =~ /[(<]/ and ty = {
?v => 'void', ?w => 'wchar_t', ?b => 'bool', ?c => 'char', ?a => 'signed char',
?h => 'unsigned char', ?s => 'short', ?t => 'unsigned short', ?i => 'int',
?j => 'unsigned int', ?l => 'long', ?m => 'unsigned long', ?x => '__int64',
?y => 'unsigned __int64', ?n => '__int128', ?o => 'unsigned __int128', ?f => 'float',
?d => 'double', ?e => 'long double', ?g => '__float128', ?z => '...'
}[name[0]]
name = name[1..-1]
ret << ty
else
fu = name[0, 2]
name = name[2..-1]
if op = {
'nw' => ' new', 'na' => ' new[]', 'dl' => ' delete', 'da' => ' delete[]',
'ps' => '+', 'ng' => '-', 'ad' => '&', 'de' => '*', 'co' => '~', 'pl' => '+',
'mi' => '-', 'ml' => '*', 'dv' => '/', 'rm' => '%', 'an' => '&', 'or' => '|',
'eo' => '^', 'aS' => '=', 'pL' => '+=', 'mI' => '-=', 'mL' => '*=', 'dV' => '/=',
'rM' => '%=', 'aN' => '&=', 'oR' => '|=', 'eO' => '^=', 'ls' => '<<', 'rs' => '>>',
'lS' => '<<=', 'rS' => '>>=', 'eq' => '==', 'ne' => '!=', 'lt' => '<', 'gt' => '>',
'le' => '<=', 'ge' => '>=', 'nt' => '!', 'aa' => '&&', 'oo' => '||', 'pp' => '++',
'mm' => '--', 'cm' => ',', 'pm' => '->*', 'pt' => '->', 'cl' => '()', 'ix' => '[]',
'qu' => '?', 'st' => ' sizeof', 'sz' => ' sizeof', 'at' => ' alignof', 'az' => ' alignof'
}[fu]
ret << "operator#{op}"
elsif fu == 'cv'
ret << "cast<"
decode_tok[]
ret << ">" if ret
else
ret = nil
end
end
end
name ||= ''
}
decode_tok[]
subs.pop
if ret and name != ''
ret << '('
decode_tok[]
while ret and name != ''
ret << ', '
decode_tok[]
end
ret << ')' if ret
end
ret
end
# scans all the sections raw for a given regexp
# return/yields all the addresses matching
# if yield returns nil/false, do not include the addr in the final result
# sections are scanned MB by MB, so this should work (slowly) on 4GB sections (eg debugger VM)
# with addr_start/length, symbol-based section are skipped
def pattern_scan(pat, addr_start=nil, length=nil, chunksz=nil, margin=nil, &b)
chunksz ||= 4*1024*1024 # scan 4MB at a time
margin ||= 65536 # add this much bytes at each chunk to find /pat/ over chunk boundaries
pat = Regexp.new(Regexp.escape(pat)) if pat.kind_of? ::String
found = []
@sections.each { |sec_addr, e|
if addr_start
length ||= 0x1000_0000
begin
if sec_addr < addr_start
next if sec_addr+e.length <= addr_start
e = e[addr_start-sec_addr, e.length]
sec_addr = addr_start
end
if sec_addr+e.length > addr_start+length
next if sec_addr > addr_start+length
e = e[0, sec_addr+e.length-(addr_start+length)]
end
rescue
puts $!, $!.message, $!.backtrace if $DEBUG
# catch arithmetic error with symbol-based section
next
end
end
e.pattern_scan(pat, chunksz, margin) { |eo|
match_addr = sec_addr + eo
found << match_addr if not b or b.call(match_addr)
false
}
}
found
end
# returns/yields [addr, string] found using pattern_scan /[\x20-\x7e]/
def strings_scan(minlen=6, &b)
ret = []
nexto = 0
pattern_scan(/[\x20-\x7e]{#{minlen},}/m, nil, 1024) { |o|
if o - nexto > 0
next unless e = get_edata_at(o)
str = e.data[e.ptr, 1024][/[\x20-\x7e]{#{minlen},}/m]
ret << [o, str] if not b or b.call(o, str)
nexto = o + str.length
end
}
ret
end
# exports the addr => symbol map (see load_map)
def save_map
@prog_binding.map { |l, o|
type = di_at(o) ? 'c' : 'd' # XXX
o = o.to_s(16).rjust(8, '0') if o.kind_of? ::Integer
"#{o} #{type} #{l}"
}
end
# loads a map file (addr => symbol)
# off is an optionnal offset to add to every address found (for eg rebased binaries)
# understands:
# standard map files (eg linux-kernel.map: <addr> <type> <name>, e.g. 'c01001ba t setup_idt')
# ida map files (<sectionidx>:<sectionoffset> <name>)
# arg is either the map itself or the filename of the map (if it contains no newline)
def load_map(str, off=0)
str = File.read(str) rescue nil if not str.index("\n")
sks = @sections.keys.sort
seen = {}
str.each_line { |l|
case l.strip
when /^([0-9A-F]+)\s+(\w+)\s+(\w+)/i # kernel.map style
addr = $1.to_i(16)+off
set_label_at(addr, $3, false, !seen[addr])
seen[addr] = true
when /^([0-9A-F]+):([0-9A-F]+)\s+([a-z_]\w+)/i # IDA style
# we do not have section load order, let's just hope that the addresses are sorted (and sortable..)
# could check the 1st part of the file, with section sizes, but it is not very convenient
# the regexp is so that we skip the 1st part with section descriptions
# in the file, section 1 is the 1st section ; we have an additionnal section (exe header) which fixes the 0-index
# XXX this is PE-specific, TODO fix it for ELF (ida references sections, we reference segments...)
addr = sks[$1.to_i(16)] + $2.to_i(16) + off
set_label_at(addr, $3, false, !seen[addr])
seen[addr] = true
end
}
end
# saves the dasm state in a file
def save_file(file)
tmpfile = file + '.tmp'
File.open(tmpfile, 'wb') { |fd| save_io(fd) }
File.rename tmpfile, file
end
# saves the dasm state to an IO
def save_io(fd)
fd.puts 'Metasm.dasm'
if @program.filename and not @program.kind_of?(Shellcode)
t = @program.filename.to_s
fd.puts "binarypath #{t.length}", t
else
t = "#{@cpu.class.name.sub(/.*::/, '')} #{@cpu.size} #{@cpu.endianness}"
fd.puts "cpu #{t.length}", t
# XXX will be reloaded as a Shellcode with this CPU, but it may be a custom EXE
# do not output binarypath, we'll be loaded as a Shellcode, 'section' will suffice
end
@sections.each { |a, e|
# forget edata exports/relocs
# dump at most 16Mo per section
t = "#{Expression[a]} #{e.length}\n" +
[e.data[0, 2**24].to_str].pack('m*')
fd.puts "section #{t.length}", t
}
t = save_map.join("\n")
fd.puts "map #{t.length}", t
t = @decoded.map { |a, d|
next if not d.kind_of? DecodedInstruction
"#{Expression[a]},#{d.bin_length} #{d.instruction}#{" ; #{d.comment.join(' ')}" if d.comment}"
}.compact.sort.join("\n")
fd.puts "decoded #{t.length}", t
t = @comment.map { |a, c|
c.map { |l| l.chomp }.join("\n").split("\n").map { |lc| "#{Expression[a]} #{lc.chomp}" }
}.join("\n")
fd.puts "comment #{t.length}", t
bl = @decoded.values.map { |d|
d.block if d.kind_of? DecodedInstruction and d.block_head?
}.compact
t = bl.map { |b|
[Expression[b.address],
b.list.map { |d| Expression[d.address] }.join(','),
b.to_normal.to_a.map { |t_| Expression[t_] }.join(','),
b.to_subfuncret.to_a.map { |t_| Expression[t_] }.join(','),
b.to_indirect.to_a.map { |t_| Expression[t_] }.join(','),
b.from_normal.to_a.map { |t_| Expression[t_] }.join(','),
b.from_subfuncret.to_a.map { |t_| Expression[t_] }.join(','),
b.from_indirect.to_a.map { |t_| Expression[t_] }.join(','),
].join(';')
}.sort.join("\n")
fd.puts "blocks #{t.length}", t
t = @function.map { |a, f|
next if not @decoded[a]
[a, *f.return_address.to_a].map { |e| Expression[e] }.join(',')
}.compact.sort.join("\n")
# TODO binding ?
fd.puts "funcs #{t.length}", t
t = @xrefs.map { |a, x|
a = ':default' if a == :default
a = ':unknown' if a == Expression::Unknown
# XXX origin
case x
when nil
when Xref
[Expression[a], x.type, x.len, (Expression[x.origin] if x.origin)].join(',')
when Array
x.map { |x_| [Expression[a], x_.type, x_.len, (Expression[x_.origin] if x_.origin)].join(',') }
end
}.compact.join("\n")
fd.puts "xrefs #{t.length}", t
t = @c_parser.to_s
fd.puts "c #{t.length}", t
#t = bl.map { |b| b.backtracked_for }
#fd.puts "trace #{t.length}" , t
end
# loads a disassembler from a saved file
def self.load(str, &b)
d = new(nil, nil)
d.load(str, &b)
d
end
# loads the dasm state from a savefile content
# will yield unknown segments / binarypath notfound
def load(str)
raise 'Not a metasm save file' if str[0, 12].chomp != 'Metasm.dasm'
off = 12
pp = Preprocessor.new
app = AsmPreprocessor.new
while off < str.length
i = str.index("\n", off) || str.length
type, len = str[off..i].chomp.split
off = i+1
data = str[off, len.to_i]
off += len.to_i
case type
when nil, ''
when 'binarypath'
data = yield(type, data) if not File.exist? data and block_given?
reinitialize AutoExe.decode_file(data)
@program.disassembler = self
@program.init_disassembler
when 'cpu'
cpuname, size, endianness = data.split
cpu = Metasm.const_get(cpuname)
raise 'invalid cpu' if not cpu < CPU
cpu = cpu.new
cpu.size = size.to_i
cpu.endianness = endianness.to_sym
reinitialize Shellcode.new(cpu)
@program.disassembler = self
@program.init_disassembler
@sections.delete(0) # rm empty section at 0, other real 'section' follow
when 'section'
info = data[0, data.index("\n") || data.length]
data = data[info.length, data.length]
pp.feed!(info)
addr = Expression.parse(pp).reduce
len = Expression.parse(pp).reduce
edata = EncodedData.new(data.unpack('m*').first, :virtsize => len)
add_section(addr, edata)
when 'map'
load_map data
when 'decoded'
data.each_line { |l|
begin
next if l !~ /^([^,]*),(\d*) ([^;]*)(?:; (.*))?/
a, len, instr, cmt = $1, $2, $3, $4
a = Expression.parse(pp.feed!(a)).reduce
instr = @cpu.parse_instruction(app.feed!(instr))
di = DecodedInstruction.new(instr, a)
di.bin_length = len.to_i
di.add_comment cmt if cmt
@decoded[a] = di
rescue
puts "load: bad di #{l.inspect}" if $VERBOSE
end
}
when 'blocks'
data.each_line { |l|
bla = l.chomp.split(';').map { |sl| sl.split(',') }
begin
a = Expression.parse(pp.feed!(bla.shift[0])).reduce
b = InstructionBlock.new(a, get_section_at(a).to_a[0])
bla.shift.each { |e|
a = Expression.parse(pp.feed!(e)).reduce
b.add_di(@decoded[a])
}
bla.zip([:to_normal, :to_subfuncret, :to_indirect, :from_normal, :from_subfuncret, :from_indirect]).each { |l_, s|
b.send("#{s}=", l_.map { |e| Expression.parse(pp.feed!(e)).reduce }) if not l_.empty?
}
rescue
puts "load: bad block #{l.inspect}" if $VERBOSE
end
}
when 'funcs'
data.each_line { |l|
begin
a, *r = l.split(',').map { |e| Expression.parse(pp.feed!(e)).reduce }
@function[a] = DecodedFunction.new
@function[a].return_address = r if not r.empty?
@function[a].finalized = true
# TODO
rescue
puts "load: bad function #{l.inspect} #$!" if $VERBOSE
end
}
when 'comment'
data.each_line { |l|
begin
a, c = l.split(' ', 2)
a = Expression.parse(pp.feed!(a)).reduce
@comment[a] ||= []
@comment[a] |= [c]
rescue
puts "load: bad comment #{l.inspect} #$!" if $VERBOSE
end
}
when 'c'
begin
# TODO parse_invalid_c, split per function, whatever
parse_c('')
@c_parser.allow_bad_c = true
parse_c(data, 'savefile#c')
rescue
puts "load: bad C: #$!", $!.backtrace if $VERBOSE
end
@c_parser.readtok until @c_parser.eos? if @c_parser
when 'xrefs'
data.each_line { |l|
begin
a, t, len, o = l.chomp.split(',')
case a
when ':default'; a = :default
when ':unknown'; a = Expression::Unknown
else a = Expression.parse(pp.feed!(a)).reduce
end
t = (t.empty? ? nil : t.to_sym)
len = (len != '' ? len.to_i : nil)
o = (o.to_s != '' ? Expression.parse(pp.feed!(o)).reduce : nil) # :default/:unknown ?
add_xref(a, Xref.new(t, o, len))
rescue
puts "load: bad xref #{l.inspect} #$!" if $VERBOSE
end
}
#when 'trace'
else
if block_given?
yield(type, data)
else
puts "load: unsupported section #{type.inspect}" if $VERBOSE
end
end
end
end
# change the base address of the loaded binary
# better done early (before disassembling anything)
# returns the delta
def rebase(newaddr)
rebase_delta(newaddr - @sections.keys.min)
end
def rebase_delta(delta)
fix = lambda { |a|
case a
when Array
a.map! { |e| fix[e] }
when Hash
tmp = {}
a.each { |k, v| tmp[fix[k]] = v }
a.replace tmp
when Integer
a += delta
when BacktraceTrace
a.origin = fix[a.origin]
a.address = fix[a.address]
end
a
}
fix[@sections]
fix[@decoded]
fix[@xrefs]
fix[@function]
fix[@addrs_todo]
fix[@addrs_done]
fix[@comment]
@prog_binding.each_key { |k| @prog_binding[k] = fix[@prog_binding[k]] }
@old_prog_binding.each_key { |k| @old_prog_binding[k] = fix[@old_prog_binding[k]] }
@label_alias_cache = nil
@decoded.values.grep(DecodedInstruction).each { |di|
if di.block_head?
b = di.block
b.address += delta
fix[b.to_normal]
fix[b.to_subfuncret]
fix[b.to_indirect]
fix[b.from_normal]
fix[b.from_subfuncret]
fix[b.from_indirect]
fix[b.backtracked_for]
end
di.address = fix[di.address]
di.next_addr = fix[di.next_addr]
}
@function.each_value { |f|
f.return_address = fix[f.return_address]
fix[f.backtracked_for]
}
@xrefs.values.flatten.compact.each { |x| x.origin = fix[x.origin] }
delta
end
# dataflow method
# walks a function, starting at addr
# follows the usage of registers, computing the evolution from the value they had at start_addr
# whenever an instruction references the register (or anything derived from it),
# yield [di, used_register, reg_value, trace_state] where reg_value is the Expression holding the value of
# the register wrt the initial value at start_addr, and trace_state the value of all registers (reg_value
# not yet applied)
# reg_value may be nil if used_register is not modified by the function (eg call [eax])
# the yield return value is propagated, unless it is nil/false
# init_state is a hash { :reg => initial value }
def trace_function_register(start_addr, init_state)
function_walk(start_addr, init_state) { |args|
trace_state = args.last
case args.first
when :di
di = args[2]
update = {}
get_fwdemu_binding(di).each { |r, v|
if v.kind_of?(Expression) and v.externals.find { |e| trace_state[e] }
# XXX may mix old (from trace) and current (from v) registers
newv = v.bind(trace_state)
update[r] = yield(di, r, newv, trace_state)
elsif r.kind_of?(ExpressionType) and rr = r.externals.find { |e| trace_state[e] }
# reg dereferenced in a write (eg mov [esp], 42)
next if update.has_key?(rr) # already yielded
if yield(di, rr, trace_state[rr], trace_state) == false
update[rr] = false
end
elsif trace_state[r]
# started on mov reg, foo
next if di.address == start_addr
update[r] = false
end
}
# directly walk the instruction argument list for registers not appearing in the binding
@cpu.instr_args_memoryptr(di).each { |ind|
b = @cpu.instr_args_memoryptr_getbase(ind)
if b and b = b.symbolic and not update.has_key?(b)
yield(di, b, nil, trace_state)
end
}
@cpu.instr_args_regs(di).each { |r|
r = r.symbolic
if not update.has_key?(r)
yield(di, r, nil, trace_state)
end
}
update.each { |r, v|
trace_state = trace_state.dup
if v
# cannot follow non-registers, or we would have to emulate every single
# instruction (try following [esp+4] across a __stdcall..)
trace_state[r] = v if r.kind_of?(::Symbol)
else
trace_state.delete r
end
}
when :subfunc
faddr = args[1]
f = @function[faddr]
f = @function[f.backtrace_binding[:thunk]] if f and f.backtrace_binding[:thunk]
if f
binding = f.backtrace_binding
if binding.empty?
backtrace_update_function_binding(faddr)
binding = f.backtrace_binding
end
# XXX fwdemu_binding ?
binding.each { |r, v|
if v.externals.find { |e| trace_state[e] }
if r.kind_of?(::Symbol)
trace_state = trace_state.dup
trace_state[r] = Expression[v.bind(trace_state)].reduce
end
elsif trace_state[r]
trace_state = trace_state.dup
trace_state.delete r
end
}
end
when :merge
# when merging paths, keep the smallest common state subset
# XXX may have unexplored froms
conflicts = args[2]
trace_state = trace_state.dup
conflicts.each { |addr, st|
trace_state.delete_if { |k, v| st[k] != v }
}
end
trace_state = false if trace_state.empty?
trace_state
}
end
# define a register as a pointer to a structure
# rename all [reg+off] as [reg+struct.member] in current function
# also trace assignments of pointer members
def trace_update_reg_structptr(addr, reg, structname, structoff=0)
sname = soff = ctx = nil
expr_to_sname = lambda { |expr|
if not expr.kind_of?(Expression) or expr.op != :+
sname = nil
next
end
sname = expr.lexpr || expr.rexpr
soff = (expr.lexpr ? expr.rexpr : 0)
if soff.kind_of?(Expression)
# ignore index in ptr array
if soff.op == :* and soff.lexpr == @cpu.size/8
soff = 0
elsif soff.rexpr.kind_of?(Expression) and soff.rexpr.op == :* and soff.rexpr.lexpr == @cpu.size/8
soff = soff.lexpr
elsif soff.lexpr.kind_of?(Expression) and soff.lexpr.op == :* and soff.lexpr.lexpr == @cpu.size/8
soff = soff.rexpr
end
elsif soff.kind_of?(::Symbol)
# array with 1 byte elements / pre-scaled idx?
if not ctx[soff]
soff = 0
end
end
}
lastdi = nil
trace_function_register(addr, reg => Expression[structname, :+, structoff]) { |di, r, val, trace|
next if r.to_s =~ /flag/ # XXX maybe too ia32-specific?
ctx = trace
@cpu.instr_args_memoryptr(di).each { |ind|
# find the structure dereference in di
b = @cpu.instr_args_memoryptr_getbase(ind)
b = b.symbolic if b
next unless trace[b]
imm = @cpu.instr_args_memoryptr_getoffset(ind) || 0
# check expr has the form 'traced_struct_reg + off'
expr_to_sname[trace[b] + imm] # Expr#+ calls Expr#reduce
next unless sname.kind_of?(::String) and soff.kind_of?(::Integer)
next if not st = c_parser.toplevel.struct[sname] or not st.kind_of?(C::Union)
# ignore lea esi, [esi+0]
next if soff == 0 and not di.backtrace_binding.find { |k, v| v-k != 0 }
# TODO if trace[b] offset != 0, we had a lea reg, [struct+substruct_off], tweak str accordingly
# resolve struct + off into struct.membername
str = st.name.dup
mb = st.expand_member_offset(c_parser, soff, str)
# patch di
imm = imm.rexpr if imm.kind_of?(Expression) and not imm.lexpr and imm.rexpr.kind_of?(ExpressionString)
imm = imm.expr if imm.kind_of?(ExpressionString)
@cpu.instr_args_memoryptr_setoffset(ind, ExpressionString.new(imm, str, :structoff))
# check if the type is an enum/bitfield, patch instruction immediates
trace_update_reg_structptr_arg_enum(di, ind, mb, str) if mb
} if lastdi != di.address
lastdi = di.address
next Expression[structname, :+, structoff] if di.address == addr and r == reg
# check if we need to trace 'r' further
val = val.reduce_rec if val.kind_of?(Expression)
val = Expression[val] if val.kind_of?(::String)
case val
when Expression
# only trace trivial structptr+off expressions
expr_to_sname[val]
if sname.kind_of?(::String) and soff.kind_of?(::Integer)
Expression[sname, :+, soff]
end
when Indirection
# di is mov reg, [ptr+struct.offset]
# check if the target member is a pointer to a struct, if so, trace it
expr_to_sname[val.pointer.reduce]
next unless sname.kind_of?(::String) and soff.kind_of?(::Integer)
if st = c_parser.toplevel.struct[sname] and st.kind_of?(C::Union)
pt = st.expand_member_offset(c_parser, soff, '')
pt = pt.untypedef if pt
if pt.kind_of?(C::Pointer)
tt = pt.type.untypedef
stars = ''
while tt.kind_of?(C::Pointer)
stars << '*'
tt = tt.type.untypedef
end
if tt.kind_of?(C::Union) and tt.name
Expression[tt.name + stars]
end
end
elsif soff == 0 and sname[-1] == ?*
# XXX pointer to pointer to struct
# full C type support would be better, but harder to fit in an Expr
Expression[sname[0...-1]]
end
# in other cases, stop trace
end
}
end
# found a special member of a struct, check if we can apply
# bitfield/enum name to other constants in the di
def trace_update_reg_structptr_arg_enum(di, ind, mb, str)
if ename = mb.has_attribute_var('enum') and enum = c_parser.toplevel.struct[ename] and enum.kind_of?(C::Enum)
# handle enums: struct moo { int __attribute__((enum(bla))) fld; };
doit = lambda { |_di|
if num = _di.instruction.args.grep(Expression).first and num_i = num.reduce and num_i.kind_of?(::Integer)
# handle enum values on tagged structs
if enum.members and name = enum.members.index(num_i)
num.lexpr = nil
num.op = :+
num.rexpr = ExpressionString.new(Expression[num_i], name, :enum)
_di.add_comment "enum::#{ename}" if _di.address != di.address
end
end
}
doit[di]
# mov eax, [ptr+struct.enumfield] => trace eax
if reg = @cpu.instr_args_regs(di).find { |r| v = di.backtrace_binding[r.symbolic] and (v - ind.symbolic) == 0 }
reg = reg.symbolic
trace_function_register(di.address, reg => Expression[0]) { |_di, r, val, trace|
next if r != reg and val != Expression[reg]
doit[_di]
val
}
end
elsif mb.untypedef.kind_of?(C::Struct)
# handle bitfields
byte_off = 0
if str =~ /\+(\d+)$/
# test byte [bitfield+1], 0x1 => test dword [bitfield], 0x100
# XXX little-endian only
byte_off = $1.to_i
str[/\+\d+$/] = ''
end
cmt = str.split('.')[-2, 2].join('.') if str.count('.') > 1
doit = lambda { |_di, add|
if num = _di.instruction.args.grep(Expression).first and num_i = num.reduce and num_i.kind_of?(::Integer)
# TODO handle ~num_i
num_left = num_i << add
s_or = []
mb.untypedef.members.each { |mm|
if bo = mb.bitoffsetof(c_parser, mm)
boff, blen = bo
if mm.name && blen == 1 && ((num_left >> boff) & 1) > 0
s_or << mm.name
num_left &= ~(1 << boff)
end
end
}
if s_or.first
if num_left != 0
s_or << ('0x%X' % num_left)
end
s = s_or.join('|')
num.lexpr = nil
num.op = :+
num.rexpr = ExpressionString.new(Expression[num_i], s, :bitfield)
_di.add_comment cmt if _di.address != di.address
end
end
}
doit[di, byte_off*8]
if reg = @cpu.instr_args_regs(di).find { |r| v = di.backtrace_binding[r.symbolic] and (v - ind.symbolic) == 0 }
reg = reg.symbolic
trace_function_register(di.address, reg => Expression[0]) { |_di, r, val, trace|
if r.kind_of?(Expression) and r.op == :&
if r.lexpr == reg
# test al, 42
doit[_di, byte_off*8]
elsif r.lexpr.kind_of?(Expression) and r.lexpr.op == :>> and r.lexpr.lexpr == reg
# test ah, 42
doit[_di, byte_off*8+r.lexpr.rexpr]
end
end
next if r != reg and val != Expression[reg]
doit[_di, byte_off*8]
_di.address == di.address && r == reg ? Expression[0] : val
}
end
end
end
# change Expression display mode for current object o to display integers as char constants
def toggle_expr_char(o)
return if not o.kind_of?(Renderable)
tochars = lambda { |v|
if v.kind_of?(::Integer)
a = []
vv = v.abs
a << (vv & 0xff)
vv >>= 8
while vv > 0
a << (vv & 0xff)
vv >>= 8
end
if a.all? { |b| b < 0x7f }
s = a.pack('C*').inspect.gsub("'") { '\\\'' }[1...-1]
ExpressionString.new(v, (v > 0 ? "'#{s}'" : "-'#{s}'"), :char)
end
end
}
o.each_expr { |e|
if e.kind_of?(Expression)
if nr = tochars[e.rexpr]
e.rexpr = nr
elsif e.rexpr.kind_of?(ExpressionString) and e.rexpr.type == :char
e.rexpr = e.rexpr.expr
end
if nl = tochars[e.lexpr]
e.lexpr = nl
elsif e.lexpr.kind_of?(ExpressionString) and e.lexpr.type == :char
e.lexpr = e.lexpr.expr
end
end
}
end
def toggle_expr_dec(o)
return if not o.kind_of?(Renderable)
o.each_expr { |e|
if e.kind_of?(Expression)
if e.rexpr.kind_of?(::Integer)
e.rexpr = ExpressionString.new(Expression[e.rexpr], e.rexpr.to_s, :decimal)
elsif e.rexpr.kind_of?(ExpressionString) and e.rexpr.type == :decimal
e.rexpr = e.rexpr.reduce
end
if e.lexpr.kind_of?(::Integer)
e.lexpr = ExpressionString.new(Expression[e.lexpr], e.lexpr.to_s, :decimal)
elsif e.lexpr.kind_of?(ExpressionString) and e.lexpr.type == :decimal
e.lexpr = e.lexpr.reduce
end
end
}
end
# patch Expressions in current object to include label names when available
# XXX should we also create labels ?
def toggle_expr_offset(o)
return if not o.kind_of? Renderable
o.each_expr { |e|
next unless e.kind_of?(Expression)
if n = @prog_binding[e.lexpr]
e.lexpr = n
elsif e.lexpr.kind_of? ::Integer and n = get_label_at(e.lexpr)
add_xref(normalize(e.lexpr), Xref.new(:addr, o.address)) if o.respond_to? :address
e.lexpr = n
end
if n = @prog_binding[e.rexpr]
e.rexpr = n
elsif e.rexpr.kind_of? ::Integer and n = get_label_at(e.rexpr)
add_xref(normalize(e.rexpr), Xref.new(:addr, o.address)) if o.respond_to? :address
e.rexpr = n
end
}
end
# toggle all ExpressionStrings
def toggle_expr_str(o)
return if not o.kind_of?(Renderable)
o.each_expr { |e|
next unless e.kind_of?(ExpressionString)
e.hide_str = !e.hide_str
}
end
# call this function on a function entrypoint if the function is in fact a __noreturn
# will cut the to_subfuncret of callers
def fix_noreturn(o)
each_xref(o, :x) { |a|
a = normalize(a.origin)
next if not di = di_at(a) or not di.opcode.props[:saveip]
# XXX should check if caller also becomes __noreturn
di.block.each_to_subfuncret { |to|
next if not tdi = di_at(to) or not tdi.block.from_subfuncret
tdi.block.from_subfuncret.delete_if { |aa| normalize(aa) == di.address }
tdi.block.from_subfuncret = nil if tdi.block.from_subfuncret.empty?
}
di.block.to_subfuncret = nil
}
end
# find the addresses of calls calling the address, handles thunks
def call_sites(funcaddr)
find_call_site = proc { |a|
until not di = di_at(a)
if di.opcode.props[:saveip]
cs = di.address
break
end
if di.block.from_subfuncret.to_a.first
while di.block.from_subfuncret.to_a.length == 1
a = di.block.from_subfuncret[0]
break if not di_at(a)
a = @decoded[a].block.list.first.address
di = @decoded[a]
end
end
break if di.block.from_subfuncret.to_a.first
break if di.block.from_normal.to_a.length != 1
a = di.block.from_normal.first
end
cs
}
ret = []
each_xref(normalize(funcaddr), :x) { |a|
ret << find_call_site[a.origin]
}
ret.compact.uniq
end
# loads a disassembler plugin script
# this is simply a ruby script instance_eval() in the disassembler
# the filename argument is autocompleted with '.rb' suffix, and also
# searched for in the Metasmdir/samples/dasm-plugins subdirectory if not found in cwd
def load_plugin(plugin_filename)
if not File.exist?(plugin_filename)
if File.exist?(plugin_filename+'.rb')
plugin_filename += '.rb'
elsif defined? Metasmdir
# try autocomplete
pf = File.join(Metasmdir, 'samples', 'dasm-plugins', plugin_filename)
if File.exist? pf
plugin_filename = pf
elsif File.exist? pf + '.rb'
plugin_filename = pf + '.rb'
end
end
end
instance_eval File.read(plugin_filename)
end
# same as load_plugin, but hides the @gui attribute while loading, preventing the plugin do popup stuff
# this is useful when you want to load a plugin from another plugin to enhance the plugin's functionnality
# XXX this also prevents setting up kbd_callbacks etc..
def load_plugin_nogui(plugin_filename)
oldgui = gui
@gui = nil
load_plugin(plugin_filename)
ensure
@gui = oldgui
end
# compose two code/instruction's backtrace_binding
# assumes bd1 is followed by bd2 in the code flow
# eg inc edi + push edi =>
# { Ind[:esp, 4] => Expr[:edi + 1], :esp => Expr[:esp - 4], :edi => Expr[:edi + 1] }
# XXX if bd1 writes to memory with a pointer that is reused in bd2, this function has to
# revert the change made by bd2, which only works with simple ptr addition now
# XXX unhandled situations may be resolved using :unknown, or by returning incorrect values
def compose_bt_binding(bd1, bd2)
if bd1.kind_of? DecodedInstruction
bd1 = bd1.backtrace_binding ||= cpu.get_backtrace_binding(bd1)
end
if bd2.kind_of? DecodedInstruction
bd2 = bd2.backtrace_binding ||= cpu.get_backtrace_binding(bd2)
end
reduce = lambda { |e| Expression[Expression[e].reduce] }
bd = {}
bd2.each { |k, v|
bd[k] = reduce[v.bind(bd1)]
}
# for each pointer appearing in keys of bd1, we must infer from bd2 what final
# pointers should appear in bd
# eg 'mov [eax], 0 mov ebx, eax' => { [eax] <- 0, [ebx] <- 0, ebx <- eax }
bd1.each { |k, v|
if k.kind_of? Indirection
done = false
k.pointer.externals.each { |e|
# XXX this will break on nontrivial pointers or bd2
bd2.each { |k2, v2|
# we dont want to invert computation of flag_zero/carry etc (booh)
next if k2.to_s =~ /flag/
# discard indirection etc, result would be too complex / not useful
next if not Expression[v2].expr_externals.include? e
done = true
# try to reverse the computation made upon 'e'
# only simple addition handled here
ptr = reduce[k.pointer.bind(e => Expression[[k2, :-, v2], :+, e])]
# if bd2 does not rewrite e, duplicate the original pointer
if not bd2[e]
bd[k] ||= reduce[v]
# here we should not see 'e' in ptr anymore
ptr = Expression::Unknown if ptr.externals.include? e
else
# cant check if add reversion was successful..
end
bd[Indirection[reduce[ptr], k.len]] ||= reduce[v]
}
}
bd[k] ||= reduce[v] if not done
else
bd[k] ||= reduce[v]
end
}
bd
end
def gui_hilight_word_regexp(word)
@cpu.gui_hilight_word_regexp(word)
end
# return a C::AllocCStruct from c_parser
# TODO handle program.class::Header.to_c_struct
def decode_c_struct(structname, addr)
if c_parser and edata = get_edata_at(addr)
c_parser.decode_c_struct(structname, edata.data, edata.ptr)
end
end
def decode_c_ary(structname, addr, len)
if c_parser and edata = get_edata_at(addr)
c_parser.decode_c_ary(structname, len, edata.data, edata.ptr)
end
end
# find the function containing addr, and find & rename stack vars in it
def name_local_vars(addr)
if @cpu.respond_to?(:name_local_vars) and faddr = find_function_start(addr)
@function[faddr] ||= DecodedFunction.new # XXX
@cpu.name_local_vars(self, faddr)
end
end
end
end
|
# This file is part of Metasm, the Ruby assembly manipulation suite
# Copyright (C) 2006-2009 Yoann GUILLOT
#
# Licence is LGPL, see LICENCE in the top-level directory
require 'metasm/exe_format/main'
require 'metasm/encode'
require 'metasm/decode'
module Metasm
# WebAssembly
# leb integer encoding taken from dex.rb
class WasmFile < ExeFormat
MAGIC = "\0asm"
MAGIC.force_encoding('binary') if MAGIC.respond_to?(:force_encoding)
SECTION_NAME = { 1 => 'Type', 2 => 'Import', 3 => 'Function', 4 => 'Table',
5 => 'Memory', 6 => 'Global', 7 => 'Export', 8 => 'Start',
9 => 'Element', 10 => 'Code', 11 => 'Data' }
TYPE = { -1 => 'i32', -2 => 'i64', -3 => 'f32', -4 => 'f64',
-0x10 => 'anyfunc', -0x20 => 'func', -0x40 => 'block' }
EXTERNAL_KIND = { 0 => 'function', 1 => 'table', 2 => 'memory', 3 => 'global' }
# begin WTF
OPCODE_IMM_COUNT = Hash.new(0)
[2, 3, 4, 0xc, 0xd, 0x10].each { |op| OPCODE_IMM_COUNT[op] = 1 }
OPCODE_IMM_COUNT[0x11] = 2
(0x20..0x24).each { |op| OPCODE_IMM_COUNT[op] = 1 }
(0x28..0x3e).each { |op| OPCODE_IMM_COUNT[op] = 2 }
(0x3f..0x42).each { |op| OPCODE_IMM_COUNT[op] = 1 }
# 0x43 followed by uint32, 0x44 followed by uint64 (float constants)
# end WTF
class SerialStruct < Metasm::SerialStruct
# TODO move uleb/sleb to new_field for sizeof
new_int_field :u4, :uleb, :sleb
end
class Header < SerialStruct
mem :sig, 4, MAGIC
decode_hook { |exe, hdr| raise InvalidExeFormat, "E: invalid WasmFile signature #{hdr.sig.inspect}" if hdr.sig != MAGIC }
u4 :ver, 1
end
class Module < SerialStruct
uleb :id
fld_enum :id, SECTION_NAME
uleb :payload_len
attr_accessor :edata, :raw_offset, :name
def decode(exe)
@raw_offset = exe.encoded.ptr
super(exe)
@edata = exe.encoded[exe.encoded.ptr, @payload_len]
exe.encoded.ptr += @payload_len
end
end
attr_accessor :endianness
def encode_u4(val) Expression[val].encode(:u32, @endianness) end
def decode_u4(edata = @encoded) edata.decode_imm(:u32, @endianness) end
def sizeof_u4 ; 4 ; end
def encode_uleb(val, signed=false)
v = val
# force_more_bytes: ensure sign bit is not mistaken as value when signed (eg encode 0x40 as 0x80, 0x40 ; not 0x40 (decoded as -0x40))
force_more_bytes = (signed and v & 0x40 > 0)
out = Expression[v & 0x7f].encode(:u8, @endianness)
v >>= 7
while v > 0 or v < -1 or force_more_bytes
force_more_bytes = (signed and v & 0x40 > 0)
out = Expression[0x80 | (v & 0x7f)].encode(:u8, @endianness) << out
v >>= 7
end
out
end
def decode_uleb(ed = @encoded, signed=false)
v = s = 0
while s < 5*7
b = ed.read(1).unpack('C').first.to_i
v |= (b & 0x7f) << s
s += 7
break if (b&0x80) == 0
end
v = Expression.make_signed(v, s) if signed
v
end
def encode_sleb(val) encode_uleb(val, true) end
def decode_sleb(ed = @encoded) decode_uleb(ed, true) end
attr_accessor :header, :modules, :type, :import, :function_signature,
:table, :memory, :global, :export, :start_function_index,
:element, :function_body, :data
def initialize(endianness=:little)
@endianness = endianness
@encoded = EncodedData.new
super()
end
def decode_type(edata=@encoded)
form = decode_sleb(edata)
type = TYPE[form] || "unk_type_#{form}"
if type == 'func'
type = { :params => [], :ret => [] }
decode_uleb(edata).times {
type[:params] << decode_type(edata)
}
decode_uleb(edata).times {
type[:ret] << decode_type(edata)
}
end
type
end
def type_to_s(t)
return t unless t.kind_of?(::Hash)
t[:ret].map { |tt| type_to_s(tt) }.join(', ') << ' f(' << t[:params].map { |tt| type_to_s(tt) }.join(', ') << ')'
end
def decode_limits(edata=@encoded)
flags = decode_uleb(edata)
out = { :initial_size => decode_uleb(edata) }
out[:maximum] = decode_uleb(edata) if flags & 1
out
end
# wtf
# read wasm bytecode until reaching the end opcode
# return the byte offset
def read_code_until_end(m=nil)
if m
raw_offset = m.raw_offset + m.edata.ptr
edata = m.edata
else
edata = @encoded
end
# XXX uleb / u8 ?
while op = decode_uleb(edata)
case op
when 0xb
# end opcode
return raw_offset
when 0xe
# indirect branch wtf
decode_uleb(edata).times { decode_uleb(edata) }
decode_uleb(edata)
when 0x43
edata.read(4)
when 0x44
edata.read(8)
else
OPCODE_IMM_COUNT[op].times {
decode_uleb(edata)
}
end
end
raw_offset
end
def decode_header
@header = Header.decode(self)
@modules = []
end
def decode
decode_header
while @encoded.ptr < @encoded.length
@modules << Module.decode(self)
end
@modules.each { |m|
f = "decode_module_#{m.id.to_s.downcase}"
send(f, m) if respond_to?(f)
}
export.to_a.each { |e|
next if e[:kind] != 'function' # TODO resolve init_offset for globals etc?
off = function_body.to_a[e[:index]]
@encoded.add_export(new_label(e[:field]), off, true) if off
}
end
def decode_module_type(m)
@type = []
decode_uleb(m.edata).times {
@type << decode_type(m.edata)
}
end
def decode_module_import(m)
@import = []
decode_uleb(m.edata).times {
mod = m.edata.read(decode_uleb(m.edata))
fld = m.edata.read(decode_uleb(m.edata))
kind = decode_uleb(m.edata)
kind = { :kind => EXTERNAL_KIND[kind] || kind }
case kind[:kind]
when 'function'
kind[:type] = @type[decode_uleb(m.edata)] # XXX keep index only, in case @type is not yet known ?
when 'table'
kind[:type] = decode_type(m.edata)
kind[:limits] = decode_limits(m.edata)
when 'memory'
kind[:limits] = decode_limits(m.edata)
when 'global'
kind[:type] = decode_type(m.edata)
kind[:mutable] = decode_uleb(m.edata)
end
@import << { :module => mod, :field => fld, :kind => kind }
}
end
def decode_module_function(m)
@function_signature = []
decode_uleb(m.edata).times {
@function_signature << @type[decode_uleb(m.edata)]
}
end
def decode_module_table(m)
@table = []
decode_uleb(m.edata).times {
@table << { :type => decode_type(m.edata), :limits => decode_limits(m.edata) }
}
end
def decode_module_memory(m)
@memory = []
decode_uleb(m.edata).times {
@memory << { :limits => decode_limits(m.edata) }
}
end
def decode_module_global(m)
@global = []
decode_uleb(m.edata).times {
@global << { :type => decode_type(m.edata), :init_offset => read_code_until_end(m) }
@encoded.add_export new_label("global_#{@global.length-1}_init"), @global.last[:init_offset]
}
end
def decode_module_export(m)
@export = []
decode_uleb(m.edata).times {
flen = decode_uleb(m.edata)
fld = m.edata.read(flen)
kind = decode_uleb(m.edata)
kind = EXTERNAL_KIND[kind] || kind
index = decode_uleb(m.edata)
@export << { :field => fld, :kind => kind, :index => index }
}
end
def decode_module_start(m)
@start_function_index = decode_uleb(m.edata)
end
def decode_module_element(m)
@element = []
decode_uleb(m.edata).times {
seg = { :table_index => decode_uleb(m.edata),
:init_offset => read_code_until_end(m),
:elems => [] }
decode_uleb(m.edata).times {
seg[:elems] << decode_uleb(m.edata)
}
@element << seg
@encoded.add_export new_label("element_#{@element.length-1}_init_addr"), @element.last[:init_offset]
}
end
def decode_module_code(m)
@function_body = []
decode_uleb(m.edata).times {
local_vars = []
body_size = decode_uleb(m.edata) # size of local defs + bytecode (in bytes)
next_ptr = m.edata.ptr + body_size
decode_uleb(m.edata).times { # nr of local vars types
n_vars_of_this_type = decode_uleb(m.edata) # nr of local vars of this type
type = decode_type(m.edata) # actual type
n_vars_of_this_type.times {
local_vars << type
}
}
code_offset = m.raw_offset + m.edata.ptr # bytecode comes next
m.edata.ptr = next_ptr
@function_body << { :local_var => local_vars, :init_offset => code_offset }
@encoded.add_export new_label("function_#{@function_body.length-1}"), @function_body.last[:init_offset]
}
end
def decode_module_data(m)
@data = []
decode_uleb(m.edata).times {
@data << { :index => decode_uleb(m.edata),
:init_offset => read_code_until_end(m),
:data => m.edata.read(decode_uleb(m.edata)) }
@encoded.add_export new_label("data_#{@data.length-1}_init_addr"), @data.last[:init_offset]
}
end
def decode_module_0(m)
# id == 0 for not well-known modules
# the module name is encoded at start of payload (uleb name length + actual name)
m.name = m.edata.read(decode_uleb(m.edata))
f = "decode_module_0_#{m.name.downcase}"
send(f, m) if respond_to?(f)
end
def decode_module_0_name(m)
# TODO parse stored names of local variables etc
end
def cpu_from_headers
WebAsm.new(self)
end
def init_disassembler
dasm = super()
@function_body.each_with_index { |fb, i|
p = @function_signature[i] if function_signature
v = fb[:local_var].map { |lv| type_to_s(lv) }.join(' ; ')
dasm.comment[fb[:init_offset]] = ["proto: #{p || 'unknown'}", "vars: #{v}"]
}
dasm
end
def each_section
yield @encoded, 0
end
def get_default_entrypoints
global.to_a.map { |g| g[:init_offset] } +
element.to_a.map { |e| e[:init_offset] } +
data.to_a.map { |d| d[:init_offset] } +
function_body.to_a.map { |f| f[:init_offset] }
end
end
end
exe/wasm: fix raw offsets
# This file is part of Metasm, the Ruby assembly manipulation suite
# Copyright (C) 2006-2009 Yoann GUILLOT
#
# Licence is LGPL, see LICENCE in the top-level directory
require 'metasm/exe_format/main'
require 'metasm/encode'
require 'metasm/decode'
module Metasm
# WebAssembly
# leb integer encoding taken from dex.rb
class WasmFile < ExeFormat
MAGIC = "\0asm"
MAGIC.force_encoding('binary') if MAGIC.respond_to?(:force_encoding)
SECTION_NAME = { 1 => 'Type', 2 => 'Import', 3 => 'Function', 4 => 'Table',
5 => 'Memory', 6 => 'Global', 7 => 'Export', 8 => 'Start',
9 => 'Element', 10 => 'Code', 11 => 'Data' }
TYPE = { -1 => 'i32', -2 => 'i64', -3 => 'f32', -4 => 'f64',
-0x10 => 'anyfunc', -0x20 => 'func', -0x40 => 'block' }
EXTERNAL_KIND = { 0 => 'function', 1 => 'table', 2 => 'memory', 3 => 'global' }
# begin WTF
OPCODE_IMM_COUNT = Hash.new(0)
[2, 3, 4, 0xc, 0xd, 0x10].each { |op| OPCODE_IMM_COUNT[op] = 1 }
OPCODE_IMM_COUNT[0x11] = 2
(0x20..0x24).each { |op| OPCODE_IMM_COUNT[op] = 1 }
(0x28..0x3e).each { |op| OPCODE_IMM_COUNT[op] = 2 }
(0x3f..0x42).each { |op| OPCODE_IMM_COUNT[op] = 1 }
# 0x43 followed by uint32, 0x44 followed by uint64 (float constants)
# end WTF
class SerialStruct < Metasm::SerialStruct
# TODO move uleb/sleb to new_field for sizeof
new_int_field :u4, :uleb, :sleb
end
class Header < SerialStruct
mem :sig, 4, MAGIC
decode_hook { |exe, hdr| raise InvalidExeFormat, "E: invalid WasmFile signature #{hdr.sig.inspect}" if hdr.sig != MAGIC }
u4 :ver, 1
end
class Module < SerialStruct
uleb :id
fld_enum :id, SECTION_NAME
uleb :payload_len
attr_accessor :edata, :raw_offset, :name
def decode(exe)
super(exe)
@raw_offset = exe.encoded.ptr
@edata = exe.encoded[exe.encoded.ptr, @payload_len]
exe.encoded.ptr += @payload_len
end
end
attr_accessor :endianness
def encode_u4(val) Expression[val].encode(:u32, @endianness) end
def decode_u4(edata = @encoded) edata.decode_imm(:u32, @endianness) end
def sizeof_u4 ; 4 ; end
def encode_uleb(val, signed=false)
v = val
# force_more_bytes: ensure sign bit is not mistaken as value when signed (eg encode 0x40 as 0x80, 0x40 ; not 0x40 (decoded as -0x40))
force_more_bytes = (signed and v & 0x40 > 0)
out = Expression[v & 0x7f].encode(:u8, @endianness)
v >>= 7
while v > 0 or v < -1 or force_more_bytes
force_more_bytes = (signed and v & 0x40 > 0)
out = Expression[0x80 | (v & 0x7f)].encode(:u8, @endianness) << out
v >>= 7
end
out
end
def decode_uleb(ed = @encoded, signed=false)
v = s = 0
while s < 5*7
b = ed.read(1).unpack('C').first.to_i
v |= (b & 0x7f) << s
s += 7
break if (b&0x80) == 0
end
v = Expression.make_signed(v, s) if signed
v
end
def encode_sleb(val) encode_uleb(val, true) end
def decode_sleb(ed = @encoded) decode_uleb(ed, true) end
attr_accessor :header, :modules, :type, :import, :function_signature,
:table, :memory, :global, :export, :start_function_index,
:element, :function_body, :data
def initialize(endianness=:little)
@endianness = endianness
@encoded = EncodedData.new
super()
end
def decode_type(edata=@encoded)
form = decode_sleb(edata)
type = TYPE[form] || "unk_type_#{form}"
if type == 'func'
type = { :params => [], :ret => [] }
decode_uleb(edata).times {
type[:params] << decode_type(edata)
}
decode_uleb(edata).times {
type[:ret] << decode_type(edata)
}
end
type
end
def type_to_s(t)
return t unless t.kind_of?(::Hash)
t[:ret].map { |tt| type_to_s(tt) }.join(', ') << ' f(' << t[:params].map { |tt| type_to_s(tt) }.join(', ') << ')'
end
def decode_limits(edata=@encoded)
flags = decode_uleb(edata)
out = { :initial_size => decode_uleb(edata) }
out[:maximum] = decode_uleb(edata) if flags & 1
out
end
# wtf
# read wasm bytecode until reaching the end opcode
# return the byte offset
def read_code_until_end(m=nil)
if m
raw_offset = m.raw_offset + m.edata.ptr
edata = m.edata
else
edata = @encoded
end
# XXX uleb / u8 ?
while op = decode_uleb(edata)
case op
when 0xb
# end opcode
return raw_offset
when 0xe
# indirect branch wtf
decode_uleb(edata).times { decode_uleb(edata) }
decode_uleb(edata)
when 0x43
edata.read(4)
when 0x44
edata.read(8)
else
OPCODE_IMM_COUNT[op].times {
decode_uleb(edata)
}
end
end
raw_offset
end
def decode_header
@header = Header.decode(self)
@modules = []
end
def decode
decode_header
while @encoded.ptr < @encoded.length
@modules << Module.decode(self)
end
@modules.each { |m|
@encoded.add_export(new_label("module_#{m.id}"), m.raw_offset)
f = "decode_module_#{m.id.to_s.downcase}"
send(f, m) if respond_to?(f)
}
export.to_a.each { |e|
next if e[:kind] != 'function' # TODO resolve init_offset for globals etc?
next if not fb = function_body.to_a[e[:index]]
@encoded.add_export(new_label(e[:field]), fb[:init_offset], true)
}
end
def decode_module_type(m)
@type = []
decode_uleb(m.edata).times {
@type << decode_type(m.edata)
}
end
def decode_module_import(m)
@import = []
decode_uleb(m.edata).times {
mod = m.edata.read(decode_uleb(m.edata))
fld = m.edata.read(decode_uleb(m.edata))
kind = decode_uleb(m.edata)
kind = { :kind => EXTERNAL_KIND[kind] || kind }
case kind[:kind]
when 'function'
kind[:type] = @type[decode_uleb(m.edata)] # XXX keep index only, in case @type is not yet known ?
when 'table'
kind[:type] = decode_type(m.edata)
kind[:limits] = decode_limits(m.edata)
when 'memory'
kind[:limits] = decode_limits(m.edata)
when 'global'
kind[:type] = decode_type(m.edata)
kind[:mutable] = decode_uleb(m.edata)
end
@import << { :module => mod, :field => fld, :kind => kind }
}
end
def decode_module_function(m)
@function_signature = []
decode_uleb(m.edata).times {
@function_signature << @type[decode_uleb(m.edata)]
}
end
def decode_module_table(m)
@table = []
decode_uleb(m.edata).times {
@table << { :type => decode_type(m.edata), :limits => decode_limits(m.edata) }
}
end
def decode_module_memory(m)
@memory = []
decode_uleb(m.edata).times {
@memory << { :limits => decode_limits(m.edata) }
}
end
def decode_module_global(m)
@global = []
decode_uleb(m.edata).times {
@global << { :type => decode_type(m.edata), :init_offset => read_code_until_end(m) }
@encoded.add_export new_label("global_#{@global.length-1}_init"), @global.last[:init_offset]
}
end
def decode_module_export(m)
@export = []
decode_uleb(m.edata).times {
flen = decode_uleb(m.edata)
fld = m.edata.read(flen)
kind = decode_uleb(m.edata)
kind = EXTERNAL_KIND[kind] || kind
index = decode_uleb(m.edata)
@export << { :field => fld, :kind => kind, :index => index }
}
end
def decode_module_start(m)
@start_function_index = decode_uleb(m.edata)
end
def decode_module_element(m)
@element = []
decode_uleb(m.edata).times {
seg = { :table_index => decode_uleb(m.edata),
:init_offset => read_code_until_end(m),
:elems => [] }
decode_uleb(m.edata).times {
seg[:elems] << decode_uleb(m.edata)
}
@element << seg
@encoded.add_export new_label("element_#{@element.length-1}_init_addr"), @element.last[:init_offset]
}
end
def decode_module_code(m)
@function_body = []
decode_uleb(m.edata).times {
local_vars = []
body_size = decode_uleb(m.edata) # size of local defs + bytecode (in bytes)
next_ptr = m.edata.ptr + body_size
decode_uleb(m.edata).times { # nr of local vars types
n_vars_of_this_type = decode_uleb(m.edata) # nr of local vars of this type
type = decode_type(m.edata) # actual type
n_vars_of_this_type.times {
local_vars << type
}
}
code_offset = m.raw_offset + m.edata.ptr # bytecode comes next
m.edata.ptr = next_ptr
@function_body << { :local_var => local_vars, :init_offset => code_offset }
@encoded.add_export new_label("function_#{@function_body.length-1}"), @function_body.last[:init_offset]
}
end
def decode_module_data(m)
@data = []
decode_uleb(m.edata).times {
@data << { :index => decode_uleb(m.edata),
:init_offset => read_code_until_end(m),
:data => m.edata.read(decode_uleb(m.edata)) }
@encoded.add_export new_label("data_#{@data.length-1}_init_addr"), @data.last[:init_offset]
}
end
def decode_module_0(m)
# id == 0 for not well-known modules
# the module name is encoded at start of payload (uleb name length + actual name)
m.name = m.edata.read(decode_uleb(m.edata))
f = "decode_module_0_#{m.name.downcase}"
send(f, m) if respond_to?(f)
end
def decode_module_0_name(m)
# TODO parse stored names of local variables etc
end
def cpu_from_headers
WebAsm.new(self)
end
def init_disassembler
dasm = super()
@function_body.each_with_index { |fb, i|
p = @function_signature[i] if function_signature
v = fb[:local_var].map { |lv| type_to_s(lv) }.join(' ; ')
dasm.comment[fb[:init_offset]] = ["proto: #{p || 'unknown'}", "vars: #{v}"]
}
dasm
end
def each_section
yield @encoded, 0
end
def get_default_entrypoints
global.to_a.map { |g| g[:init_offset] } +
element.to_a.map { |e| e[:init_offset] } +
data.to_a.map { |d| d[:init_offset] } +
function_body.to_a.map { |f| f[:init_offset] }
end
end
end
|
Added Ruby implementation of fibonacci series
# Fibonacci recurrence relation:
# fib(0) = 0
# fib(1) = 1
# fib(n) = fib(n-1) + fib(n-2)
# This is the recursive version of the Fibonacci series
# It does not use tail-call optimisation, since that
# would complicate the basic algorithm
def fib(n)
if n < 2
return n
else
return fib(n-1) + fib(n-2)
end
# This is the tail-call optimizabel version
# of the fibonacci series.
#
# Note: Tail-call optimization is not
# supported in all Ruby implementations.
def fib_tco(n, a=0, b=1):
if n == 0
a
else
fib_tco_actual(n-1, b, a+b)
# This implemenation does not rely on recursion,
# which makes it optimal for large values of n,
# since you can't cause a stack overflow.
# The only limit you have is the maximum int value you can have.
def fib_loop(n):
a, b = 0, 1
while n != 0
a, b = b, a+b
n -= 1
end
# No return neccessary, since Ruby
# returns the last evaluated expression
a |
class KdeExtraCmakeModules < Formula
desc "Extra modules and scripts for CMake"
homepage "https://api.kde.org/frameworks/extra-cmake-modules/html/index.html"
url "https://download.kde.org/stable/frameworks/5.79/extra-cmake-modules-5.79.0.tar.xz"
sha256 "b29602db99c566d88fa92106abe114bd57b7ffc6ca20773426f896ffde68bed8"
license all_of: ["BSD-2-Clause", "BSD-3-Clause", "MIT"]
revision 1
head "https://invent.kde.org/frameworks/extra-cmake-modules.git"
# We check the tags from the `head` repository because the latest stable
# version doesn't seem to be easily available elsewhere.
livecheck do
url :head
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "6ead5fff1239a71f31c0bf7f19d54b0132f4c67dacedecb13d4abe758e5df1f9"
sha256 cellar: :any_skip_relocation, big_sur: "f83bd2fccc4e8bf34dfe94c34f13adebb3dcba9baa1d1b2e8b0b7b66ce688567"
sha256 cellar: :any_skip_relocation, catalina: "26b07f9160defd8fccdc26089004aa69a1e6317f5803037523c5815add954216"
sha256 cellar: :any_skip_relocation, mojave: "5a87fd54c8bbf969207f49fac0855d768ad061f38cf040080286c70680a9af7b"
end
depends_on "cmake" => [:build, :test]
depends_on "qt@5" => :build
depends_on "sphinx-doc" => :build
def install
args = std_cmake_args
args << "-DBUILD_HTML_DOCS=ON"
args << "-DBUILD_MAN_DOCS=ON"
args << "-DBUILD_QTHELP_DOCS=ON"
args << "-DBUILD_TESTING=OFF"
system "cmake", ".", *args
system "make", "install"
end
test do
(testpath/"CMakeLists.txt").write("find_package(ECM REQUIRED)")
system "cmake", ".", "-Wno-dev"
expected="ECM_DIR:PATH=#{HOMEBREW_PREFIX}/share/ECM/cmake"
assert_match expected, File.read(testpath/"CMakeCache.txt")
end
end
kde-extra-cmake-modules: update 5.79.0_1 bottle.
class KdeExtraCmakeModules < Formula
desc "Extra modules and scripts for CMake"
homepage "https://api.kde.org/frameworks/extra-cmake-modules/html/index.html"
url "https://download.kde.org/stable/frameworks/5.79/extra-cmake-modules-5.79.0.tar.xz"
sha256 "b29602db99c566d88fa92106abe114bd57b7ffc6ca20773426f896ffde68bed8"
license all_of: ["BSD-2-Clause", "BSD-3-Clause", "MIT"]
revision 1
head "https://invent.kde.org/frameworks/extra-cmake-modules.git"
# We check the tags from the `head` repository because the latest stable
# version doesn't seem to be easily available elsewhere.
livecheck do
url :head
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "b037f9a37b5602092d85b8af767ad3f46d970c295aff9bf4b55ca21ecdfd11c0"
sha256 cellar: :any_skip_relocation, big_sur: "fc8d6944b8c8900f3fb464cc8f4589bec834d6b7ab9adbce8b380dcf8d7bc00b"
sha256 cellar: :any_skip_relocation, catalina: "6461611d4f810ef660c4554eadb4f708fe1f952458d2cd374a8200e36895f1cc"
sha256 cellar: :any_skip_relocation, mojave: "daccf07232ea1f687e2f20b0f86823f7ebf421da92f1f4e7608c5197f556ead4"
end
depends_on "cmake" => [:build, :test]
depends_on "qt@5" => :build
depends_on "sphinx-doc" => :build
def install
args = std_cmake_args
args << "-DBUILD_HTML_DOCS=ON"
args << "-DBUILD_MAN_DOCS=ON"
args << "-DBUILD_QTHELP_DOCS=ON"
args << "-DBUILD_TESTING=OFF"
system "cmake", ".", *args
system "make", "install"
end
test do
(testpath/"CMakeLists.txt").write("find_package(ECM REQUIRED)")
system "cmake", ".", "-Wno-dev"
expected="ECM_DIR:PATH=#{HOMEBREW_PREFIX}/share/ECM/cmake"
assert_match expected, File.read(testpath/"CMakeCache.txt")
end
end
|
Add new formula to support mongodb via the legacy driver. (#389)
Add new formula to support mongodb via the legacy driver.
class MongoCxxDriverLegacy < Formula
desc "C++ driver for MongoDB"
homepage "https://github.com/mongodb/mongo-cxx-driver"
url "https://github.com/mongodb/mongo-cxx-driver/archive/legacy-1.1.3.tar.gz"
sha256 "50304162f706c2c73e04f200cdac767cb2c55d47cf724811cbfc8bb34a0fd6bc"
bottle do
cellar :any
sha256 "9ce364cb4545f7cb4453ca6adcac2d381dd724cc3df4bcddc87921d2481b586e" => :high_sierra
sha256 "5a16f976b70d1f99247e02276debb9098a42d1a92693e8447cbb62cf4e8e2f41" => :sierra
sha256 "228a9e3cc0f097b54e9464422528abd89a95c485305a4cc951f9ec0426cdfbbd" => :el_capitan
end
keg_only "Newer driver in homebrew core"
needs :cxx11
patch :DATA
depends_on "scons" => :build
depends_on "boost"
resource "connect_test" do
url "https://raw.githubusercontent.com/mongodb/mongo-cxx-driver/legacy/src/mongo/client/examples/tutorial.cpp"
sha256 "39ad991cf07722312398cd9dbfefb2b8df00729c2224bdf0b644475b95a240dc"
end
resource "bson_test" do
url "https://raw.githubusercontent.com/mongodb/mongo-cxx-driver/legacy/src/mongo/bson/bsondemo/bsondemo.cpp"
sha256 "299c87b57f11e3ff9ac0fd2e8ac3f8eb174b64c673951199831a0ba176292164"
end
def install
args = [
"--prefix=#{prefix}",
"--c++11=on",
"--libc++",
"--osx-version-min=10.9",
"--extrapath=#{Formula["boost"].opt_prefix}",
"install"
]
scons(*args)
end
test do
resource("connect_test").stage do
system ENV.cxx, "-o", "test", "tutorial.cpp",
"-I#{include}/",
"-L#{lib}", "-lmongoclient", "-pthread", "-lboost_thread-mt", "-lboost_system", "-lboost_regex", "-std=c++11", "-stdlib=libc++"
assert_match "couldn't connect : couldn't connect to server 0.0.0.0:27017 (0.0.0.0), address resolved to 0.0.0.0",
shell_output("./test mongodb://0.0.0.0 2>&1", 1)
end
resource("bson_test").stage do
system ENV.cxx, "-o", "test", "bsondemo.cpp",
"-I#{include}",
"-L#{lib}", "-lmongoclient", "-lboost_thread-mt", "-lboost_system", "-lboost_regex", "-std=c++11", "-stdlib=libc++"
system "./test"
end
end
end
__END__
diff --git a/src/mongo/client/command_writer.h b/src/mongo/client/command_writer.h
index 09cd752..6d60721 100644
--- a/src/mongo/client/command_writer.h
+++ b/src/mongo/client/command_writer.h
@@ -17,6 +17,11 @@
#include "mongo/client/dbclient_writer.h"
+#include <boost/version.hpp>
+#if BOOST_VERSION >= 106700
+#include <boost/next_prior.hpp>
+#endif
+
namespace mongo {
class DBClientBase;
--
2.17.0
diff --git a/src/mongo/client/wire_protocol_writer.h b/src/mongo/client/wire_protocol_writer.h
index 10cc935..72bb191 100644
--- a/src/mongo/client/wire_protocol_writer.h
+++ b/src/mongo/client/wire_protocol_writer.h
@@ -16,6 +16,10 @@
#pragma once
#include "mongo/client/dbclient_writer.h"
+#include <boost/version.hpp>
+#if BOOST_VERSION >= 106700
+#include <boost/next_prior.hpp>
+#endif
namespace mongo {
--
2.17.0
|
class OpenlibertyWebprofile9 < Formula
desc "Lightweight open framework for Java (Jakarta EE Web Profile 9)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/22.0.0.9/openliberty-webProfile9-22.0.0.9.zip"
sha256 "a12bf09ff84d69be92bfda6eb54efde7121dbd0583681256e77892681625459f"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "5d1f0ee603d5151fa439fefcf37a736c89970322ebaf019235322ea85670ef68"
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-webprofile9").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Jakarta EE Web Profile 9 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-webprofile9", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-webprofile9", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>webProfile-9.1</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
openliberty-webprofile9: update 22.0.0.9 bottle.
class OpenlibertyWebprofile9 < Formula
desc "Lightweight open framework for Java (Jakarta EE Web Profile 9)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/22.0.0.9/openliberty-webProfile9-22.0.0.9.zip"
sha256 "a12bf09ff84d69be92bfda6eb54efde7121dbd0583681256e77892681625459f"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "c0f422d95f23ee748e1cc6ef4b122aa8310ac1a384a36c3fd2ae667bf8518294"
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-webprofile9").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Jakarta EE Web Profile 9 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-webprofile9", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-webprofile9", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>webProfile-9.1</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
|
rootdir = File.expand_path(File.dirname(__FILE__))
require "#{rootdir}/lib/prawn/emoji/version"
Gem::Specification.new do |spec|
spec.name = 'prawn-emoji'
spec.version = Prawn::Emoji::VERSION
spec.author = 'Katsuya HIDAKA'
spec.email = 'hidakatsuya@gmail.com'
spec.summary = 'Adds Emoji support to Prawn'
spec.description = 'Prawn::Emoji is an extention that adds Emoji support to Prawn'
spec.homepage = 'https://github.com/hidakatsuya/prawn-emoji'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.4'
spec.files = `git ls-files`.split("\n")
spec.test_files = `git ls-files -- {test}/*`.split("\n")
spec.require_path = 'lib'
spec.add_runtime_dependency 'prawn', '~> 2.2.0'
spec.add_runtime_dependency 'unicode-emoji', '~> 2.2.0'
spec.add_development_dependency 'bundler', '>= 1.0.0'
spec.add_development_dependency 'rake', '>= 0'
spec.add_development_dependency 'minitest', '>= 5.12.2'
spec.add_development_dependency 'rr', '>= 0'
spec.add_development_dependency 'pdf-inspector', '>= 1.2.0'
spec.add_development_dependency 'rubyzip', '>= 1.0.0'
end
Update to unicode-emoji 2.3.1
rootdir = File.expand_path(File.dirname(__FILE__))
require "#{rootdir}/lib/prawn/emoji/version"
Gem::Specification.new do |spec|
spec.name = 'prawn-emoji'
spec.version = Prawn::Emoji::VERSION
spec.author = 'Katsuya HIDAKA'
spec.email = 'hidakatsuya@gmail.com'
spec.summary = 'Adds Emoji support to Prawn'
spec.description = 'Prawn::Emoji is an extention that adds Emoji support to Prawn'
spec.homepage = 'https://github.com/hidakatsuya/prawn-emoji'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.4'
spec.files = `git ls-files`.split("\n")
spec.test_files = `git ls-files -- {test}/*`.split("\n")
spec.require_path = 'lib'
spec.add_runtime_dependency 'prawn', '~> 2.2.0'
spec.add_runtime_dependency 'unicode-emoji', '~> 2.3.1'
spec.add_development_dependency 'bundler', '>= 1.0.0'
spec.add_development_dependency 'rake', '>= 0'
spec.add_development_dependency 'minitest', '>= 5.12.2'
spec.add_development_dependency 'rr', '>= 0'
spec.add_development_dependency 'pdf-inspector', '>= 1.2.0'
spec.add_development_dependency 'rubyzip', '>= 1.0.0'
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'badcards/version'
Gem::Specification.new do |spec|
spec.name = "badcards"
spec.version = Badcards::VERSION
spec.authors = ["Benjamin Hsieh, Ben's Potatoes"]
spec.email = ["benspotatoes@gmail.com"]
spec.summary = %q{Ruby library for playing cards including BaDEmporium images.}
spec.description = %q{Includes cards, decks (of multiple sizes), hands, and drawing (of multiple cards).}
spec.homepage = "http://github.com/sicophrenic/badcards"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "coveralls"
end
Remove open-ended, pessimistic gemspec dependency
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'badcards/version'
Gem::Specification.new do |spec|
spec.name = "badcards"
spec.version = Badcards::VERSION
spec.authors = ["Benjamin Hsieh, Ben's Potatoes"]
spec.email = ["benspotatoes@gmail.com"]
spec.summary = %q{Ruby library for playing cards including BaDEmporium images.}
spec.description = %q{Includes cards, decks (of multiple sizes), hands, and drawing (of multiple cards).}
spec.homepage = "http://github.com/sicophrenic/badcards"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake", "~> 10.1.0", ">= 10.1.0"
spec.add_development_dependency "rspec", "~> 2.14.1", ">= 2.14.1"
spec.add_development_dependency "coveralls", "~> 0.7.0", ">= 0.7.0"
end
|
# Encoding: utf-8
require 'friendly_id'
require 'refinery/core/base_model'
require 'refinery/pages/url'
require 'refinery/pages/finder'
module Refinery
class Page < Core::BaseModel
extend FriendlyId
translates :title, :menu_title, :custom_slug, :slug, :include => :seo_meta
attribute :title
attribute :menu_title
attribute :custom_slug
attribute :slug
after_save { translations.collect(&:save) }
class Translation
is_seo_meta
def self.seo_fields
::SeoMeta.attributes.keys.map{ |a| [a, :"#{a}="]}.flatten
end
end
class FriendlyIdOptions
def self.options
# Docs for friendly_id https://github.com/norman/friendly_id
friendly_id_options = {
use: [:reserved],
reserved_words: Refinery::Pages.friendly_id_reserved_words
}
if ::Refinery::Pages.scope_slug_by_parent
friendly_id_options[:use] << :scoped
friendly_id_options.merge!(scope: :parent)
end
friendly_id_options[:use] << :globalize
friendly_id_options
end
end
# If title changes tell friendly_id to regenerate slug when saving record
def should_generate_new_friendly_id?
changes.keys.include?("title") || changes.keys.include?("custom_slug")
end
# Delegate SEO Attributes to globalize translation
delegate(*(Translation.seo_fields << {:to => :translation}))
validates :title, :presence => true
validates :custom_slug, :uniqueness => true, :allow_blank => true
# Docs for acts_as_nested_set https://github.com/collectiveidea/awesome_nested_set
# rather than :delete_all we want :destroy
acts_as_nested_set counter_cache: :children_count, dependent: :destroy, touch: true
friendly_id :custom_slug_or_title, FriendlyIdOptions.options
has_many :parts, -> {
scope = order('position ASC')
scope = scope.includes(:translations) if ::Refinery::PagePart.respond_to?(:translation_class)
scope
}, :foreign_key => :refinery_page_id,
:class_name => '::Refinery::PagePart',
:inverse_of => :page,
:dependent => :destroy
accepts_nested_attributes_for :parts, :allow_destroy => true
before_destroy :deletable?
after_save :reposition_parts!
after_save { update_all_descendants if descendants.any? }
after_move { update_all_descendants if descendants.any? }
class << self
# Live pages are 'allowed' to be shown in the frontend of your website.
# By default, this is all pages that are not set as 'draft'.
def live
where(:draft => false)
end
# Find page by path, checking for scoping rules
def find_by_path(path)
Pages::Finder.by_path(path)
end
# Helps to resolve the situation where you have a path and an id
# and if the path is unfriendly then a different finder method is required
# than find_by_path.
def find_by_path_or_id(path, id)
Pages::Finder.by_path_or_id(path, id)
end
# Helps to resolve the situation where you have a path and an id
# and if the path is unfriendly then a different finder method is required
# than find_by_path.
#
# raise ActiveRecord::RecordNotFound if not found.
def find_by_path_or_id!(path, id)
page = find_by_path_or_id(path, id)
raise ActiveRecord::RecordNotFound unless page
page
end
# Finds pages by their title. This method is necessary because pages
# are translated which means the title attribute does not exist on the
# pages table thus requiring us to find the attribute on the translations table
# and then join to the pages table again to return the associated record.
def by_title(title)
Pages::Finder.by_title(title)
end
# Finds pages by their slug. This method is necessary because pages
# are translated which means the slug attribute does not exist on the
# pages table thus requiring us to find the attribute on the translations table
# and then join to the pages table again to return the associated record.
def by_slug(slug, conditions = {})
Pages::Finder.by_slug(slug, conditions)
end
# Shows all pages with :show_in_menu set to true, but it also
# rejects any page that has not been translated to the current locale.
# This works using a query against the translated content first and then
# using all of the page_ids we further filter against this model's table.
def in_menu
where(:show_in_menu => true).with_globalize
end
# An optimised scope containing only live pages ordered for display in a menu.
def fast_menu
live.in_menu.order(arel_table[:lft]).includes(:parent, :translations)
end
# Wrap up the logic of finding the pages based on the translations table.
def with_globalize(conditions = {})
Pages::Finder.with_globalize(conditions)
end
# Returns how many pages per page should there be when paginating pages
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.pages_per_admin_index
end
def rebuild!
super
nullify_duplicate_slugs_under_the_same_parent!
end
protected
def nullify_duplicate_slugs_under_the_same_parent!
t_slug = translation_class.arel_table[:slug]
joins(:translations).group(:locale, :parent_id, t_slug).having(t_slug.count.gt(1)).count.
each do |(locale, parent_id, slug), count|
by_slug(slug, :locale => locale).where(:parent_id => parent_id).drop(1).each do |page|
page.slug = nil # kill the duplicate slug
page.save # regenerate the slug
end
end
end
end
def translated_to_default_locale?
persisted? && translations.any?{ |t| t.locale == Refinery::I18n.default_frontend_locale}
end
# The canonical page for this particular page.
# Consists of:
# * The current locale's translated slug
def canonical
Globalize.with_locale(::Refinery::I18n.current_frontend_locale) { url }
end
# The canonical slug for this particular page.
# This is the slug for the current frontend locale.
def canonical_slug
Globalize.with_locale(::Refinery::I18n.current_frontend_locale) { slug }
end
# Returns in cascading order: custom_slug or menu_title or title depending on
# which attribute is first found to be present for this page.
def custom_slug_or_title
(Refinery::Pages.use_custom_slugs && custom_slug.presence) ||
menu_title.presence || title.presence
end
# Am I allowed to delete this page?
# If a link_url is set we don't want to break the link so we don't allow them to delete
# If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages
def deletable?
deletable && link_url.blank? && menu_match.blank?
end
# Repositions the child page_parts that belong to this page.
# This ensures that they are in the correct 0,1,2,3,4... etc order.
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_columns position: index
end
end
# Before destroying a page we check to see if it's a deletable page or not
# Refinery system pages are not deletable.
def destroy
return super if deletable?
puts_destroy_help
false
end
# If you want to destroy a page that is set to be not deletable this is the way to do it.
def destroy!
self.update_attributes(:menu_match => nil, :link_url => nil, :deletable => true)
self.destroy
end
# Returns the full path to this page.
# This automatically prints out this page title and all parent page titles.
# The result is joined by the path_separator argument.
def path(path_separator: ' - ', ancestors_first: true)
return title if root?
chain = ancestors_first ? self_and_ancestors : self_and_ancestors.reverse
chain.map(&:title).join(path_separator)
end
def url
Pages::Url.build(self)
end
def nested_url
Globalize.with_locale(slug_locale) do
if ::Refinery::Pages.scope_slug_by_parent && !root?
self_and_ancestors.includes(:translations).map(&:to_param)
else
[to_param.to_s]
end
end
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
alias_method :uncached_nested_url, :nested_url
# Returns the string version of nested_url, i.e., the path that should be
# generated by the router
def nested_path
['', nested_url].join('/')
end
# Returns true if this page is "published"
def live?
!draft?
end
# Return true if this page can be shown in the navigation.
# If it's a draft or is set to not show in the menu it will return false.
def in_menu?
live? && show_in_menu?
end
def not_in_menu?
!in_menu?
end
# Returns all visible sibling pages that can be rendered for the menu
def shown_siblings
siblings.reject(&:not_in_menu?)
end
def to_refinery_menu_item
{
:id => id,
:lft => lft,
:depth => depth,
:menu_match => menu_match,
:parent_id => parent_id,
:rgt => rgt,
:title => menu_title.presence || title.presence,
:type => self.class.name,
:url => url
}
end
# Accessor method to get a page part from a page.
# Example:
#
# ::Refinery::Page.first.content_for(:body)
#
# Will return the body page part of the first page.
def content_for(part_slug)
part_with_slug(part_slug).try(:body)
end
# Accessor method to test whether a page part
# exists and has content for this page.
# Example:
#
# ::Refinery::Page.first.content_for?(:body)
#
# Will return true if the page has a body page part and it is not blank.
def content_for?(part_slug)
content_for(part_slug).present?
end
# Accessor method to get a page part object from a page.
# Example:
#
# ::Refinery::Page.first.part_with_slug(:body)
#
# Will return the Refinery::PagePart object with that slug using the first page.
def part_with_slug(part_slug)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.slug_matches?(part_slug)
end
end
# Protects generated slugs from title if they are in the list of reserved words
# This applies mostly to plugin-generated pages.
# This only kicks in when Refinery::Pages.marketable_urls is enabled.
# Also check for global scoping, and if enabled, allow slashes in slug.
#
# Returns the sluggified string
def normalize_friendly_id(slug_string)
FriendlyIdPath.normalize_friendly_id(slug_string)
end
private
class FriendlyIdPath
def self.normalize_friendly_id_path(slug_string)
# Remove leading and trailing slashes, but allow internal
slug_string
.sub(%r{^/*}, '')
.sub(%r{/*$}, '')
.split('/')
.select(&:present?)
.map { |slug| self.normalize_friendly_id(slug) }.join('/')
end
def self.normalize_friendly_id(slug_string)
# If we are scoping by parent, no slashes are allowed. Otherwise, slug is
# potentially a custom slug that contains a custom route to the page.
if !Pages.scope_slug_by_parent && slug_string.include?('/')
self.normalize_friendly_id_path(slug_string)
else
self.protected_slug_string(slug_string)
end
end
def self.protected_slug_string(slug_string)
sluggified = slug_string.to_slug.normalize!
if Pages.marketable_urls && Refinery::Pages.friendly_id_reserved_words.include?(sluggified)
sluggified << "-page"
end
sluggified
end
end
def puts_destroy_help
puts "This page is not deletable. Please use .destroy! if you really want it deleted "
puts "unset .link_url," if link_url.present?
puts "unset .menu_match," if menu_match.present?
puts "set .deletable to true" unless deletable
end
def slug_locale
return Globalize.locale if translation_for(Globalize.locale, false).try(:slug).present?
if translations.empty? || translation_for(Refinery::I18n.default_frontend_locale, false).present?
Refinery::I18n.default_frontend_locale
else
translations.first.locale
end
end
def update_all_descendants
self.descendants.update_all(updated_at: DateTime.now)
end
end
end
Bugfix Refinery::Page#slug_locale : Add .try(:slug)
This will fix the friendly slug in the path of a page with only one locale when the partial rendering is cached
# Encoding: utf-8
require 'friendly_id'
require 'refinery/core/base_model'
require 'refinery/pages/url'
require 'refinery/pages/finder'
module Refinery
class Page < Core::BaseModel
extend FriendlyId
translates :title, :menu_title, :custom_slug, :slug, :include => :seo_meta
attribute :title
attribute :menu_title
attribute :custom_slug
attribute :slug
after_save { translations.collect(&:save) }
class Translation
is_seo_meta
def self.seo_fields
::SeoMeta.attributes.keys.map{ |a| [a, :"#{a}="]}.flatten
end
end
class FriendlyIdOptions
def self.options
# Docs for friendly_id https://github.com/norman/friendly_id
friendly_id_options = {
use: [:reserved],
reserved_words: Refinery::Pages.friendly_id_reserved_words
}
if ::Refinery::Pages.scope_slug_by_parent
friendly_id_options[:use] << :scoped
friendly_id_options.merge!(scope: :parent)
end
friendly_id_options[:use] << :globalize
friendly_id_options
end
end
# If title changes tell friendly_id to regenerate slug when saving record
def should_generate_new_friendly_id?
changes.keys.include?("title") || changes.keys.include?("custom_slug")
end
# Delegate SEO Attributes to globalize translation
delegate(*(Translation.seo_fields << {:to => :translation}))
validates :title, :presence => true
validates :custom_slug, :uniqueness => true, :allow_blank => true
# Docs for acts_as_nested_set https://github.com/collectiveidea/awesome_nested_set
# rather than :delete_all we want :destroy
acts_as_nested_set counter_cache: :children_count, dependent: :destroy, touch: true
friendly_id :custom_slug_or_title, FriendlyIdOptions.options
has_many :parts, -> {
scope = order('position ASC')
scope = scope.includes(:translations) if ::Refinery::PagePart.respond_to?(:translation_class)
scope
}, :foreign_key => :refinery_page_id,
:class_name => '::Refinery::PagePart',
:inverse_of => :page,
:dependent => :destroy
accepts_nested_attributes_for :parts, :allow_destroy => true
before_destroy :deletable?
after_save :reposition_parts!
after_save { update_all_descendants if descendants.any? }
after_move { update_all_descendants if descendants.any? }
class << self
# Live pages are 'allowed' to be shown in the frontend of your website.
# By default, this is all pages that are not set as 'draft'.
def live
where(:draft => false)
end
# Find page by path, checking for scoping rules
def find_by_path(path)
Pages::Finder.by_path(path)
end
# Helps to resolve the situation where you have a path and an id
# and if the path is unfriendly then a different finder method is required
# than find_by_path.
def find_by_path_or_id(path, id)
Pages::Finder.by_path_or_id(path, id)
end
# Helps to resolve the situation where you have a path and an id
# and if the path is unfriendly then a different finder method is required
# than find_by_path.
#
# raise ActiveRecord::RecordNotFound if not found.
def find_by_path_or_id!(path, id)
page = find_by_path_or_id(path, id)
raise ActiveRecord::RecordNotFound unless page
page
end
# Finds pages by their title. This method is necessary because pages
# are translated which means the title attribute does not exist on the
# pages table thus requiring us to find the attribute on the translations table
# and then join to the pages table again to return the associated record.
def by_title(title)
Pages::Finder.by_title(title)
end
# Finds pages by their slug. This method is necessary because pages
# are translated which means the slug attribute does not exist on the
# pages table thus requiring us to find the attribute on the translations table
# and then join to the pages table again to return the associated record.
def by_slug(slug, conditions = {})
Pages::Finder.by_slug(slug, conditions)
end
# Shows all pages with :show_in_menu set to true, but it also
# rejects any page that has not been translated to the current locale.
# This works using a query against the translated content first and then
# using all of the page_ids we further filter against this model's table.
def in_menu
where(:show_in_menu => true).with_globalize
end
# An optimised scope containing only live pages ordered for display in a menu.
def fast_menu
live.in_menu.order(arel_table[:lft]).includes(:parent, :translations)
end
# Wrap up the logic of finding the pages based on the translations table.
def with_globalize(conditions = {})
Pages::Finder.with_globalize(conditions)
end
# Returns how many pages per page should there be when paginating pages
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.pages_per_admin_index
end
def rebuild!
super
nullify_duplicate_slugs_under_the_same_parent!
end
protected
def nullify_duplicate_slugs_under_the_same_parent!
t_slug = translation_class.arel_table[:slug]
joins(:translations).group(:locale, :parent_id, t_slug).having(t_slug.count.gt(1)).count.
each do |(locale, parent_id, slug), count|
by_slug(slug, :locale => locale).where(:parent_id => parent_id).drop(1).each do |page|
page.slug = nil # kill the duplicate slug
page.save # regenerate the slug
end
end
end
end
def translated_to_default_locale?
persisted? && translations.any?{ |t| t.locale == Refinery::I18n.default_frontend_locale}
end
# The canonical page for this particular page.
# Consists of:
# * The current locale's translated slug
def canonical
Globalize.with_locale(::Refinery::I18n.current_frontend_locale) { url }
end
# The canonical slug for this particular page.
# This is the slug for the current frontend locale.
def canonical_slug
Globalize.with_locale(::Refinery::I18n.current_frontend_locale) { slug }
end
# Returns in cascading order: custom_slug or menu_title or title depending on
# which attribute is first found to be present for this page.
def custom_slug_or_title
(Refinery::Pages.use_custom_slugs && custom_slug.presence) ||
menu_title.presence || title.presence
end
# Am I allowed to delete this page?
# If a link_url is set we don't want to break the link so we don't allow them to delete
# If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages
def deletable?
deletable && link_url.blank? && menu_match.blank?
end
# Repositions the child page_parts that belong to this page.
# This ensures that they are in the correct 0,1,2,3,4... etc order.
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_columns position: index
end
end
# Before destroying a page we check to see if it's a deletable page or not
# Refinery system pages are not deletable.
def destroy
return super if deletable?
puts_destroy_help
false
end
# If you want to destroy a page that is set to be not deletable this is the way to do it.
def destroy!
self.update_attributes(:menu_match => nil, :link_url => nil, :deletable => true)
self.destroy
end
# Returns the full path to this page.
# This automatically prints out this page title and all parent page titles.
# The result is joined by the path_separator argument.
def path(path_separator: ' - ', ancestors_first: true)
return title if root?
chain = ancestors_first ? self_and_ancestors : self_and_ancestors.reverse
chain.map(&:title).join(path_separator)
end
def url
Pages::Url.build(self)
end
def nested_url
Globalize.with_locale(slug_locale) do
if ::Refinery::Pages.scope_slug_by_parent && !root?
self_and_ancestors.includes(:translations).map(&:to_param)
else
[to_param.to_s]
end
end
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
alias_method :uncached_nested_url, :nested_url
# Returns the string version of nested_url, i.e., the path that should be
# generated by the router
def nested_path
['', nested_url].join('/')
end
# Returns true if this page is "published"
def live?
!draft?
end
# Return true if this page can be shown in the navigation.
# If it's a draft or is set to not show in the menu it will return false.
def in_menu?
live? && show_in_menu?
end
def not_in_menu?
!in_menu?
end
# Returns all visible sibling pages that can be rendered for the menu
def shown_siblings
siblings.reject(&:not_in_menu?)
end
def to_refinery_menu_item
{
:id => id,
:lft => lft,
:depth => depth,
:menu_match => menu_match,
:parent_id => parent_id,
:rgt => rgt,
:title => menu_title.presence || title.presence,
:type => self.class.name,
:url => url
}
end
# Accessor method to get a page part from a page.
# Example:
#
# ::Refinery::Page.first.content_for(:body)
#
# Will return the body page part of the first page.
def content_for(part_slug)
part_with_slug(part_slug).try(:body)
end
# Accessor method to test whether a page part
# exists and has content for this page.
# Example:
#
# ::Refinery::Page.first.content_for?(:body)
#
# Will return true if the page has a body page part and it is not blank.
def content_for?(part_slug)
content_for(part_slug).present?
end
# Accessor method to get a page part object from a page.
# Example:
#
# ::Refinery::Page.first.part_with_slug(:body)
#
# Will return the Refinery::PagePart object with that slug using the first page.
def part_with_slug(part_slug)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.slug_matches?(part_slug)
end
end
# Protects generated slugs from title if they are in the list of reserved words
# This applies mostly to plugin-generated pages.
# This only kicks in when Refinery::Pages.marketable_urls is enabled.
# Also check for global scoping, and if enabled, allow slashes in slug.
#
# Returns the sluggified string
def normalize_friendly_id(slug_string)
FriendlyIdPath.normalize_friendly_id(slug_string)
end
private
class FriendlyIdPath
def self.normalize_friendly_id_path(slug_string)
# Remove leading and trailing slashes, but allow internal
slug_string
.sub(%r{^/*}, '')
.sub(%r{/*$}, '')
.split('/')
.select(&:present?)
.map { |slug| self.normalize_friendly_id(slug) }.join('/')
end
def self.normalize_friendly_id(slug_string)
# If we are scoping by parent, no slashes are allowed. Otherwise, slug is
# potentially a custom slug that contains a custom route to the page.
if !Pages.scope_slug_by_parent && slug_string.include?('/')
self.normalize_friendly_id_path(slug_string)
else
self.protected_slug_string(slug_string)
end
end
def self.protected_slug_string(slug_string)
sluggified = slug_string.to_slug.normalize!
if Pages.marketable_urls && Refinery::Pages.friendly_id_reserved_words.include?(sluggified)
sluggified << "-page"
end
sluggified
end
end
def puts_destroy_help
puts "This page is not deletable. Please use .destroy! if you really want it deleted "
puts "unset .link_url," if link_url.present?
puts "unset .menu_match," if menu_match.present?
puts "set .deletable to true" unless deletable
end
def slug_locale
return Globalize.locale if translation_for(Globalize.locale, false).try(:slug).present?
if translations.empty? || translation_for(Refinery::I18n.default_frontend_locale, false).try(:slug).present?
Refinery::I18n.default_frontend_locale
else
translations.first.locale
end
end
def update_all_descendants
self.descendants.update_all(updated_at: DateTime.now)
end
end
end
|
module Refinery
class Page < Refinery::Core::BaseModel
# when collecting the pages path how is each of the pages seperated?
PATH_SEPARATOR = " - "
if self.respond_to?(:translates)
translates :title, :menu_title, :custom_slug, :include => :seo_meta
end
attr_accessible :title
# Delegate SEO Attributes to globalize3 translation
seo_fields = ::SeoMeta.attributes.keys.map{|a| [a, :"#{a}="]}.flatten
delegate(*(seo_fields << {:to => :translation}))
attr_accessible :id, :deletable, :link_url, :menu_match, :meta_keywords,
:skip_to_first_child, :position, :show_in_menu, :draft,
:parts_attributes, :browser_title, :meta_description,
:parent_id, :menu_title, :created_at, :updated_at,
:page_id, :layout_template, :view_template, :custom_slug
attr_accessor :locale # to hold temporarily
validates :title, :presence => true
# Docs for acts_as_nested_set https://github.com/collectiveidea/awesome_nested_set
# rather than :delete_all we want :destroy
acts_as_nested_set :dependent => :destroy
# Docs for friendly_id http://github.com/norman/friendly_id
has_friendly_id :custom_slug_or_title, :use_slug => true,
:default_locale => (::Refinery::I18n.default_frontend_locale rescue :en),
:reserved_words => %w(index new session login logout users refinery admin images wymiframe),
:approximate_ascii => Refinery::Pages.approximate_ascii,
:strip_non_ascii => Refinery::Pages.strip_non_ascii,
:scope => :parent
# Docs for acts_as_indexed http://github.com/dougal/acts_as_indexed
acts_as_indexed :fields => [:title, :meta_keywords, :meta_description,
:menu_title, :browser_title, :all_page_part_content]
has_many :parts,
:foreign_key => :refinery_page_id,
:class_name => '::Refinery::PagePart',
:order => 'position ASC',
:inverse_of => :page,
:dependent => :destroy,
:include => ((:translations) if ::Refinery::PagePart.respond_to?(:translation_class))
accepts_nested_attributes_for :parts, :allow_destroy => true
before_save { |m| m.translation.save }
before_create :ensure_locale, :if => proc { ::Refinery.i18n_enabled? }
before_destroy :deletable?
after_save :reposition_parts!, :invalidate_cached_urls, :expire_page_caching
after_update :invalidate_cached_urls
after_destroy :expire_page_caching
class << self
# Live pages are 'allowed' to be shown in the frontend of your website.
# By default, this is all pages that are not set as 'draft'.
def live
where(:draft => false)
end
# With slugs scoped to the parent page we need to find a page by its full path.
# For example with about/example we would need to find 'about' and then its child
# called 'example' otherwise it may clash with another page called /example.
def find_by_path(path)
split_path = path.to_s.split('/')
page = ::Refinery::Page.find(split_path.shift)
page = page.children.find(split_path.shift) until split_path.empty?
page
end
# Finds a page using its title. This method is necessary because pages
# are translated which means the title attribute does not exist on the
# pages table thus requiring us to find the attribute on the translations table
# and then join to the pages table again to return the associated record.
def by_title(title)
with_globalize(:title => title)
end
# Shows all pages with :show_in_menu set to true, but it also
# rejects any page that has not been translated to the current locale.
# This works using a query against the translated content first and then
# using all of the page_ids we further filter against this model's table.
def in_menu
where(:show_in_menu => true).with_globalize
end
# Because pages are translated this can have a negative performance impact
# on your website and can introduce scaling issues. What fast_menu does is
# finds all of the columns necessary to render a +Refinery::Menu+ structure
# using only one SQL query. This has limitations, including not being able
# to access any other attributes of the pages but you can specify more columns
# by passing in an array e.g. fast_menu([:column1, :column2])
def fast_menu(columns = [])
# First, apply a filter to determine which pages to show.
# We need to join to the page's slug to avoid multiple queries.
pages = live.in_menu.includes(:slug, :slugs).order('lft ASC')
# Now we only want to select particular columns to avoid any further queries.
# Title and menu_title are retrieved in the next block below so they are not here.
(menu_columns | columns).each do |column|
pages = pages.select(arel_table[column.to_sym])
end
# We have to get title and menu_title from the translations table.
# To avoid calling globalize3 an extra time, we get title as page_title
# and we get menu_title as page_menu_title.
# These is used in 'to_refinery_menu_item' in the Page model.
%w(title menu_title).each do |column|
pages = pages.joins(:translations).select(
"#{translation_class.table_name}.#{column} as page_#{column}"
)
end
pages
end
# Wrap up the logic of finding the pages based on the translations table.
def with_globalize(conditions = {})
conditions = {:locale => Globalize.locale}.merge(conditions)
globalized_conditions = {}
conditions.keys.each do |key|
if (translated_attribute_names.map(&:to_s) | %w(locale)).include?(key.to_s)
globalized_conditions["#{self.translation_class.table_name}.#{key}"] = conditions.delete(key)
end
end
# A join implies readonly which we don't really want.
joins(:translations).where(globalized_conditions).where(conditions).readonly(false)
end
# Wraps up all the checks that we need to do to figure out whether
# the current frontend locale is different to the current one set by ::I18n.locale.
# This terminates in a false if i18n engine is not defined or enabled.
def different_frontend_locale?
::Refinery.i18n_enabled? && ::Refinery::I18n.current_frontend_locale != ::I18n.locale
end
# Override this method to change which columns you want to select to render your menu.
# title and menu_title are always retrieved so omit these.
def menu_columns
%w(id depth parent_id lft rgt link_url menu_match)
end
# Returns how many pages per page should there be when paginating pages
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.config.pages_per_admin_index
end
def expire_page_caching
begin
Rails.cache.delete_matched(/.*pages.*/)
rescue NotImplementedError
Rails.cache.clear
warn "**** [REFINERY] The cache store you are using is not compatible with Rails.cache#delete_matched - clearing entire cache instead ***"
ensure
return true # so that other callbacks process.
end
end
end
# Returns in cascading order: custom_slug or menu_title or title depending on
# which attribute is first found to be present for this page.
def custom_slug_or_title
if custom_slug.present?
custom_slug
elsif menu_title.present?
menu_title
else
title
end
end
# Am I allowed to delete this page?
# If a link_url is set we don't want to break the link so we don't allow them to delete
# If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages
def deletable?
deletable && link_url.blank? and menu_match.blank?
end
# Repositions the child page_parts that belong to this page.
# This ensures that they are in the correct 0,1,2,3,4... etc order.
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_attribute(:position, index)
end
end
# Before destroying a page we check to see if it's a deletable page or not
# Refinery system pages are not deletable.
def destroy
return super if deletable?
unless Rails.env.test?
# give useful feedback when trying to delete from console
puts "This page is not deletable. Please use .destroy! if you really want it deleted "
puts "unset .link_url," if link_url.present?
puts "unset .menu_match," if menu_match.present?
puts "set .deletable to true" unless deletable
end
false
end
# If you want to destroy a page that is set to be not deletable this is the way to do it.
def destroy!
self.menu_match = nil
self.link_url = nil
self.deletable = true
destroy
end
# Used for the browser title to get the full path to this page
# It automatically prints out this page title and all of it's parent page titles joined by a PATH_SEPARATOR
def path(options = {})
# Override default options with any supplied.
options = {:reversed => true}.merge(options)
unless parent_id.nil?
parts = [title, parent.path(options)]
parts.reverse! if options[:reversed]
parts.join(PATH_SEPARATOR)
else
title
end
end
# When this page is rendered in the navigation, where should it link?
# If a custom "link_url" is set, it uses that otherwise it defaults to a normal page URL.
# The "link_url" is often used to link to a plugin rather than a page.
#
# For example if I had a "Contact" page I don't want it to just render a contact us page
# I want it to show the Inquiries form so I can collect inquiries. So I would set the "link_url"
# to "/contact"
def url
if link_url.present?
link_url_localised?
elsif Refinery::Pages.marketable_urls
with_locale_param url_marketable
elsif to_param.present?
with_locale_param url_normal
end
end
# Adds the locale key into the URI for this page's link_url attribute, unless
# the current locale is set as the default locale.
def link_url_localised?
return link_url unless ::Refinery.i18n_enabled?
current_url = link_url
if current_url =~ %r{^/} && ::Refinery::I18n.current_frontend_locale != ::Refinery::I18n.default_frontend_locale
current_url = "/#{::Refinery::I18n.current_frontend_locale}#{current_url}"
end
current_url
end
# Add 'marketable url' attributes into this page's url.
# This sets 'path' as the nested_url value and sets 'id' to nil.
# For example, this might evaluate to /about for the "About" page.
def url_marketable
# :id => nil is important to prevent any other params[:id] from interfering with this route.
url_normal.merge(:path => nested_url, :id => nil)
end
# Returns a url suitable to be used in url_for in Rails (such as link_to).
# For example, this might evaluate to /pages/about for the "About" page.
def url_normal
{:controller => '/refinery/pages', :action => 'show', :path => nil, :id => to_param, :only_path => true}
end
# If the current locale is set to something other than the default locale
# then the :locale attribute will be set on the url hash, otherwise it won't be.
def with_locale_param(url_hash)
if self.class.different_frontend_locale?
url_hash.update(:locale => ::Refinery::I18n.current_frontend_locale)
end
url_hash
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
def nested_url
Rails.cache.fetch(url_cache_key) { uncached_nested_url }
end
def uncached_nested_url
[parent.try(:nested_url), to_param].compact.flatten
end
# Returns the string version of nested_url, i.e., the path that should be generated
# by the router
def nested_path
Rails.cache.fetch(path_cache_key) { ['', nested_url].join('/') }
end
def path_cache_key
[cache_key, 'nested_path'].join('#')
end
def url_cache_key
[cache_key, 'nested_url'].join('#')
end
def cache_key
[Refinery::Core.base_cache_key, ::I18n.locale, id].compact.join('/')
end
# Returns true if this page is "published"
def live?
not draft?
end
# Return true if this page can be shown in the navigation.
# If it's a draft or is set to not show in the menu it will return false.
def in_menu?
live? && show_in_menu?
end
def not_in_menu?
not in_menu?
end
# Returns true if this page is the home page or links to it.
def home?
link_url == '/'
end
# Returns all visible sibling pages that can be rendered for the menu
def shown_siblings
siblings.reject(&:not_in_menu?)
end
def refinery_menu_title
self[:page_menu_title].presence ||
self[:page_title].presence ||
self[:menu_title].presence ||
self[:title]
end
def to_refinery_menu_item
{
:id => id,
:lft => lft,
:menu_match => menu_match,
:parent_id => parent_id,
:rgt => rgt,
:title => refinery_menu_title,
:type => self.class.name,
:url => url
}
end
# Accessor method to get a page part from a page.
# Example:
#
# ::Refinery::Page.first.content_for(:body)
#
# Will return the body page part of the first page.
def content_for(part_title)
part_with_title(part_title).try(:body)
end
# Accessor method to get a page part object from a page.
# Example:
#
# ::Refinery::Page.first.part_with_title(:body)
#
# Will return the Refinery::PagePart object with that title using the first page.
def part_with_title(part_title)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.title.present? and # protecting against the problem that occurs when have nil title
part.title == part_title.to_s or
part.title.downcase.gsub(" ", "_") == part_title.to_s.downcase.gsub(" ", "_")
end
end
# In the admin area we use a slightly different title to inform the which pages are draft or hidden pages
# We show the title from the next available locale if there is no title for the current locale
def title_with_meta
if self.title.present?
title = [self.title]
else
title = [self.translations.detect {|t| t.title.present?}.title]
end
title << "<em>(#{::I18n.t('hidden', :scope => 'refinery.admin.pages.page')})</em>" unless show_in_menu?
title << "<em>(#{::I18n.t('draft', :scope => 'refinery.admin.pages.page')})</em>" if draft?
title.join(' ')
end
# Used to index all the content on this page so it can be easily searched.
def all_page_part_content
parts.map(&:body).join(" ")
end
##
# Protects generated slugs from title if they are in the list of reserved words
# This applies mostly to plugin-generated pages.
#
# Returns the sluggified string
def normalize_friendly_id(slug_string)
slug_string.gsub!('_', '-')
sluggified = super
if Refinery::Pages.marketable_urls && self.class.friendly_id_config.reserved_words.include?(sluggified)
sluggified << "-page"
end
sluggified
end
private
def invalidate_cached_urls
return true unless Refinery::Pages.marketable_urls
[self, children].flatten.each do |page|
Rails.cache.delete(page.url_cache_key)
Rails.cache.delete(page.path_cache_key)
end
end
alias_method :invalidate_child_cached_url, :invalidate_cached_urls
# Make sures that a translation exists for this page.
# The translation is set to the default frontend locale.
def ensure_locale
unless self.translations.present?
self.translations.build :locale => ::Refinery::I18n.default_frontend_locale
end
end
def expire_page_caching
self.class.expire_page_caching
end
end
end
Unique cache_key for Refinery::Page
module Refinery
class Page < Refinery::Core::BaseModel
# when collecting the pages path how is each of the pages seperated?
PATH_SEPARATOR = " - "
if self.respond_to?(:translates)
translates :title, :menu_title, :custom_slug, :include => :seo_meta
end
attr_accessible :title
# Delegate SEO Attributes to globalize3 translation
seo_fields = ::SeoMeta.attributes.keys.map{|a| [a, :"#{a}="]}.flatten
delegate(*(seo_fields << {:to => :translation}))
attr_accessible :id, :deletable, :link_url, :menu_match, :meta_keywords,
:skip_to_first_child, :position, :show_in_menu, :draft,
:parts_attributes, :browser_title, :meta_description,
:parent_id, :menu_title, :created_at, :updated_at,
:page_id, :layout_template, :view_template, :custom_slug
attr_accessor :locale # to hold temporarily
validates :title, :presence => true
# Docs for acts_as_nested_set https://github.com/collectiveidea/awesome_nested_set
# rather than :delete_all we want :destroy
acts_as_nested_set :dependent => :destroy
# Docs for friendly_id http://github.com/norman/friendly_id
has_friendly_id :custom_slug_or_title, :use_slug => true,
:default_locale => (::Refinery::I18n.default_frontend_locale rescue :en),
:reserved_words => %w(index new session login logout users refinery admin images wymiframe),
:approximate_ascii => Refinery::Pages.approximate_ascii,
:strip_non_ascii => Refinery::Pages.strip_non_ascii,
:scope => :parent
# Docs for acts_as_indexed http://github.com/dougal/acts_as_indexed
acts_as_indexed :fields => [:title, :meta_keywords, :meta_description,
:menu_title, :browser_title, :all_page_part_content]
has_many :parts,
:foreign_key => :refinery_page_id,
:class_name => '::Refinery::PagePart',
:order => 'position ASC',
:inverse_of => :page,
:dependent => :destroy,
:include => ((:translations) if ::Refinery::PagePart.respond_to?(:translation_class))
accepts_nested_attributes_for :parts, :allow_destroy => true
before_save { |m| m.translation.save }
before_create :ensure_locale, :if => proc { ::Refinery.i18n_enabled? }
before_destroy :deletable?
after_save :reposition_parts!, :invalidate_cached_urls, :expire_page_caching
after_update :invalidate_cached_urls
after_destroy :expire_page_caching
class << self
# Live pages are 'allowed' to be shown in the frontend of your website.
# By default, this is all pages that are not set as 'draft'.
def live
where(:draft => false)
end
# With slugs scoped to the parent page we need to find a page by its full path.
# For example with about/example we would need to find 'about' and then its child
# called 'example' otherwise it may clash with another page called /example.
def find_by_path(path)
split_path = path.to_s.split('/')
page = ::Refinery::Page.find(split_path.shift)
page = page.children.find(split_path.shift) until split_path.empty?
page
end
# Finds a page using its title. This method is necessary because pages
# are translated which means the title attribute does not exist on the
# pages table thus requiring us to find the attribute on the translations table
# and then join to the pages table again to return the associated record.
def by_title(title)
with_globalize(:title => title)
end
# Shows all pages with :show_in_menu set to true, but it also
# rejects any page that has not been translated to the current locale.
# This works using a query against the translated content first and then
# using all of the page_ids we further filter against this model's table.
def in_menu
where(:show_in_menu => true).with_globalize
end
# Because pages are translated this can have a negative performance impact
# on your website and can introduce scaling issues. What fast_menu does is
# finds all of the columns necessary to render a +Refinery::Menu+ structure
# using only one SQL query. This has limitations, including not being able
# to access any other attributes of the pages but you can specify more columns
# by passing in an array e.g. fast_menu([:column1, :column2])
def fast_menu(columns = [])
# First, apply a filter to determine which pages to show.
# We need to join to the page's slug to avoid multiple queries.
pages = live.in_menu.includes(:slug, :slugs).order('lft ASC')
# Now we only want to select particular columns to avoid any further queries.
# Title and menu_title are retrieved in the next block below so they are not here.
(menu_columns | columns).each do |column|
pages = pages.select(arel_table[column.to_sym])
end
# We have to get title and menu_title from the translations table.
# To avoid calling globalize3 an extra time, we get title as page_title
# and we get menu_title as page_menu_title.
# These is used in 'to_refinery_menu_item' in the Page model.
%w(title menu_title).each do |column|
pages = pages.joins(:translations).select(
"#{translation_class.table_name}.#{column} as page_#{column}"
)
end
pages
end
# Wrap up the logic of finding the pages based on the translations table.
def with_globalize(conditions = {})
conditions = {:locale => Globalize.locale}.merge(conditions)
globalized_conditions = {}
conditions.keys.each do |key|
if (translated_attribute_names.map(&:to_s) | %w(locale)).include?(key.to_s)
globalized_conditions["#{self.translation_class.table_name}.#{key}"] = conditions.delete(key)
end
end
# A join implies readonly which we don't really want.
joins(:translations).where(globalized_conditions).where(conditions).readonly(false)
end
# Wraps up all the checks that we need to do to figure out whether
# the current frontend locale is different to the current one set by ::I18n.locale.
# This terminates in a false if i18n engine is not defined or enabled.
def different_frontend_locale?
::Refinery.i18n_enabled? && ::Refinery::I18n.current_frontend_locale != ::I18n.locale
end
# Override this method to change which columns you want to select to render your menu.
# title and menu_title are always retrieved so omit these.
def menu_columns
%w(id depth parent_id lft rgt link_url menu_match)
end
# Returns how many pages per page should there be when paginating pages
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.config.pages_per_admin_index
end
def expire_page_caching
begin
Rails.cache.delete_matched(/.*pages.*/)
rescue NotImplementedError
Rails.cache.clear
warn "**** [REFINERY] The cache store you are using is not compatible with Rails.cache#delete_matched - clearing entire cache instead ***"
ensure
return true # so that other callbacks process.
end
end
end
# Returns in cascading order: custom_slug or menu_title or title depending on
# which attribute is first found to be present for this page.
def custom_slug_or_title
if custom_slug.present?
custom_slug
elsif menu_title.present?
menu_title
else
title
end
end
# Am I allowed to delete this page?
# If a link_url is set we don't want to break the link so we don't allow them to delete
# If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages
def deletable?
deletable && link_url.blank? and menu_match.blank?
end
# Repositions the child page_parts that belong to this page.
# This ensures that they are in the correct 0,1,2,3,4... etc order.
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_attribute(:position, index)
end
end
# Before destroying a page we check to see if it's a deletable page or not
# Refinery system pages are not deletable.
def destroy
return super if deletable?
unless Rails.env.test?
# give useful feedback when trying to delete from console
puts "This page is not deletable. Please use .destroy! if you really want it deleted "
puts "unset .link_url," if link_url.present?
puts "unset .menu_match," if menu_match.present?
puts "set .deletable to true" unless deletable
end
false
end
# If you want to destroy a page that is set to be not deletable this is the way to do it.
def destroy!
self.menu_match = nil
self.link_url = nil
self.deletable = true
destroy
end
# Used for the browser title to get the full path to this page
# It automatically prints out this page title and all of it's parent page titles joined by a PATH_SEPARATOR
def path(options = {})
# Override default options with any supplied.
options = {:reversed => true}.merge(options)
unless parent_id.nil?
parts = [title, parent.path(options)]
parts.reverse! if options[:reversed]
parts.join(PATH_SEPARATOR)
else
title
end
end
# When this page is rendered in the navigation, where should it link?
# If a custom "link_url" is set, it uses that otherwise it defaults to a normal page URL.
# The "link_url" is often used to link to a plugin rather than a page.
#
# For example if I had a "Contact" page I don't want it to just render a contact us page
# I want it to show the Inquiries form so I can collect inquiries. So I would set the "link_url"
# to "/contact"
def url
if link_url.present?
link_url_localised?
elsif Refinery::Pages.marketable_urls
with_locale_param url_marketable
elsif to_param.present?
with_locale_param url_normal
end
end
# Adds the locale key into the URI for this page's link_url attribute, unless
# the current locale is set as the default locale.
def link_url_localised?
return link_url unless ::Refinery.i18n_enabled?
current_url = link_url
if current_url =~ %r{^/} && ::Refinery::I18n.current_frontend_locale != ::Refinery::I18n.default_frontend_locale
current_url = "/#{::Refinery::I18n.current_frontend_locale}#{current_url}"
end
current_url
end
# Add 'marketable url' attributes into this page's url.
# This sets 'path' as the nested_url value and sets 'id' to nil.
# For example, this might evaluate to /about for the "About" page.
def url_marketable
# :id => nil is important to prevent any other params[:id] from interfering with this route.
url_normal.merge(:path => nested_url, :id => nil)
end
# Returns a url suitable to be used in url_for in Rails (such as link_to).
# For example, this might evaluate to /pages/about for the "About" page.
def url_normal
{:controller => '/refinery/pages', :action => 'show', :path => nil, :id => to_param, :only_path => true}
end
# If the current locale is set to something other than the default locale
# then the :locale attribute will be set on the url hash, otherwise it won't be.
def with_locale_param(url_hash)
if self.class.different_frontend_locale?
url_hash.update(:locale => ::Refinery::I18n.current_frontend_locale)
end
url_hash
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
def nested_url
Rails.cache.fetch(url_cache_key) { uncached_nested_url }
end
def uncached_nested_url
[parent.try(:nested_url), to_param].compact.flatten
end
# Returns the string version of nested_url, i.e., the path that should be generated
# by the router
def nested_path
Rails.cache.fetch(path_cache_key) { ['', nested_url].join('/') }
end
def path_cache_key
[cache_key, 'nested_path'].join('#')
end
def url_cache_key
[cache_key, 'nested_url'].join('#')
end
def cache_key
[Refinery::Core.base_cache_key, 'page', ::I18n.locale, id].compact.join('/')
end
# Returns true if this page is "published"
def live?
not draft?
end
# Return true if this page can be shown in the navigation.
# If it's a draft or is set to not show in the menu it will return false.
def in_menu?
live? && show_in_menu?
end
def not_in_menu?
not in_menu?
end
# Returns true if this page is the home page or links to it.
def home?
link_url == '/'
end
# Returns all visible sibling pages that can be rendered for the menu
def shown_siblings
siblings.reject(&:not_in_menu?)
end
def refinery_menu_title
self[:page_menu_title].presence ||
self[:page_title].presence ||
self[:menu_title].presence ||
self[:title]
end
def to_refinery_menu_item
{
:id => id,
:lft => lft,
:menu_match => menu_match,
:parent_id => parent_id,
:rgt => rgt,
:title => refinery_menu_title,
:type => self.class.name,
:url => url
}
end
# Accessor method to get a page part from a page.
# Example:
#
# ::Refinery::Page.first.content_for(:body)
#
# Will return the body page part of the first page.
def content_for(part_title)
part_with_title(part_title).try(:body)
end
# Accessor method to get a page part object from a page.
# Example:
#
# ::Refinery::Page.first.part_with_title(:body)
#
# Will return the Refinery::PagePart object with that title using the first page.
def part_with_title(part_title)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.title.present? and # protecting against the problem that occurs when have nil title
part.title == part_title.to_s or
part.title.downcase.gsub(" ", "_") == part_title.to_s.downcase.gsub(" ", "_")
end
end
# In the admin area we use a slightly different title to inform the which pages are draft or hidden pages
# We show the title from the next available locale if there is no title for the current locale
def title_with_meta
if self.title.present?
title = [self.title]
else
title = [self.translations.detect {|t| t.title.present?}.title]
end
title << "<em>(#{::I18n.t('hidden', :scope => 'refinery.admin.pages.page')})</em>" unless show_in_menu?
title << "<em>(#{::I18n.t('draft', :scope => 'refinery.admin.pages.page')})</em>" if draft?
title.join(' ')
end
# Used to index all the content on this page so it can be easily searched.
def all_page_part_content
parts.map(&:body).join(" ")
end
##
# Protects generated slugs from title if they are in the list of reserved words
# This applies mostly to plugin-generated pages.
#
# Returns the sluggified string
def normalize_friendly_id(slug_string)
slug_string.gsub!('_', '-')
sluggified = super
if Refinery::Pages.marketable_urls && self.class.friendly_id_config.reserved_words.include?(sluggified)
sluggified << "-page"
end
sluggified
end
private
def invalidate_cached_urls
return true unless Refinery::Pages.marketable_urls
[self, children].flatten.each do |page|
Rails.cache.delete(page.url_cache_key)
Rails.cache.delete(page.path_cache_key)
end
end
alias_method :invalidate_child_cached_url, :invalidate_cached_urls
# Make sures that a translation exists for this page.
# The translation is set to the default frontend locale.
def ensure_locale
unless self.translations.present?
self.translations.build :locale => ::Refinery::I18n.default_frontend_locale
end
end
def expire_page_caching
self.class.expire_page_caching
end
end
end
|
module Refinery
class Page < ActiveRecord::Base
# when collecting the pages path how is each of the pages seperated?
PATH_SEPARATOR = " - "
if self.respond_to?(:translates)
translates :title, :menu_title, :meta_keywords, :meta_description, :browser_title, :custom_slug, :include => :seo_meta
end
attr_accessible :title
# Delegate SEO Attributes to globalize3 translation
seo_fields = ::SeoMeta.attributes.keys.map{|a| [a, :"#{a}="]}.flatten
delegate *(seo_fields << {:to => :translation})
attr_accessible :id, :deletable, :link_url, :menu_match, :meta_keywords,
:skip_to_first_child, :position, :show_in_menu, :draft,
:parts_attributes, :browser_title, :meta_description,
:parent_id, :menu_title, :created_at, :updated_at,
:page_id, :layout_template, :view_template, :custom_slug
attr_accessor :locale # to hold temporarily
validates :title, :presence => true
# Docs for acts_as_nested_set https://github.com/collectiveidea/awesome_nested_set
# rather than :delete_all we want :destroy
unless $rake_assets_precompiling
acts_as_nested_set :dependent => :destroy
# Docs for friendly_id http://github.com/norman/friendly_id
has_friendly_id :custom_slug_or_title, :use_slug => true,
:default_locale => (::Refinery::I18n.default_frontend_locale rescue :en),
:reserved_words => %w(index new session login logout users refinery admin images wymiframe),
:approximate_ascii => ::Refinery::Setting.find_or_set(:approximate_ascii, false, :scoping => "pages"),
:strip_non_ascii => ::Refinery::Setting.find_or_set(:strip_non_ascii, false, :scoping => "pages")
end
# Docs for acts_as_indexed http://github.com/dougal/acts_as_indexed
acts_as_indexed :fields => [:title, :meta_keywords, :meta_description,
:menu_title, :browser_title, :all_page_part_content]
has_many :parts,
:foreign_key => :refinery_page_id,
:class_name => '::Refinery::PagePart',
:order => 'position ASC',
:inverse_of => :page,
:dependent => :destroy,
:include => ((:translations) if ::Refinery::PagePart.respond_to?(:translation_class))
accepts_nested_attributes_for :parts, :allow_destroy => true
before_save { |m| m.translation.save }
before_create :ensure_locale, :if => proc { |c| ::Refinery.i18n_enabled? }
before_destroy :deletable?
after_save :reposition_parts!, :invalidate_cached_urls, :expire_page_caching
after_update :invalidate_cached_urls
after_destroy :expire_page_caching
scope :live, where(:draft => false)
scope :by_title, proc {|t| with_globalize(:title => t)}
# Shows all pages with :show_in_menu set to true, but it also
# rejects any page that has not been translated to the current locale.
# This works using a query against the translated content first and then
# using all of the page_ids we further filter against this model's table.
scope :in_menu, proc { where(:show_in_menu => true).with_globalize }
scope :fast_menu, proc {
# First, apply a filter to determine which pages to show.
# We need to join to the page's slug to avoid multiple queries.
pages = live.in_menu.includes(:slug, :slugs).order('lft ASC')
# Now we only want to select particular columns to avoid any further queries.
# Title and menu_title are retrieved in the next block below so they are not here.
menu_columns.each do |column|
pages = pages.select(arel_table[column.to_sym])
end
# We have to get title and menu_title from the translations table.
# To avoid calling globalize3 an extra time, we get title as page_title
# and we get menu_title as page_menu_title.
# These is used in 'to_refinery_menu_item' in the Page model.
%w(title menu_title).each do |column|
pages = pages.joins(:translations).select(
"#{translation_class.table_name}.#{column} as page_#{column}"
)
end
pages
}
class << self
# Wrap up the logic of finding the pages based on the translations table.
def with_globalize(conditions = {})
conditions = {:locale => Globalize.locale}.merge(conditions)
globalized_conditions = {}
conditions.keys.each do |key|
if (translated_attribute_names.map(&:to_s) | %w(locale)).include?(key.to_s)
globalized_conditions["#{self.translation_class.table_name}.#{key}"] = conditions.delete(key)
end
end
# A join implies readonly which we don't really want.
joins(:translations).where(globalized_conditions).where(conditions).readonly(false)
end
# Accessor to find out the default page parts created for each new page
def default_parts
::Refinery::Setting.find_or_set(:default_page_parts, ["Body", "Side Body"])
end
# Wraps up all the checks that we need to do to figure out whether
# the current frontend locale is different to the current one set by ::I18n.locale.
# This terminates in a false if i18n engine is not defined or enabled.
def different_frontend_locale?
::Refinery.i18n_enabled? && ::Refinery::I18n.current_frontend_locale != ::I18n.locale
end
# Override this method to change which columns you want to select to render your menu.
# title and menu_title are always retrieved so omit these.
def menu_columns
%w(id depth parent_id lft rgt link_url menu_match)
end
# Returns how many pages per page should there be when paginating pages
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.pages_per_admin_index
end
def expire_page_caching
begin
Rails.cache.delete_matched(/.*pages.*/)
rescue NotImplementedError
Rails.cache.clear
warn "**** [REFINERY] The cache store you are using is not compatible with Rails.cache#delete_matched - clearing entire cache instead ***"
ensure
return true # so that other callbacks process.
end
end
end
def custom_slug_or_title
if custom_slug.present?
custom_slug
elsif menu_title.present?
menu_title
else
title
end
end
# Am I allowed to delete this page?
# If a link_url is set we don't want to break the link so we don't allow them to delete
# If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages
def deletable?
deletable && link_url.blank? and menu_match.blank?
end
# Repositions the child page_parts that belong to this page.
# This ensures that they are in the correct 0,1,2,3,4... etc order.
def reposition_parts!
parts.each_with_index do |part, index|
part.update_attribute(:position, index)
end
end
# Before destroying a page we check to see if it's a deletable page or not
# Refinery system pages are not deletable.
def destroy
return super if deletable?
unless Rails.env.test?
# give useful feedback when trying to delete from console
puts "This page is not deletable. Please use .destroy! if you really want it deleted "
puts "unset .link_url," if link_url.present?
puts "unset .menu_match," if menu_match.present?
puts "set .deletable to true" unless deletable
end
false
end
# If you want to destroy a page that is set to be not deletable this is the way to do it.
def destroy!
self.menu_match = nil
self.link_url = nil
self.deletable = true
destroy
end
# Used for the browser title to get the full path to this page
# It automatically prints out this page title and all of it's parent page titles joined by a PATH_SEPARATOR
def path(options = {})
# Override default options with any supplied.
options = {:reversed => true}.merge(options)
unless parent_id.nil?
parts = [title, parent.path(options)]
parts.reverse! if options[:reversed]
parts.join(PATH_SEPARATOR)
else
title
end
end
# When this page is rendered in the navigation, where should it link?
# If a custom "link_url" is set, it uses that otherwise it defaults to a normal page URL.
# The "link_url" is often used to link to a plugin rather than a page.
#
# For example if I had a "Contact" page I don't want it to just render a contact us page
# I want it to show the Inquiries form so I can collect inquiries. So I would set the "link_url"
# to "/contact"
def url
if link_url.present?
link_url_localised?
elsif ::Refinery::Pages.use_marketable_urls?
with_locale_param url_marketable
elsif to_param.present?
with_locale_param url_normal
end
end
def link_url_localised?
return link_url unless ::Refinery.i18n_enabled?
current_url = link_url
if current_url =~ %r{^/} && ::Refinery::I18n.current_frontend_locale != ::Refinery::I18n.default_frontend_locale
current_url = "/#{::Refinery::I18n.current_frontend_locale}#{current_url}"
end
current_url
end
def url_marketable
# except(:id) is important to prevent any other params[:id] from interfering with this route.
url_normal.merge(:path => nested_url).except(:id)
end
def url_normal
{:controller => '/refinery/pages', :action => 'show', :path => nil, :id => to_param}
end
def with_locale_param(url_hash)
if self.class.different_frontend_locale?
url_hash.update(:locale => ::Refinery::I18n.current_frontend_locale)
end
url_hash
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
def nested_url
Rails.cache.fetch(url_cache_key) { uncached_nested_url }
end
def uncached_nested_url
[parent.try(:nested_url), to_param].compact.flatten
end
# Returns the string version of nested_url, i.e., the path that should be generated
# by the router
def nested_path
Rails.cache.fetch(path_cache_key) { ['', nested_url].join('/') }
end
def path_cache_key
[cache_key, 'nested_path'].join('#')
end
def url_cache_key
[cache_key, 'nested_url'].join('#')
end
def cache_key
[Refinery.base_cache_key, ::I18n.locale, to_param].compact.join('/')
end
# Returns true if this page is "published"
def live?
not draft?
end
# Return true if this page can be shown in the navigation.
# If it's a draft or is set to not show in the menu it will return false.
def in_menu?
live? && show_in_menu?
end
def not_in_menu?
not in_menu?
end
# Returns true if this page is the home page or links to it.
def home?
link_url == '/'
end
# Returns all visible sibling pages that can be rendered for the menu
def shown_siblings
siblings.reject(&:not_in_menu?)
end
def to_refinery_menu_item
{
:id => id,
:lft => lft,
:menu_match => menu_match,
:parent_id => parent_id,
:rgt => rgt,
:title => page_menu_title.blank? ? page_title : page_menu_title,
:type => self.class.name,
:url => url
}
end
# Accessor method to get a page part from a page.
# Example:
#
# ::Refinery::Page.first.content_for(:body)
#
# Will return the body page part of the first page.
def content_for(part_title)
part_with_title(part_title).try(:body)
end
# Accessor method to get a page part object from a page.
# Example:
#
# ::Refinery::Page.first.part_with_title(:body)
#
# Will return the Refinery::PagePart object with that title using the first page.
def part_with_title(part_title)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.title.present? and # protecting against the problem that occurs when have nil title
part.title == part_title.to_s or
part.title.downcase.gsub(" ", "_") == part_title.to_s.downcase.gsub(" ", "_")
end
end
# In the admin area we use a slightly different title to inform the which pages are draft or hidden pages
# We show the title from the next available locale if there is no title for the current locale
def title_with_meta
if self.title.present?
title = [self.title]
else
title = [self.translations.detect {|t| t.title.present?}.title]
end
title << "<em>(#{::I18n.t('hidden', :scope => 'refinery.admin.pages.page')})</em>" unless show_in_menu?
title << "<em>(#{::I18n.t('draft', :scope => 'refinery.admin.pages.page')})</em>" if draft?
title.join(' ')
end
# Used to index all the content on this page so it can be easily searched.
def all_page_part_content
parts.collect {|p| p.body}.join(" ")
end
##
# Protects generated slugs from title if they are in the list of reserved words
# This applies mostly to plugin-generated pages.
#
# Returns the sluggified string
def normalize_friendly_id(slug_string)
slug_string.gsub!('_', '-')
sluggified = super
if ::Refinery::Pages.use_marketable_urls? && self.class.friendly_id_config.reserved_words.include?(sluggified)
sluggified << "-page"
end
sluggified
end
private
def invalidate_cached_urls
return true unless ::Refinery::Pages.use_marketable_urls?
[self, children].flatten.each do |page|
Rails.cache.delete(page.url_cache_key)
Rails.cache.delete(page.path_cache_key)
end
end
alias_method :invalidate_child_cached_url, :invalidate_cached_urls
def ensure_locale
unless self.translations.present?
self.translations.build :locale => ::Refinery::I18n.default_frontend_locale
end
end
def expire_page_caching
self.class.expire_page_caching
end
end
end
Fix failing spec on postgresql.
module Refinery
class Page < ActiveRecord::Base
# when collecting the pages path how is each of the pages seperated?
PATH_SEPARATOR = " - "
if self.respond_to?(:translates)
translates :title, :menu_title, :meta_keywords, :meta_description, :browser_title, :custom_slug, :include => :seo_meta
end
attr_accessible :title
# Delegate SEO Attributes to globalize3 translation
seo_fields = ::SeoMeta.attributes.keys.map{|a| [a, :"#{a}="]}.flatten
delegate *(seo_fields << {:to => :translation})
attr_accessible :id, :deletable, :link_url, :menu_match, :meta_keywords,
:skip_to_first_child, :position, :show_in_menu, :draft,
:parts_attributes, :browser_title, :meta_description,
:parent_id, :menu_title, :created_at, :updated_at,
:page_id, :layout_template, :view_template, :custom_slug
attr_accessor :locale # to hold temporarily
validates :title, :presence => true
# Docs for acts_as_nested_set https://github.com/collectiveidea/awesome_nested_set
# rather than :delete_all we want :destroy
unless $rake_assets_precompiling
acts_as_nested_set :dependent => :destroy
# Docs for friendly_id http://github.com/norman/friendly_id
has_friendly_id :custom_slug_or_title, :use_slug => true,
:default_locale => (::Refinery::I18n.default_frontend_locale rescue :en),
:reserved_words => %w(index new session login logout users refinery admin images wymiframe),
:approximate_ascii => ::Refinery::Setting.find_or_set(:approximate_ascii, false, :scoping => "pages"),
:strip_non_ascii => ::Refinery::Setting.find_or_set(:strip_non_ascii, false, :scoping => "pages")
end
# Docs for acts_as_indexed http://github.com/dougal/acts_as_indexed
acts_as_indexed :fields => [:title, :meta_keywords, :meta_description,
:menu_title, :browser_title, :all_page_part_content]
has_many :parts,
:foreign_key => :refinery_page_id,
:class_name => '::Refinery::PagePart',
:order => 'position ASC',
:inverse_of => :page,
:dependent => :destroy,
:include => ((:translations) if ::Refinery::PagePart.respond_to?(:translation_class))
accepts_nested_attributes_for :parts, :allow_destroy => true
before_save { |m| m.translation.save }
before_create :ensure_locale, :if => proc { |c| ::Refinery.i18n_enabled? }
before_destroy :deletable?
after_save :reposition_parts!, :invalidate_cached_urls, :expire_page_caching
after_update :invalidate_cached_urls
after_destroy :expire_page_caching
scope :live, where(:draft => false)
scope :by_title, proc {|t| with_globalize(:title => t)}
# Shows all pages with :show_in_menu set to true, but it also
# rejects any page that has not been translated to the current locale.
# This works using a query against the translated content first and then
# using all of the page_ids we further filter against this model's table.
scope :in_menu, proc { where(:show_in_menu => true).with_globalize }
scope :fast_menu, proc {
# First, apply a filter to determine which pages to show.
# We need to join to the page's slug to avoid multiple queries.
pages = live.in_menu.includes(:slug, :slugs).order('lft ASC')
# Now we only want to select particular columns to avoid any further queries.
# Title and menu_title are retrieved in the next block below so they are not here.
menu_columns.each do |column|
pages = pages.select(arel_table[column.to_sym])
end
# We have to get title and menu_title from the translations table.
# To avoid calling globalize3 an extra time, we get title as page_title
# and we get menu_title as page_menu_title.
# These is used in 'to_refinery_menu_item' in the Page model.
%w(title menu_title).each do |column|
pages = pages.joins(:translations).select(
"#{translation_class.table_name}.#{column} as page_#{column}"
)
end
pages
}
class << self
# Wrap up the logic of finding the pages based on the translations table.
def with_globalize(conditions = {})
conditions = {:locale => Globalize.locale}.merge(conditions)
globalized_conditions = {}
conditions.keys.each do |key|
if (translated_attribute_names.map(&:to_s) | %w(locale)).include?(key.to_s)
globalized_conditions["#{self.translation_class.table_name}.#{key}"] = conditions.delete(key)
end
end
# A join implies readonly which we don't really want.
joins(:translations).where(globalized_conditions).where(conditions).readonly(false)
end
# Accessor to find out the default page parts created for each new page
def default_parts
::Refinery::Setting.find_or_set(:default_page_parts, ["Body", "Side Body"])
end
# Wraps up all the checks that we need to do to figure out whether
# the current frontend locale is different to the current one set by ::I18n.locale.
# This terminates in a false if i18n engine is not defined or enabled.
def different_frontend_locale?
::Refinery.i18n_enabled? && ::Refinery::I18n.current_frontend_locale != ::I18n.locale
end
# Override this method to change which columns you want to select to render your menu.
# title and menu_title are always retrieved so omit these.
def menu_columns
%w(id depth parent_id lft rgt link_url menu_match)
end
# Returns how many pages per page should there be when paginating pages
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.pages_per_admin_index
end
def expire_page_caching
begin
Rails.cache.delete_matched(/.*pages.*/)
rescue NotImplementedError
Rails.cache.clear
warn "**** [REFINERY] The cache store you are using is not compatible with Rails.cache#delete_matched - clearing entire cache instead ***"
ensure
return true # so that other callbacks process.
end
end
end
def custom_slug_or_title
if custom_slug.present?
custom_slug
elsif menu_title.present?
menu_title
else
title
end
end
# Am I allowed to delete this page?
# If a link_url is set we don't want to break the link so we don't allow them to delete
# If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages
def deletable?
deletable && link_url.blank? and menu_match.blank?
end
# Repositions the child page_parts that belong to this page.
# This ensures that they are in the correct 0,1,2,3,4... etc order.
def reposition_parts!
parts.each_with_index do |part, index|
part.update_attribute(:position, index)
end
end
# Before destroying a page we check to see if it's a deletable page or not
# Refinery system pages are not deletable.
def destroy
return super if deletable?
unless Rails.env.test?
# give useful feedback when trying to delete from console
puts "This page is not deletable. Please use .destroy! if you really want it deleted "
puts "unset .link_url," if link_url.present?
puts "unset .menu_match," if menu_match.present?
puts "set .deletable to true" unless deletable
end
false
end
# If you want to destroy a page that is set to be not deletable this is the way to do it.
def destroy!
self.menu_match = nil
self.link_url = nil
self.deletable = true
destroy
end
# Used for the browser title to get the full path to this page
# It automatically prints out this page title and all of it's parent page titles joined by a PATH_SEPARATOR
def path(options = {})
# Override default options with any supplied.
options = {:reversed => true}.merge(options)
unless parent_id.nil?
parts = [title, parent.path(options)]
parts.reverse! if options[:reversed]
parts.join(PATH_SEPARATOR)
else
title
end
end
# When this page is rendered in the navigation, where should it link?
# If a custom "link_url" is set, it uses that otherwise it defaults to a normal page URL.
# The "link_url" is often used to link to a plugin rather than a page.
#
# For example if I had a "Contact" page I don't want it to just render a contact us page
# I want it to show the Inquiries form so I can collect inquiries. So I would set the "link_url"
# to "/contact"
def url
if link_url.present?
link_url_localised?
elsif ::Refinery::Pages.use_marketable_urls?
with_locale_param url_marketable
elsif to_param.present?
with_locale_param url_normal
end
end
def link_url_localised?
return link_url unless ::Refinery.i18n_enabled?
current_url = link_url
if current_url =~ %r{^/} && ::Refinery::I18n.current_frontend_locale != ::Refinery::I18n.default_frontend_locale
current_url = "/#{::Refinery::I18n.current_frontend_locale}#{current_url}"
end
current_url
end
def url_marketable
# except(:id) is important to prevent any other params[:id] from interfering with this route.
url_normal.merge(:path => nested_url).except(:id)
end
def url_normal
{:controller => '/refinery/pages', :action => 'show', :path => nil, :id => to_param}
end
def with_locale_param(url_hash)
if self.class.different_frontend_locale?
url_hash.update(:locale => ::Refinery::I18n.current_frontend_locale)
end
url_hash
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
def nested_url
Rails.cache.fetch(url_cache_key) { uncached_nested_url }
end
def uncached_nested_url
[parent.try(:nested_url), to_param].compact.flatten
end
# Returns the string version of nested_url, i.e., the path that should be generated
# by the router
def nested_path
Rails.cache.fetch(path_cache_key) { ['', nested_url].join('/') }
end
def path_cache_key
[cache_key, 'nested_path'].join('#')
end
def url_cache_key
[cache_key, 'nested_url'].join('#')
end
def cache_key
[Refinery.base_cache_key, ::I18n.locale, to_param].compact.join('/')
end
# Returns true if this page is "published"
def live?
not draft?
end
# Return true if this page can be shown in the navigation.
# If it's a draft or is set to not show in the menu it will return false.
def in_menu?
live? && show_in_menu?
end
def not_in_menu?
not in_menu?
end
# Returns true if this page is the home page or links to it.
def home?
link_url == '/'
end
# Returns all visible sibling pages that can be rendered for the menu
def shown_siblings
siblings.reject(&:not_in_menu?)
end
def to_refinery_menu_item
{
:id => id,
:lft => lft,
:menu_match => menu_match,
:parent_id => parent_id,
:rgt => rgt,
:title => page_menu_title.blank? ? page_title : page_menu_title,
:type => self.class.name,
:url => url
}
end
# Accessor method to get a page part from a page.
# Example:
#
# ::Refinery::Page.first.content_for(:body)
#
# Will return the body page part of the first page.
def content_for(part_title)
part_with_title(part_title).try(:body)
end
# Accessor method to get a page part object from a page.
# Example:
#
# ::Refinery::Page.first.part_with_title(:body)
#
# Will return the Refinery::PagePart object with that title using the first page.
def part_with_title(part_title)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.title.present? and # protecting against the problem that occurs when have nil title
part.title == part_title.to_s or
part.title.downcase.gsub(" ", "_") == part_title.to_s.downcase.gsub(" ", "_")
end
end
# In the admin area we use a slightly different title to inform the which pages are draft or hidden pages
# We show the title from the next available locale if there is no title for the current locale
def title_with_meta
if self.title.present?
title = [self.title]
else
title = [self.translations.detect {|t| t.title.present?}.title]
end
title << "<em>(#{::I18n.t('hidden', :scope => 'refinery.admin.pages.page')})</em>" unless show_in_menu?
title << "<em>(#{::I18n.t('draft', :scope => 'refinery.admin.pages.page')})</em>" if draft?
title.join(' ')
end
# Used to index all the content on this page so it can be easily searched.
def all_page_part_content
parts.sort.collect {|p| p.body}.join(" ")
end
##
# Protects generated slugs from title if they are in the list of reserved words
# This applies mostly to plugin-generated pages.
#
# Returns the sluggified string
def normalize_friendly_id(slug_string)
slug_string.gsub!('_', '-')
sluggified = super
if ::Refinery::Pages.use_marketable_urls? && self.class.friendly_id_config.reserved_words.include?(sluggified)
sluggified << "-page"
end
sluggified
end
private
def invalidate_cached_urls
return true unless ::Refinery::Pages.use_marketable_urls?
[self, children].flatten.each do |page|
Rails.cache.delete(page.url_cache_key)
Rails.cache.delete(page.path_cache_key)
end
end
alias_method :invalidate_child_cached_url, :invalidate_cached_urls
def ensure_locale
unless self.translations.present?
self.translations.build :locale => ::Refinery::I18n.default_frontend_locale
end
end
def expire_page_caching
self.class.expire_page_caching
end
end
end
|
# frozen_string_literal: true
require_relative 'base'
module DiscourseTranslator
class Microsoft < Base
DATA_URI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
SCOPE_URI = "api.cognitive.microsofttranslator.com"
GRANT_TYPE = "client_credentials"
TRANSLATE_URI = "https://api.cognitive.microsofttranslator.com/translate"
DETECT_URI = "https://api.cognitive.microsofttranslator.com/detect"
ISSUE_TOKEN_URI = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"
LENGTH_LIMIT = 10_000
SUPPORTED_LANG = {
en: 'en',
en_US: 'en',
bs_BA: 'bs-Latn',
cs: 'cs',
da: 'da',
de: 'de',
ar: 'ar',
es: 'es',
fi: 'fi',
fr: 'fr',
he: 'he',
id: 'id',
it: 'it',
ja: 'ja',
ko: 'ko',
nl: 'nl',
pt: 'pt',
ro: 'ro',
ru: 'ru',
sv: 'sv',
uk: 'uk',
zh_CN: 'zh-CHS',
zh_TW: 'zh-CHT',
tr_TR: 'tr',
te: nil,
sq: nil,
pt_BR: 'pt',
pl_PL: 'pl',
no_NO: 'no',
fa_IR: 'fa'
}
def self.access_token_key
"microsoft-translator"
end
def self.access_token
existing_token = $redis.get(cache_key)
if existing_token
return existing_token
else
if !SiteSetting.translator_azure_subscription_key.blank?
response = Excon.post("#{DiscourseTranslator::Microsoft::ISSUE_TOKEN_URI}?Subscription-Key=#{SiteSetting.translator_azure_subscription_key}")
if response.status == 200 && (response_body = response.body).present?
$redis.setex(cache_key, 8.minutes.to_i, response_body)
response_body
elsif response.body.blank?
raise TranslatorError.new(I18n.t("translator.microsoft.missing_token"))
else
body = JSON.parse(response.body)
raise TranslatorError.new("#{body['statusCode']}: #{body['message']}")
end
end
end
end
def self.detect(post)
post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] ||= begin
text = post.raw.truncate(LENGTH_LIMIT)
body = [
{ "Text" => text }
].to_json
uri = URI(DETECT_URI)
uri.query = URI.encode_www_form(self.default_query)
response_body = result(
uri.to_s,
body,
default_headers
)
response_body.first["language"]
end
end
def self.translate(post)
detected_lang = detect(post)
if !SUPPORTED_LANG.keys.include?(detected_lang.to_sym) &&
!SUPPORTED_LANG.values.include?(detected_lang.to_s)
raise TranslatorError.new(I18n.t('translator.failed'))
end
raise TranslatorError.new(I18n.t('translator.too_long')) if post.cooked.length > LENGTH_LIMIT
translated_text = from_custom_fields(post) do
query = default_query.merge(
"from" => detected_lang,
"to" => locale
)
body = [
{ "Text" => post.cooked }
].to_json
uri = URI(TRANSLATE_URI)
uri.query = URI.encode_www_form(query)
response_body = result(uri.to_s, body, default_headers)
response_body.first["translations"].first["text"]
end
[detected_lang, translated_text]
end
private
def self.locale
SUPPORTED_LANG[I18n.locale] || (raise I18n.t("translator.not_supported"))
end
def self.post(uri, body, headers = {})
Excon.post(uri, body: body, headers: headers)
end
def self.result(uri, body, headers)
response = post(uri, body, headers)
response_body = JSON.parse(response.body)
if response.status != 200
raise TranslatorError.new(response_body)
else
response_body
end
end
def self.default_headers
{
'Authorization' => "Bearer #{access_token}",
'Content-Type' => 'application/json'
}
end
def self.default_query
{
"api-version" => "3.0"
}
end
end
end
Use zh-Hans and zh-Hant as language codes for Microsoft API
# frozen_string_literal: true
require_relative 'base'
module DiscourseTranslator
class Microsoft < Base
DATA_URI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
SCOPE_URI = "api.cognitive.microsofttranslator.com"
GRANT_TYPE = "client_credentials"
TRANSLATE_URI = "https://api.cognitive.microsofttranslator.com/translate"
DETECT_URI = "https://api.cognitive.microsofttranslator.com/detect"
ISSUE_TOKEN_URI = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"
LENGTH_LIMIT = 10_000
SUPPORTED_LANG = {
en: 'en',
en_US: 'en',
bs_BA: 'bs-Latn',
cs: 'cs',
da: 'da',
de: 'de',
ar: 'ar',
es: 'es',
fi: 'fi',
fr: 'fr',
he: 'he',
id: 'id',
it: 'it',
ja: 'ja',
ko: 'ko',
nl: 'nl',
pt: 'pt',
ro: 'ro',
ru: 'ru',
sv: 'sv',
uk: 'uk',
zh_CN: 'zh-Hans',
zh_TW: 'zh-Hant',
tr_TR: 'tr',
te: nil,
sq: nil,
pt_BR: 'pt',
pl_PL: 'pl',
no_NO: 'no',
fa_IR: 'fa'
}
def self.access_token_key
"microsoft-translator"
end
def self.access_token
existing_token = $redis.get(cache_key)
if existing_token
return existing_token
else
if !SiteSetting.translator_azure_subscription_key.blank?
response = Excon.post("#{DiscourseTranslator::Microsoft::ISSUE_TOKEN_URI}?Subscription-Key=#{SiteSetting.translator_azure_subscription_key}")
if response.status == 200 && (response_body = response.body).present?
$redis.setex(cache_key, 8.minutes.to_i, response_body)
response_body
elsif response.body.blank?
raise TranslatorError.new(I18n.t("translator.microsoft.missing_token"))
else
body = JSON.parse(response.body)
raise TranslatorError.new("#{body['statusCode']}: #{body['message']}")
end
end
end
end
def self.detect(post)
post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] ||= begin
text = post.raw.truncate(LENGTH_LIMIT)
body = [
{ "Text" => text }
].to_json
uri = URI(DETECT_URI)
uri.query = URI.encode_www_form(self.default_query)
response_body = result(
uri.to_s,
body,
default_headers
)
response_body.first["language"]
end
end
def self.translate(post)
detected_lang = detect(post)
if !SUPPORTED_LANG.keys.include?(detected_lang.to_sym) &&
!SUPPORTED_LANG.values.include?(detected_lang.to_s)
raise TranslatorError.new(I18n.t('translator.failed'))
end
raise TranslatorError.new(I18n.t('translator.too_long')) if post.cooked.length > LENGTH_LIMIT
translated_text = from_custom_fields(post) do
query = default_query.merge(
"from" => detected_lang,
"to" => locale
)
body = [
{ "Text" => post.cooked }
].to_json
uri = URI(TRANSLATE_URI)
uri.query = URI.encode_www_form(query)
response_body = result(uri.to_s, body, default_headers)
response_body.first["translations"].first["text"]
end
[detected_lang, translated_text]
end
private
def self.locale
SUPPORTED_LANG[I18n.locale] || (raise I18n.t("translator.not_supported"))
end
def self.post(uri, body, headers = {})
Excon.post(uri, body: body, headers: headers)
end
def self.result(uri, body, headers)
response = post(uri, body, headers)
response_body = JSON.parse(response.body)
if response.status != 200
raise TranslatorError.new(response_body)
else
response_body
end
end
def self.default_headers
{
'Authorization' => "Bearer #{access_token}",
'Content-Type' => 'application/json'
}
end
def self.default_query
{
"api-version" => "3.0"
}
end
end
end
|
def self.crc32_crack(start_letter, end_letter, length, salt, hash) # Gets the crc32 code of the given length using the range from a start_letter...end_letter that matches the salt/hash
(start_letter..end_letter).to_a.repeated_permutation(length.to_i).each do |guess|
guess = guess.join
return guess if (crc32_check(guess + salt).to_i == hash.to_i)
end
end
def self.crc32_check(str, js_32_bit = true)
table = Zlib::crc_table.map {|el| el.to_s(16).upcase} # hex crc32 table
crc = 0
crc = crc ^ (-1)
max_32_int = (2**32)
str.length.times do |k|
a = (crc >> 8)
b = ("0x" + table[((crc ^ str[k].ord ) & 0x000000FF)]).to_i(16)
crc = (a ^ b)
if js_32_bit # See http://stackoverflow.com/questions/17056263/getting-the-same-result-from-ruby-as-javascript-for-bitwise-xor?noredirect=1#comment24669730_17056263
if crc > (max_32_int/2)
crc = crc - max_32_int
elsif crc < -(max_32_int/2)
crc = crc + max_32_int
end
end
end
crc = crc ^ (-1)
crc = crc.abs
return crc
end
Removed redundant table build
def self.crc32_crack(start_letter, end_letter, length, salt, hash) # Gets the crc32 code of the given length using the range from a start_letter...end_letter that matches the salt/hash
(start_letter..end_letter).to_a.repeated_permutation(length.to_i).each do |guess|
guess = guess.join
return guess if (crc32_check(guess + salt).to_i == hash.to_i)
end
end
def self.crc32_check(str, js_32_bit = true)
crc = 0
crc = crc ^ (-1)
max_32_int = (2**32)
str.length.times do |k|
a = (crc >> 8)
b = Zlib::crc_table[((crc ^ str[k].ord ) & 0x000000FF)]
crc = (a ^ b)
if js_32_bit # See http://stackoverflow.com/questions/17056263/getting-the-same-result-from-ruby-as-javascript-for-bitwise-xor?noredirect=1#comment24669730_17056263
if crc > (max_32_int/2)
crc = crc - max_32_int
elsif crc < -(max_32_int/2)
crc = crc + max_32_int
end
end
end
crc = crc ^ (-1)
crc = crc.abs
return crc
end
|
class AbilityLoader < GraphQL::Batch::Loader
def initialize(model)
@model = model
return if [User, UserConProfile].include?(model)
raise 'model must be either User or UserConProfile'
end
def perform(keys)
associated_records_loader = associated_records_loader(keys)
users_with_keys(keys).each do |(key, user)|
fulfill(key, Ability.new(user, associated_records_loader: associated_records_loader))
end
keys.each { |key| fulfill(key, nil) unless fulfilled?(key) }
end
private
def user_ids(keys)
if @model == UserConProfile
keys.map(&:user_id)
else
keys.map(&:id)
end
end
def associated_records_loader(keys)
Ability::AssociatedRecordsLoader.new(user_ids(keys))
end
def users_with_keys(keys)
if @model == UserConProfile
user_con_profiles_by_user_id = keys.index_by(&:user_id)
User.where(id: user_con_profiles_by_user_id.keys).map do |user|
[user_con_profiles_by_user_id[user.id], user]
end
else
keys.map { |user| [user, user] }
end
end
end
Unbreak loading abilities in GraphQL
class AbilityLoader < GraphQL::Batch::Loader
def initialize(model)
@model = model
return if [User, UserConProfile].include?(model)
raise 'model must be either User or UserConProfile'
end
def perform(keys)
associated_records_loader = associated_records_loader(keys)
users_with_keys(keys).each do |(key, user)|
fulfill(key, Ability.new(user, nil, associated_records_loader: associated_records_loader))
end
keys.each { |key| fulfill(key, nil) unless fulfilled?(key) }
end
private
def user_ids(keys)
if @model == UserConProfile
keys.map(&:user_id)
else
keys.map(&:id)
end
end
def associated_records_loader(keys)
Ability::AssociatedRecordsLoader.new(user_ids(keys))
end
def users_with_keys(keys)
if @model == UserConProfile
user_con_profiles_by_user_id = keys.index_by(&:user_id)
User.where(id: user_con_profiles_by_user_id.keys).map do |user|
[user_con_profiles_by_user_id[user.id], user]
end
else
keys.map { |user| [user, user] }
end
end
end
|
# Copyright: 2007-2010 Thomas von Deyen and Carsten Fregin
# Author: Thomas von Deyen
# Date: 02.06.2010
# License: GPL
# All methods (helpers) in this helper are used by Alchemy to render elements, contents and layouts on the Page.
# You can call this helper the most important part of Alchemy. This helper is Alchemy, actually :)
#
# TODO: list all important infos here.
#
# Most Important Infos:
# ---
#
# 1. The most important helpers for webdevelopers are the render_navigation(), render_elements() and the render_page_layout() helpers.
# 2. The currently displayed page can be accessed via the @page variable.
# 3. All important meta data from @page will be rendered via the render_meta_data() helper.
module AlchemyHelper
include FastGettext::Translation
def configuration(name)
return Alchemy::Configuration.parameter(name)
end
# Did not know of the truncate helepr form rails at this time.
# The way is to pass this to truncate....
def shorten(text, length)
if text.length <= length - 1
text
else
text[0..length - 1] + "..."
end
end
def render_editor(element)
render_element(element, :editor)
end
def get_content(element, position)
return element.contents[position - 1]
end
# Renders all elements from @page.
# ---
# == Options are:
# :only => [] A list of element names to be rendered only. Very usefull if you want to render a specific element type in a special html part (e.g.. <div>) of your page and all other elements in another part.
# :except => [] A list of element names to be rendered. The opposite of the only option.
# :from_page The Page.page_layout string from which the elements are rendered from, or you even pass a Page object.
# :count The amount of elements to be rendered (beginns with first element found)
# :fallback => {:for => 'ELEMENT_NAME', :with => 'ELEMENT_NAME', :from => 'PAGE_LAYOUT'} when no element from this name is found on page, then use this element from that page
# :sort_by => Content#name A Content name to sort the elements by
# :reverse => boolean Reverse the rendering order
#
# This helper also stores all pages where elements gets rendered on, so we can sweep them later if caching expires!
#
def render_elements(options = {})
default_options = {
:except => [],
:only => [],
:from_page => "",
:count => nil,
:render_format => "html",
:fallback => nil
}
options = default_options.merge(options)
if options[:from_page].blank?
page = @page
else
if options[:from_page].class == Page
page = options[:from_page]
else
page = Page.find_all_by_page_layout_and_language_id(options[:from_page], session[:language_id])
end
end
if page.blank?
warning('Page is nil')
return ""
else
show_non_public = configuration(:cache_pages) ? false : defined?(current_user)
if page.class == Array
all_elements = page.collect { |p| p.find_elements(options, show_non_public) }.flatten
else
all_elements = page.find_elements(options, show_non_public)
end
unless options[:sort_by].blank?
all_elements = all_elements.sort_by { |e| e.contents.detect { |c| c.name == options[:sort_by] }.ingredient }
end
all_elements.reverse! if options[:reverse_sort] || options[:reverse]
element_string = ""
if options[:fallback]
unless all_elements.detect { |e| e.name == options[:fallback][:for] }
from = Page.find_by_page_layout(options[:fallback][:from])
all_elements += from.elements.find_all_by_name(options[:fallback][:with].blank? ? options[:fallback][:for] : options[:fallback][:with])
end
end
all_elements.each_with_index do |element, i|
element_string += render_element(element, :view, options, i+1)
end
element_string
end
end
# This helper renders the Element partial for either the view or the editor part.
# Generate element partials with ./script/generate elements
def render_element(element, part = :view, options = {}, i = 1)
if element.blank?
warning('Element is nil')
render :partial => "elements/#{part}_not_found", :locals => {:name => 'nil'}
else
default_options = {
:shorten_to => nil,
:render_format => "html"
}
options = default_options.merge(options)
element.store_page(@page) if part == :view
path1 = "#{RAILS_ROOT}/app/views/elements/"
path2 = "#{RAILS_ROOT}/vendor/plugins/alchemy/app/views/elements/"
partial_name = "_#{element.name.underscore}_#{part}.html.erb"
if File.exists?(path1 + partial_name) || File.exists?(path2 + partial_name)
render(
:partial => "elements/#{element.name.underscore}_#{part}.#{options[:render_format]}.erb",
:locals => {
:element => element,
:options => options,
:counter => i
}
)
else
warning(%(
Element #{part} partial not found for #{element.name}.\n
Looking for #{partial_name}, but not found
neither in #{path1}
nor in #{path2}
Use ./script/generate elements to generate them.
Maybe you still have old style partial names? (like .rhtml). Then please rename them in .html.erb'
))
render :partial => "elements/#{part}_not_found", :locals => {:name => element.name, :error => "Element #{part} partial not found. Use ./script/generate elements to generate them."}
end
end
end
# DEPRICATED: It is useless to render a helper that only renders a partial.
# Unless it is something the website producer uses. But this is not the case here.
def render_element_head element
render :partial => "elements/partials/element_head", :locals => {:element_head => element}
end
# Renders the Content partial that is given (:editor, or :view).
# You can pass several options that are used by the different contents.
#
# For the view partial:
# :image_size => "111x93" Used by EssencePicture to render the image via RMagick to that size.
# :css_class => "" This css class gets attached to the content view.
# :date_format => "Am %d. %m. %Y, um %H:%Mh" Espacially fot the EssenceDate. See Date.strftime for date formatting.
# :caption => true Pass true to enable that the EssencePicture.caption value gets rendered.
# :blank_value => "" Pass a String that gets rendered if the content.essence is blank.
#
# For the editor partial:
# :css_class => "" This css class gets attached to the content editor.
# :last_image_deletable => false Pass true to enable that the last image of an imagecollection (e.g. image gallery) is deletable.
def render_essence(content, part = :view, options = {})
if content.nil?
return part == :view ? "" : warning('Content is nil', _("content_not_found"))
elsif content.essence.nil?
return part == :view ? "" : warning('Essence is nil', _("content_essence_not_found"))
end
defaults = {
:for_editor => {
:as => 'text_field',
:css_class => 'long',
:render_format => "html"
},
:for_view => {
:image_size => "120x90",
:css_class => "",
:date_format => "%d. %m. %Y, %H:%Mh",
:caption => true,
:blank_value => "",
:render_format => "html"
}
}
options_for_partial = defaults[('for_' + part.to_s).to_sym].merge(options[('for_' + part.to_s).to_sym])
options = options.merge(defaults)
render(
:partial => "essences/#{content.essence.class.name.underscore}_#{part.to_s}.#{options_for_partial[:render_format]}.erb",
:locals => {
:content => content,
:options => options_for_partial
}
)
end
# Renders the Content editor partial from the given Content.
# For options see -> render_essence
def render_essence_editor(content, options = {})
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content view partial from the given Content.
# For options see -> render_essence
def render_essence_view(content, options = {})
render_essence(content, :view, :for_view => options)
end
# Renders the Content editor partial from the given Element for the essence_type (e.g. EssenceRichtext).
# For multiple contents of same kind inside one molecue just pass a position so that will be rendered.
# Otherwise the first content found for this type will be rendered.
# For options see -> render_essence
def render_essence_editor_by_type(element, type, position = nil, options = {})
if element.blank?
return warning('Element is nil', _("no_element_given"))
end
if position.nil?
content = element.content_by_type(type)
else
content = element.contents.find_by_essence_type_and_position(type, position)
end
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content view partial from the given Element for the essence_type (e.g. EssenceRichtext).
# For multiple contents of same kind inside one molecue just pass a position so that will be rendered.
# Otherwise the first content found for this type will be rendered.
# For options see -> render_essence
def render_essence_view_by_type(element, type, position, options = {})
if element.blank?
warning('Element is nil')
return ""
end
if position.nil?
content = element.content_by_type(type)
else
content = element.contents.find_by_essence_type_and_position(type, position)
end
render_essence(content, :view, :for_view => options)
end
# Renders the Content view partial from the given Element by position (e.g. 1).
# For options see -> render_essence
def render_essence_view_by_position(element, position, options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.contents.find_by_position(position)
render_essence(content, :view, :for_view => options)
end
# Renders the Content editor partial from the given Element by position (e.g. 1).
# For options see -> render_essence
def render_essence_editor_by_position(element, position, options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.contents.find_by_position(position)
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content editor partial found in views/contents/ for the content with name inside the passed Element.
# For options see -> render_essence
def render_essence_editor_by_name(element, name, options = {})
if element.blank?
return warning('Element is nil', _("no_element_given"))
end
content = element.content_by_name(name)
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content view partial from the passed Element for passed content name.
# For options see -> render_essence
def render_essence_view_by_name(element, name, options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.content_by_name(name)
render_essence(content, :view, :for_view => options)
end
# Renders the name of elements content or the default name defined in elements.yml
def render_content_name(content)
if content.blank?
warning('Element is nil')
return ""
else
content_name = t("content_names.#{content.element.name}.#{content.name}", :default => ["content_names.#{content.name}".to_sym, content.name.capitalize])
end
if content.description.blank?
warning("Content #{content.name} is missing its description")
title = _("Warning: Content '%{contentname}' is missing its description.") % {:contentname => content.name}
content_name = %(<span class="warning icon" title="#{title}"></span> ) + content_name
end
content_name
end
# Returns @page.title
#
# The options are:
# :prefix => ""
# :seperator => "|"
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_page_title options={}
default_options = {
:prefix => "",
:seperator => "|"
}
default_options.update(options)
unless @page.title.blank?
h("#{default_options[:prefix]} #{default_options[:seperator]} #{@page.title}")
else
h("")
end
end
# Returns a complete html <title> tag for the <head> part of the html document.
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_title_tag options={}
default_options = {
:prefix => "",
:seperator => "|"
}
options = default_options.merge(options)
title = render_page_title(options)
%(<title>#{title}</title>)
end
# Renders a html <meta> tag for :name => "" and :content => ""
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_meta_tag(options={})
default_options = {
:name => "",
:default_language => "de",
:content => ""
}
options = default_options.merge(options)
lang = (@page.language.blank? ? options[:default_language] : @page.language.code)
%(<meta name="#{options[:name]}" content="#{options[:content]}" lang="#{lang}" xml:lang="#{lang}" />)
end
# Renders a html <meta http-equiv="Content-Language" content="#{lang}" /> for @page.language.
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_meta_content_language_tag(options={})
default_options = {
:default_language => "de"
}
options = default_options.merge(options)
lang = (@page.language.blank? ? options[:default_language] : @page.language.code)
%(<meta http-equiv="Content-Language" content="#{lang}" />)
end
# = This helper takes care of all important meta tags for your @page.
# ---
# The meta data is been taken from the @page.title, @page.meta_description, @page.meta_keywords, @page.updated_at and @page.language database entries managed by the Alchemy user via the Alchemy cockpit.
#
# Assume that the user has entered following data into the Alchemy cockpit of the Page "home" and that the user wants that the searchengine (aka. google) robot should index the page and should follow all links on this page:
#
# Title = Homepage
# Description = Your page description
# Keywords: cms, ruby, rubyonrails, rails, software, development, html, javascript, ajax
#
# Then placing render_meta_data(:title_prefix => "company", :title_seperator => "::") into the <head> part of the pages.html.erb layout produces:
#
# <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
# <meta http-equiv="Content-Language" content="de" />
# <title>Company :: #{@page.title}</title>
# <meta name="description" content="Your page description" />
# <meta name="keywords" content="cms, ruby, rubyonrails, rails, software, development, html, javascript, ajax" />
# <meta name="generator" content="Alchemy VERSION" />
# <meta name="date" content="Tue Dec 16 10:21:26 +0100 2008" />
# <meta name="robots" content="index, follow" />
#
def render_meta_data options={}
default_options = {
:title_prefix => "",
:title_seperator => "|",
:default_lang => "de"
}
options = default_options.merge(options)
#render meta description of the root page from language if the current meta description is empty
if @page.meta_description.blank?
description = Page.find_by_language_root_and_language_id(true, session[:language_id]).meta_description rescue ""
else
description = @page.meta_description
end
#render meta keywords of the root page from language if the current meta keywords is empty
if @page.meta_keywords.blank?
keywords = Page.find_by_language_root_and_language_id(true, session[:language_id]).meta_keywords rescue ""
else
keywords = @page.meta_keywords
end
robot = "#{@page.robot_index? ? "" : "no"}index, #{@page.robot_follow? ? "" : "no"}follow"
meta_string = %(
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
#{render_meta_content_language_tag}
#{render_title_tag( :prefix => options[:title_prefix], :seperator => options[:title_seperator])}
#{render_meta_tag( :name => "description", :content => description)}
#{render_meta_tag( :name => "keywords", :content => keywords)}
<meta name="generator" content="Alchemy #{configuration(:alchemy_version)}" />
<meta name="date" content="#{@page.updated_at}" />
<meta name="robots" content="#{robot}" />
)
if @page.contains_feed?
meta_string += %(
<link rel="alternate" type="application/rss+xml" title="RSS" href="#{multi_language? ? show_page_with_language_url(:protocol => 'feed', :urlname => @page.urlname, :lang => Alchemy::Controller.current_language.code, :format => :rss) : show_page_url(:protocol => 'feed', :urlname => @page.urlname, :format => :rss)}" />
)
end
return meta_string
end
# Returns an array of all pages in the same branch from current. Used internally to find the active page in navigations.
def breadcrumb(current)
return [] if current.nil?
result = Array.new
result << current
while current = current.parent
result << current
end
return result.reverse
end
# Returns a html string for a linked breadcrumb from root to current page.
# == Options:
# :seperator => %(<span class="seperator">></span>) Maybe you don't want this seperator. Pass another one.
# :page => @page Pass a different Page instead of the default (@page).
# :without => nil Pass Pageobject or array of Pages that must not be displayed.
# :public_only => false Pass boolean for displaying hidden pages only.
# :visible_only => true Pass boolean for displaying (in navigation) visible pages only.
# :restricted_only => false Pass boolean for displaying restricted pages only.
# :reverse => false Pass boolean for displaying reversed breadcrumb.
def render_breadcrumb(options={})
default_options = {
:seperator => %(<span class="seperator">></span>),
:page => @page,
:without => nil,
:public_only => false,
:visible_only => true,
:restricted_only => false,
:reverse => false
}
options = default_options.merge(options)
pages = breadcrumb(options[:page])
pages.delete(Page.root)
unless options[:without].nil?
unless options[:without].class == Array
pages.delete(options[:without])
else
pages = pages - options[:without]
end
end
if(options[:visible_only])
pages.reject!{|p| !p.visible? }
end
if(options[:public_only])
pages.reject!{|p| !p.public? }
end
if(options[:restricted_only])
pages.reject!{|p| !p.restricted? }
end
if(options[:reverse])
pages.reverse!
end
bc = []
pages.each do |page|
urlname = page.urlname
(page.name == @page.name) ? css_class = "active" : nil
if page == pages.last
css_class.blank? ? css_class = "last" : css_class = [css_class, "last"].join(" ")
elsif page == pages.first
css_class.blank? ? css_class = "first" : css_class = [css_class, "last"].join(" ")
end
if multi_language?
url = show_page_with_language_url(:urlname => urlname, :lang => Alchemy::Controller.current_language.code)
else
url = show_page_url(:urlname => urlname)
end
bc << link_to( h(page.name), url, :class => css_class, :title => page.title )
end
bc.join(options[:seperator])
end
# returns true if page is in the active branch
def page_active? page
@breadcrumb ||= breadcrumb(@page)
@breadcrumb.include? page
end
# = This helper renders the navigation.
#
# It produces a html <ul><li></li></ul> structure with all necessary classes and ids so you can produce nearly every navigation the web uses today.
# E.G. dropdown-navigations, simple mainnavigations or even complex nested ones.
# ---
# == En detail:
#
# <ul>
# <li class="first" id="home"><a href="home" class="active">Homepage</a></li>
# <li id="contact"><a href="contact">Contact</a></li>
# <li class="last" id="imprint"><a href="imprint">Imprint</a></li>
# </ul>
#
# As you can see: Everything you need.
#
# Not pleased with the way Alchemy produces the navigation structure?
# Then feel free to overwrite the partials (_navigation_renderer.html.erb and _navigation_link.html.erb) found in views/pages/partials/ or pass different partials via the options :navigation_partial and :navigation_link_partial.
#
# == The options are:
#
# :submenu => false Do you want a nested <ul> <li> structure for the deeper levels of your navigation, or not? Used to display the subnavigation within the mainnaviagtion. E.g. for dropdown menues.
# :from_page => @root_page Do you want to render a navigation from a different page then the current page? Then pass an Page instance or a PageLayout name as string.
# :spacer => "" Yeah even a spacer for the entries can be passed. Simple string, or even a complex html structure. E.g: "<span class='spacer'>|</spacer>". Only your imagination is the limit. And the W3C of course :)
# :navigation_partial => "navigation_renderer" Pass a different partial to be taken for the navigation rendering. CAUTION: Only for the advanced Alchemy webdevelopers. The standard partial takes care of nearly everything. But maybe you are an adventures one ^_^
# :navigation_link_partial => "navigation_link" Alchemy places an <a> html link in <li> tags. The tag automatically has an active css class if necessary. So styling is everything. But maybe you don't want this. So feel free to make you own partial and pass the filename here.
# :show_nonactive => false Commonly Alchemy only displays the submenu of the active page (if :submenu => true). If you want to display all child pages then pass true (together with :submenu => true of course). E.g. for the popular css-driven dropdownmenues these days.
# :show_title => true For our beloved SEOs :). Appends a title attribute to all links and places the page.title content into it.
def render_navigation(options = {})
default_options = {
:submenu => false,
:all_sub_menues => false,
:from_page => @root_page,
:spacer => "",
:navigation_partial => "partials/navigation_renderer",
:navigation_link_partial => "partials/navigation_link",
:show_nonactive => false,
:restricted_only => nil,
:show_title => true,
:reverse => false,
:reverse_children => false
}
options = default_options.merge(options)
if options[:from_page].is_a?(String)
page = Page.find_by_page_layout_and_language_id(options[:from_page], session[:language_id])
else
page = options[:from_page]
end
if page.blank?
warning("No Page found for #{options[:from_page]}")
return ""
end
conditions = {
:parent_id => page.id,
:restricted => options[:restricted_only] || false,
:visible => true
}
if options[:restricted_only].nil?
conditions.delete(:restricted)
end
pages = Page.all(
:conditions => conditions,
:order => "lft ASC"
)
if options[:reverse]
pages.reverse!
end
render :partial => options[:navigation_partial], :locals => {:options => options, :pages => pages}
end
# Renders the children of the given page (standard is the current page), the given page and its siblings if there are no children, or it renders just nil.
# Use this helper if you want to render the subnavigation independent from the mainnavigation. E.g. to place it in a different layer on your website.
# If :from_page's level in the site-hierarchy is greater than :level (standard is 2) and the given page has no children, the returned output will be the :from_page and it's siblings
# This method will assign all its options to the the render_navigation method, so you are able to assign the same options as to the render_navigation method.
# Normally there is no need to change the level parameter, just in a few special cases.
def render_subnavigation(options = {})
default_options = {
:from_page => @page,
:level => 2
}
options = default_options.merge(options)
if !options[:from_page].nil?
if (options[:from_page].children.blank? && options[:from_page].level > options[:level]) || !options[:from_page].children.select{ |page| !page.visible || !page.public }.blank?
options = options.merge(:from_page => Page.find(options[:from_page].parent_id))
end
render_navigation(options)
else
return nil
end
end
# = This helper renders the paginated navigation.
#
# :pagination => {
# :level_X => {
# :size => X,
# :current => params[:navigation_level_X_page]
# }
# } This one is a funky complex pagination option for the navigation. I'll explain in the next episode.
def render_paginated_navigation(options = {})
default_options = {
:submenu => false,
:all_sub_menues => false,
:from_page => @root_page,
:spacer => "",
:pagination => {},
:navigation_partial => "pages/partials/navigation_renderer",
:navigation_link_partial => "pages/partials/navigation_link",
:show_nonactive => false,
:show_title => true,
:level => 1
}
options = default_options.merge(options)
if options[:from_page].nil?
warning('options[:from_page] is nil')
return ""
else
pagination_options = options[:pagination].stringify_keys["level_#{options[:from_page].depth}"]
find_conditions = { :parent_id => options[:from_page].id, :visible => true }
pages = Page.all(
:page => pagination_options,
:conditions => find_conditions,
:order => "lft ASC"
)
render :partial => options[:navigation_partial], :locals => {:options => options, :pages => pages}
end
end
# Used to display the pagination links for the paginated navigation.
def link_to_navigation_pagination name, urlname, pages, page, css_class = ""
p = {}
p["navigation_level_1_page"] = params[:navigation_level_1_page] unless params[:navigation_level_1_page].nil?
p["navigation_level_2_page"] = params[:navigation_level_2_page] unless params[:navigation_level_2_page].nil?
p["navigation_level_3_page"] = params[:navigation_level_3_page] unless params[:navigation_level_3_page].nil?
p["navigation_level_#{pages.to_a.first.depth}_page"] = page
link_to name, show_page_url(urlname, p), :class => (css_class unless css_class.empty?)
end
# Returns true if the current_user (The logged-in Alchemy User) has the admin role.
def is_admin?
return false if !current_user
current_user.admin?
end
# This helper renders the link for a protoypejs-window overlay. We use this for our fancy modal overlay windows in the Alchemy cockpit.
def link_to_overlay_window(content, url, options={}, html_options={})
default_options = {
:size => "100x100",
:resizable => false,
:modal => true
}
options = default_options.merge(options)
link_to_function(
content,
"Alchemy.openWindow(
\'#{url}\',
\'#{options[:title]}\',
\'#{options[:size].split('x')[0].to_s}\',
\'#{options[:size].split('x')[1].to_s}\',
\'#{options[:resizable]}\',
\'#{options[:modal]}\',
\'#{options[:overflow]}\'
)",
html_options
)
end
# Used for rendering the folder link in Admin::Pages.index sitemap.
def sitemapFolderLink(page)
return '' if page.level == 1
if page.folded?(current_user.id)
css_class = 'folded'
title = _('Show childpages')
else
css_class = 'collapsed'
title = _('Hide childpages')
end
link_to_remote(
'',
:url => {
:controller => 'admin/pages',
:action => :fold,
:id => page.id
},
:html => {
:class => "page_folder #{css_class}",
:title => title,
:id => "fold_button_#{page.id}"
}
)
end
# Renders an image_tag with an file icon for files suffix.
# The images are in vendor/plugins/alchemy/assets/images/file_icons
# They will be copyied into public/alchemy/file_icons on app launch.
#
# ===Fileicons so far:
#
# * GIF
# * PDF
# * FLV (Flashvideo)
# * ZIP
# * SWF (Flashmovie)
# * MP3
# * Empty File
#
def render_file_icon file
case file.filename.split(".").last
when "pdf"
then icon = "pdf.png"
when "flv"
then icon = "flv.png"
when "gif"
then icon = "gif.png"
when "zip"
then icon = "zip.png"
when "mp3"
then icon = "mp3.png"
when "swf"
then icon = "swf.png"
when "doc"
then icon = "doc.png"
when "jpg"
then icon = "jpg.png"
else
icon = "file.png"
end
image_tag("alchemy/file_icons/#{icon}")
end
# Renders an image_tag from for an image in public/images folder so it can be cached.
# *Not really working!*
def static_image_tag image, options={}
image_tag url_for(:controller => :images, :action => :show_static, :image => image)
end
# Renders the layout from @page.page_layout. File resists in /app/views/page_layouts/_LAYOUT-NAME.html.erb
def render_page_layout(options={})
default_options = {
:render_format => "html"
}
options = default_options.merge(options)
if File.exists?("#{RAILS_ROOT}/app/views/page_layouts/_#{@page.page_layout.downcase}.#{options[:render_format]}.erb") || File.exists?("#{RAILS_ROOT}/vendor/plugins/alchemy/app/views/page_layouts/_#{@page.page_layout.downcase}.#{options[:render_format]}.erb")
render :partial => "page_layouts/#{@page.page_layout.downcase}.#{options[:render_format]}.erb"
else
render :partial => "page_layouts/standard"
end
end
# Returns @current_language set in the action (e.g. Page.show)
def current_language
if @current_language.nil?
warning('@current_language is not set')
return nil
else
@current_language
end
end
# Returns true if the current page is the root page in the nested set of Pages, false if not.
def root_page?
@page == @root_page
end
# Returns the full url containing host, page and anchor for the given element
def full_url_for_element element
"http://" + request.env["HTTP_HOST"] + "/" + element.page.urlname + "##{element.name}_#{element.id}"
end
# Used for language selector in Alchemy cockpit sitemap. So the user can select the language branche of the page.
def language_codes_for_select
configuration(:languages).collect{ |language|
language[:language_code]
}
end
# Used for translations selector in Alchemy cockpit user settings.
def translations_for_select
configuration(:translations).collect{ |translation|
[translation[:language], translation[:language_code]]
}
end
# Used by Alchemy to display a javascript driven filter for lists in the Alchemy cockpit.
def js_filter_field options = {}
default_options = {
:class => "thin_border js_filter_field",
:onkeyup => "Alchemy.ListFilter('#contact_list li')",
:id => "search_field"
}
options = default_options.merge(options)
options[:onkeyup] << ";jQuery('#search_field').val().length >= 1 ? jQuery('.js_filter_field_clear').show() : jQuery('.js_filter_field_clear').hide();"
filter_field = "<div class=\"js_filter_field_box\">"
filter_field << text_field_tag("filter", "", options)
filter_field << link_to_function(
"",
"$('#{options[:id]}').value = '';#{options[:onkeyup]}",
:class => "js_filter_field_clear",
:style => "display:none",
:title => _("click_to_show_all")
)
filter_field << ("<br /><label for=\"search_field\">" + _("search") + "</label>")
filter_field << "</div>"
filter_field
end
def clipboard_select_tag(items, html_options = {})
unless items.blank?
options = [[_('Please choose'), ""]]
items.each do |item|
options << [item.class.to_s == 'Element' ? item.display_name_with_preview_text : item.name, item.id]
end
select_tag(
'paste_from_clipboard',
options_for_select(options),
{
:class => html_options[:class] || 'very_long',
:style => html_options[:style]
}
)
end
end
# returns all elements that could be placed on that page because of the pages layout as array to be used in alchemy_selectbox form builder
def elements_for_select(elements)
return [] if elements.nil?
elements.collect{ |p| [p["display_name"], p["name"]] }
end
def link_to_confirmation_window(link_string = "", message = "", url = "", html_options = {})
title = _("please_confirm")
ok_lable = _("yes")
cancel_lable = _("no")
link_to_function(
link_string,
"Alchemy.confirmToDeleteWindow('#{url}', '#{title}', '#{message}', '#{ok_lable}', '#{cancel_lable}');",
html_options
)
end
def page_selector(element, content_name, options = {}, select_options = {})
default_options = {
:except => {
:page_layout => [""]
},
:only => {
:page_layout => [""]
}
}
options = default_options.merge(options)
content = element.content_by_name(content_name)
if content.nil?
return warning('Content', _('content_not_found'))
elsif content.essence.nil?
return warning('Content', _('content_essence_not_found'))
end
pages = Page.find(
:all,
:conditions => {
:language_id => session[:language_id],
:page_layout => options[:only][:page_layout],
:public => true
}
)
select_tag(
"contents[content_#{content.id}][body]",
pages_for_select(pages, content.essence.body),
select_options
)
end
# Returns all Pages found in the database as an array for the rails select_tag helper.
# You can pass a collection of pages to only returns these pages as array.
# Pass an Page.name or Page.urlname as second parameter to pass as selected for the options_for_select helper.
def pages_for_select(pages = nil, selected = nil, prompt = "Bitte wählen Sie eine Seite")
result = [[prompt, ""]]
if pages.blank?
pages = Page.find_all_by_language_id_and_public(session[:language_id], true)
end
pages.each do |p|
result << [p.send(:name), p.send(:urlname)]
end
options_for_select(result, selected)
end
# Returns all public elements found by Element.name.
# Pass a count to return only an limited amount of elements.
def all_elements_by_name(name, options = {})
warning('options[:language] option not allowed any more in all_elements_by_name helper')
default_options = {
:count => :all,
:from_page => :all
}
options = default_options.merge(options)
if options[:from_page] == :all
elements = Element.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])
elsif options[:from_page].class == String
page = Page.find_by_page_layout_and_language_id(options[:from_page], session[:language_id])
return [] if page.blank?
elements = page.elements.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])
else
elements = options[:from_page].elements.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])
end
end
# Returns the public element found by Element.name from the given public Page, either by Page.id or by Page.urlname
def element_from_page(options = {})
default_options = {
:page_urlname => "",
:page_id => nil,
:element_name => ""
}
options = default_options.merge(options)
if options[:page_id].blank?
page = Page.find_by_urlname_and_public(options[:page_urlname], true)
else
page = Page.find_by_id_and_public(options[:page_id], true)
end
return "" if page.blank?
element = page.elements.find_by_name_and_public(options[:element_name], true)
return element
end
# This helper renderes the picture editor for the elements on the Alchemy Desktop.
# It brings full functionality for adding images to the element, deleting images from it and sorting them via drag'n'drop.
# Just place this helper inside your element editor view, pass the element as parameter and that's it.
#
# Options:
# :maximum_amount_of_images (integer), default nil. This option let you handle the amount of images your customer can add to this element.
def render_picture_editor(element, options={})
default_options = {
:last_image_deletable => true,
:maximum_amount_of_images => nil,
:refresh_sortable => true
}
options = default_options.merge(options)
picture_contents = element.all_contents_by_type("EssencePicture")
render(
:partial => "admin/elements/picture_editor",
:locals => {
:picture_contents => picture_contents,
:element => element,
:options => options
}
)
end
def render_essence_selection_editor(element, content, select_options)
if content.class == String
content = element.contents.find_by_name(content)
else
content = element.contents[content - 1]
end
if content.essence.nil?
return warning('Element', _('content_essence_not_found'))
end
select_options = options_for_select(select_options, content.essence.content)
select_tag(
"contents[content_#{content.id}]",
select_options
)
end
# TOOD: include these via asset_packer yml file
def stylesheets_from_plugins
Dir.glob("vendor/plugins/*/assets/stylesheets/*.css").select{|s| !s.include? "vendor/plugins/alchemy"}.inject("") do |acc, s|
filename = File.basename(s)
plugin = s.split("/")[2]
acc << stylesheet_link_tag("#{plugin}/#{filename}")
end
end
# TOOD: include these via asset_packer yml file
def javascripts_from_plugins
Dir.glob("vendor/plugins/*/assets/javascripts/*.js").select{|s| !s.include? "vendor/plugins/alchemy"}.inject("") do |acc, s|
filename = File.basename(s)
plugin = s.split("/")[2]
acc << javascript_include_tag("#{plugin}/#{filename}")
end
end
def admin_main_navigation
navigation_entries = alchemy_plugins.collect{ |p| p["navigation"] }
render :partial => 'layouts/partials/mainnavigation_entry', :collection => navigation_entries.flatten
end
# Renders the Subnavigation for the admin interface.
def render_admin_subnavigation(entries)
render :partial => "layouts/partials/sub_navigation", :locals => {:entries => entries}
end
def admin_subnavigation
plugin = alchemy_plugin(:controller => params[:controller], :action => params[:action])
unless plugin.nil?
entries = plugin["navigation"]['sub_navigation']
render_admin_subnavigation(entries) unless entries.nil?
else
""
end
end
def admin_mainnavi_active?(mainnav)
subnavi = mainnav["sub_navigation"]
nested = mainnav["nested"]
if !subnavi.blank?
(!subnavi.detect{ |subnav| subnav["controller"] == params[:controller] && subnav["action"] == params[:action] }.blank?) ||
(!nested.nil? && !nested.detect{ |n| n["controller"] == params[:controller] && n["action"] == params[:action] }.blank?)
else
mainnav["controller"] == params[:controller] && mainnav["action"] == params["action"]
end
end
# Generates the url for the preview frame.
# target_url must contain target_controller and target_action.
def generate_preview_url(target_url)
preview_url = url_for(
:controller => ('/' + target_url["target_controller"]),
:action => target_url["target_action"],
:id => params[:id]
)
end
# Returns a string for the id attribute of a html element for the given element
def element_dom_id(element)
return "" if element.nil?
"#{element.name}_#{element.id}"
end
# Returns a string for the id attribute of a html element for the given content
def content_dom_id(content)
return "" if content.nil?
if content.class == String
a = Content.find_by_name(content)
return "" if a.nil?
else
a = content
end
"#{a.essence_type.underscore}_#{a.id}"
end
# Helper for including the nescessary javascripts and stylesheets for the different views.
# Together with the rails caching we achieve a good load time.
def alchemy_assets_set(setname = 'combined')
asset_sets = YAML.load_file(File.join(File.dirname(__FILE__), '..', '..', 'config/asset_packages.yml'))
content_for(:javascript_includes) do
js_set = asset_sets['javascripts'].detect { |js| js[setname.to_s] }[setname.to_s]
javascript_include_tag(js_set, :cache => 'alchemy/' + setname.to_s)
end
content_for(:stylesheets) do
css_set = asset_sets['stylesheets'].detect { |css| css[setname.to_s] }[setname.to_s]
stylesheet_link_tag(css_set, :cache => 'alchemy/' + setname.to_s)
end
end
def parse_sitemap_name(page)
if multi_language?
pathname = "/#{session[:language_code]}/#{page.urlname}"
else
pathname = "/#{page.urlname}"
end
pathname
end
def render_new_content_link(element)
link_to_overlay_window(
_('add new content'),
new_admin_element_content_path(element),
{
:size => '305x40',
:title => _('Select an content'),
:overflow => true
},
{
:id => "add_content_for_element_#{element.id}",
:class => 'button new_content_link'
}
)
end
def render_create_content_link(element, options = {})
defaults = {
:label => _('add new content')
}
options = defaults.merge(options)
link_to_remote(
options[:label],
{
:url => contents_path(
:content => {
:name => options[:content_name],
:element_id => element.id
}
),
:method => 'post'
},
{
:id => "add_content_for_element_#{element.id}",
:class => 'button new_content_link'
}
)
end
# Returns an icon
def render_icon(icon_class)
content_tag('span', '', :class => "icon #{icon_class}")
end
def alchemy_preview_mode_code
if @preview_mode
append_javascript = %(
var s = document.createElement('script');
s.src = '/javascripts/alchemy/jquery-1.5.min.js';
s.language = 'javascript';
s.type = 'text/javascript';
document.getElementsByTagName("body")[0].appendChild(s);
)
str = javascript_tag("if(typeof(jQuery)=='function'){jQuery.noConflict();}else{#{append_javascript}}")
str += javascript_include_tag("alchemy/alchemy")
str += javascript_tag("jQuery(document).ready(function(){Alchemy.ElementSelector();});jQuery('a').attr('href', 'javascript:void(0)');")
return str
else
return nil
end
end
def element_preview_code(element)
if @preview_mode
"data-alchemy-element='#{element.id}'"
end
end
# Logs a message in the Rails logger (warn level) and optionally displays an error message to the user.
def warning(message, text = nil)
logger.warn %(\n
++++ WARNING: #{message}! from: #{caller.first}\n
)
unless text.nil?
warning = content_tag('p', :class => 'content_editor_error') do
render_icon('warning') + text
end
return warning
end
end
def alchemy_combined_assets
alchemy_assets_set
end
# This helper returns a path for use inside a link_to helper.
# You may pass a page_layout or an urlname.
# Any additional options are passed to the url_helper, so you can add arguments to your url.
# Example:
# <%= link_to '» order now', page_path_for(:page_layout => 'orderform', :product_id => element.id) %>
def page_path_for(options={})
return warning("No page_layout, or urlname given. I got #{options.inspect} ") if options[:page_layout].blank? && options[:urlname].blank?
if options[:urlname].blank?
page = Page.find_by_page_layout(options[:page_layout])
return warning("No page found for #{options.inspect} ") if page.blank?
urlname = page.urlname
else
urlname = options[:urlname]
end
if multi_language?
show_page_with_language_path({:urlname => urlname, :lang => @language.code}.merge(options.except(:page_layout, :urlname)))
else
show_page_path({:urlname => urlname}.merge(options.except(:page_layout, :urlname)))
end
end
# Returns the current page.
def current_page
@page
end
end
Fixing inclusion of jQuery in alchemy_preview_mode_code() helper
# Copyright: 2007-2010 Thomas von Deyen and Carsten Fregin
# Author: Thomas von Deyen
# Date: 02.06.2010
# License: GPL
# All methods (helpers) in this helper are used by Alchemy to render elements, contents and layouts on the Page.
# You can call this helper the most important part of Alchemy. This helper is Alchemy, actually :)
#
# TODO: list all important infos here.
#
# Most Important Infos:
# ---
#
# 1. The most important helpers for webdevelopers are the render_navigation(), render_elements() and the render_page_layout() helpers.
# 2. The currently displayed page can be accessed via the @page variable.
# 3. All important meta data from @page will be rendered via the render_meta_data() helper.
module AlchemyHelper
include FastGettext::Translation
def configuration(name)
return Alchemy::Configuration.parameter(name)
end
# Did not know of the truncate helepr form rails at this time.
# The way is to pass this to truncate....
def shorten(text, length)
if text.length <= length - 1
text
else
text[0..length - 1] + "..."
end
end
def render_editor(element)
render_element(element, :editor)
end
def get_content(element, position)
return element.contents[position - 1]
end
# Renders all elements from @page.
# ---
# == Options are:
# :only => [] A list of element names to be rendered only. Very usefull if you want to render a specific element type in a special html part (e.g.. <div>) of your page and all other elements in another part.
# :except => [] A list of element names to be rendered. The opposite of the only option.
# :from_page The Page.page_layout string from which the elements are rendered from, or you even pass a Page object.
# :count The amount of elements to be rendered (beginns with first element found)
# :fallback => {:for => 'ELEMENT_NAME', :with => 'ELEMENT_NAME', :from => 'PAGE_LAYOUT'} when no element from this name is found on page, then use this element from that page
# :sort_by => Content#name A Content name to sort the elements by
# :reverse => boolean Reverse the rendering order
#
# This helper also stores all pages where elements gets rendered on, so we can sweep them later if caching expires!
#
def render_elements(options = {})
default_options = {
:except => [],
:only => [],
:from_page => "",
:count => nil,
:render_format => "html",
:fallback => nil
}
options = default_options.merge(options)
if options[:from_page].blank?
page = @page
else
if options[:from_page].class == Page
page = options[:from_page]
else
page = Page.find_all_by_page_layout_and_language_id(options[:from_page], session[:language_id])
end
end
if page.blank?
warning('Page is nil')
return ""
else
show_non_public = configuration(:cache_pages) ? false : defined?(current_user)
if page.class == Array
all_elements = page.collect { |p| p.find_elements(options, show_non_public) }.flatten
else
all_elements = page.find_elements(options, show_non_public)
end
unless options[:sort_by].blank?
all_elements = all_elements.sort_by { |e| e.contents.detect { |c| c.name == options[:sort_by] }.ingredient }
end
all_elements.reverse! if options[:reverse_sort] || options[:reverse]
element_string = ""
if options[:fallback]
unless all_elements.detect { |e| e.name == options[:fallback][:for] }
from = Page.find_by_page_layout(options[:fallback][:from])
all_elements += from.elements.find_all_by_name(options[:fallback][:with].blank? ? options[:fallback][:for] : options[:fallback][:with])
end
end
all_elements.each_with_index do |element, i|
element_string += render_element(element, :view, options, i+1)
end
element_string
end
end
# This helper renders the Element partial for either the view or the editor part.
# Generate element partials with ./script/generate elements
def render_element(element, part = :view, options = {}, i = 1)
if element.blank?
warning('Element is nil')
render :partial => "elements/#{part}_not_found", :locals => {:name => 'nil'}
else
default_options = {
:shorten_to => nil,
:render_format => "html"
}
options = default_options.merge(options)
element.store_page(@page) if part == :view
path1 = "#{RAILS_ROOT}/app/views/elements/"
path2 = "#{RAILS_ROOT}/vendor/plugins/alchemy/app/views/elements/"
partial_name = "_#{element.name.underscore}_#{part}.html.erb"
if File.exists?(path1 + partial_name) || File.exists?(path2 + partial_name)
render(
:partial => "elements/#{element.name.underscore}_#{part}.#{options[:render_format]}.erb",
:locals => {
:element => element,
:options => options,
:counter => i
}
)
else
warning(%(
Element #{part} partial not found for #{element.name}.\n
Looking for #{partial_name}, but not found
neither in #{path1}
nor in #{path2}
Use ./script/generate elements to generate them.
Maybe you still have old style partial names? (like .rhtml). Then please rename them in .html.erb'
))
render :partial => "elements/#{part}_not_found", :locals => {:name => element.name, :error => "Element #{part} partial not found. Use ./script/generate elements to generate them."}
end
end
end
# DEPRICATED: It is useless to render a helper that only renders a partial.
# Unless it is something the website producer uses. But this is not the case here.
def render_element_head element
render :partial => "elements/partials/element_head", :locals => {:element_head => element}
end
# Renders the Content partial that is given (:editor, or :view).
# You can pass several options that are used by the different contents.
#
# For the view partial:
# :image_size => "111x93" Used by EssencePicture to render the image via RMagick to that size.
# :css_class => "" This css class gets attached to the content view.
# :date_format => "Am %d. %m. %Y, um %H:%Mh" Espacially fot the EssenceDate. See Date.strftime for date formatting.
# :caption => true Pass true to enable that the EssencePicture.caption value gets rendered.
# :blank_value => "" Pass a String that gets rendered if the content.essence is blank.
#
# For the editor partial:
# :css_class => "" This css class gets attached to the content editor.
# :last_image_deletable => false Pass true to enable that the last image of an imagecollection (e.g. image gallery) is deletable.
def render_essence(content, part = :view, options = {})
if content.nil?
return part == :view ? "" : warning('Content is nil', _("content_not_found"))
elsif content.essence.nil?
return part == :view ? "" : warning('Essence is nil', _("content_essence_not_found"))
end
defaults = {
:for_editor => {
:as => 'text_field',
:css_class => 'long',
:render_format => "html"
},
:for_view => {
:image_size => "120x90",
:css_class => "",
:date_format => "%d. %m. %Y, %H:%Mh",
:caption => true,
:blank_value => "",
:render_format => "html"
}
}
options_for_partial = defaults[('for_' + part.to_s).to_sym].merge(options[('for_' + part.to_s).to_sym])
options = options.merge(defaults)
render(
:partial => "essences/#{content.essence.class.name.underscore}_#{part.to_s}.#{options_for_partial[:render_format]}.erb",
:locals => {
:content => content,
:options => options_for_partial
}
)
end
# Renders the Content editor partial from the given Content.
# For options see -> render_essence
def render_essence_editor(content, options = {})
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content view partial from the given Content.
# For options see -> render_essence
def render_essence_view(content, options = {})
render_essence(content, :view, :for_view => options)
end
# Renders the Content editor partial from the given Element for the essence_type (e.g. EssenceRichtext).
# For multiple contents of same kind inside one molecue just pass a position so that will be rendered.
# Otherwise the first content found for this type will be rendered.
# For options see -> render_essence
def render_essence_editor_by_type(element, type, position = nil, options = {})
if element.blank?
return warning('Element is nil', _("no_element_given"))
end
if position.nil?
content = element.content_by_type(type)
else
content = element.contents.find_by_essence_type_and_position(type, position)
end
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content view partial from the given Element for the essence_type (e.g. EssenceRichtext).
# For multiple contents of same kind inside one molecue just pass a position so that will be rendered.
# Otherwise the first content found for this type will be rendered.
# For options see -> render_essence
def render_essence_view_by_type(element, type, position, options = {})
if element.blank?
warning('Element is nil')
return ""
end
if position.nil?
content = element.content_by_type(type)
else
content = element.contents.find_by_essence_type_and_position(type, position)
end
render_essence(content, :view, :for_view => options)
end
# Renders the Content view partial from the given Element by position (e.g. 1).
# For options see -> render_essence
def render_essence_view_by_position(element, position, options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.contents.find_by_position(position)
render_essence(content, :view, :for_view => options)
end
# Renders the Content editor partial from the given Element by position (e.g. 1).
# For options see -> render_essence
def render_essence_editor_by_position(element, position, options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.contents.find_by_position(position)
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content editor partial found in views/contents/ for the content with name inside the passed Element.
# For options see -> render_essence
def render_essence_editor_by_name(element, name, options = {})
if element.blank?
return warning('Element is nil', _("no_element_given"))
end
content = element.content_by_name(name)
render_essence(content, :editor, :for_editor => options)
end
# Renders the Content view partial from the passed Element for passed content name.
# For options see -> render_essence
def render_essence_view_by_name(element, name, options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.content_by_name(name)
render_essence(content, :view, :for_view => options)
end
# Renders the name of elements content or the default name defined in elements.yml
def render_content_name(content)
if content.blank?
warning('Element is nil')
return ""
else
content_name = t("content_names.#{content.element.name}.#{content.name}", :default => ["content_names.#{content.name}".to_sym, content.name.capitalize])
end
if content.description.blank?
warning("Content #{content.name} is missing its description")
title = _("Warning: Content '%{contentname}' is missing its description.") % {:contentname => content.name}
content_name = %(<span class="warning icon" title="#{title}"></span> ) + content_name
end
content_name
end
# Returns @page.title
#
# The options are:
# :prefix => ""
# :seperator => "|"
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_page_title options={}
default_options = {
:prefix => "",
:seperator => "|"
}
default_options.update(options)
unless @page.title.blank?
h("#{default_options[:prefix]} #{default_options[:seperator]} #{@page.title}")
else
h("")
end
end
# Returns a complete html <title> tag for the <head> part of the html document.
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_title_tag options={}
default_options = {
:prefix => "",
:seperator => "|"
}
options = default_options.merge(options)
title = render_page_title(options)
%(<title>#{title}</title>)
end
# Renders a html <meta> tag for :name => "" and :content => ""
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_meta_tag(options={})
default_options = {
:name => "",
:default_language => "de",
:content => ""
}
options = default_options.merge(options)
lang = (@page.language.blank? ? options[:default_language] : @page.language.code)
%(<meta name="#{options[:name]}" content="#{options[:content]}" lang="#{lang}" xml:lang="#{lang}" />)
end
# Renders a html <meta http-equiv="Content-Language" content="#{lang}" /> for @page.language.
#
# == Webdevelopers:
# Please use the render_meta_data() helper. There all important meta information gets rendered in one helper.
# So you dont have to worry about anything.
def render_meta_content_language_tag(options={})
default_options = {
:default_language => "de"
}
options = default_options.merge(options)
lang = (@page.language.blank? ? options[:default_language] : @page.language.code)
%(<meta http-equiv="Content-Language" content="#{lang}" />)
end
# = This helper takes care of all important meta tags for your @page.
# ---
# The meta data is been taken from the @page.title, @page.meta_description, @page.meta_keywords, @page.updated_at and @page.language database entries managed by the Alchemy user via the Alchemy cockpit.
#
# Assume that the user has entered following data into the Alchemy cockpit of the Page "home" and that the user wants that the searchengine (aka. google) robot should index the page and should follow all links on this page:
#
# Title = Homepage
# Description = Your page description
# Keywords: cms, ruby, rubyonrails, rails, software, development, html, javascript, ajax
#
# Then placing render_meta_data(:title_prefix => "company", :title_seperator => "::") into the <head> part of the pages.html.erb layout produces:
#
# <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
# <meta http-equiv="Content-Language" content="de" />
# <title>Company :: #{@page.title}</title>
# <meta name="description" content="Your page description" />
# <meta name="keywords" content="cms, ruby, rubyonrails, rails, software, development, html, javascript, ajax" />
# <meta name="generator" content="Alchemy VERSION" />
# <meta name="date" content="Tue Dec 16 10:21:26 +0100 2008" />
# <meta name="robots" content="index, follow" />
#
def render_meta_data options={}
default_options = {
:title_prefix => "",
:title_seperator => "|",
:default_lang => "de"
}
options = default_options.merge(options)
#render meta description of the root page from language if the current meta description is empty
if @page.meta_description.blank?
description = Page.find_by_language_root_and_language_id(true, session[:language_id]).meta_description rescue ""
else
description = @page.meta_description
end
#render meta keywords of the root page from language if the current meta keywords is empty
if @page.meta_keywords.blank?
keywords = Page.find_by_language_root_and_language_id(true, session[:language_id]).meta_keywords rescue ""
else
keywords = @page.meta_keywords
end
robot = "#{@page.robot_index? ? "" : "no"}index, #{@page.robot_follow? ? "" : "no"}follow"
meta_string = %(
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
#{render_meta_content_language_tag}
#{render_title_tag( :prefix => options[:title_prefix], :seperator => options[:title_seperator])}
#{render_meta_tag( :name => "description", :content => description)}
#{render_meta_tag( :name => "keywords", :content => keywords)}
<meta name="generator" content="Alchemy #{configuration(:alchemy_version)}" />
<meta name="date" content="#{@page.updated_at}" />
<meta name="robots" content="#{robot}" />
)
if @page.contains_feed?
meta_string += %(
<link rel="alternate" type="application/rss+xml" title="RSS" href="#{multi_language? ? show_page_with_language_url(:protocol => 'feed', :urlname => @page.urlname, :lang => Alchemy::Controller.current_language.code, :format => :rss) : show_page_url(:protocol => 'feed', :urlname => @page.urlname, :format => :rss)}" />
)
end
return meta_string
end
# Returns an array of all pages in the same branch from current. Used internally to find the active page in navigations.
def breadcrumb(current)
return [] if current.nil?
result = Array.new
result << current
while current = current.parent
result << current
end
return result.reverse
end
# Returns a html string for a linked breadcrumb from root to current page.
# == Options:
# :seperator => %(<span class="seperator">></span>) Maybe you don't want this seperator. Pass another one.
# :page => @page Pass a different Page instead of the default (@page).
# :without => nil Pass Pageobject or array of Pages that must not be displayed.
# :public_only => false Pass boolean for displaying hidden pages only.
# :visible_only => true Pass boolean for displaying (in navigation) visible pages only.
# :restricted_only => false Pass boolean for displaying restricted pages only.
# :reverse => false Pass boolean for displaying reversed breadcrumb.
def render_breadcrumb(options={})
default_options = {
:seperator => %(<span class="seperator">></span>),
:page => @page,
:without => nil,
:public_only => false,
:visible_only => true,
:restricted_only => false,
:reverse => false
}
options = default_options.merge(options)
pages = breadcrumb(options[:page])
pages.delete(Page.root)
unless options[:without].nil?
unless options[:without].class == Array
pages.delete(options[:without])
else
pages = pages - options[:without]
end
end
if(options[:visible_only])
pages.reject!{|p| !p.visible? }
end
if(options[:public_only])
pages.reject!{|p| !p.public? }
end
if(options[:restricted_only])
pages.reject!{|p| !p.restricted? }
end
if(options[:reverse])
pages.reverse!
end
bc = []
pages.each do |page|
urlname = page.urlname
(page.name == @page.name) ? css_class = "active" : nil
if page == pages.last
css_class.blank? ? css_class = "last" : css_class = [css_class, "last"].join(" ")
elsif page == pages.first
css_class.blank? ? css_class = "first" : css_class = [css_class, "last"].join(" ")
end
if multi_language?
url = show_page_with_language_url(:urlname => urlname, :lang => Alchemy::Controller.current_language.code)
else
url = show_page_url(:urlname => urlname)
end
bc << link_to( h(page.name), url, :class => css_class, :title => page.title )
end
bc.join(options[:seperator])
end
# returns true if page is in the active branch
def page_active? page
@breadcrumb ||= breadcrumb(@page)
@breadcrumb.include? page
end
# = This helper renders the navigation.
#
# It produces a html <ul><li></li></ul> structure with all necessary classes and ids so you can produce nearly every navigation the web uses today.
# E.G. dropdown-navigations, simple mainnavigations or even complex nested ones.
# ---
# == En detail:
#
# <ul>
# <li class="first" id="home"><a href="home" class="active">Homepage</a></li>
# <li id="contact"><a href="contact">Contact</a></li>
# <li class="last" id="imprint"><a href="imprint">Imprint</a></li>
# </ul>
#
# As you can see: Everything you need.
#
# Not pleased with the way Alchemy produces the navigation structure?
# Then feel free to overwrite the partials (_navigation_renderer.html.erb and _navigation_link.html.erb) found in views/pages/partials/ or pass different partials via the options :navigation_partial and :navigation_link_partial.
#
# == The options are:
#
# :submenu => false Do you want a nested <ul> <li> structure for the deeper levels of your navigation, or not? Used to display the subnavigation within the mainnaviagtion. E.g. for dropdown menues.
# :from_page => @root_page Do you want to render a navigation from a different page then the current page? Then pass an Page instance or a PageLayout name as string.
# :spacer => "" Yeah even a spacer for the entries can be passed. Simple string, or even a complex html structure. E.g: "<span class='spacer'>|</spacer>". Only your imagination is the limit. And the W3C of course :)
# :navigation_partial => "navigation_renderer" Pass a different partial to be taken for the navigation rendering. CAUTION: Only for the advanced Alchemy webdevelopers. The standard partial takes care of nearly everything. But maybe you are an adventures one ^_^
# :navigation_link_partial => "navigation_link" Alchemy places an <a> html link in <li> tags. The tag automatically has an active css class if necessary. So styling is everything. But maybe you don't want this. So feel free to make you own partial and pass the filename here.
# :show_nonactive => false Commonly Alchemy only displays the submenu of the active page (if :submenu => true). If you want to display all child pages then pass true (together with :submenu => true of course). E.g. for the popular css-driven dropdownmenues these days.
# :show_title => true For our beloved SEOs :). Appends a title attribute to all links and places the page.title content into it.
def render_navigation(options = {})
default_options = {
:submenu => false,
:all_sub_menues => false,
:from_page => @root_page,
:spacer => "",
:navigation_partial => "partials/navigation_renderer",
:navigation_link_partial => "partials/navigation_link",
:show_nonactive => false,
:restricted_only => nil,
:show_title => true,
:reverse => false,
:reverse_children => false
}
options = default_options.merge(options)
if options[:from_page].is_a?(String)
page = Page.find_by_page_layout_and_language_id(options[:from_page], session[:language_id])
else
page = options[:from_page]
end
if page.blank?
warning("No Page found for #{options[:from_page]}")
return ""
end
conditions = {
:parent_id => page.id,
:restricted => options[:restricted_only] || false,
:visible => true
}
if options[:restricted_only].nil?
conditions.delete(:restricted)
end
pages = Page.all(
:conditions => conditions,
:order => "lft ASC"
)
if options[:reverse]
pages.reverse!
end
render :partial => options[:navigation_partial], :locals => {:options => options, :pages => pages}
end
# Renders the children of the given page (standard is the current page), the given page and its siblings if there are no children, or it renders just nil.
# Use this helper if you want to render the subnavigation independent from the mainnavigation. E.g. to place it in a different layer on your website.
# If :from_page's level in the site-hierarchy is greater than :level (standard is 2) and the given page has no children, the returned output will be the :from_page and it's siblings
# This method will assign all its options to the the render_navigation method, so you are able to assign the same options as to the render_navigation method.
# Normally there is no need to change the level parameter, just in a few special cases.
def render_subnavigation(options = {})
default_options = {
:from_page => @page,
:level => 2
}
options = default_options.merge(options)
if !options[:from_page].nil?
if (options[:from_page].children.blank? && options[:from_page].level > options[:level]) || !options[:from_page].children.select{ |page| !page.visible || !page.public }.blank?
options = options.merge(:from_page => Page.find(options[:from_page].parent_id))
end
render_navigation(options)
else
return nil
end
end
# = This helper renders the paginated navigation.
#
# :pagination => {
# :level_X => {
# :size => X,
# :current => params[:navigation_level_X_page]
# }
# } This one is a funky complex pagination option for the navigation. I'll explain in the next episode.
def render_paginated_navigation(options = {})
default_options = {
:submenu => false,
:all_sub_menues => false,
:from_page => @root_page,
:spacer => "",
:pagination => {},
:navigation_partial => "pages/partials/navigation_renderer",
:navigation_link_partial => "pages/partials/navigation_link",
:show_nonactive => false,
:show_title => true,
:level => 1
}
options = default_options.merge(options)
if options[:from_page].nil?
warning('options[:from_page] is nil')
return ""
else
pagination_options = options[:pagination].stringify_keys["level_#{options[:from_page].depth}"]
find_conditions = { :parent_id => options[:from_page].id, :visible => true }
pages = Page.all(
:page => pagination_options,
:conditions => find_conditions,
:order => "lft ASC"
)
render :partial => options[:navigation_partial], :locals => {:options => options, :pages => pages}
end
end
# Used to display the pagination links for the paginated navigation.
def link_to_navigation_pagination name, urlname, pages, page, css_class = ""
p = {}
p["navigation_level_1_page"] = params[:navigation_level_1_page] unless params[:navigation_level_1_page].nil?
p["navigation_level_2_page"] = params[:navigation_level_2_page] unless params[:navigation_level_2_page].nil?
p["navigation_level_3_page"] = params[:navigation_level_3_page] unless params[:navigation_level_3_page].nil?
p["navigation_level_#{pages.to_a.first.depth}_page"] = page
link_to name, show_page_url(urlname, p), :class => (css_class unless css_class.empty?)
end
# Returns true if the current_user (The logged-in Alchemy User) has the admin role.
def is_admin?
return false if !current_user
current_user.admin?
end
# This helper renders the link for a protoypejs-window overlay. We use this for our fancy modal overlay windows in the Alchemy cockpit.
def link_to_overlay_window(content, url, options={}, html_options={})
default_options = {
:size => "100x100",
:resizable => false,
:modal => true
}
options = default_options.merge(options)
link_to_function(
content,
"Alchemy.openWindow(
\'#{url}\',
\'#{options[:title]}\',
\'#{options[:size].split('x')[0].to_s}\',
\'#{options[:size].split('x')[1].to_s}\',
\'#{options[:resizable]}\',
\'#{options[:modal]}\',
\'#{options[:overflow]}\'
)",
html_options
)
end
# Used for rendering the folder link in Admin::Pages.index sitemap.
def sitemapFolderLink(page)
return '' if page.level == 1
if page.folded?(current_user.id)
css_class = 'folded'
title = _('Show childpages')
else
css_class = 'collapsed'
title = _('Hide childpages')
end
link_to_remote(
'',
:url => {
:controller => 'admin/pages',
:action => :fold,
:id => page.id
},
:html => {
:class => "page_folder #{css_class}",
:title => title,
:id => "fold_button_#{page.id}"
}
)
end
# Renders an image_tag with an file icon for files suffix.
# The images are in vendor/plugins/alchemy/assets/images/file_icons
# They will be copyied into public/alchemy/file_icons on app launch.
#
# ===Fileicons so far:
#
# * GIF
# * PDF
# * FLV (Flashvideo)
# * ZIP
# * SWF (Flashmovie)
# * MP3
# * Empty File
#
def render_file_icon file
case file.filename.split(".").last
when "pdf"
then icon = "pdf.png"
when "flv"
then icon = "flv.png"
when "gif"
then icon = "gif.png"
when "zip"
then icon = "zip.png"
when "mp3"
then icon = "mp3.png"
when "swf"
then icon = "swf.png"
when "doc"
then icon = "doc.png"
when "jpg"
then icon = "jpg.png"
else
icon = "file.png"
end
image_tag("alchemy/file_icons/#{icon}")
end
# Renders an image_tag from for an image in public/images folder so it can be cached.
# *Not really working!*
def static_image_tag image, options={}
image_tag url_for(:controller => :images, :action => :show_static, :image => image)
end
# Renders the layout from @page.page_layout. File resists in /app/views/page_layouts/_LAYOUT-NAME.html.erb
def render_page_layout(options={})
default_options = {
:render_format => "html"
}
options = default_options.merge(options)
if File.exists?("#{RAILS_ROOT}/app/views/page_layouts/_#{@page.page_layout.downcase}.#{options[:render_format]}.erb") || File.exists?("#{RAILS_ROOT}/vendor/plugins/alchemy/app/views/page_layouts/_#{@page.page_layout.downcase}.#{options[:render_format]}.erb")
render :partial => "page_layouts/#{@page.page_layout.downcase}.#{options[:render_format]}.erb"
else
render :partial => "page_layouts/standard"
end
end
# Returns @current_language set in the action (e.g. Page.show)
def current_language
if @current_language.nil?
warning('@current_language is not set')
return nil
else
@current_language
end
end
# Returns true if the current page is the root page in the nested set of Pages, false if not.
def root_page?
@page == @root_page
end
# Returns the full url containing host, page and anchor for the given element
def full_url_for_element element
"http://" + request.env["HTTP_HOST"] + "/" + element.page.urlname + "##{element.name}_#{element.id}"
end
# Used for language selector in Alchemy cockpit sitemap. So the user can select the language branche of the page.
def language_codes_for_select
configuration(:languages).collect{ |language|
language[:language_code]
}
end
# Used for translations selector in Alchemy cockpit user settings.
def translations_for_select
configuration(:translations).collect{ |translation|
[translation[:language], translation[:language_code]]
}
end
# Used by Alchemy to display a javascript driven filter for lists in the Alchemy cockpit.
def js_filter_field options = {}
default_options = {
:class => "thin_border js_filter_field",
:onkeyup => "Alchemy.ListFilter('#contact_list li')",
:id => "search_field"
}
options = default_options.merge(options)
options[:onkeyup] << ";jQuery('#search_field').val().length >= 1 ? jQuery('.js_filter_field_clear').show() : jQuery('.js_filter_field_clear').hide();"
filter_field = "<div class=\"js_filter_field_box\">"
filter_field << text_field_tag("filter", "", options)
filter_field << link_to_function(
"",
"$('#{options[:id]}').value = '';#{options[:onkeyup]}",
:class => "js_filter_field_clear",
:style => "display:none",
:title => _("click_to_show_all")
)
filter_field << ("<br /><label for=\"search_field\">" + _("search") + "</label>")
filter_field << "</div>"
filter_field
end
def clipboard_select_tag(items, html_options = {})
unless items.blank?
options = [[_('Please choose'), ""]]
items.each do |item|
options << [item.class.to_s == 'Element' ? item.display_name_with_preview_text : item.name, item.id]
end
select_tag(
'paste_from_clipboard',
options_for_select(options),
{
:class => html_options[:class] || 'very_long',
:style => html_options[:style]
}
)
end
end
# returns all elements that could be placed on that page because of the pages layout as array to be used in alchemy_selectbox form builder
def elements_for_select(elements)
return [] if elements.nil?
elements.collect{ |p| [p["display_name"], p["name"]] }
end
def link_to_confirmation_window(link_string = "", message = "", url = "", html_options = {})
title = _("please_confirm")
ok_lable = _("yes")
cancel_lable = _("no")
link_to_function(
link_string,
"Alchemy.confirmToDeleteWindow('#{url}', '#{title}', '#{message}', '#{ok_lable}', '#{cancel_lable}');",
html_options
)
end
def page_selector(element, content_name, options = {}, select_options = {})
default_options = {
:except => {
:page_layout => [""]
},
:only => {
:page_layout => [""]
}
}
options = default_options.merge(options)
content = element.content_by_name(content_name)
if content.nil?
return warning('Content', _('content_not_found'))
elsif content.essence.nil?
return warning('Content', _('content_essence_not_found'))
end
pages = Page.find(
:all,
:conditions => {
:language_id => session[:language_id],
:page_layout => options[:only][:page_layout],
:public => true
}
)
select_tag(
"contents[content_#{content.id}][body]",
pages_for_select(pages, content.essence.body),
select_options
)
end
# Returns all Pages found in the database as an array for the rails select_tag helper.
# You can pass a collection of pages to only returns these pages as array.
# Pass an Page.name or Page.urlname as second parameter to pass as selected for the options_for_select helper.
def pages_for_select(pages = nil, selected = nil, prompt = "Bitte wählen Sie eine Seite")
result = [[prompt, ""]]
if pages.blank?
pages = Page.find_all_by_language_id_and_public(session[:language_id], true)
end
pages.each do |p|
result << [p.send(:name), p.send(:urlname)]
end
options_for_select(result, selected)
end
# Returns all public elements found by Element.name.
# Pass a count to return only an limited amount of elements.
def all_elements_by_name(name, options = {})
warning('options[:language] option not allowed any more in all_elements_by_name helper')
default_options = {
:count => :all,
:from_page => :all
}
options = default_options.merge(options)
if options[:from_page] == :all
elements = Element.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])
elsif options[:from_page].class == String
page = Page.find_by_page_layout_and_language_id(options[:from_page], session[:language_id])
return [] if page.blank?
elements = page.elements.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])
else
elements = options[:from_page].elements.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])
end
end
# Returns the public element found by Element.name from the given public Page, either by Page.id or by Page.urlname
def element_from_page(options = {})
default_options = {
:page_urlname => "",
:page_id => nil,
:element_name => ""
}
options = default_options.merge(options)
if options[:page_id].blank?
page = Page.find_by_urlname_and_public(options[:page_urlname], true)
else
page = Page.find_by_id_and_public(options[:page_id], true)
end
return "" if page.blank?
element = page.elements.find_by_name_and_public(options[:element_name], true)
return element
end
# This helper renderes the picture editor for the elements on the Alchemy Desktop.
# It brings full functionality for adding images to the element, deleting images from it and sorting them via drag'n'drop.
# Just place this helper inside your element editor view, pass the element as parameter and that's it.
#
# Options:
# :maximum_amount_of_images (integer), default nil. This option let you handle the amount of images your customer can add to this element.
def render_picture_editor(element, options={})
default_options = {
:last_image_deletable => true,
:maximum_amount_of_images => nil,
:refresh_sortable => true
}
options = default_options.merge(options)
picture_contents = element.all_contents_by_type("EssencePicture")
render(
:partial => "admin/elements/picture_editor",
:locals => {
:picture_contents => picture_contents,
:element => element,
:options => options
}
)
end
def render_essence_selection_editor(element, content, select_options)
if content.class == String
content = element.contents.find_by_name(content)
else
content = element.contents[content - 1]
end
if content.essence.nil?
return warning('Element', _('content_essence_not_found'))
end
select_options = options_for_select(select_options, content.essence.content)
select_tag(
"contents[content_#{content.id}]",
select_options
)
end
# TOOD: include these via asset_packer yml file
def stylesheets_from_plugins
Dir.glob("vendor/plugins/*/assets/stylesheets/*.css").select{|s| !s.include? "vendor/plugins/alchemy"}.inject("") do |acc, s|
filename = File.basename(s)
plugin = s.split("/")[2]
acc << stylesheet_link_tag("#{plugin}/#{filename}")
end
end
# TOOD: include these via asset_packer yml file
def javascripts_from_plugins
Dir.glob("vendor/plugins/*/assets/javascripts/*.js").select{|s| !s.include? "vendor/plugins/alchemy"}.inject("") do |acc, s|
filename = File.basename(s)
plugin = s.split("/")[2]
acc << javascript_include_tag("#{plugin}/#{filename}")
end
end
def admin_main_navigation
navigation_entries = alchemy_plugins.collect{ |p| p["navigation"] }
render :partial => 'layouts/partials/mainnavigation_entry', :collection => navigation_entries.flatten
end
# Renders the Subnavigation for the admin interface.
def render_admin_subnavigation(entries)
render :partial => "layouts/partials/sub_navigation", :locals => {:entries => entries}
end
def admin_subnavigation
plugin = alchemy_plugin(:controller => params[:controller], :action => params[:action])
unless plugin.nil?
entries = plugin["navigation"]['sub_navigation']
render_admin_subnavigation(entries) unless entries.nil?
else
""
end
end
def admin_mainnavi_active?(mainnav)
subnavi = mainnav["sub_navigation"]
nested = mainnav["nested"]
if !subnavi.blank?
(!subnavi.detect{ |subnav| subnav["controller"] == params[:controller] && subnav["action"] == params[:action] }.blank?) ||
(!nested.nil? && !nested.detect{ |n| n["controller"] == params[:controller] && n["action"] == params[:action] }.blank?)
else
mainnav["controller"] == params[:controller] && mainnav["action"] == params["action"]
end
end
# Generates the url for the preview frame.
# target_url must contain target_controller and target_action.
def generate_preview_url(target_url)
preview_url = url_for(
:controller => ('/' + target_url["target_controller"]),
:action => target_url["target_action"],
:id => params[:id]
)
end
# Returns a string for the id attribute of a html element for the given element
def element_dom_id(element)
return "" if element.nil?
"#{element.name}_#{element.id}"
end
# Returns a string for the id attribute of a html element for the given content
def content_dom_id(content)
return "" if content.nil?
if content.class == String
a = Content.find_by_name(content)
return "" if a.nil?
else
a = content
end
"#{a.essence_type.underscore}_#{a.id}"
end
# Helper for including the nescessary javascripts and stylesheets for the different views.
# Together with the rails caching we achieve a good load time.
def alchemy_assets_set(setname = 'combined')
asset_sets = YAML.load_file(File.join(File.dirname(__FILE__), '..', '..', 'config/asset_packages.yml'))
content_for(:javascript_includes) do
js_set = asset_sets['javascripts'].detect { |js| js[setname.to_s] }[setname.to_s]
javascript_include_tag(js_set, :cache => 'alchemy/' + setname.to_s)
end
content_for(:stylesheets) do
css_set = asset_sets['stylesheets'].detect { |css| css[setname.to_s] }[setname.to_s]
stylesheet_link_tag(css_set, :cache => 'alchemy/' + setname.to_s)
end
end
def parse_sitemap_name(page)
if multi_language?
pathname = "/#{session[:language_code]}/#{page.urlname}"
else
pathname = "/#{page.urlname}"
end
pathname
end
def render_new_content_link(element)
link_to_overlay_window(
_('add new content'),
new_admin_element_content_path(element),
{
:size => '305x40',
:title => _('Select an content'),
:overflow => true
},
{
:id => "add_content_for_element_#{element.id}",
:class => 'button new_content_link'
}
)
end
def render_create_content_link(element, options = {})
defaults = {
:label => _('add new content')
}
options = defaults.merge(options)
link_to_remote(
options[:label],
{
:url => contents_path(
:content => {
:name => options[:content_name],
:element_id => element.id
}
),
:method => 'post'
},
{
:id => "add_content_for_element_#{element.id}",
:class => 'button new_content_link'
}
)
end
# Returns an icon
def render_icon(icon_class)
content_tag('span', '', :class => "icon #{icon_class}")
end
def alchemy_preview_mode_code
if @preview_mode
append_javascript = %(
var s = document.createElement('script');
s.src = '/javascripts/alchemy/jquery-1.5.min.js';
s.language = 'javascript';
s.type = 'text/javascript';
document.getElementsByTagName("body")[0].appendChild(s);
)
str = javascript_tag("if (typeof(jQuery) !== 'function') {#{append_javascript}}") + "\n"
str += javascript_tag("jQuery.noConflict();") + "\n"
str += javascript_include_tag("alchemy/alchemy") + "\n"
str += javascript_tag("jQuery(document).ready(function($) {\nAlchemy.ElementSelector();\n});\n$('a').attr('href', 'javascript:void(0)');")
return str
else
return nil
end
end
def element_preview_code(element)
if @preview_mode
"data-alchemy-element='#{element.id}'"
end
end
# Logs a message in the Rails logger (warn level) and optionally displays an error message to the user.
def warning(message, text = nil)
logger.warn %(\n
++++ WARNING: #{message}! from: #{caller.first}\n
)
unless text.nil?
warning = content_tag('p', :class => 'content_editor_error') do
render_icon('warning') + text
end
return warning
end
end
def alchemy_combined_assets
alchemy_assets_set
end
# This helper returns a path for use inside a link_to helper.
# You may pass a page_layout or an urlname.
# Any additional options are passed to the url_helper, so you can add arguments to your url.
# Example:
# <%= link_to '» order now', page_path_for(:page_layout => 'orderform', :product_id => element.id) %>
def page_path_for(options={})
return warning("No page_layout, or urlname given. I got #{options.inspect} ") if options[:page_layout].blank? && options[:urlname].blank?
if options[:urlname].blank?
page = Page.find_by_page_layout(options[:page_layout])
return warning("No page found for #{options.inspect} ") if page.blank?
urlname = page.urlname
else
urlname = options[:urlname]
end
if multi_language?
show_page_with_language_path({:urlname => urlname, :lang => @language.code}.merge(options.except(:page_layout, :urlname)))
else
show_page_path({:urlname => urlname}.merge(options.except(:page_layout, :urlname)))
end
end
# Returns the current page.
def current_page
@page
end
end
|
module Merb
module GlobalHelpers
CRUD_ACTIONS = ["list", "index", "show", "edit", "new"]
MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
def page_title
begin
generate_page_title
rescue
return "MostFit" rescue Exception
end
end
def link_to_with_class(name, url)
link_to_with_rights(name, url, :class => ((request.uri==(url) or request.uri.index(url)==0) ? "selected" : ""))
end
def link_to_with_rights(text, path, params = {}, method="GET")
uri = URI.parse(path)
method = method.to_s.upcase || "GET"
request = Merb::Request.new(
Merb::Const::REQUEST_PATH => uri.path,
Merb::Const::REQUEST_METHOD => method,
Merb::Const::QUERY_STRING => uri.query)
route = Merb::Router.match(request)[1] rescue nil
return link_to(text,path,params) if session.user.can_access?(route, params)
end
def url_for_loan(loan, action = '', opts = {})
# this is to generate links to loans, as the resouce method doesn't work for descendant classes of Loan
# it expects the whole context (@branch, @center, @client) to exist
base = if @branch and @center and @client
url(:branch_center_client, @branch.id, @center.id, @client.id)
elsif @client
url(:branch_center_client, @client.center.branch_id, @client.center_id, @client.id)
else
client = loan.client
url(:branch_center_client, client.center.branch_id, client.center_id, client.id)
end
base + "/loans/#{loan.id}/" + action.to_s + (opts.length>0 ? "?#{opts.inject([]){|s,x| s << "#{x[0]}=#{x[1]}"}.join("&")}" : '')
end
def select_staff_member_for(obj, col, attrs = {}, allow_unsigned=false)
id_col = "#{col.to_s}_staff_id".to_sym
selected = ((obj.send(id_col) and obj.send(id_col)!="") ? obj.send(id_col).to_s : attrs[:selected] || "0")
select(col,
:collection => staff_members_collection,
:name => "#{obj.class.to_s.snake_case}[#{id_col}]",
:id => attrs[:id] || "#{obj.class.to_s.snake_case}_#{id_col}",
:selected => selected)
end
def select_center_for(obj, col, attrs = {})
id_col = "#{col.to_s}_id".to_sym
collection = []
catalog = Center.catalog(session.user)
catalog.keys.sort.each do |branch_name|
collection << ['', branch_name]
catalog[branch_name].sort_by{|x| x[1]}.each{ |k,v| collection << [k.to_s, "!!!!!!!!!#{v}"] }
end
html = select col,
:collection => collection,
:name => "#{obj.class.to_s.snake_case}[#{id_col}]",
:id => "#{obj.class.to_s.snake_case}_#{id_col}",
:selected => (obj.send(id_col) ? obj.send(id_col).to_s : nil),
:prompt => (attrs[:prompt] or "<select a center>")
html.gsub('!!!', ' ') # otherwise the entities get escaped
end
def select_funding_line_for(obj, col, attrs = {}) # Fix me: Refactor this with all select_*_for
id_col = "#{col.to_s}_id".to_sym
catalog = Funder.catalog
collection = []
catalog.keys.sort.each do |funder_name|
collection << ['', funder_name]
catalog[funder_name].each_pair { |k,v| collection << [k.to_s, "!!!!!!#{v}"]}
end
html = select col,
:collection => collection,
:name => "#{obj.class.to_s.snake_case}[#{id_col}]",
:id => "#{obj.class.to_s.snake_case}_#{id_col}",
:selected => (obj.send(id_col) ? obj.send(id_col).to_s : nil),
:prompt => (attrs[:prompt] or "<select a funding line>")
html.gsub('!!!', ' ') # otherwise the entities get escaped
end
def date_select(name, date=Date.today, opts={})
# defaults to Date.today
# should refactor
attrs = {}
attrs.merge!(:name => name)
attrs.merge!(:date => date)
attrs.merge!(:id => opts[:id]||name)
attrs.merge!(:date => date)
attrs.merge!(:min_date => opts[:min_date]||Date.min_date)
attrs.merge!(:max_date => opts[:max_date]||Date.max_date)
date_select_html(attrs)
end
def date_select_for(obj, col = nil, attrs = {})
attrs.merge!(:name => "#{obj.class.to_s.snake_case}[#{col.to_s}]")
attrs.merge!(:id => "#{obj.class.to_s.snake_case}_#{col.to_s}")
nullable = attrs[:nullable] ? true : false
date = obj.send(col)
date = Date.today if date.blank? and not nullable
date = nil if date.blank? and nullable
attrs.merge!(:date => date)
attrs.merge!(:min_date => attrs[:min_date]||Date.min_date)
attrs.merge!(:max_date => attrs[:max_date]||Date.max_date)
date_select_html(attrs, obj, col)
# errorify_field(attrs, col)
end
def date_select_html (attrs, obj = nil, col = nil)
str = %Q{
<input type='text' name="#{attrs[:name]}" id="#{attrs[:id]}" value="#{attrs[:date]}" size="12">
<script type="text/javascript">
$(function(){
$("##{attrs[:id]}").datepicker('destroy').datepicker({altField: '##{attrs[:id]}', buttonImage: "/images/calendar.png", changeYear: true, buttonImageOnly: true,
yearRange: '#{attrs[:min_date].year}:#{attrs[:max_date].year}',
dateFormat: '#{datepicker_dateformat}', altFormat: '#{datepicker_dateformat}', minDate: '#{attrs[:min_date]}',
maxDate: '#{attrs[:max_date]}', showOn: 'both', setDate: "#{attrs[:date]}" })
});
</script>
}
return str
end
def datepicker_dateformat
if $globals and $globals[:mfi_details] and $globals[:mfi_details][:date_format]
ourDateFormat = $globals[:mfi_details][:date_format]
else
ourDateFormat = "%Y-%m-%d"
end
s = ourDateFormat.dup
s.gsub!("%Y","yy")
s.gsub!("%y","y")
s.gsub!("%m","mm")
s.gsub!("%d","dd")
s.gsub!("%B","MM")
s.gsub!("%A","DD")
return s
end
#old func it shows textbox
def date_select_old_html (attrs, obj = nil, col = nil)
date = attrs[:date]
nullable = attrs[:nullable]
day_attrs = attrs.merge(
:name => attrs[:name] + '[day]',
:id => attrs[:id] + '_day',
:selected => (date ? date.day.to_s : ''),
:class => (obj and col) ? (obj.errors[col] ? 'error' : '') : nil,
:collection => (nullable ? [['', '-']] : []) + (1..31).to_a.map{ |x| x = [x.to_s, x.to_s] }
)
count = 0
month_attrs = attrs.merge(
:name => attrs[:name] + '[month]',
:id => attrs[:id] + '_month',
:selected => (date ? date.month.to_s : ''),
:class => obj ? (obj.errors[col] ? 'error' : '') : nil,
:collection => (nullable ? [['', '-']] : []) + MONTHS.map { |x| count += 1; x = [count, x] }
)
min_year = attrs[:min_date] ? attrs[:min_date].year : 1900
max_year = attrs[:max_date] ? attrs[:max_date].year : date.year + 3
year_attrs = attrs.merge(
:name => attrs[:name] + '[year]',
:id => attrs[:id] + '_year',
:selected => (date ? date.year.to_s : ''),
:class => obj ? (obj.errors[col] ? 'error' : '') : nil,
:collection => (nullable ? [['', '-']] : []) + (min_year..max_year).to_a.reverse.map{|x| x = [x.to_s, x.to_s]}
)
select(month_attrs) + '' + select(day_attrs) + '' + select(year_attrs)
end
def ofc2(width, height, url, id = Time.now.usec, swf_base = '/')
<<-HTML
<div id='flashcontent_#{id}'></div>
<script type="text/javascript">
swfobject.embedSWF(
"#{swf_base}open-flash-chart.swf", "flashcontent_#{id}",
"#{width}", "#{height}", "9.0.0", "expressInstall.swf",
{"data-file":"#{url}", "loading":"Waiting for data... (reload page when it takes too long)"} );
</script>
HTML
end
def breadcrums
# breadcrums use the request.uri and the instance vars of the parent
# resources (@branch, @center) that are available -- so no db queries
crums, url = [], ''
request.uri.split("?")[0][1..-1].split('/').each_with_index do |part, index|
url << '/' + part
if part.to_i.to_s.length == part.length # true when a number (id)
o = instance_variable_get('@'+url.split('/')[-2].singular) # get the object (@branch)
s = (o.respond_to?(:name) ? link_to(o.name, url) : link_to('#'+o.object_id.to_s, url))
crums[-1] += ": <b><i>#{s}</i></b>" # merge the instance names (or numbers)
else # when not a number (id)
crums << link_to(part.gsub('_', ' '), url) # add the resource name
end
end
['You are here', crums].join(' <b>>></b> ') # fancy separator
end
def format_currency(i)
# in case of our rupees we do not count with cents, if you want to have cents do that here
i.to_f.round(2).to_s + " INR"
end
def plurial_nouns(freq)
case freq.to_sym
when :daily
'days'
when :weekly
'weeks'
when :monthly
'months'
else
'????'
end
end
def difference_in_days(start_date, end_date, words = ['days early', 'days late'])
d = end_date - start_date
return '' if d == 0
"#{d.abs} #{d > 0 ? words[1] : words[0]}"
end
def debug_info
[
{:name => 'merb_config', :code => 'Merb::Config.to_hash', :obj => Merb::Config.to_hash},
{:name => 'params', :code => 'params.to_hash', :obj => params.to_hash},
{:name => 'session', :code => 'session.to_hash', :obj => session.to_hash},
{:name => 'cookies', :code => 'cookies', :obj => cookies},
{:name => 'request', :code => 'request', :obj => request},
{:name => 'exceptions', :code => 'request.exceptions', :obj => request.exceptions},
{:name => 'env', :code => 'request.env', :obj => request.env},
{:name => 'routes', :code => 'Merb::Router.routes', :obj => Merb::Router.routes},
{:name => 'named_routes', :code => 'Merb::Router.named_routes', :obj => Merb::Router.named_routes},
{:name => 'resource_routes', :code => 'Merb::Router.resource_routes', :obj => Merb::Router.resource_routes},
]
end
def paginate(pagination, *args, &block)
DmPagination::PaginationBuilder.new(self, pagination, *args, &block)
end
def chart(url, width=430, height=200, id=nil)
id||= (rand()*100000).to_i + 100
"<div id='flashcontent_#{id}'></div>
<script type='text/javascript'>
swfobject.embedSWF('/open-flash-chart.swf', \"flashcontent_#{id}\", #{width}, #{height}, '9.0.0', 'expressInstall.swf',
{\"data-file\": \"#{url}\",
\"loading\": \"Waiting for data... (reload page when it takes too long)\"
});
</script>"
end
def centers_paying_today_collection(date)
[["","---"]] + Center.paying_today(session.user, date).map {|c| [c.id.to_s,c.name]}
end
def audit_trail_url
"/audit_trails?"+params.to_a.map{|x| "audit_for[#{x[0]}]=#{x[1]}"}.join("&")
end
def diff_display(arr, model, action)
arr.map{|change|
next unless change
change.map{|k, v|
str="<tr><td>#{k.humanize}</td><td>"
str+=if action==:update
"changed from #{v.first}</td><td>to #{v.last}"
elsif action==:create and v.class==Array
"#{v}"
else
"#{v}"
end
str+="</td></tr>"
}
}
end
def search_url(hash, model)
hash[:controller] = "search"
hash[:action] = "advanced"
hash[:model] = model.to_s.downcase
hash = hash.map{|x|
[(x[0].class==DataMapper::Query::Operator ? "#{x[0].target}.#{x[0].operator}" : x[0]), x[1]]
}.to_hash
url(hash)
end
def use_tinymce
@content_for_tinymce = ""
content_for :tinymce do
js_include_tag "tiny_mce/tiny_mce"
end
@content_for_tinymce_init = ""
content_for :tinymce_init do
js_include_tag "mce_editor"
end
end
def get_accessible_branches
if session.user.staff_member
[session.user.staff_member.centers.branches, session.user.staff_member.branches].flatten
else
Branch.all(:order => [:name])
end
end
def get_accessible_centers(branch_id)
centers = if session.user.staff_member
[session.user.staff_member.centers, session.user.staff_member.branches.centers].flatten
elsif branch_id and not branch_id.blank?
Center.all(:branch_id => branch_id, :order => [:name])
else
[]
end
centers.map{|x| [x.id, "#{x.name}"]}
end
def get_accessible_staff_members
staff_members = if session.user.staff_member
st = session.user.staff_member
if branches = st.branches and branches.length>0
[st] + branches.centers.managers
else
st
end
else
StaffMember.all
end
staff_members.sort_by{|x| x.name}.map{|x| [x.id, x.name]}
end
def select_mass_entry_field(attrs)
collection = []
MASS_ENTRY_FIELDS.keys.each do |model|
collection << ['', model.to_s.camelcase(' ')]
MASS_ENTRY_FIELDS[model].sort_by{|x| x.to_s}.each{|k| collection << ["#{model}[#{k.to_s}]", "!!!!!!#{k.to_s.camelcase(' ')}"] }
end
select(
:collection => collection,
:name => "#{attrs[:name]}",
:id => "#{attrs[:id]||'select_mass_entry'}",
:prompt => (attrs[:prompt] or "<select a field>")).gsub("!!!", " ")
end
private
def staff_members_collection(allow_unsigned=false)
if session.user.staff_member
staff = session.user.staff_member
bms = staff.branches.collect{|x| x.manager}
cms = staff.branches.centers.collect{|x| x.manager}
managers = [bms, cms, staff].flatten.uniq
[["0", "<Select a staff member"]] + managers.map{|x| [x.id, x.name]}
else
[["0", "<Select a staff member"]] + StaffMember.all(:active => true).map{|x| [x.id, x.name]}
end
end
def join_segments(*args)
args.map{|x| x.class==Array ? x.uniq : x}.flatten.reject{|x| not x or x.blank?}.join(' - ').capitalize
end
def generate_page_title
prefix, postfix = [], []
controller=params[:controller].split("/")[-1]
controller_name = (params[:action]=="list" or params[:action]=="index") ? controller.join_snake(' ') : controller.singularize.join_snake(' ')
controller_name = controller_name.map{|x| x.join_snake(' ')}.join(' ')
prefix << params[:namespace].join_snake(' ') if params[:namespace]
postfix << params[:action].join_snake(' ') if not CRUD_ACTIONS.include?(params[:action])
prefix << params[:action].join_snake(' ') if CRUD_ACTIONS[3..-1].include?(params[:action])
return "Loan for #{@loan.client.name}" if controller=="payments" and @loan
return params[:report_type] if controller=="reports" and params[:report_type]
#Check if @<controller> is available
unless instance_variables.include?("@"+controller.singularize)
return join_segments(prefix, controller_name, postfix)
end
#if @<controller> is indeed present
obj = instance_variable_get("@"+controller.singularize)
# prefix += "New" if obj.new?
postfix << "for #{@loan.client.name}" if obj.respond_to?(:client)
return join_segments(prefix, controller_name, obj.name, postfix) if obj.respond_to?(:name) and not obj.new?
#catch all
return join_segments(prefix, controller_name, postfix)
end
end
end
Fixed audit trail bug
module Merb
module GlobalHelpers
CRUD_ACTIONS = ["list", "index", "show", "edit", "new"]
MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
def page_title
begin
generate_page_title
rescue
return "MostFit" rescue Exception
end
end
def link_to_with_class(name, url)
link_to_with_rights(name, url, :class => ((request.uri==(url) or request.uri.index(url)==0) ? "selected" : ""))
end
def link_to_with_rights(text, path, params = {}, method="GET")
uri = URI.parse(path)
method = method.to_s.upcase || "GET"
request = Merb::Request.new(
Merb::Const::REQUEST_PATH => uri.path,
Merb::Const::REQUEST_METHOD => method,
Merb::Const::QUERY_STRING => uri.query)
route = Merb::Router.match(request)[1] rescue nil
return link_to(text,path,params) if session.user.can_access?(route, params)
end
def url_for_loan(loan, action = '', opts = {})
# this is to generate links to loans, as the resouce method doesn't work for descendant classes of Loan
# it expects the whole context (@branch, @center, @client) to exist
base = if @branch and @center and @client
url(:branch_center_client, @branch.id, @center.id, @client.id)
elsif @client
url(:branch_center_client, @client.center.branch_id, @client.center_id, @client.id)
else
client = loan.client
url(:branch_center_client, client.center.branch_id, client.center_id, client.id)
end
base + "/loans/#{loan.id}/" + action.to_s + (opts.length>0 ? "?#{opts.inject([]){|s,x| s << "#{x[0]}=#{x[1]}"}.join("&")}" : '')
end
def select_staff_member_for(obj, col, attrs = {}, allow_unsigned=false)
id_col = "#{col.to_s}_staff_id".to_sym
selected = ((obj.send(id_col) and obj.send(id_col)!="") ? obj.send(id_col).to_s : attrs[:selected] || "0")
select(col,
:collection => staff_members_collection,
:name => "#{obj.class.to_s.snake_case}[#{id_col}]",
:id => attrs[:id] || "#{obj.class.to_s.snake_case}_#{id_col}",
:selected => selected)
end
def select_center_for(obj, col, attrs = {})
id_col = "#{col.to_s}_id".to_sym
collection = []
catalog = Center.catalog(session.user)
catalog.keys.sort.each do |branch_name|
collection << ['', branch_name]
catalog[branch_name].sort_by{|x| x[1]}.each{ |k,v| collection << [k.to_s, "!!!!!!!!!#{v}"] }
end
html = select col,
:collection => collection,
:name => "#{obj.class.to_s.snake_case}[#{id_col}]",
:id => "#{obj.class.to_s.snake_case}_#{id_col}",
:selected => (obj.send(id_col) ? obj.send(id_col).to_s : nil),
:prompt => (attrs[:prompt] or "<select a center>")
html.gsub('!!!', ' ') # otherwise the entities get escaped
end
def select_funding_line_for(obj, col, attrs = {}) # Fix me: Refactor this with all select_*_for
id_col = "#{col.to_s}_id".to_sym
catalog = Funder.catalog
collection = []
catalog.keys.sort.each do |funder_name|
collection << ['', funder_name]
catalog[funder_name].each_pair { |k,v| collection << [k.to_s, "!!!!!!#{v}"]}
end
html = select col,
:collection => collection,
:name => "#{obj.class.to_s.snake_case}[#{id_col}]",
:id => "#{obj.class.to_s.snake_case}_#{id_col}",
:selected => (obj.send(id_col) ? obj.send(id_col).to_s : nil),
:prompt => (attrs[:prompt] or "<select a funding line>")
html.gsub('!!!', ' ') # otherwise the entities get escaped
end
def date_select(name, date=Date.today, opts={})
# defaults to Date.today
# should refactor
attrs = {}
attrs.merge!(:name => name)
attrs.merge!(:date => date)
attrs.merge!(:id => opts[:id]||name)
attrs.merge!(:date => date)
attrs.merge!(:min_date => opts[:min_date]||Date.min_date)
attrs.merge!(:max_date => opts[:max_date]||Date.max_date)
date_select_html(attrs)
end
def date_select_for(obj, col = nil, attrs = {})
attrs.merge!(:name => "#{obj.class.to_s.snake_case}[#{col.to_s}]")
attrs.merge!(:id => "#{obj.class.to_s.snake_case}_#{col.to_s}")
nullable = attrs[:nullable] ? true : false
date = obj.send(col)
date = Date.today if date.blank? and not nullable
date = nil if date.blank? and nullable
attrs.merge!(:date => date)
attrs.merge!(:min_date => attrs[:min_date]||Date.min_date)
attrs.merge!(:max_date => attrs[:max_date]||Date.max_date)
date_select_html(attrs, obj, col)
# errorify_field(attrs, col)
end
def date_select_html (attrs, obj = nil, col = nil)
str = %Q{
<input type='text' name="#{attrs[:name]}" id="#{attrs[:id]}" value="#{attrs[:date]}" size="12">
<script type="text/javascript">
$(function(){
$("##{attrs[:id]}").datepicker('destroy').datepicker({altField: '##{attrs[:id]}', buttonImage: "/images/calendar.png", changeYear: true, buttonImageOnly: true,
yearRange: '#{attrs[:min_date].year}:#{attrs[:max_date].year}',
dateFormat: '#{datepicker_dateformat}', altFormat: '#{datepicker_dateformat}', minDate: '#{attrs[:min_date]}',
maxDate: '#{attrs[:max_date]}', showOn: 'both', setDate: "#{attrs[:date]}" })
});
</script>
}
return str
end
def datepicker_dateformat
if $globals and $globals[:mfi_details] and $globals[:mfi_details][:date_format]
ourDateFormat = $globals[:mfi_details][:date_format]
else
ourDateFormat = "%Y-%m-%d"
end
s = ourDateFormat.dup
s.gsub!("%Y","yy")
s.gsub!("%y","y")
s.gsub!("%m","mm")
s.gsub!("%d","dd")
s.gsub!("%B","MM")
s.gsub!("%A","DD")
return s
end
#old func it shows textbox
def date_select_old_html (attrs, obj = nil, col = nil)
date = attrs[:date]
nullable = attrs[:nullable]
day_attrs = attrs.merge(
:name => attrs[:name] + '[day]',
:id => attrs[:id] + '_day',
:selected => (date ? date.day.to_s : ''),
:class => (obj and col) ? (obj.errors[col] ? 'error' : '') : nil,
:collection => (nullable ? [['', '-']] : []) + (1..31).to_a.map{ |x| x = [x.to_s, x.to_s] }
)
count = 0
month_attrs = attrs.merge(
:name => attrs[:name] + '[month]',
:id => attrs[:id] + '_month',
:selected => (date ? date.month.to_s : ''),
:class => obj ? (obj.errors[col] ? 'error' : '') : nil,
:collection => (nullable ? [['', '-']] : []) + MONTHS.map { |x| count += 1; x = [count, x] }
)
min_year = attrs[:min_date] ? attrs[:min_date].year : 1900
max_year = attrs[:max_date] ? attrs[:max_date].year : date.year + 3
year_attrs = attrs.merge(
:name => attrs[:name] + '[year]',
:id => attrs[:id] + '_year',
:selected => (date ? date.year.to_s : ''),
:class => obj ? (obj.errors[col] ? 'error' : '') : nil,
:collection => (nullable ? [['', '-']] : []) + (min_year..max_year).to_a.reverse.map{|x| x = [x.to_s, x.to_s]}
)
select(month_attrs) + '' + select(day_attrs) + '' + select(year_attrs)
end
def ofc2(width, height, url, id = Time.now.usec, swf_base = '/')
<<-HTML
<div id='flashcontent_#{id}'></div>
<script type="text/javascript">
swfobject.embedSWF(
"#{swf_base}open-flash-chart.swf", "flashcontent_#{id}",
"#{width}", "#{height}", "9.0.0", "expressInstall.swf",
{"data-file":"#{url}", "loading":"Waiting for data... (reload page when it takes too long)"} );
</script>
HTML
end
def breadcrums
# breadcrums use the request.uri and the instance vars of the parent
# resources (@branch, @center) that are available -- so no db queries
crums, url = [], ''
request.uri.split("?")[0][1..-1].split('/').each_with_index do |part, index|
url << '/' + part
if part.to_i.to_s.length == part.length # true when a number (id)
o = instance_variable_get('@'+url.split('/')[-2].singular) # get the object (@branch)
s = (o.respond_to?(:name) ? link_to(o.name, url) : link_to('#'+o.object_id.to_s, url))
crums[-1] += ": <b><i>#{s}</i></b>" # merge the instance names (or numbers)
else # when not a number (id)
crums << link_to(part.gsub('_', ' '), url) # add the resource name
end
end
['You are here', crums].join(' <b>>></b> ') # fancy separator
end
def format_currency(i)
# in case of our rupees we do not count with cents, if you want to have cents do that here
i.to_f.round(2).to_s + " INR"
end
def plurial_nouns(freq)
case freq.to_sym
when :daily
'days'
when :weekly
'weeks'
when :monthly
'months'
else
'????'
end
end
def difference_in_days(start_date, end_date, words = ['days early', 'days late'])
d = end_date - start_date
return '' if d == 0
"#{d.abs} #{d > 0 ? words[1] : words[0]}"
end
def debug_info
[
{:name => 'merb_config', :code => 'Merb::Config.to_hash', :obj => Merb::Config.to_hash},
{:name => 'params', :code => 'params.to_hash', :obj => params.to_hash},
{:name => 'session', :code => 'session.to_hash', :obj => session.to_hash},
{:name => 'cookies', :code => 'cookies', :obj => cookies},
{:name => 'request', :code => 'request', :obj => request},
{:name => 'exceptions', :code => 'request.exceptions', :obj => request.exceptions},
{:name => 'env', :code => 'request.env', :obj => request.env},
{:name => 'routes', :code => 'Merb::Router.routes', :obj => Merb::Router.routes},
{:name => 'named_routes', :code => 'Merb::Router.named_routes', :obj => Merb::Router.named_routes},
{:name => 'resource_routes', :code => 'Merb::Router.resource_routes', :obj => Merb::Router.resource_routes},
]
end
def paginate(pagination, *args, &block)
DmPagination::PaginationBuilder.new(self, pagination, *args, &block)
end
def chart(url, width=430, height=200, id=nil)
id||= (rand()*100000).to_i + 100
"<div id='flashcontent_#{id}'></div>
<script type='text/javascript'>
swfobject.embedSWF('/open-flash-chart.swf', \"flashcontent_#{id}\", #{width}, #{height}, '9.0.0', 'expressInstall.swf',
{\"data-file\": \"#{url}\",
\"loading\": \"Waiting for data... (reload page when it takes too long)\"
});
</script>"
end
def centers_paying_today_collection(date)
[["","---"]] + Center.paying_today(session.user, date).map {|c| [c.id.to_s,c.name]}
end
def audit_trail_url
"/audit_trails?"+params.to_a.map{|x| "audit_for[#{x[0]}]=#{x[1]}"}.join("&")
end
def diff_display(arr, model, action)
arr.map{|change|
next unless change
change.map{|k, v|
str="<tr><td>#{k.humanize}</td><td>"
str+=if action==:update and v.class==Array
"changed from #{v.first}</td><td>to #{v.last}"
elsif action==:create and v.class==Array
"#{v}"
else
"#{v}"
end
str+="</td></tr>"
}
}
end
def search_url(hash, model)
hash[:controller] = "search"
hash[:action] = "advanced"
hash[:model] = model.to_s.downcase
hash = hash.map{|x|
[(x[0].class==DataMapper::Query::Operator ? "#{x[0].target}.#{x[0].operator}" : x[0]), x[1]]
}.to_hash
url(hash)
end
def use_tinymce
@content_for_tinymce = ""
content_for :tinymce do
js_include_tag "tiny_mce/tiny_mce"
end
@content_for_tinymce_init = ""
content_for :tinymce_init do
js_include_tag "mce_editor"
end
end
def get_accessible_branches
if session.user.staff_member
[session.user.staff_member.centers.branches, session.user.staff_member.branches].flatten
else
Branch.all(:order => [:name])
end
end
def get_accessible_centers(branch_id)
centers = if session.user.staff_member
[session.user.staff_member.centers, session.user.staff_member.branches.centers].flatten
elsif branch_id and not branch_id.blank?
Center.all(:branch_id => branch_id, :order => [:name])
else
[]
end
centers.map{|x| [x.id, "#{x.name}"]}
end
def get_accessible_staff_members
staff_members = if session.user.staff_member
st = session.user.staff_member
if branches = st.branches and branches.length>0
[st] + branches.centers.managers
else
st
end
else
StaffMember.all
end
staff_members.sort_by{|x| x.name}.map{|x| [x.id, x.name]}
end
def select_mass_entry_field(attrs)
collection = []
MASS_ENTRY_FIELDS.keys.each do |model|
collection << ['', model.to_s.camelcase(' ')]
MASS_ENTRY_FIELDS[model].sort_by{|x| x.to_s}.each{|k| collection << ["#{model}[#{k.to_s}]", "!!!!!!#{k.to_s.camelcase(' ')}"] }
end
select(
:collection => collection,
:name => "#{attrs[:name]}",
:id => "#{attrs[:id]||'select_mass_entry'}",
:prompt => (attrs[:prompt] or "<select a field>")).gsub("!!!", " ")
end
private
def staff_members_collection(allow_unsigned=false)
if session.user.staff_member
staff = session.user.staff_member
bms = staff.branches.collect{|x| x.manager}
cms = staff.branches.centers.collect{|x| x.manager}
managers = [bms, cms, staff].flatten.uniq
[["0", "<Select a staff member"]] + managers.map{|x| [x.id, x.name]}
else
[["0", "<Select a staff member"]] + StaffMember.all(:active => true).map{|x| [x.id, x.name]}
end
end
def join_segments(*args)
args.map{|x| x.class==Array ? x.uniq : x}.flatten.reject{|x| not x or x.blank?}.join(' - ').capitalize
end
def generate_page_title
prefix, postfix = [], []
controller=params[:controller].split("/")[-1]
controller_name = (params[:action]=="list" or params[:action]=="index") ? controller.join_snake(' ') : controller.singularize.join_snake(' ')
controller_name = controller_name.map{|x| x.join_snake(' ')}.join(' ')
prefix << params[:namespace].join_snake(' ') if params[:namespace]
postfix << params[:action].join_snake(' ') if not CRUD_ACTIONS.include?(params[:action])
prefix << params[:action].join_snake(' ') if CRUD_ACTIONS[3..-1].include?(params[:action])
return "Loan for #{@loan.client.name}" if controller=="payments" and @loan
return params[:report_type] if controller=="reports" and params[:report_type]
#Check if @<controller> is available
unless instance_variables.include?("@"+controller.singularize)
return join_segments(prefix, controller_name, postfix)
end
#if @<controller> is indeed present
obj = instance_variable_get("@"+controller.singularize)
# prefix += "New" if obj.new?
postfix << "for #{@loan.client.name}" if obj.respond_to?(:client)
return join_segments(prefix, controller_name, obj.name, postfix) if obj.respond_to?(:name) and not obj.new?
#catch all
return join_segments(prefix, controller_name, postfix)
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'validic/version'
Gem::Specification.new do |spec|
spec.name = "validic"
spec.version = Validic::VERSION
spec.authors = ["Julius Francisco & Jay Balanay"]
spec.email = ["julius@validic.com", "jay@validic.com"]
spec.description = %q{API Wrapper for Validic}
spec.summary = spec.description
spec.homepage = "https://validic.com"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'faraday_middleware', '~> 0.9.0'
spec.add_dependency 'hashie', '~> 2.0.3'
spec.add_dependency 'activesupport'
spec.add_dependency 'multi_json'
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "simplecov-rcov"
spec.add_development_dependency "yard"
spec.add_development_dependency "vcr", '~> 2.8.0'
spec.add_development_dependency "shoulda"
spec.add_development_dependency "webmock", '~> 1.8.0'
spec.add_development_dependency "api_matchers"
end
Fixing activesupport dependency to 3.2.x beacause the gem does not work with 4.x
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'validic/version'
Gem::Specification.new do |spec|
spec.name = "validic"
spec.version = Validic::VERSION
spec.authors = ["Julius Francisco & Jay Balanay"]
spec.email = ["julius@validic.com", "jay@validic.com"]
spec.description = %q{API Wrapper for Validic}
spec.summary = spec.description
spec.homepage = "https://validic.com"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'faraday_middleware', '~> 0.9.0'
spec.add_dependency 'hashie', '~> 2.0.3'
spec.add_dependency 'activesupport', '~>3.2'
spec.add_dependency 'multi_json'
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "simplecov-rcov"
spec.add_development_dependency "yard"
spec.add_development_dependency "vcr", '~> 2.8.0'
spec.add_development_dependency "shoulda"
spec.add_development_dependency "webmock", '~> 1.8.0'
spec.add_development_dependency "api_matchers"
end
|
module HistoryHelper
def card_history_additions(card_histories)
return {} if card_histories.empty?
num_cards_played = card_histories.joins(:card).where('cards.type != ?', :hero).length # exclude hero powers
content = escape_once(render(partial: 'card_history', locals: { grouped_card_histories: group_card_histories_by_card_and_sort_by_mana(card_histories) }))
{
class: 'has-popover dotted-baseline',
data: {
container: 'body',
title: "Cards played (#{num_cards_played})",
trigger: 'hover',
placement: 'bottom',
content: content,
html: true
}
}
end
def timeline_additions(result)
return {} if result.card_histories.empty?
header = escape_once(render(partial: 'timeline_header', locals: { result: result }))
content = escape_once(render(partial: 'timeline', locals: { grouped_card_histories: group_card_histories_chronologically(result.card_histories) }))
{
class: 'btn btn-default btn-xs timeline-button',
data: {
container: 'body',
title: header,
content: content,
html: true
}
}
end
def hero_label(hero_name, label = hero_name, additions = {})
[
hero_icon(hero_name),
content_tag(:span, label, additions)
].join(' ').html_safe
end
def player_label_for_result(result, additions = {})
if result.deck
label_for_deck(result.deck, additions)
else
hero_label(result.hero.name, result.hero.name, additions)
end
end
def opponent_label_for_result(result, additions = {})
if result.opponent_deck
label_for_deck(result.opponent_deck, additions)
else
hero_label(result.opponent.name, result.opponent.name, additions)
end
end
def label_for_deck(deck, additions = {})
hero_label(deck.hero.name, deck.name, additions)
end
def hero_icon(name)
content_tag(:span, '', class: "#{name.downcase}-icon")
end
def match_duration(secs)
"#{(secs / 60.0).ceil} minutes"
end
private
def group_card_histories_by_card_and_sort_by_mana(card_histories)
card_histories.group_by(&:card).sort_by { |card, _| card.mana || -1 }
end
def group_card_histories_chronologically(card_histories)
groups = []
current_card_group = []
current_player = nil
card_histories.each do |card_history|
if current_player && current_player != card_history.player
groups << current_card_group
current_card_group = []
end
current_player = card_history.player
current_card_group << card_history
end
if current_card_group.any?
groups << current_card_group
end
groups
end
end
proper pluralization
module HistoryHelper
def card_history_additions(card_histories)
return {} if card_histories.empty?
num_cards_played = card_histories.joins(:card).where('cards.type != ?', :hero).length # exclude hero powers
content = escape_once(render(partial: 'card_history', locals: { grouped_card_histories: group_card_histories_by_card_and_sort_by_mana(card_histories) }))
{
class: 'has-popover dotted-baseline',
data: {
container: 'body',
title: "Cards played (#{num_cards_played})",
trigger: 'hover',
placement: 'bottom',
content: content,
html: true
}
}
end
def timeline_additions(result)
return {} if result.card_histories.empty?
header = escape_once(render(partial: 'timeline_header', locals: { result: result }))
content = escape_once(render(partial: 'timeline', locals: { grouped_card_histories: group_card_histories_chronologically(result.card_histories) }))
{
class: 'btn btn-default btn-xs timeline-button',
data: {
container: 'body',
title: header,
content: content,
html: true
}
}
end
def hero_label(hero_name, label = hero_name, additions = {})
[
hero_icon(hero_name),
content_tag(:span, label, additions)
].join(' ').html_safe
end
def player_label_for_result(result, additions = {})
if result.deck
label_for_deck(result.deck, additions)
else
hero_label(result.hero.name, result.hero.name, additions)
end
end
def opponent_label_for_result(result, additions = {})
if result.opponent_deck
label_for_deck(result.opponent_deck, additions)
else
hero_label(result.opponent.name, result.opponent.name, additions)
end
end
def label_for_deck(deck, additions = {})
hero_label(deck.hero.name, deck.name, additions)
end
def hero_icon(name)
content_tag(:span, '', class: "#{name.downcase}-icon")
end
def match_duration(secs)
pluralize((secs / 60.0).ceil, "minute")
end
private
def group_card_histories_by_card_and_sort_by_mana(card_histories)
card_histories.group_by(&:card).sort_by { |card, _| card.mana || -1 }
end
def group_card_histories_chronologically(card_histories)
groups = []
current_card_group = []
current_player = nil
card_histories.each do |card_history|
if current_player && current_player != card_history.player
groups << current_card_group
current_card_group = []
end
current_player = card_history.player
current_card_group << card_history
end
if current_card_group.any?
groups << current_card_group
end
groups
end
end
|
require 'fileutils'
require 'audit'
require 'open3'
module UploadsHelper
class Postprocessor
private
PROCS = {}
public
def self.create_handler(name, &block)
name = name.to_s
# slight shenanigans to access the private :define_method and :remove_method methods
# but this avoids the icky "warning: tried to create Proc object without a block"
PROCS.class.send(:define_method, :temp_method, &block)
PROCS[name] = PROCS.class.instance_method(:temp_method).bind(PROCS)
PROCS.class.send(:remove_method, :temp_method)
end
def self.alias_handler(new_name, old_name)
new_name = new_name.to_s
old_name = old_name.to_s
PROCS[new_name] = PROCS[old_name]
end
def self.process(extracted_path, f)
ext = File.extname(f)[1..-1]
PROCS[ext]&.call(extracted_path, f)
end
def self.no_files_found(extracted_path)
File.open(extracted_path.join("no_files.txt"), "w") do |f|
f.write "This is an automated message:\nNo files were found in this submission"
end
end
create_handler :rtf do |extracted_path, f|
return false unless (File.read(f, 6) == "{\\rtf1" rescue false)
# Creates the path .../converted/directory/where/file/is/
# and excludes the filename from the directory structure,
# since only one output file is created
converted_path = extracted_path.dirname.join("converted")
output_path = File.dirname(f).to_s.gsub(extracted_path.to_s, converted_path.to_s)
puts "Making .rtf output for #{f} go to #{output_path}"
Pathname.new(output_path).mkpath
output, err, status, timed_out = ApplicationHelper.capture3("soffice", "--headless",
"--convert-to", "pdf:writer_pdf_Export",
"--outdir", output_path,
f,
timeout: 30)
if status.success? && !timed_out
return true
else
puts "Failed!"
FileUtils.rm "#{output_path}/#{File.basename(f, '.*')}.pdf", force: true
Audit.log <<ERROR
================================
Problem processing #{f}:
Status: #{status}
Error: #{err}
Output: #{output}
================================
ERROR
return false
end
end
create_handler :rkt do |extracted_path, f|
embeds_path = extracted_path.dirname.join("embedded")
# Creates the path .../embedded/path/to/filename.rkt/embed#.png
# includes the filename in the directory structure deliberately,
# in case multiple racket files coexist in the same directory
output_path = f.to_s.gsub(extracted_path.to_s, embeds_path.to_s)
puts "Making .rkt output for #{f} go to #{output_path}"
Pathname.new(output_path).mkpath
output, err, status = Open3.capture3("xvfb-run", "-a", "--server-num", "1",
"racket", Rails.root.join("lib/assets/render-racket.rkt").to_s,
"-e", output_path,
"-o", f + "ext",
f)
if status.success?
contents = File.read(f + "ext")
File.open(f, "w") do |f|
f.write contents.gsub(Upload.base_upload_dir.to_s, "/files")
end
FileUtils.rm(f + "ext")
Audit.log "Successfully processed #{f}"
return true
else
FileUtils.rm (f + "ext"), force: true
Audit.log <<ERROR
================================
Problem processing #{f}:
Status: #{status}
Error: #{err}
Output: #{output}
================================
ERROR
return false
end
end
alias_handler :ss, :rkt
end
end
Now that we're using soffice, add support for .doc and .docx file conversion too
require 'fileutils'
require 'audit'
require 'open3'
module UploadsHelper
class Postprocessor
private
PROCS = {}
public
def self.create_handler(name, &block)
name = name.to_s
# slight shenanigans to access the private :define_method and :remove_method methods
# but this avoids the icky "warning: tried to create Proc object without a block"
PROCS.class.send(:define_method, :temp_method, &block)
PROCS[name] = PROCS.class.instance_method(:temp_method).bind(PROCS)
PROCS.class.send(:remove_method, :temp_method)
end
def self.alias_handler(new_name, old_name)
new_name = new_name.to_s
old_name = old_name.to_s
PROCS[new_name] = PROCS[old_name]
end
def self.process(extracted_path, f)
ext = File.extname(f)[1..-1]
PROCS[ext]&.call(extracted_path, f)
end
def self.no_files_found(extracted_path)
File.open(extracted_path.join("no_files.txt"), "w") do |f|
f.write "This is an automated message:\nNo files were found in this submission"
end
end
create_handler :rtf do |extracted_path, f|
return false unless (File.read(f, 6) == "{\\rtf1" rescue false)
# Creates the path .../converted/directory/where/file/is/
# and excludes the filename from the directory structure,
# since only one output file is created
converted_path = extracted_path.dirname.join("converted")
output_path = File.dirname(f).to_s.gsub(extracted_path.to_s, converted_path.to_s)
Pathname.new(output_path).mkpath
output, err, status, timed_out = ApplicationHelper.capture3("soffice", "--headless",
"--convert-to", "pdf:writer_pdf_Export",
"--outdir", output_path,
f,
timeout: 30)
if status.success? && !timed_out
Audit.log "Successfully processed #{f} to #{output_path}"
return true
else
FileUtils.rm "#{output_path}/#{File.basename(f, '.*')}.pdf", force: true
Audit.log <<ERROR
================================
Problem processing #{f}:
Status: #{status}
Error: #{err}
Output: #{output}
================================
ERROR
return false
end
end
create_handler :doc do |extracted_path, f|
return false unless (File.read(f, 8) == "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" rescue false)
# Creates the path .../converted/directory/where/file/is/
# and excludes the filename from the directory structure,
# since only one output file is created
converted_path = extracted_path.dirname.join("converted")
output_path = File.dirname(f).to_s.gsub(extracted_path.to_s, converted_path.to_s)
Pathname.new(output_path).mkpath
output, err, status, timed_out = ApplicationHelper.capture3("soffice", "--headless",
"--convert-to", "pdf:writer_pdf_Export",
"--outdir", output_path,
f,
timeout: 30)
if status.success? && !timed_out
Audit.log "Successfully processed #{f} to #{output_path}"
return true
else
FileUtils.rm "#{output_path}/#{File.basename(f, '.*')}.pdf", force: true
Audit.log <<ERROR
================================
Problem processing #{f}:
Status: #{status}
Error: #{err}
Output: #{output}
================================
ERROR
return false
end
end
create_handler :docx do |extracted_path, f|
return false unless (File.read(f, 4) == "\x50\x4B\x03\x04" rescue false)
# Creates the path .../converted/directory/where/file/is/
# and excludes the filename from the directory structure,
# since only one output file is created
converted_path = extracted_path.dirname.join("converted")
output_path = File.dirname(f).to_s.gsub(extracted_path.to_s, converted_path.to_s)
Pathname.new(output_path).mkpath
output, err, status, timed_out = ApplicationHelper.capture3("soffice", "--headless",
"--convert-to", "pdf:writer_pdf_Export",
"--outdir", output_path,
f,
timeout: 30)
if status.success? && !timed_out
Audit.log "Successfully processed #{f} to #{output_path}"
return true
else
FileUtils.rm "#{output_path}/#{File.basename(f, '.*')}.pdf", force: true
Audit.log <<ERROR
================================
Problem processing #{f}:
Status: #{status}
Error: #{err}
Output: #{output}
================================
ERROR
return false
end
end
create_handler :rkt do |extracted_path, f|
embeds_path = extracted_path.dirname.join("embedded")
# Creates the path .../embedded/path/to/filename.rkt/embed#.png
# includes the filename in the directory structure deliberately,
# in case multiple racket files coexist in the same directory
output_path = f.to_s.gsub(extracted_path.to_s, embeds_path.to_s)
Pathname.new(output_path).mkpath
output, err, status = Open3.capture3("xvfb-run", "-a", "--server-num", "1",
"racket", Rails.root.join("lib/assets/render-racket.rkt").to_s,
"-e", output_path,
"-o", f + "ext",
f)
if status.success?
contents = File.read(f + "ext")
File.open(f, "w") do |f|
f.write contents.gsub(Upload.base_upload_dir.to_s, "/files")
end
FileUtils.rm(f + "ext")
Audit.log "Successfully processed #{f} to #{output_path}"
return true
else
FileUtils.rm (f + "ext"), force: true
Audit.log <<ERROR
================================
Problem processing #{f}:
Status: #{status}
Error: #{err}
Output: #{output}
================================
ERROR
return false
end
end
alias_handler :ss, :rkt
end
end
|
# `dropdb bbpress`
# `createdb bbpress`
# `bundle exec rake db:migrate`
BB_PRESS_DB = "import"
require 'mysql2'
@client = Mysql2::Client.new(
host: "localhost",
username: "root",
password: "password",
:database => BB_PRESS_DB
)
require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
SiteSetting.email_domains_blacklist = ''
RateLimiter.disable
def create_admin
User.new.tap { |admin|
admin.email = "sam.saffron@gmail.com"
admin.username = "sam"
admin.password = SecureRandom.uuid
admin.save
admin.grant_admin!
admin.change_trust_level!(:regular)
admin.email_tokens.update_all(confirmed: true)
}
end
def create_user(opts, import_id)
opts[:name] = User.suggest_name(opts[:name] || opts[:email])
opts[:username] = UserNameSuggester.suggest(opts[:username] || opts[:name] || opts[:email])
opts[:email] = opts[:email].downcase
u = User.new(opts)
u.custom_fields["import_id"] = import_id
u.save!
u
end
def create_post(opts)
user = User.find(opts[:user_id])
opts = opts.merge(skip_validations: true)
PostCreator.create(user, opts)
end
results = @client.query("
select ID,
user_login username,
display_name name,
user_url website,
user_email email,
user_registered created_at
from wp_users where spam = 0 and deleted = 0").to_a
users = {}
UserCustomField.where(name: 'import_id')
.pluck(:user_id, :value)
.each do |user_id, import_id|
users[import_id.to_i] = user_id
end
skipped = 0
results.delete_if do |u|
skipped+= 1 if users[u["ID"]]
end
puts "Importing #{results.length} users (skipped #{skipped})"
i = 0
results.each do |u|
putc "." if ((i+=1)%10) == 0
id = u.delete("ID")
users[id] = create_user(ActiveSupport::HashWithIndifferentAccess.new(u), id).id
end
results = @client.query("
select ID, post_name from wp_posts where post_type = 'forum'
").to_a
categories={}
CategoryCustomField.where(name: 'import_id')
.pluck(:category_id, :value)
.each do |category_id, import_id|
categories[import_id.to_i] = category_id
end
skipped = 0
results.delete_if do |u|
skipped+= 1 if categories[u["ID"]]
end
puts
puts "Importing #{results.length} categories (skipped #{skipped})"
results.each do |c|
c["post_name"] = "unknown" if c["post_name"].blank?
category = Category.new(name: c["post_name"], user_id: -1)
category.custom_fields["import_id"] = c["ID"]
category.save!
categories[c["ID"]] = category.id
end
results = @client.query("
select ID,
post_author,
post_date,
post_content,
post_title,
post_type,
post_parent
from wp_posts
where post_status <> 'spam'
and post_type in ('topic', 'reply')
order by ID
").to_a
posts={}
PostCustomField.where(name: 'import_id')
.pluck(:post_id, :value)
.each do |post_id, import_id|
posts[import_id.to_i] = post_id
end
skipped = 0
results.delete_if do |u|
skipped+= 1 if posts[u["ID"]]
end
puts "Importing #{results.length} posts (skipped #{skipped})"
topic_lookup = {}
Post.pluck(:id, :topic_id, :post_number).each do |p,t,n|
topic_lookup[p] = {topic_id: t, post_number: n}
end
i = 0
results.each do |post|
putc "." if ((i+=1)%10) == 0
mapped = {}
mapped[:user_id] = users[post["post_author"]]
mapped[:raw] = post["post_content"]
mapped[:created_at] = post["post_date"]
if post["post_type"] == "topic"
mapped[:category] = categories[post["post_parent"]]
mapped[:title] = CGI.unescapeHTML post["post_title"]
else
parent_id = posts[post["post_parent"]]
parent = topic_lookup[parent_id]
unless parent
puts; puts "Skipping #{post["ID"]}: #{post["post_content"][0..40]}"
next
end
mapped[:topic_id] = parent[:topic_id]
mapped[:reply_to_post_number] = parent[:post_number] if parent[:post_number] > 1
end
mapped[:custom_fields] = {import_id: post["ID"]}
d_post = create_post(mapped)
posts[post["ID"]] = d_post.id
topic_lookup[d_post.id] = {post_number: d_post.post_number, topic_id: d_post.topic_id}
end
Post.exec_sql("update topics t set bumped_at = (select max(created_at) from posts where topic_id = t.id)")
fallback to email lookup if needed
# `dropdb bbpress`
# `createdb bbpress`
# `bundle exec rake db:migrate`
BB_PRESS_DB = "import"
require 'mysql2'
@client = Mysql2::Client.new(
host: "localhost",
username: "root",
password: "password",
:database => BB_PRESS_DB
)
require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
SiteSetting.email_domains_blacklist = ''
RateLimiter.disable
def create_admin
User.new.tap { |admin|
admin.email = "sam.saffron@gmail.com"
admin.username = "sam"
admin.password = SecureRandom.uuid
admin.save
admin.grant_admin!
admin.change_trust_level!(:regular)
admin.email_tokens.update_all(confirmed: true)
}
end
def create_user(opts, import_id)
opts[:name] = User.suggest_name(opts[:name] || opts[:email])
opts[:username] = UserNameSuggester.suggest(opts[:username] || opts[:name] || opts[:email])
opts[:email] = opts[:email].downcase
u = User.new(opts)
u.custom_fields["import_id"] = import_id
u.save!
u
rescue
# try based on email
u = User.find_by(email: opts[:email].downcase)
u.custom_fields["import_id"] = import_id
u.save!
u
end
def create_post(opts)
user = User.find(opts[:user_id])
opts = opts.merge(skip_validations: true)
PostCreator.create(user, opts)
end
results = @client.query("
select ID,
user_login username,
display_name name,
user_url website,
user_email email,
user_registered created_at
from wp_users where spam = 0 and deleted = 0").to_a
users = {}
UserCustomField.where(name: 'import_id')
.pluck(:user_id, :value)
.each do |user_id, import_id|
users[import_id.to_i] = user_id
end
skipped = 0
results.delete_if do |u|
skipped+= 1 if users[u["ID"]]
end
puts "Importing #{results.length} users (skipped #{skipped})"
i = 0
results.each do |u|
putc "." if ((i+=1)%10) == 0
id = u.delete("ID")
users[id] = create_user(ActiveSupport::HashWithIndifferentAccess.new(u), id).id
end
results = @client.query("
select ID, post_name from wp_posts where post_type = 'forum'
").to_a
categories={}
CategoryCustomField.where(name: 'import_id')
.pluck(:category_id, :value)
.each do |category_id, import_id|
categories[import_id.to_i] = category_id
end
skipped = 0
results.delete_if do |u|
skipped+= 1 if categories[u["ID"]]
end
puts
puts "Importing #{results.length} categories (skipped #{skipped})"
results.each do |c|
c["post_name"] = "unknown" if c["post_name"].blank?
category = Category.new(name: c["post_name"], user_id: -1)
category.custom_fields["import_id"] = c["ID"]
category.save!
categories[c["ID"]] = category.id
end
results = @client.query("
select ID,
post_author,
post_date,
post_content,
post_title,
post_type,
post_parent
from wp_posts
where post_status <> 'spam'
and post_type in ('topic', 'reply')
order by ID
").to_a
posts={}
PostCustomField.where(name: 'import_id')
.pluck(:post_id, :value)
.each do |post_id, import_id|
posts[import_id.to_i] = post_id
end
skipped = 0
results.delete_if do |u|
skipped+= 1 if posts[u["ID"]]
end
puts "Importing #{results.length} posts (skipped #{skipped})"
topic_lookup = {}
Post.pluck(:id, :topic_id, :post_number).each do |p,t,n|
topic_lookup[p] = {topic_id: t, post_number: n}
end
i = 0
results.each do |post|
putc "." if ((i+=1)%10) == 0
mapped = {}
mapped[:user_id] = users[post["post_author"]]
mapped[:raw] = post["post_content"]
mapped[:created_at] = post["post_date"]
if post["post_type"] == "topic"
mapped[:category] = categories[post["post_parent"]]
mapped[:title] = CGI.unescapeHTML post["post_title"]
else
parent_id = posts[post["post_parent"]]
parent = topic_lookup[parent_id]
unless parent
puts; puts "Skipping #{post["ID"]}: #{post["post_content"][0..40]}"
next
end
mapped[:topic_id] = parent[:topic_id]
mapped[:reply_to_post_number] = parent[:post_number] if parent[:post_number] > 1
end
mapped[:custom_fields] = {import_id: post["ID"]}
d_post = create_post(mapped)
posts[post["ID"]] = d_post.id
topic_lookup[d_post.id] = {post_number: d_post.post_number, topic_id: d_post.topic_id}
end
Post.exec_sql("update topics t set bumped_at = (select max(created_at) from posts where topic_id = t.id)")
|
class FetchMembersJob < ActiveJob::Base
queue_as :urgent
def perform(cache_key, request_uri, params)
Rails.cache.fetch(cache_key, expires_in: 2.days) do
request = Github::Client.new(request_uri, params).find
# Fetch members async
request.parsed_response["items"].map{|u| u["login"]}.map{|username|
FetchMemberJob.perform_later(username)
}
# Cache the JSON response
{
members: Github::Response.new(request).collection,
rels: Pagination.new(request.headers).build
}.to_json
end
end
end
Indent code
class FetchMembersJob < ActiveJob::Base
queue_as :urgent
def perform(cache_key, request_uri, params)
Rails.cache.fetch(cache_key, expires_in: 2.days) do
request = Github::Client.new(request_uri, params).find
# Fetch members async
request.parsed_response["items"].map{|u| u["login"]}.map{|username|
FetchMemberJob.perform_later(username)
}
# Cache the JSON response
{
members: Github::Response.new(request).collection,
rels: Pagination.new(request.headers).build
}.to_json
end
end
end |
require 'csv'
only_nfp = []
only_hbx = []
nfp_rows = []
hbx_rows = []
nfp_search_hash = Hash.new { |h, k| h[k] = Array.new }
hbx_search_hash = Hash.new { |h, k| h[k] = Array.new }
def premium_total_amount(pre_amt)
return 0.00 if pre_amt.blank?
pre_amt.strip.gsub("$", "").gsub(",", "").to_f
end
def match_row?(nfp_row, hbx_row)
n_s_id = nfp_row["SubscriberID"]
n_m_id = nfp_row["MemberID"]
# n_eg_id = nfp_row["PolicyID"]
n_hios_id = nfp_row["HIOSID"]
n_ssn = nfp_row["SSN"]
n_pre_tot = nfp_row[:pre_amt_tot]
n_fein = nfp_row["EmployerFEIN"]
h_s_id = hbx_row["Subscriber ID"]
h_m_id = hbx_row["Member ID"]
# h_eg_id = hbx_row["Policy ID"]
h_hios_id = hbx_row["HIOS ID"]
h_ssn = hbx_row["SSN"]
n_cs = nfp_row['CoverageStart']
n_ce = nfp_row['CoverageEnd']
h_cs = hbx_row['Coverage Start']
h_ce = hbx_row['Coverage End']
h_pre_tot = hbx_row[:pre_amt_tot]
h_fein = hbx_row["Employer FEIN"]
(
(n_s_id == h_s_id) &&
(n_m_id == h_m_id) &&
# (n_eg_id == h_eg_id) &&
(n_hios_id == h_hios_id) &&
# (n_ssn == h_ssn) &&
(n_pre_tot == h_pre_tot) &&
(n_fein == h_fein) &&
(n_cs == h_cs) &&
(n_ce == h_ce)
)
end
def is_cancel_garbage?(nfp_row)
cs = nfp_row['CoverageStart']
ce = nfp_row['CoverageEnd']
n_s_id = nfp_row["SubscriberID"]
n_m_id = nfp_row["MemberID"]
return true if (n_s_id != n_m_id)
c_start = Date.parse(cs)
return true if c_start < Date.new(2014,12,31)
return false if ce.blank?
c_end = Date.parse(ce)
c_end <= c_start
end
CSV.foreach("congressional_audit.csv", headers: true) do |row|
h_row = row.to_hash
h_row.merge!(:pre_amt_tot => premium_total_amount(h_row["Premium Total"]))
hbx_row = [h_row, row.fields]
hbx_rows << hbx_row
hbx_search_hash[h_row.to_hash["Subscriber ID"]] = hbx_search_hash[h_row.to_hash["Subscriber ID"]] + [hbx_row]
end
CSV.foreach("CongressAudit.csv", headers: true, :encoding => 'windows-1251:utf-8') do |row|
data = row.to_hash
if !is_cancel_garbage?(data)
h_row = row.to_hash
h_row.merge!(:pre_amt_tot => premium_total_amount(h_row["PremiumTotal"]))
nfp_row = [h_row.to_hash, row.fields]
nfp_rows << nfp_row
nfp_search_hash[h_row.to_hash["SubscriberID"]] = nfp_search_hash[h_row.to_hash["SubscriberID"]] + [nfp_row]
end
end
CSV.open("nfp_only.csv", "w") do |csv|
nfp_rows.each do |nfp_row|
searchable_rows = hbx_search_hash[nfp_row.first["SubscriberID"]]
unless (searchable_rows.any? { |h_row| match_row?(nfp_row.first, h_row.first) })
puts nfp_row.first.inspect
csv << nfp_row.last
end
end
end
CSV.open("hbx_only.csv", "w") do |csv|
hbx_rows.each do |hbx_row|
searchable_rows = nfp_search_hash[hbx_row.first["Subscriber ID"]]
unless (searchable_rows.any? { |n_row| match_row?(n_row.first, hbx_row.first) })
csv << hbx_row.last
end
end
end
Trying out Dan's idea
require 'csv'
only_nfp = []
only_hbx = []
nfp_rows = []
hbx_rows = []
nfp_search_hash = Hash.new { |h, k| h[k] = Array.new }
hbx_search_hash = Hash.new { |h, k| h[k] = Array.new }
def premium_total_amount(pre_amt)
return 0.00 if pre_amt.blank?
pre_amt.strip.gsub("$", "").gsub(",", "").to_f
end
def match_row?(nfp_row, hbx_row)
# normalize the keys by removing spaces so keys match
hbx_row.keys.each do |k|
next if k.is_a? Symbol
hbx_row[k.gsub(' ', '')] = hbx_row[k]
hbx_row.delete(k)
end
nfp_row == hbx_row
end
def is_cancel_garbage?(nfp_row)
cs = nfp_row['CoverageStart']
ce = nfp_row['CoverageEnd']
n_s_id = nfp_row["SubscriberID"]
n_m_id = nfp_row["MemberID"]
return true if (n_s_id != n_m_id)
c_start = Date.parse(cs)
return true if c_start < Date.new(2014,12,31)
return false if ce.blank?
c_end = Date.parse(ce)
c_end <= c_start
end
CSV.foreach("congressional_audit.csv", headers: true) do |row|
h_row = row.to_hash
h_row.merge!(:pre_amt_tot => premium_total_amount(h_row["Premium Total"]))
hbx_row = [h_row, row.fields]
hbx_rows << hbx_row
hbx_search_hash[h_row.to_hash["Subscriber ID"]] = hbx_search_hash[h_row.to_hash["Subscriber ID"]] + [hbx_row]
end
CSV.foreach("CongressAudit.csv", headers: true, :encoding => 'windows-1251:utf-8') do |row|
data = row.to_hash
if !is_cancel_garbage?(data)
h_row = row.to_hash
h_row.merge!(:pre_amt_tot => premium_total_amount(h_row["PremiumTotal"]))
nfp_row = [h_row.to_hash, row.fields]
nfp_rows << nfp_row
nfp_search_hash[h_row.to_hash["SubscriberID"]] = nfp_search_hash[h_row.to_hash["SubscriberID"]] + [nfp_row]
end
end
CSV.open("nfp_only.csv", "w") do |csv|
nfp_rows.each do |nfp_row|
searchable_rows = hbx_search_hash[nfp_row.first["SubscriberID"]]
unless (searchable_rows.any? { |h_row| match_row?(nfp_row.first, h_row.first) })
puts nfp_row.first.inspect
csv << nfp_row.last
end
end
end
CSV.open("hbx_only.csv", "w") do |csv|
hbx_rows.each do |hbx_row|
searchable_rows = nfp_search_hash[hbx_row.first["Subscriber ID"]]
unless (searchable_rows.any? { |n_row| match_row?(n_row.first, hbx_row.first) })
csv << hbx_row.last
end
end
end
|
module Pakyow
class RouteSet
def initialize
@routes = {:get => [], :post => [], :put => [], :delete => []}
@routes_by_name = {}
@grouped_routes_by_name = {}
@funcs = {}
@groups = {}
@templates = {}
@handlers = []
@scope = {:name => nil, :path => '/', :hooks => {:before => [], :after => []}}
end
def match(path, method)
path = Router.normalize_path(path)
@routes[method.to_sym].each{|r|
case r[0]
when Regexp
if data = r[0].match(path)
return r, data
end
when String
if r[0] == path
return r
end
end
}
end
def handle(name_or_code)
@handlers.each{ |h|
return h if h[0] == name_or_code || h[1] == name_or_code
}
nil
end
# Name based route lookup
def route(name, group = nil)
return @routes_by_name[name] unless group
if grouped_routes = @grouped_routes_by_name[group]
grouped_routes[name]
end
end
# Creates or retreivs a named func
def fn(name, &block)
@funcs[name] = block and return if block
[@funcs[name]]
end
def handler(name, *args, &block)
code, fn = args
fn = code and code = nil if code.is_a?(Proc)
fn = block if block_given?
@handlers << [name, code, [fn]]
end
def default(*args, &block)
self.register_route(:get, '/', *args, &block)
end
def get(*args, &block)
self.register_route(:get, *args, &block)
end
def put(*args, &block)
self.register_route(:put, *args, &block)
end
def post(*args, &block)
self.register_route(:post, *args, &block)
end
def delete(*args, &block)
self.register_route(:delete, *args, &block)
end
def call(controller, action)
lambda {
controller = Object.const_get(controller)
action ||= Configuration::Base.app.default_action
instance = controller.new
request.controller = instance
request.action = action
instance.send(action)
}
end
def group(name, *args, &block)
# deep clone existing hooks to reset at the close of this group
original_hooks = Marshal.load(Marshal.dump(@scope[:hooks]))
@scope[:hooks] = self.merge_hooks(@scope[:hooks], args[0]) if @scope[:hooks] && args[0]
@scope[:name] = name
@groups[name] = []
@grouped_routes_by_name[name] = {}
self.instance_exec(&block)
@scope[:name] = nil
@scope[:hooks] = original_hooks
end
def namespace(path, *args, &block)
name, hooks = args
hooks = name if name.is_a?(Hash)
original_path = @scope[:path]
@scope[:path] = File.join(@scope[:path], path)
self.group(name, hooks || {}, &block)
@scope[:path] = original_path
end
def template(name, &block)
@templates[name] = block
end
def expand(t_name, g_name, path = nil, data = nil, &block)
data = path and path = nil if path.is_a?(Hash)
# evaluate block in context of some class that implements
# method_missing to store map of functions
# (e.g. index, show)
t = RouteTemplate.new(block, g_name, path, self)
# evaluate template in same context, where func looks up funcs
# from map and extends get (and others) to add proper names
t.expand(@templates[t_name], data)
end
def merge_hooks(h1, h2)
# normalize
h1[:before] ||= []
h1[:after] ||= []
h1[:around] ||= []
h2[:before] ||= []
h2[:after] ||= []
h2[:around] ||= []
# merge
h1[:before].concat(h2[:before])
h1[:after].concat(h2[:after])
h1[:around].concat(h2[:around])
h1
end
protected
def register_route(method, path, *args, &block)
name, fns, hooks = self.parse_route_args(args)
fns ||= []
# add passed block to fns
fns << block if block_given?
hooks = self.merge_hooks(hooks || {}, @scope[:hooks])
# build the final list of fns
fns = self.build_fns(fns, hooks)
# prepend scope path if we're in a scope
path = File.join(@scope[:path], path)
path = Router.normalize_path(path)
# get regex and vars for path
regex, vars = self.build_route_matcher(path)
# create the route tuple
route = [regex, vars, name, fns, path]
@routes[method] << route
@routes_by_name[name] = route
# store group references if we're in a scope
return unless group = @scope[:name]
@groups[group] << route
@grouped_routes_by_name[group][name] = route
end
def parse_route_args(args)
ret = []
args.each { |arg|
if arg.is_a?(Hash) # we have hooks
ret[2] = arg
elsif arg.is_a?(Array) # we have fns
ret[1] = arg
elsif arg.is_a?(Proc) # we have a fn
ret[1] = [arg]
else # we have a name
ret[0] = arg
end
}
ret
end
def build_fns(main_fns, hooks)
fns = []
fns.concat(hooks[:around]) if hooks && hooks[:around]
fns.concat(hooks[:before]) if hooks && hooks[:before]
fns.concat(main_fns) if main_fns
fns.concat(hooks[:after]) if hooks && hooks[:after]
fns.concat(hooks[:around]) if hooks && hooks[:around]
fns
end
def build_route_matcher(path)
return path, [] if path.is_a?(Regexp)
# check for vars
return path, [] unless path[0,1] == ':' || path.index('/:')
# we have vars
vars = []
position_counter = 1
regex_route = path
route_segments = path.split('/')
route_segments.each_with_index { |segment, i|
if segment.include?(':')
vars << { :position => position_counter, :var => segment.gsub(':', '').to_sym }
if i == route_segments.length-1 then
regex_route = regex_route.sub(segment, '((\w|[-.~:@!$\'\(\)\*\+,;])*)')
position_counter += 2
else
regex_route = regex_route.sub(segment, '((\w|[-.~:@!$\'\(\)\*\+,;])*)')
position_counter += 2
end
end
}
reg = Regexp.new("^#{regex_route}$")
return reg, vars
end
end
end
Fix not found bug introduced with previous commit
module Pakyow
class RouteSet
def initialize
@routes = {:get => [], :post => [], :put => [], :delete => []}
@routes_by_name = {}
@grouped_routes_by_name = {}
@funcs = {}
@groups = {}
@templates = {}
@handlers = []
@scope = {:name => nil, :path => '/', :hooks => {:before => [], :after => []}}
end
def match(path, method)
path = Router.normalize_path(path)
@routes[method.to_sym].each{|r|
case r[0]
when Regexp
if data = r[0].match(path)
return r, data
end
when String
if r[0] == path
return r
end
end
}
nil
end
def handle(name_or_code)
@handlers.each{ |h|
return h if h[0] == name_or_code || h[1] == name_or_code
}
nil
end
# Name based route lookup
def route(name, group = nil)
return @routes_by_name[name] unless group
if grouped_routes = @grouped_routes_by_name[group]
grouped_routes[name]
end
end
# Creates or retreivs a named func
def fn(name, &block)
@funcs[name] = block and return if block
[@funcs[name]]
end
def handler(name, *args, &block)
code, fn = args
fn = code and code = nil if code.is_a?(Proc)
fn = block if block_given?
@handlers << [name, code, [fn]]
end
def default(*args, &block)
self.register_route(:get, '/', *args, &block)
end
def get(*args, &block)
self.register_route(:get, *args, &block)
end
def put(*args, &block)
self.register_route(:put, *args, &block)
end
def post(*args, &block)
self.register_route(:post, *args, &block)
end
def delete(*args, &block)
self.register_route(:delete, *args, &block)
end
def call(controller, action)
lambda {
controller = Object.const_get(controller)
action ||= Configuration::Base.app.default_action
instance = controller.new
request.controller = instance
request.action = action
instance.send(action)
}
end
def group(name, *args, &block)
# deep clone existing hooks to reset at the close of this group
original_hooks = Marshal.load(Marshal.dump(@scope[:hooks]))
@scope[:hooks] = self.merge_hooks(@scope[:hooks], args[0]) if @scope[:hooks] && args[0]
@scope[:name] = name
@groups[name] = []
@grouped_routes_by_name[name] = {}
self.instance_exec(&block)
@scope[:name] = nil
@scope[:hooks] = original_hooks
end
def namespace(path, *args, &block)
name, hooks = args
hooks = name if name.is_a?(Hash)
original_path = @scope[:path]
@scope[:path] = File.join(@scope[:path], path)
self.group(name, hooks || {}, &block)
@scope[:path] = original_path
end
def template(name, &block)
@templates[name] = block
end
def expand(t_name, g_name, path = nil, data = nil, &block)
data = path and path = nil if path.is_a?(Hash)
# evaluate block in context of some class that implements
# method_missing to store map of functions
# (e.g. index, show)
t = RouteTemplate.new(block, g_name, path, self)
# evaluate template in same context, where func looks up funcs
# from map and extends get (and others) to add proper names
t.expand(@templates[t_name], data)
end
def merge_hooks(h1, h2)
# normalize
h1[:before] ||= []
h1[:after] ||= []
h1[:around] ||= []
h2[:before] ||= []
h2[:after] ||= []
h2[:around] ||= []
# merge
h1[:before].concat(h2[:before])
h1[:after].concat(h2[:after])
h1[:around].concat(h2[:around])
h1
end
protected
def register_route(method, path, *args, &block)
name, fns, hooks = self.parse_route_args(args)
fns ||= []
# add passed block to fns
fns << block if block_given?
hooks = self.merge_hooks(hooks || {}, @scope[:hooks])
# build the final list of fns
fns = self.build_fns(fns, hooks)
# prepend scope path if we're in a scope
path = File.join(@scope[:path], path)
path = Router.normalize_path(path)
# get regex and vars for path
regex, vars = self.build_route_matcher(path)
# create the route tuple
route = [regex, vars, name, fns, path]
@routes[method] << route
@routes_by_name[name] = route
# store group references if we're in a scope
return unless group = @scope[:name]
@groups[group] << route
@grouped_routes_by_name[group][name] = route
end
def parse_route_args(args)
ret = []
args.each { |arg|
if arg.is_a?(Hash) # we have hooks
ret[2] = arg
elsif arg.is_a?(Array) # we have fns
ret[1] = arg
elsif arg.is_a?(Proc) # we have a fn
ret[1] = [arg]
else # we have a name
ret[0] = arg
end
}
ret
end
def build_fns(main_fns, hooks)
fns = []
fns.concat(hooks[:around]) if hooks && hooks[:around]
fns.concat(hooks[:before]) if hooks && hooks[:before]
fns.concat(main_fns) if main_fns
fns.concat(hooks[:after]) if hooks && hooks[:after]
fns.concat(hooks[:around]) if hooks && hooks[:around]
fns
end
def build_route_matcher(path)
return path, [] if path.is_a?(Regexp)
# check for vars
return path, [] unless path[0,1] == ':' || path.index('/:')
# we have vars
vars = []
position_counter = 1
regex_route = path
route_segments = path.split('/')
route_segments.each_with_index { |segment, i|
if segment.include?(':')
vars << { :position => position_counter, :var => segment.gsub(':', '').to_sym }
if i == route_segments.length-1 then
regex_route = regex_route.sub(segment, '((\w|[-.~:@!$\'\(\)\*\+,;])*)')
position_counter += 2
else
regex_route = regex_route.sub(segment, '((\w|[-.~:@!$\'\(\)\*\+,;])*)')
position_counter += 2
end
end
}
reg = Regexp.new("^#{regex_route}$")
return reg, vars
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.