repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
talentnest/compendium
|
spec/param_types_spec.rb
|
require 'compendium/param_types'
describe Compendium::Param do
subject{ described_class.new(:test) }
it { should_not be_scalar }
it { should_not be_boolean }
it { should_not be_date }
it { should_not be_dropdown }
it { should_not be_radio }
describe "#==" do
it "should compare to the param's value" do
subject.stub(value: :test_value)
subject.should == :test_value
end
end
end
describe Compendium::ScalarParam do
subject{ described_class.new(123) }
it { should be_scalar }
it { should_not be_boolean }
it { should_not be_date }
it { should_not be_dropdown }
it { should_not be_radio }
it "should not change values" do
subject.should == 123
end
end
describe Compendium::ParamWithChoices do
subject{ described_class.new(0, %w(a b c)) }
it { should_not be_boolean }
it { should_not be_date }
it { should_not be_dropdown }
it { should_not be_radio }
it "should return the index when given an index" do
p = described_class.new(1, [:foo, :bar, :baz])
p.should == 1
end
it "should return the index when given a value" do
p = described_class.new(:foo, [:foo, :bar, :baz])
p.should == 0
end
it "should return the index when given a string value" do
p = described_class.new("2", [:foo, :bar, :baz])
p.should == 2
end
it "should raise an error if given an invalid index" do
expect { described_class.new(3, [:foo, :bar, :baz]) }.to raise_error IndexError
end
it "should raise an error if given a value that is not included in the choices" do
expect { described_class.new(:quux, [:foo, :bar, :baz]) }.to raise_error IndexError
end
describe "#value" do
it "should return the value of the given choice" do
p = described_class.new(2, [:foo, :bar, :baz])
p.value.should == :baz
end
end
end
describe Compendium::BooleanParam do
subject{ described_class.new(true) }
it { should_not be_scalar }
it { should be_boolean }
it { should_not be_date }
it { should_not be_dropdown }
it { should_not be_radio }
it "should pass along 0 and 1" do
described_class.new(0).should == 0
described_class.new(1).should == 1
end
it "should convert a numeric string to a number" do
described_class.new('0').should == 0
described_class.new('1').should == 1
end
it "should return 0 for a truthy value" do
described_class.new(true).should == 0
described_class.new(:abc).should == 0
end
it "should return 1 for a falsey value" do
described_class.new(false).should == 1
described_class.new(nil).should == 1
end
describe "#value" do
it "should return true for a truthy value" do
described_class.new(true).value.should == true
described_class.new(:abc).value.should == true
described_class.new(0).value.should == true
end
it "should return false for a falsey value" do
described_class.new(false).value.should == false
described_class.new(nil).value.should == false
described_class.new(1).value.should == false
end
end
describe "#!" do
it "should return false if the boolean is true" do
!described_class.new(true).should == false
end
it "should return true if the boolean is false" do
end
end
end
describe Compendium::DateParam do
subject{ described_class.new(Date.today) }
it { should_not be_scalar }
it { should_not be_boolean }
it { should be_date }
it { should_not be_dropdown }
it { should_not be_radio }
it "should convert date strings to date objects" do
p = described_class.new("2010-05-20")
p.should == Date.new(2010, 5, 20)
end
it "should convert other date/time formats to date objects" do
described_class.new(DateTime.new(2010, 5, 20, 10, 30, 59)) == Date.new(2010, 5, 20)
described_class.new(Time.new(2010, 5, 20, 10, 30, 59)) == Date.new(2010, 5, 20)
described_class.new(Date.new(2010, 5, 20)) == Date.new(2010, 5, 20)
end
end
describe Compendium::DropdownParam do
subject{ described_class.new(0, %w(a b c)) }
it { should_not be_scalar }
it { should_not be_boolean }
it { should_not be_date }
it { should be_dropdown }
it { should_not be_radio }
end
describe Compendium::RadioParam do
subject{ described_class.new(0, %w(a b c)) }
it { should_not be_scalar }
it { should_not be_boolean }
it { should_not be_date }
it { should_not be_dropdown }
it { should be_radio }
end
|
talentnest/compendium
|
app/controllers/compendium/reports_controller.rb
|
<gh_stars>10-100
module Compendium
class ReportsController < ::ApplicationController
helper Compendium::ReportsHelper
include Compendium::ReportsHelper
before_filter :find_report
before_filter :find_query
before_filter :validate_options, only: [:run, :export]
before_filter :run_report, only: [:run, :export]
def setup
render_setup
end
def run
respond_to do |format|
format.json do
render json: @query ? @query.results : @report.results
end
format.any do
template = template_exists?(@prefix, get_template_prefixes) ? @prefix : 'run'
render action: template, locals: { report: @report }
end
end
end
def export
unless @report.exports?(request.format)
redirect_to action: :setup, format: nil
return
end
respond_to do |format|
format.csv do
filename = @report.report_name.to_s.parameterize + '-' + Time.current.strftime('%Y%m%d%H%I%S')
response.headers['Content-Disposition'] = 'attachment; filename="' + filename + '.csv"'
query = @report.queries[@report.exporters[:csv]]
render text: query.render_csv
end
format.any do
redirect_to action: :setup, format: nil
end
end
end
private
def find_report
@prefix = params[:report_name]
@report_name = "#{@prefix}_report"
begin
require(@report_name) unless Rails.env.development? || Module.const_defined?(@report_name.classify)
@report_class = @report_name.camelize.constantize
@report = setup_report
rescue LoadError
flash[:error] = t(:invalid_report, scope: 'compendium.reports')
redirect_to action: :index
end
end
def find_query
return unless params[:query]
@query = @report.queries[params[:query]]
unless @query
flash[:error] = t(:invalid_report_query, scope: 'compendium.reports')
redirect_to action: :setup, report_name: params[:report_name]
end
end
def render_setup(opts = {})
locals = { report: @report, prefix: @prefix }
opts.empty? ? render(action: :setup, locals: locals) : render_if_exists(opts.merge(locals: locals)) || render(action: :setup, locals: locals)
end
def setup_report
@report_class.new(params[:report] || {})
end
def validate_options
render_setup && return unless @report.valid?
end
def run_report
@report.run(self, @query ? { only: @query.name } : {})
end
def get_template_prefixes
paths = []
klass = self.class
begin
paths << klass.name.underscore.gsub(/_controller$/, '')
klass = klass.superclass
end while(klass != ActionController::Base)
paths
end
end
end
|
talentnest/compendium
|
config/initializers/rails/active_record/connection_adapters/quoting.rb
|
# ActiveRecord doesn't know how to handle SimpleDelegators when creating SQL
# This means that when passing a SimpleDelegator (ie. Compendium::Param) into ActiveRecord::Base.find, it'll
# crash.
# Override AR::ConnectionAdapters::Quoting to forward a SimpleDelegator's object to be quoted.
module ActiveRecord::ConnectionAdapters::Quoting
def quote_with_simple_delegator(value, column = nil)
return value.quoted_id if value.respond_to?(:quoted_id)
value = value.__getobj__ if value.is_a?(SimpleDelegator)
quote_without_simple_delegator(value, column)
end
alias_method_chain :quote, :simple_delegator
end
|
talentnest/compendium
|
app/classes/compendium/presenters/metric.rb
|
<filename>app/classes/compendium/presenters/metric.rb
module Compendium::Presenters
class Metric < Base
presents :metric
delegate :name, :query, :description, :ran?, to: :metric
def initialize(template, object, options = {})
super(template, object)
@options = options
end
def label
@options[:label] || t("#{query}.#{name}")
end
def description
@options[:description]
end
def result(number_format = '%0.1f', display_nil_as = :na)
if metric.result
sprintf(number_format, metric.result)
else
t(display_nil_as)
end
end
def render
@template.render 'compendium/reports/metric', metric: self
end
end
end
|
talentnest/compendium
|
config/initializers/ruby/numeric.rb
|
<filename>config/initializers/ruby/numeric.rb
# Monkey patch to determine if an object is numeric
# Only Numerics and Strings/Symbols that are representations of numbers are numeric
class Object
def numeric?
false
end
end
class String
def numeric?
!(self =~ /\A-?\d+(\.\d+)?\z|\A-?\.\d+\z/).nil?
end
end
class Symbol
def numeric?
to_s.numeric?
end
end
class Numeric
def numeric?
true
end
end
|
talentnest/compendium
|
app/classes/compendium/presenters/settings/query.rb
|
module Compendium::Presenters::Settings
class Query
attr_reader :query
delegate :[], :fetch, to: :@settings
delegate :report, to: :query, allow_nil: true
def initialize(query = nil)
@settings = {}.with_indifferent_access
@query = query
end
def update(&block)
instance_exec(self, &block)
end
def method_missing(name, *args, &block)
if block_given?
@settings[name] = block.call(*args)
elsif !args.empty?
@settings[name] = args.length == 1 ? args.first : args
elsif name.to_s.end_with?('?')
prefix = name.to_s.gsub(/\?\z/, '')
@settings.key?(prefix)
else
@settings[name]
end
end
end
end
|
talentnest/compendium
|
lib/compendium/errors.rb
|
module Compendium
CompendiumError = Class.new(StandardError)
InvalidCommand = Class.new(CompendiumError)
CannotRedefineQueryType = Class.new(CompendiumError)
end
|
talentnest/compendium
|
lib/compendium/metric.rb
|
module Compendium
Metric = Struct.new(:name, :query, :command, :options) do
attr_accessor :result
def initialize(*)
super
self.options ||= {}
end
def run(ctx, data)
self.result = if condition_failed?(ctx)
nil
else
command.is_a?(Symbol) ? ctx.send(command, data) : ctx.instance_exec(data, &command)
end
end
def ran?
!result.nil?
end
alias_method :has_ran?, :ran?
def render(template, *options, &block)
Compendium::Presenters::Metric.new(template, self, *options, &block).render
end
private
def condition_failed?(ctx)
(options.key?(:if) && !ctx.instance_exec(&options[:if])) || (options.key?(:unless) && ctx.instance_exec(&options[:unless]))
end
end
end
|
talentnest/compendium
|
spec/presenters/settings/table_spec.rb
|
require 'spec_helper'
require 'compendium/presenters/table'
describe Compendium::Presenters::Settings::Table do
let(:results) { double('Results', records: [{ one: 1, two: 2 }, { one: 3, two: 4 }], keys: [:one, :two]) }
let(:query) { double('Query', results: results, options: {}, table_settings: nil) }
let(:table) { Compendium::Presenters::Table.new(nil, query) }
subject { table.settings }
context 'default settings' do
its(:number_format) { should == '%0.2f' }
its(:table_class) { should == 'results' }
its(:header_class) { should == 'headings' }
its(:row_class) { should == 'data' }
its(:totals_class) { should == 'totals' }
its(:display_nil_as) { should be_nil }
its(:skipped_total_cols) { should be_empty }
end
context 'overriding default settings' do
let(:table) do
Compendium::Presenters::Table.new(nil, query) do |t|
t.number_format '%0.1f'
t.table_class 'report_table'
t.header_class 'report_heading'
t.display_nil_as 'N/A'
end
end
its(:number_format) { should == '%0.1f' }
its(:table_class) { should == 'report_table' }
its(:header_class) { should == 'report_heading' }
its(:display_nil_as) { should == 'N/A' }
end
describe '#update' do
it 'should override previous settings' do
subject.update do |s|
s.number_format '%0.3f'
end
subject.number_format.should == '%0.3f'
end
end
describe '#skip_total_for' do
it 'should add columns to the setting' do
subject.skip_total_for :foo, :bar
subject.skipped_total_cols.should == [:foo, :bar]
end
it 'should be callable multiple times' do
subject.skip_total_for :foo, :bar
subject.skip_total_for :quux
subject.skipped_total_cols.should == [:foo, :bar, :quux]
end
it 'should not care about type' do
subject.skip_total_for 'foo'
subject.skipped_total_cols.should == [:foo]
end
end
end
|
talentnest/compendium
|
lib/compendium/sum_query.rb
|
require 'compendium/errors'
require 'compendium/query'
module Compendium
# A SumQuery is a Query which runs an SQL sum statement (with a given column)
# Often useful in conjunction with a grouped query and counter cache
# (alternately, see CountQuery)
class SumQuery < Query
attr_accessor :column
def initialize(*args)
@report = args.shift if arg_is_report?(args.first)
@column = args.slice!(1)
super(*args)
@options.reverse_merge!(order: "SUM(#{@column})", reverse: true)
end
private
def execute_command(command)
return [] if command.nil?
raise InvalidCommand unless command.respond_to?(:sum)
command.sum(column)
end
end
end
|
talentnest/compendium
|
lib/compendium/engine.rb
|
<gh_stars>10-100
require 'compendium/engine/mount'
module Compendium
if defined?(Rails)
class Engine < ::Rails::Engine
end
end
end
|
talentnest/compendium
|
lib/compendium/report.rb
|
<reponame>talentnest/compendium
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/string/inflections'
require 'compendium/dsl'
module Compendium
class Report
attr_accessor :params, :results
extend Compendium::DSL
delegate :valid?, :errors, to: :params
delegate :report_name, :url, to: 'self.class'
class << self
delegate :validate, to: :params_class
def inherited(report)
Compendium.reports << report
# Each Report object has its own Params class so that validations can be added without affecting other
# reports. However, validations also need to be inherited, so when inheriting a report, subclass its
# params_class
report.params_class = Class.new(self.params_class)
report.params_class.class_eval %Q{
def self.model_name
ActiveModel::Name.new(Compendium::Params, Compendium, "compendium.params.#{report.name.underscore rescue 'report'}")
end
}
end
def report_name
name.underscore.gsub(/_report$/,'').to_sym
end
# Get a URL for this report (format: :json set by default)
def url(params = {})
path_helper(params)
end
# Define predicate methods for getting the report type
# ie. r.spending? checks that r == SpendingReport
def method_missing(name, *args, &block)
prefix = name.to_s.gsub(/[?!]\z/, '')
report_class = "#{prefix}_report".classify.constantize rescue nil
return self == report_class if name.to_s.end_with?('?') && Compendium.reports.include?(report_class)
super
end
def respond_to_missing?(name, include_private = false)
prefix = name.to_s.gsub(/[?!]\z/, '')
report_class = "#{prefix}_report".classify.constantize rescue nil
return true if name.to_s.end_with?('?') && Compendium.reports.include?(report_class)
super
end
private
def path_helper(params)
raise ActionController::RoutingError, "compendium_reports_run_path must be defined" unless route_helper_defined?
Rails.application.routes.url_helpers.compendium_reports_run_path(self.report_name, params.reverse_merge(format: :json))
end
def route_helper_defined?
@route_helpers ||= Module.new { include Rails.application.routes.url_helpers }
@route_helpers.method_defined?(:compendium_reports_run_path)
end
end
def initialize(params = {})
@params = self.class.params_class.new(params, options)
# When creating a new report, map each query back to the report
queries.each { |q| q.report = self }
end
def run(context = nil, options = {})
self.context = context
self.results = {}
only = Array.wrap(options.delete(:only)).compact
except = Array.wrap(options.delete(:except)).compact
raise ArgumentError, 'cannot specify only and except options at the same time' if !only.empty? && !except.empty?
(only + except).flatten.each { |q| raise ArgumentError, "invalid query #{q}" unless queries.include?(q) }
queries_to_run = if !only.empty?
queries.slice(*only)
elsif !except.empty?
queries.except(*except)
else
queries
end
queries_to_run.each{ |q| self.results[q.name] = q.run(params, ContextWrapper.wrap(context, self)) }
self
end
def metrics
Collection[Metric, queries.map{ |q| q.metrics.to_a }.flatten]
end
def exports?(type)
return exporters[type.to_sym]
end
private
attr_accessor :context
def method_missing(name, *args, &block)
prefix = name.to_s.sub(/(?:_results|\?)\Z/, '').to_sym
return queries[name] if queries.keys.include?(name)
return results[prefix] if name.to_s.end_with?('_results') && queries.keys.include?(prefix)
return params[name] if options.keys.include?(name)
return !!params[prefix] if name.to_s.end_with?('?') && options.keys.include?(prefix)
super
end
def respond_to_missing?(name, include_private = false)
prefix = name.to_s.sub(/_results\Z/, '').to_sym
return true if queries.keys.include?(name)
return true if name.to_s.end_with?('_results') && queries.keys.include?(prefix)
super
end
end
end
|
talentnest/compendium
|
app/classes/compendium/presenters/table.rb
|
<filename>app/classes/compendium/presenters/table.rb
module Compendium::Presenters
class Table < Query
attr_reader :records, :totals, :settings
def initialize(*)
super
@records = results.records
@settings = settings_class.new(query)
@settings.set_headings(results.keys)
@settings.update(&query.table_settings) if query.table_settings
yield @settings if block_given?
if has_totals_row?
@totals = @records.pop
totals[totals.keys.first] = translate(:total)
end
end
def render
content_tag(:table, class: @settings.table_class) do
table = ActiveSupport::SafeBuffer.new
table << content_tag(:thead, build_row(headings, settings.header_class, :th, &heading_proc))
table << content_tag(:tbody) do
tbody = ActiveSupport::SafeBuffer.new
records.each { |row| tbody << build_row(row, settings.row_class, &data_proc) }
tbody
end
table << content_tag(:tfoot, build_row(totals, @settings.totals_class, :th, &totals_proc)) if has_totals_row?
table
end
end
private
def headings
@settings.headings
end
def has_totals_row?
query.options.fetch(:totals, false)
end
def data_proc
proc { |key, val| formatted_value(key, val) }
end
def heading_proc
proc { |_, val| formatted_heading(val) }
end
def totals_proc
proc { |key, val| formatted_value(key, val) unless settings.skipped_total_cols.include?(key.to_sym) }
end
def build_row(row, row_class, cell_type = :td)
content_tag(:tr, class: row_class) do
out = ActiveSupport::SafeBuffer.new
row.each.with_index do |(key, val), i|
val = yield key, val, i if block_given?
out << content_tag(cell_type, val)
end
out
end
end
def formatted_heading(v)
v.is_a?(Symbol) ? translate(v) : v
end
def formatted_value(k, v)
if @settings.formatters[k]
@settings.formatters[k].call(v)
else
if v.numeric?
if v.zero? && @settings.display_zero_as?
@settings.display_zero_as
else
sprintf(@settings.number_format, v)
end
elsif v.nil?
@settings.display_nil_as
end
end || v
end
def translate(v, opts = {})
opts.reverse_merge!(scope: settings.i18n_scope) if settings.i18n_scope?
opts[:default] = -> * { I18n.t(v, scope: 'compendium') }
I18n.t(v, opts)
end
end
end
|
talentnest/compendium
|
lib/compendium/context_wrapper.rb
|
<gh_stars>10-100
require 'delegate'
module Compendium
class ContextWrapper
def self.wrap(ctx, parent, params = nil, &block)
delegator = ::SimpleDelegator.new(parent)
delegator.define_singleton_method(:__context__) { ctx }
delegator.instance_eval do
def method_missing(name, *args, &block)
return __context__.__send__(name, *args, &block) if __context__.respond_to?(name)
super
end
def respond_to_missing?(name, include_private = false)
return true if __context__.respond_to?(name, include_private)
super
end
end
return delegator.instance_exec(params, &block) if block_given?
delegator
end
end
end
|
talentnest/compendium
|
spec/presenters/base_spec.rb
|
require 'spec_helper'
require 'compendium/presenters/base'
TestPresenter = Class.new(Compendium::Presenters::Base) do
presents :test_obj
end
describe Compendium::Presenters::Base do
let(:template) { double("Template", delegated?: true) }
subject { TestPresenter.new(template, :test) }
it "should allow the object name to be overridden" do
subject.test_obj.should == :test
end
it "should delegate missing methods to the template object" do
template.should_receive(:delegated?)
subject.should be_delegated
end
end
|
talentnest/compendium
|
spec/through_query_spec.rb
|
<reponame>talentnest/compendium<gh_stars>0
require 'compendium/through_query'
describe Compendium::ThroughQuery do
describe "#initialize" do
let(:options) { double("Options") }
let(:proc) { double("Proc") }
let(:through) { double("Query") }
context "when supplying a report" do
let(:r) { Compendium::Report.new }
subject { described_class.new(r, :test, through, options, proc)}
its(:report) { should == r }
its(:name) { should == :test }
its(:through) { should == through }
its(:options) { should == options }
its(:proc) { should == proc }
end
context "when not supplying a report" do
subject { described_class.new(:test, through, options, proc)}
its(:report) { should be_nil }
its(:name) { should == :test }
its(:through) { should == through }
its(:options) { should == options }
its(:proc) { should == proc }
end
end
describe "#run" do
let(:parent1) { Compendium::Query.new(:parent1, {}, -> * { }) }
let(:parent2) { Compendium::Query.new(:parent2, {}, -> * { }) }
let(:parent3) { Compendium::Query.new(:parent3, {}, -> * { [[1, 2, 3]] }) }
before { parent3.stub(:execute_query) { |cmd| cmd } }
it "should pass along the params if the proc collects it" do
params = { one: 1, two: 2 }
q = described_class.new(:through, parent3, {}, -> r, params { params })
q.run(params).should == params
end
it "should pass along the params if the proc has a splat argument" do
params = { one: 1, two: 2 }
q = described_class.new(:through, parent3, {}, -> *args { args })
q.run(params).should == [[[1, 2, 3]], params.with_indifferent_access]
end
it "should not pass along the params if the proc doesn't collects it" do
params = { one: 1, two: 2 }
q = described_class.new(:through, parent3, {}, -> r { r })
q.run(params).should == [[1, 2, 3]]
end
it "should not affect its parent query" do
q = described_class.new(:through, parent3, {}, -> r { r.map!{ |i| i * 2 } })
q.run(nil).should == [[1, 2, 3, 1, 2, 3]]
parent3.results.should == [[1, 2, 3]]
end
context "with a single parent" do
subject { described_class.new(:sub, parent1, {}, -> r { r.first }) }
it "should not try to run a through query if the parent query has no results" do
expect { subject.run(nil) }.to_not raise_error
subject.results.should be_empty
end
end
context "with multiple parents" do
subject { described_class.new(:sub, [parent1, parent2], {}, -> r { r.first }) }
it "should not try to run a through query with multiple parents all of which have no results" do
expect { subject.run(nil) }.to_not raise_error
subject.results.should be_empty
end
it "should allow non blank queries" do
subject.through = parent3
subject.run(nil)
subject.results.should == [1, 2, 3]
end
end
context "when the through option is an actual query" do
subject { described_class.new(:sub, parent3, {}, -> r { r.first }) }
before { subject.run(nil) }
its(:through) { should == parent3 }
its(:results) { should == [1, 2, 3] }
end
end
end
|
talentnest/compendium
|
app/classes/compendium/presenters/settings/table.rb
|
<gh_stars>10-100
require 'compendium/presenters/settings/query'
module Compendium::Presenters::Settings
class Table < Query
attr_reader :headings
def initialize(*)
super
@headings = {}
# Set default values for settings
number_format '%0.2f'
table_class 'results'
header_class 'headings'
row_class 'data'
totals_class 'totals'
skipped_total_cols []
end
def set_headings(headings)
headings.map!(&:to_sym)
@headings = Hash[headings.zip(headings)].with_indifferent_access
end
def override_heading(*args, &block)
if block_given?
@headings.each do |key, val|
res = yield val.to_s
@headings[key] = res if res
end
else
col, label = args
@headings[col] = label
end
end
def format(column, &block)
@settings[:formatters] ||= {}
@settings[:formatters][column] = block
end
def formatters
(@settings[:formatters] || {})
end
def skip_total_for(*cols)
@settings[:skipped_total_cols].concat(cols.map(&:to_sym))
end
end
end
|
talentnest/compendium
|
spec/context_wrapper_spec.rb
|
<reponame>talentnest/compendium<filename>spec/context_wrapper_spec.rb
require 'compendium/context_wrapper'
class Wrapper1
def test_val
123
end
end
class Wrapper2
def wrapped
true
end
end
class Wrapper3
def wrapper_num
3
end
end
class Wrapper4
def wrapper_num
4
end
end
describe Compendium::ContextWrapper do
describe ".wrap" do
let(:w1) { Wrapper1.new }
let(:w2) { Wrapper2.new }
let(:w3) { Wrapper3.new }
let(:w4) { Wrapper4.new }
subject { described_class.wrap(w2, w1) }
it { should respond_to :test_val }
it { should respond_to :wrapped }
its(:test_val) { should == 123 }
its(:wrapped) { should == true }
it "should not affect the original objects" do
subject
w1.should_not respond_to :wrapped
w2.should_not respond_to :test_val
end
it "should yield a block if given" do
described_class.wrap(w2, w1) { test_val }.should == 123
end
context "overriding methods" do
subject { described_class.wrap(w4, w3) }
its(:wrapper_num) { should == 4 }
end
context "nested wrapping" do
let(:inner) { described_class.wrap(w2, w1) }
subject { described_class.wrap(inner, w3) }
it { should respond_to :test_val }
it { should respond_to :wrapped }
it { should respond_to :wrapper_num }
it "should not extend the inner wrap" do
subject
inner.should_not respond_to :wrapper_num
end
end
end
end
|
talentnest/compendium
|
lib/compendium/count_query.rb
|
require 'compendium/errors'
require 'compendium/query'
module Compendium
# A CountQuery is a Query which runs an SQL count statement
# Often useful in conjunction with a grouped query
class CountQuery < Query
def initialize(*args)
super
@options.reverse_merge!(order: 'COUNT(*)', reverse: true)
end
private
def execute_command(command)
return [] if command.nil?
raise InvalidCommand unless command.respond_to?(:count)
command.count
end
end
end
|
talentnest/compendium
|
spec/presenters/option_spec.rb
|
<filename>spec/presenters/option_spec.rb
require 'spec_helper'
require 'compendium/presenters/option'
require 'compendium/option'
describe Compendium::Presenters::Option do
let(:template) do
t = double('Template')
t.stub(:t) { |key| key } # Stub I18n.t to just return the given value
t
end
let(:option) { Compendium::Option.new(name: :test_option) }
subject { described_class.new(template, option) }
describe "#name" do
it "should pass the name through I18n" do
template.should_receive(:t).with('options.test_option', anything)
subject.name
end
end
describe "#note" do
before { template.stub(:content_tag) }
it "should return nil if no note is specified" do
subject.note.should be_nil
end
it "should pass to I18n if the note option is set to true" do
option.merge!(note: true)
template.should_receive(:t).with(:test_option_note)
subject.note
end
it "should pass to I18n if the note option is set" do
option.merge!(note: :the_note)
template.should_receive(:t).with(:the_note)
subject.note
end
it "should create the note within a div with class option-note" do
option.merge!(note: true)
template.should_receive(:content_tag).with(:div, anything, class: 'option-note')
subject.note
end
end
end
|
talentnest/compendium
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb
$:.unshift File.expand_path("../../app/classes", __FILE__)
|
talentnest/compendium
|
spec/query_spec.rb
|
<reponame>talentnest/compendium<gh_stars>0
require 'spec_helper'
require 'compendium/query'
describe Compendium::Query do
describe "#initialize" do
let(:options) { double("Options") }
let(:proc) { double("Proc") }
context "when supplying a report" do
let(:r) { Compendium::Report.new }
subject { described_class.new(r, :test, options, proc)}
its(:report) { should == r }
its(:name) { should == :test }
its(:options) { should == options }
its(:proc) { should == proc }
end
context "when not supplying a report" do
subject { described_class.new(:test, options, proc)}
its(:report) { should be_nil }
its(:name) { should == :test }
its(:options) { should == options }
its(:proc) { should == proc }
end
end
describe "#run" do
let(:command) { -> * { [{ value: 1 }, { value: 2 }] } }
let(:query) do
described_class.new(:test, {}, command)
end
before do
query.stub(:fetch_results) { |c| c }
end
it "should return the result of the query" do
results = query.run(nil)
results.should be_a Compendium::ResultSet
results.to_a.should == [{ 'value' => 1 }, { 'value' => 2 }]
end
it "should mark the query as having ran" do
query.run(nil)
query.should have_run
end
it "should not affect any cloned queries" do
q2 = query.clone
query.run(nil)
q2.should_not have_run
end
it "should return an empty result set if running an query with no proc" do
query = described_class.new(:blank, {}, nil)
query.run(nil).should be_empty
end
it "should filter the result set if a filter is provided" do
query.add_filter(-> data { data.reject{ |d| d[:value].odd? } })
query.run(nil).to_a.should == [{ 'value' => 2 }]
end
it "should run multiple filters if given" do
query.add_filter(-> data { data.reject{ |d| d[:value].odd? } })
query.add_filter(-> data { data.reject{ |d| d[:value].even? } })
query.run(nil).should be_empty
end
it 'should allow the result set to be a single hash when filters are present' do
query = described_class.new(:test, {}, -> * { { value1: 1, value2: 2, value3: 3 } })
query.stub(:fetch_results) { |c| c }
query.add_filter(-> d { d })
query.run(nil)
query.results.records.should == { value1: 1, value2: 2, value3: 3 }.with_indifferent_access
end
context 'ordering' do
let(:cmd) do
cmd = double('Command')
cmd.stub(order: cmd, reverse_order: cmd)
cmd
end
let(:command) do
-> c { -> * { c } }.(cmd)
end
before { query.options[:order] = 'col1' }
it 'should order the query' do
cmd.should_receive(:order)
query.run(nil)
end
it 'should not reverse the order by default' do
cmd.should_not_receive(:reverse_order)
query.run(nil)
end
it 'should reverse order if the query is given reverse: true' do
query.options[:reverse] = true
cmd.should_receive(:reverse_order)
query.run(nil)
end
end
context "when the query belongs to a report class" do
let(:report) do
Class.new(Compendium::Report) do
query(:test) { [1, 2, 3] }
end
end
subject { report.queries[:test] }
before { described_class.any_instance.stub(:fetch_results) { |c| c } }
it "should return its results" do
subject.run(nil).should == [1, 2, 3]
end
it "should not affect the report" do
subject.run(nil)
report.queries[:test].results.should be_nil
end
it "should not affect future instances of the report" do
subject.run(nil)
report.new.queries[:test].results.should be_nil
end
end
end
describe "#nil?" do
it "should return true if the query's proc is nil" do
Compendium::Query.new(:test, {}, nil).should be_nil
end
it "should return false if the query's proc is not nil" do
Compendium::Query.new(:test, {}, ->{}).should_not be_nil
end
end
describe "#render_chart" do
let(:template) { double("Template") }
subject { described_class.new(:test, {}, -> * {}) }
it "should initialize a new Chart presenter if the query has no results" do
subject.stub(empty?: true)
Compendium::Presenters::Chart.should_receive(:new).with(template, subject).and_return(double("Presenter").as_null_object)
subject.render_chart(template)
end
it "should initialize a new Chart presenter if the query has results" do
subject.stub(empty?: false)
Compendium::Presenters::Chart.should_receive(:new).with(template, subject).and_return(double("Presenter").as_null_object)
subject.render_chart(template)
end
end
describe "#render_table" do
let(:template) { double("Template") }
subject { described_class.new(:test, {}, -> * {}) }
it "should return nil if the query has no results" do
subject.stub(empty?: true)
subject.render_table(template).should be_nil
end
it "should initialize a new Table presenter if the query has results" do
subject.stub(empty?: false)
Compendium::Presenters::Table.should_receive(:new).with(template, subject).and_return(double("Presenter").as_null_object)
subject.render_table(template)
end
end
describe "#url" do
let(:report) { double("Report") }
subject { described_class.new(:test, {}, ->{}) }
before { subject.report = report }
it "should build a URL using its report's URL" do
report.should_receive(:url).with(query: :test)
subject.url
end
end
end
|
talentnest/compendium
|
app/helpers/compendium/reports_helper.rb
|
<gh_stars>10-100
module Compendium
module ReportsHelper
private
def expose(*args)
klass = args.pop if args.last.is_a?(Class)
klass ||= "Compendium::Presenters::#{args.first.class}".constantize
presenter = klass.new(self, *(args.empty? ? [nil] : args))
yield presenter if block_given?
presenter
end
def render_report_setup(assigns)
render file: "#{Compendium::Engine.root}/app/views/compendium/reports/setup", locals: assigns
end
def render_if_exists(options = {})
if lookup_context.template_exists?(options[:partial] || options[:template], options[:path], options.key?(:partial))
render(options)
end
end
end
end
|
talentnest/compendium
|
lib/compendium/param_types.rb
|
require_relative '../../config/initializers/ruby/numeric'
require 'delegate'
module Compendium
class Param < ::SimpleDelegator
def scalar?; false; end
def boolean?; false; end
def date?; false; end
def dropdown?; false; end
def radio?; false; end
def ==(other)
return true if (value == other rescue false)
super
end
# Need to explicitly delegate nil? to the object, otherwise it's always false
# This is because SimpleDelegator is a non-nil object, and it only forwards non-defined methods!
def nil?
__getobj__.nil?
end
def to_f
Kernel.Float(__getobj__)
end
def to_i
Kernel.Integer(__getobj__)
end
end
class ParamWithChoices < Param
def initialize(obj, choices)
@choices = choices
if @choices.respond_to?(:call)
# If given a proc, defer determining values until later.
index = obj
else
index = obj.numeric? ? obj.to_i : @choices.index(obj)
raise IndexError if (!obj.nil? && index.nil?) || index.to_i.abs > @choices.length - 1
end
super(index)
end
def value
@choices[self]
end
end
class ScalarParam < Param
def initialize(obj, *)
super obj
end
# A scalar param just keeps track of a value with no modifications
def scalar?
true
end
end
class BooleanParam < Param
def initialize(obj, *)
# If given 0, 1, or a version thereof (ie. "0"), pass it along
return super obj.to_i if obj.numeric? && (0..1).cover?(obj.to_i)
super !!obj ? 0 : 1
end
def boolean?
true
end
def value
[true, false][self]
end
# When negating a BooleanParam, use the value instead
def !
!value
end
end
class DateParam < Param
def initialize(obj, *)
if obj.respond_to?(:to_date)
obj = obj.to_date
else
obj = Date.parse(obj) rescue nil
end
super obj
end
def date?
true
end
end
class RadioParam < ParamWithChoices
def radio?
true
end
end
class DropdownParam < ParamWithChoices
def dropdown?
true
end
end
end
|
talentnest/compendium
|
lib/compendium/option.rb
|
<reponame>talentnest/compendium
require 'compendium/open_hash'
require 'active_support/string_inquirer'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/module/delegation'
module Compendium
class Option
attr_accessor :name, :type, :default, :choices, :options
delegate :boolean?, :date?, :dropdown?, :radio?, :scalar?, to: :type
delegate :merge, :merge!, :[], to: :@options
def initialize(hash = {})
raise ArgumentError, "name must be provided" unless hash.key?(:name)
@name = hash.delete(:name).to_sym
@default = hash.delete(:default)
@choices = hash.delete(:choices)
self.type = hash.delete(:type)
@options = hash.with_indifferent_access
end
def type=(type)
@type = ActiveSupport::StringInquirer.new(type.to_s)
end
def method_missing(name, *args, &block)
return options[name] if options.key?(name)
return options.key?(name[0...-1]) if name.to_s.end_with?('?')
super
end
def respond_to_missing?(name, include_private = false)
return true if options.key?(name)
super
end
end
end
|
talentnest/compendium
|
spec/params_spec.rb
|
require 'compendium/params'
describe Compendium::Params do
let(:options) {
opts = Collection[Compendium::Option]
opts << Compendium::Option.new(name: :starting_on, type: :date, default: ->{ Date.today })
opts << Compendium::Option.new(name: :ending_on, type: :date)
opts << Compendium::Option.new(name: :report_type, type: :radio, choices: [:big, :small])
opts << Compendium::Option.new(name: :boolean, type: :boolean)
opts << Compendium::Option.new(name: :another_boolean, type: :boolean)
opts << Compendium::Option.new(name: :number, type: :scalar)
opts
}
subject{ described_class.new(@params, options) }
it "should only allow keys that are given as options" do
@params = { starting_on: '2013-10-15', foo: :bar }
subject.keys.should_not include :foo
end
it "should set missing options to their default value" do
@params = {}
subject.starting_on.should == Date.today
end
it "should set missing options to nil if there is no default value" do
@params = {}
subject.ending_on.should be_nil
end
describe "#validations" do
let(:report_class) { Class.new(described_class) }
context 'presence' do
subject { report_class.new({}, options) }
before do
report_class.validates :ending_on, presence: true
subject.valid?
end
it { should_not be_valid }
its('errors.keys') { should include :ending_on }
end
context 'numericality' do
subject { report_class.new({ number: 'abcd' }, options) }
before do
report_class.validates :number, numericality: true
subject.valid?
end
it { should_not be_valid }
its('errors.keys') { should include :number }
end
end
end
|
talentnest/compendium
|
spec/count_query_spec.rb
|
<reponame>talentnest/compendium
require 'spec_helper'
require 'compendium'
require 'compendium/count_query'
require 'active_support/core_ext'
class SingleCounter
def count
1792
end
end
class MultipleCounter
def order(*)
@order = true
self
end
def reverse_order
@reverse = true
self
end
def count
results = { 1 => 340, 2 => 204, 3 => 983 }
if @order
results = results.sort_by{ |r| r[1] }
results.reverse! if @reverse
results = Hash[results]
end
results
end
end
describe Compendium::CountQuery do
subject { described_class.new(:counted_query, { count: true }, -> * { @counter }) }
it 'should have a default order' do
subject.options[:order].should == 'COUNT(*)'
subject.options[:reverse].should == true
end
describe "#run" do
it "should call count on the proc result" do
@counter = SingleCounter.new
@counter.should_receive(:count).and_return(1234)
subject.run(nil, self)
end
it "should return the count" do
@counter = SingleCounter.new
subject.run(nil, self).should == [1792]
end
context 'when given a hash' do
before { @counter = MultipleCounter.new }
it "should return a hash" do
subject.run(nil, self).should == { 3 => 983, 1 => 340, 2 => 204 }
end
it 'should be ordered in descending order' do
subject.run(nil, self).keys.should == [3, 1, 2]
end
it 'should use the given options' do
subject.options[:reverse] = false
subject.run(nil, self).keys.should == [2, 1, 3]
end
end
it "should raise an error if the proc does not respond to count" do
@counter = Class.new
expect { subject.run(nil, self) }.to raise_error Compendium::InvalidCommand
end
end
end
|
talentnest/compendium
|
spec/presenters/settings/query_spec.rb
|
require 'spec_helper'
require 'compendium/presenters/settings/query'
describe Compendium::Presenters::Settings::Query do
subject { described_class.new }
describe '#update' do
before { subject.foo = :bar }
it 'should override previous settings' do
subject.update do |s|
s.foo :quux
end
subject.foo.should == :quux
end
it 'should allow the block parameter to be skipped' do
subject.update do
foo :quux
end
subject.foo.should == :quux
end
end
end
|
rdicrist/haikunator
|
lib/haikunator.rb
|
<filename>lib/haikunator.rb
require "haikunator/version"
require "securerandom"
module Haikunator
class << self
def haikunate(token_range = 9999, delimiter = "\ ")
build(token_range, delimiter)
end
private
def build(token_range, delimiter)
sections = [
adjectives[random_seed % adjectives.length],
nouns[random_seed % nouns.length],
token(token_range)
]
sections.compact.join(delimiter)
end
def random_seed
SecureRandom.random_number(4096)
end
def token(range)
SecureRandom.random_number(range) if range > 0
end
def adjectives
%w(
amber amethyst aqua aquamarine auburn azure beige blue blush
burgundy cardinal carmine carnelian celadon cerise
cerulean chamoisee chartreuse cherry chestnut cinereous cinnabar cinnamon citrine cobalt copper coral
cordovan cornflower cream crimson cyan daffodil dandelion ecru eggplant eggshell emerald fallow
fawn feldgrau fuchsia gainsboro gamboge ginger gold goldenrod gray green
honeydew indigo iris isabelline ivory jade jasmine jasper jet jonquil lapis laurel
extinguish\ lavender lemon licorice lilac lime linen magenta magnolia mahogany maize malachite mardi\ gras
maroon mauve mauvelous midnight mint moonstone moss meadow
mulberry myrtle navy neon ochre olive olivine onyx orange orchid
pastel\ alue pastel\ green pastel\ magenta pastel\ orange pastel\ pink pastel\ purple pastel\ red
pastel\ violet pastel\ yellow peach pear pearl peridot periwinkle persimmon pine pink pistachio platinum plum puce pumpkin
purple quartz rackley raw\ umber razzmatazz red redwood regalia rose rosewood rosso\ corsa royal\ fuchsia
royal\ purple ruby rufous russet saddle\ arown saffron salmon sand sangria sapphire scarlet seafoam seashell sepia shadow
shamrock mimi\ pink sienna silver sinopia skobeloff sky\ alue sky\ magenta slate smokey\ topaz smoky\ alack snow spring
steel stizza stormcloud straw sunglow sunset tangelo tangerine taupe matcha teal thistle tiffany
timberwolf topaz turquoise tuscan\ red twilight\ lavender ultraviolet ultramarine umber urobilin venetian\ red verdigris vermilion
violet viridian wenge white wisteria xanadu yellow zaffre
)
end
def nouns
%w(
heron egret swan goose mallard osprey eagle hawk kestrel falcon gull dove owl swallow blue\ jay crow chickadee bluebird
robin catbird mockingbird vireo warbler cardinal sparrow junco blackbird grackle finch goldfinch starling kingbird phoebe swift oriole
thrasher pelican avocet tern cormorant raven wren tanager kinglet coot quail penguin
)
end
end
end
|
cosmo0920/-embulk-input-cloudwatch_logs
|
lib/embulk/input/cloudwatch_logs.rb
|
<filename>lib/embulk/input/cloudwatch_logs.rb<gh_stars>1-10
Embulk::JavaPlugin.register_input(
"cloudwatch_logs", "org.embulk.input.cloudwatch_logs.CloudwatchLogsInputPlugin",
File.expand_path('../../../../classpath', __FILE__))
|
tjhubert/devise_phone
|
lib/devise_phone/version.rb
|
<reponame>tjhubert/devise_phone
module DevisePhone
VERSION = "0.0.1667".freeze
end
|
tjhubert/devise_phone
|
devise_phone.gemspec
|
<reponame>tjhubert/devise_phone
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'devise_phone/version'
Gem::Specification.new do |s|
s.name = "devise_phone"
s.version = DevisePhone::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/tjhubert/devise_phone"
s.license = "MIT"
s.summary = "Send SMS to verify phone number"
s.description = "It sends verification code via SMS (using Twilio). User enters the code to confirm the phone number."
s.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
# s.files = Dir["{app,config,lib}/**/*"] + %w[LICENSE README.rdoc]
# s.require_path = "lib"
# s.rdoc_options = ["--main", "README.rdoc", "--charset=UTF-8"]
# s.required_ruby_version = '>= 1.8.6'
# s.required_rubygems_version = '>= 1.3.6'
s.bindir = "exe"
s.executables = s.files.grep(%r{^exe/}) { |f| File.basename(f) }
s.require_paths = ["lib"]
{
'bundler' => '~> 1.10',
# 'rspec',
'rake' => '~> 10.0'
}.each do |lib, version|
s.add_development_dependency(lib, version)
end
{
'rails' => '>= 4.0.0',
'devise' => '>= 3.0.0',
'twilio-ruby' => '>= 4.0.0'
}.each do |lib, version|
s.add_runtime_dependency(lib, version)
end
end
|
tjhubert/devise_phone
|
lib/models/phone.rb
|
require "devise_phone/hooks"
module Devise
module Models
module Phone
extend ActiveSupport::Concern
included do
before_create :set_unverified_phone_attributes, :if => :phone_verification_needed?
# after_create :private_generate_verification_code_and_send_sms, :if => :phone_verification_needed?
# before_save :remember_old_phone_number
after_save :private_generate_verification_code_and_send_sms, :if => :regenerate_phone_verification_needed?
end
def generate_verification_code_and_send_sms
if(phone_verification_needed?)
private_generate_verification_code_and_send_sms
end
self.save!
end
def verify_phone_number_with_code_entered(code_entered)
if phone_verification_needed? && (code_entered == self.phone_verification_code)
mark_phone_as_verified!
true
else
false
end
end
private
def private_generate_verification_code_and_send_sms
self.phone_verification_code = generate_phone_verification_code
set_unverified_phone_attributes
if phone_number.present?
send_sms_verification_code
end
end
def mark_phone_as_verified!
update!(phone_number_verified: true,
phone_verification_code: nil,
phone_verification_code_sent_at: nil,
phone_verified_at: DateTime.now)
end
# check if phone verification is needed and set errors here
def phone_verification_needed?
if phone_number.blank?
self.errors.add(:phone_verification_code, :empty_phone_number_field)
false
elsif phone_number_verified
self.errors.add(:phone_verification_code, :phone_verification_not_needed)
false
else
true
end
end
def regenerate_phone_verification_needed?
if phone_number.present?
if phone_number_changed?
true
else
false
end
# self.errors.add(:phone_verification_code, :empty_phone_number_field)
# false
else
false
end
end
# set attributes to user indicating the phone number is unverified
def set_unverified_phone_attributes
self.phone_number_verified = false
self.phone_verification_code_sent_at = DateTime.now
self.phone_verified_at = nil
# removes all white spaces, hyphens, and parenthesis
if self.phone_number
self.phone_number.gsub!(/[\s\-\(\)]+/, '')
end
end
# return 6 digits random code a-z,0-9
def generate_phone_verification_code
verification_code = SecureRandom.hex(3)
verification_code
end
# sends a message to number indicated in the secrets.yml
def send_sms_verification_code
number_to_send_to = self.phone_number
verification_code = self.phone_verification_code
twilio_sid = Rails.application.config.twilio[:sid]
twilio_token = Rails.application.config.twilio[:token]
twilio_phone_number = Rails.application.config.twilio[:phone_number]
twilio_message_body = I18n.t("devise.phone.message_body", :verification_code => verification_code)
@twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
@twilio_client.account.messages.create(
:from => "+1#{twilio_phone_number}",
:to => number_to_send_to,
:body => twilio_message_body
)
end
end
end
end
|
tjhubert/devise_phone
|
lib/devise_phone.rb
|
require "devise"
require "twilio-ruby"
$: << File.expand_path("..", __FILE__)
require "devise_phone/routes"
require "devise_phone/schema"
require 'devise_phone/controllers/url_helpers'
require 'devise_phone/controllers/helpers'
require 'devise_phone/rails'
module Devise
end
Devise.add_module :phone, :model => "models/phone", :controller => :phone_verifications, :route => :phone_verification
|
tjhubert/devise_phone
|
app/controllers/devise/phone_verifications_controller.rb
|
<gh_stars>1-10
class Devise::PhoneVerificationsController < DeviseController
# GET /resource/phone_verification/new
# def new
# build_resource({})
# render :new
# end
# POST /resource/phone_verification
# def create
# end
# GET /resource/phone_verification/send_code
def send_code
current_user.generate_verification_code_and_send_sms
# render nothing: true
respond_to do |format|
msg = { :status => "ok", :message => "SMS sent!" }
format.json { render :json => msg } # don't do msg.to_json
end
end
# GET or POST /resource/phone_verification/verify_code
def verify_code
verify_success = current_user.verify_phone_number_with_code_entered(params[:code_entered])
# render nothing: true
respond_to do |format|
if verify_success
message_response = "verification successful"
else
message_response = "verification fail"
end
msg = { :status => "ok", :message => message_response }
format.json { render :json => msg } # don't do msg.to_json
end
end
protected
def build_resource(hash = nil)
self.resource = resource_class.new
end
end
|
amiel/hyperion
|
lib/hyperion/base.rb
|
class Hyperion
class HyperionException < Exception; end
class NoKey < HyperionException; end
def self.hyperion_defaults(defaults)
class_variable_set(:@@redis_defaults, defaults)
end
def self.redis
@@redis ||= Redis.new
end
end
|
amiel/hyperion
|
spec/spec_helper.rb
|
require 'rubygems'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'hyperion'
RSpec.configure do |config|
config.mock_with :rspec
end
class DefaultKey < Hyperion
attr_accessor :content, :key
hyperion_key :key
end
class NoKey < Hyperion
attr_accessor :content
end
class IndexedObject < Hyperion
attr_accessor :content, :other_content, :key
hyperion_key :key
hyperion_index :other_content
hyperion_index [:content, :other_content]
end
def random_string(length = 10)
'asdfdsfasd' # todo lolololol
end
|
amiel/hyperion
|
lib/hyperion/logger.rb
|
require 'logger'
class Hyperion
module Logger
def logger
unless class_variable_defined?('@@logger') then
@@logger = ::Logger.new(STDOUT)
@@logger.level = ::Logger::DEBUG
end
@@logger
end
end
end
|
amiel/hyperion
|
lib/hyperion.rb
|
<gh_stars>1-10
require 'active_support'
require 'yaml'
require 'redis'
# TODO: splat this
require 'hyperion/base'
require 'hyperion/indices'
require 'hyperion/keys'
require 'hyperion/logger'
require 'hyperion/version'
class Hyperion
extend Indices
extend Keys
extend Version
extend Logger
DEBUG = false
# TODO: ActiveModel lint it _mayhaps_
# TODO: atomic operations
# TODO: default key called #{class}_id if there isn't any @@redis_key
def initialize(opts = {})
defaults = (self.class.class_variable_defined?('@@redis_defaults') ? self.class.class_variable_get('@@redis_defaults') : {})
defaults.merge(opts).each {|k,v|
self.send(k.to_s+'=',v)
}
end
def self.first(conds)
# FIXME: gotta be a faster way ;)
self.find(conds).first
end
def self.find(conds)
Hyperion.logger.debug("[RS] Searching for #{conds.inspect}") if Hyperion::DEBUG
if conds.is_a? Hash then
Hyperion.logger.debug("[RS] Its a Hash, digging through indexes!") if Hyperion::DEBUG
ids = []
index_keys = []
index_values = []
if conds.keys.size > 1 then
conds.sort.each {|k,v|
index_values << v
index_keys << k.to_s
}
index_key = self.to_s.downcase + '_' + index_keys.join('.') + '_' + index_values.join('.')
ids << Hyperion.redis.smembers(index_key)
else
conds.each{|k,v|
index_key = self.to_s.downcase + '_' + k.to_s + '_' + v.to_s
ids << Hyperion.redis.smembers(index_key)
}
end
ids.flatten.uniq.collect{|i|
self.find(i)
}
else
Hyperion.logger.debug("[RS] Fetching #{self.to_s.downcase + '_' + conds.to_s}") if Hyperion::DEBUG
v = redis[self.to_s.downcase + '_' + conds.to_s].to_s
if v and not v.empty? then
self.deserialize(v)
else
nil
end
end
end
def self.deserialize(what); YAML.load(what); end
def serialize; YAML::dump(self); end
def save
Hyperion.logger.debug("[RS] Saving a #{self.class.to_s}:") if Hyperion::DEBUG
unless (self.class.class_variable_defined?('@@redis_key')) then
self.class.send('attr_accessor', 'id')
self.class.class_variable_set('@@redis_key', 'id')
end
unless (self.send(self.class.class_variable_get('@@redis_key'))) then
Hyperion.logger.debug("[RS] Generating new key!") if Hyperion::DEBUG
self.send(self.class.class_variable_get('@@redis_key').to_s + '=', new_key)
end
Hyperion.logger.debug("[RS] Saving into #{full_key}: #{self.inspect}") if Hyperion::DEBUG
Hyperion.redis[full_key] = self.serialize
# Now lets update any indexes
# BUG: need to clear out any old indexes of us
self.class.class_variable_get('@@redis_indexes').each{|idx|
Hyperion.logger.debug("[RS] Updating index for #{idx}") if Hyperion::DEBUG
if idx.is_a?(Array) then
index_values = idx.sort.collect {|i| self.send(i) }.join('.')
index_key = self.class.to_s.downcase + '_' + idx.sort.join('.').to_s + '_' + index_values
else
value = self.send(idx)
index_key = self.class.to_s.downcase + '_' + idx.to_s + '_' + value.to_s if value
end
Hyperion.logger.debug("[RS] Saving index #{index_key}: #{self.send(self.class.class_variable_get('@@redis_key'))}") if Hyperion::DEBUG
Hyperion.redis.sadd(index_key, self.send(self.class.class_variable_get('@@redis_key')))
} if self.class.class_variable_defined?('@@redis_indexes')
end
def self.dump(output = STDOUT, lock = false)
# TODO: lockability and progress
output.write(<<-eos)
# Hyperion Dump
# Generated by @adrianpike's Hyperion gem.
eos
output.write('# Generated on ' + Time.current.to_s + "\n")
output.write('# DB size is ' + redis.dbsize.to_s + "\n")
redis.keys.each{|k|
case redis.type(k)
when "string"
output.write({ k => redis.get(k)}.to_yaml)
when "set"
output.write({ k => redis.smembers(k) }.to_yaml)
end
}
end
# THIS IS MAD DANGEROUS AND UNTESTED, BEWARE DATA INTEGRITY
def self.load(file = STDIN, truncate = true, lock = false)
# TODO: lockability and progress
YAML.each_document( file ) do |ydoc|
ydoc.each {|k,v|
redis.del(k) if truncate
case v.class.to_s
when 'String'
redis[k] = v
when 'Array'
v.each{|val|
redis.sadd(k,val)
}
else
p v.class
end
}
end
end
# THIS IS TOTALLY IRREVERSIBLE YO
def self.truncate!
redis.flushdb
end
private
def new_key
if (self.class.class_variable_defined?('@@redis_generate_key') and self.class.class_variable_get('@@redis_generate_key') == false)
raise NoKey
else
Hyperion.redis.incr(self.class.to_s.downcase + '_' + self.class.class_variable_get('@@redis_key').to_s)
end
end
def full_key
self.class.to_s.downcase + '_' + self.send(self.class.class_variable_get('@@redis_key')).to_s
end
end
|
amiel/hyperion
|
lib/hyperion/keys.rb
|
<reponame>amiel/hyperion<gh_stars>1-10
class Hyperion
module Keys
def hyperion_key(key, opts = {})
class_variable_set(:@@redis_key, key)
class_variable_set(:@@redis_generate_key, opts[:generate])
end
end
end
|
amiel/hyperion
|
benchmarks.rb
|
require 'benchmark'
require 'ruby-prof'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'lib'))
require 'hyperion'
class DefaultKey < Hyperion
attr_accessor :content, :key
hyperion_key :key
end
class NoKey < Hyperion
attr_accessor :content
end
class IndexedObject < Hyperion
attr_accessor :content, :other_content, :key
hyperion_key :key
hyperion_index :other_content
hyperion_index [:content, :other_content]
end
[100,1000,10000,100000].each {|n|
puts "===== #{n} ====="
puts "#{n} inserts:"
bm = Benchmark.measure {
n.times do |k|
f = DefaultKey.new({
:key => k,
:content => "Benchmarking!"
})
f.save
end
}
p bm
puts "#{n} fetches:"
bm = Benchmark.measure {
n.times do |k|
f = DefaultKey.find(k)
end
}
p bm
puts "#{n} inserts w/autoincrement:"
bm = Benchmark.measure {
n.times do |k|
f = DefaultKey.new({
:content => "Benchmarking!"
})
f.save
end
}
p bm
puts "#{n} inserts with indexes and autoincrement:"
bm = Benchmark.measure {
n.times do |k|
f = IndexedObject.new({
:content => "Benchmarking!",
:other_content => k
})
f.save
end
}
p bm
puts "#{n} fetches on a single index:"
bm = Benchmark.measure {
n.times do |k|
f = IndexedObject.find({
:other_content => k
})
end
}
p bm
puts "#{n} fetches on a complex index:"
bm = Benchmark.measure {
n.times do |k|
f = IndexedObject.find({
:content => 'Benchmarking!',
:other_content => k
})
end
}
p bm
puts "#{n} indexless updates:"
bm = Benchmark.measure {
n.times do |k|
f = DefaultKey.find(k)
f.content = 'Second time around'
f.save
end
}
p bm
}
|
amiel/hyperion
|
lib/hyperion/indices.rb
|
class Hyperion
module Indices
class NoIndex < HyperionException; end
def hyperion_index(index)
if class_variable_defined?(:@@redis_indexes) then
class_variable_set(:@@redis_indexes, class_variable_get(:@@redis_indexes) << index)
else
class_variable_set(:@@redis_indexes, [index])
end
end
def reindex!
# TODO
end
# Indexes need to be sorted sets!
# ZSET scores can supposedly be large floats, should explore max ZSET score size.
end
end
|
amiel/hyperion
|
lib/hyperion/finders.rb
|
class Hyperion
module Finders
# find(id)
# find(:all, {})
# find(:first, {})
# find(:last, {})
# we can do > and < if we use ZRANGEBYSCORE, but scores have to be integer :/
end
end
|
amiel/hyperion
|
lib/hyperion/version.rb
|
class Hyperion
module Version
def branch; nil; end
def major; 0; end
def minor; 1; end
def patch; 0; end
def version
[branch,major,minor,patch].compact.collect(&:to_s).join('.')
end
end
end
|
everthis/leetcode-ruby
|
208-implement-trie-prefix-tree.rb
|
TrieNode = Hash
class Trie
=begin
Initialize your data structure here.
=end
def initialize()
@root = TrieNode.new
end
=begin
Inserts a word into the trie.
:type word: String
:rtype: Void
=end
def insert(word)
curr = @root
word.each_char do |char|
curr = (curr[char] ||= TrieNode.new)
end
curr[:_] = true
end
=begin
Returns if the word is in the trie.
:type word: String
:rtype: Boolean
=end
def search(word)
last = word.each_char.inject(@root) do |curr, char|
curr.is_a?(TrieNode) ? curr[char] : nil
end
last && last[:_] || false
end
=begin
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: String
:rtype: Boolean
=end
def starts_with(prefix)
curr = @root
prefix.each_char.all? do |char|
curr = curr[char]
end
end
end
# Your Trie object will be instantiated and called as such:
# obj = Trie.new()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.starts_with(prefix)
|
everthis/leetcode-ruby
|
454-4sum-ii.rb
|
<reponame>everthis/leetcode-ruby
# @param {Integer[]} a
# @param {Integer[]} b
# @param {Integer[]} c
# @param {Integer[]} d
# @return {Integer}
def four_sum_count(a, b, c, d)
h = Hash.new(0); res = 0
a.each{ |el_a| b.each{ |el_b| h[el_a + el_b] += 1 } }
c.each{ |el_c| d.each{ |el_d| res += h[-(el_c + el_d)] } }
return res
end
|
everthis/leetcode-ruby
|
264-ugly-number-ii.rb
|
<filename>264-ugly-number-ii.rb
# @param {Integer} n
# @return {Integer}
def nth_ugly_number(n)
uglies = [1]
i_2 = i_3 = i_5 = 0
(n-1).times do
min = [uglies[i_2]*2, uglies[i_3]*3, uglies[i_5]*5].min
uglies << min
i_2 += 1 if min % 2 == 0
i_3 += 1 if min % 3 == 0
i_5 += 1 if min % 5 == 0
end
uglies.last
end
|
everthis/leetcode-ruby
|
263-ugly-number.rb
|
<gh_stars>0
# @param {Integer} num
# @return {Boolean}
def is_ugly(num)
return false if num < 1
return true if num == 1
valid_primes = [2, 3, 5]
valid_primes.each do |prime|
while num % prime == 0
num = num / prime
end
end
num == 1
end
|
everthis/leetcode-ruby
|
337-house-robber-iii.rb
|
<gh_stars>0
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Integer}
def rob(root)
rob_helper(root).max
end
def rob_helper(root)
return [0, 0] if root.nil?
l_taken, l_not_taken = rob_helper(root.left)
r_taken, r_not_taken = rob_helper(root.right)
[root.val + l_not_taken + r_not_taken, [l_taken, l_not_taken].max + [r_taken, r_not_taken].max]
end
|
everthis/leetcode-ruby
|
223-rectangle-area.rb
|
# @param {Integer} a
# @param {Integer} b
# @param {Integer} c
# @param {Integer} d
# @param {Integer} e
# @param {Integer} f
# @param {Integer} g
# @param {Integer} h
# @return {Integer}
def compute_area(a, b, c, d, e, f, g, h)
first_rect = (c - a) * (d - b)
second_rect = (g - e) * (h - f)
if c < e || g < a || b > h || f > d
intersection_rect = 0
else
intersection_rect = ([c, g].min - [a, e].max) * ([d, h].min - [b, f].max)
end
first_rect + second_rect - intersection_rect
end
|
everthis/leetcode-ruby
|
228-summary-ranges.rb
|
<reponame>everthis/leetcode-ruby
# @param {Integer[]} nums
# @return {String[]}
def summary_ranges(nums)
return [] if !nums || nums.empty?
size = nums.size
return ["#{nums[0]}"] if size == 1
result = []
start = nums[0]
last = nums[0]
i = 1
while i < size
current = nums[i]
if current - 1 != last
result << result_string(start, last)
start = current
end
last = current
result << result_string(start, last) if i == (size - 1)
i += 1
end
result
end
def result_string(start, last)
return start != last ? "#{start}->#{last}" : "#{start}"
end
|
everthis/leetcode-ruby
|
504-base-7.rb
|
# @param {Integer} num
# @return {String}
def convert_to_base7(num)
return "0" if num == 0
result = ''
alphabet = (0...7).map(&:to_s)
negative = num < 0
num = num.abs
while num != 0
num, digit = num.divmod(7)
result = alphabet[digit] + result
end
negative ? '-' + result : result
end
# another
def convert_to_base7(num)
num.to_s(7)
end
|
everthis/leetcode-ruby
|
224-basic-calculator.rb
|
# @param {String} s
# @return {Integer}
def calculate(s)
current_num = 0
sign = 1
result = 0
stack = []
s.each_char do |char|
if is_digit?(char)
current_num = (current_num * 10) + char.to_i
elsif char == "+"
result += sign * current_num
sign = 1
current_num = 0
elsif char == "-"
result += sign * current_num
sign = -1
current_num = 0
elsif char == '('
stack << result
stack << sign
sign = 1
current_num = 0
result = 0
elsif char == ')'
result += sign * current_num
stack_sign = stack.pop
stack_result = stack.pop
result *= stack_sign
result += stack_result
current_num = 0
end
end
result += sign * current_num
end
def is_digit?(char)
/[0-9]/.match?(char)
end
|
everthis/leetcode-ruby
|
506-relative-ranks.rb
|
<filename>506-relative-ranks.rb
# @param {Integer[]} nums
# @return {String[]}
def find_relative_ranks(nums)
m = Hash.new
m[1] = 'Gold Medal'
m[2] = 'Silver Medal'
m[3] = 'Bronze Medal'
ranks = nums.dup
nums.to_enum.with_index.map(&->(num, idx) { [num, idx] })
.sort_by(&:first).reverse
.each_with_index { |(_, idx), rank| ranks[idx] = m.fetch(rank + 1, "#{rank + 1}") }
ranks
end
|
zetter/scraper-tools
|
lib/scraper_tools/cache/null.rb
|
module ScraperTools
module Cache
class Null
def cache(key)
yield
end
end
end
end
|
zetter/scraper-tools
|
scraper_tools.gemspec
|
<gh_stars>0
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require 'scraper_tools/version'
Gem::Specification.new do |s|
s.name = "scraper_tools"
s.version = ScraperTools::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["<NAME>"]
s.summary = "A framework for scraping websites."
s.add_dependency "nokogiri"
s.add_dependency "faraday"
s.add_development_dependency "minitest"
s.add_development_dependency "webmock"
s.add_development_dependency "mocha"
s.add_development_dependency "redis"
s.files = Dir.glob("{lib}/**/*") + %w(LICENSE)
s.require_path = 'lib'
end
|
zetter/scraper-tools
|
test/units/test_scraper_tools.rb
|
require "minitest/autorun"
require 'scraper_tools'
describe ScraperTools do
describe "version" do
it "it has a version" do
assert ScraperTools::VERSION
end
end
end
|
zetter/scraper-tools
|
lib/scraper_tools/cache/redis.rb
|
<filename>lib/scraper_tools/cache/redis.rb
require 'zlib'
module ScraperTools
module Cache
class Redis
def initialize(client: client)
@client = client
end
def cache(key)
compressed_data = @client.get(key)
if compressed_data
value = Zlib::Inflate.inflate(compressed_data)
else
value = yield
compressed_data = Zlib::Deflate.deflate(value)
@client.set(key, compressed_data)
end
value
end
end
end
end
|
zetter/scraper-tools
|
test/units/cache/test_null.rb
|
<reponame>zetter/scraper-tools
require "minitest/autorun"
require 'scraper_tools'
describe ScraperTools::Cache::Null do
before do
@cache = ScraperTools::Cache::Null.new
end
describe 'using the cache method' do
it "returns the result of the block" do
result = @cache.cache('key') { 'value_1' }
assert_equal 'value_1', result
end
it "does not perform any caching" do
@cache.cache('key') { 'value_1' }
result = @cache.cache('key') { 'value_2' }
assert_equal 'value_2', result
end
end
end
|
zetter/scraper-tools
|
test/features/test_scraping_html_site.rb
|
<gh_stars>0
require "minitest/autorun"
require 'scraper_tools'
require 'support/fixtures'
describe 'scraping a html site' do
include Fixtures
describe "version" do
before do
$scraped_data = []
stub_get_requests
end
after do
$scraped_data = nil
end
it "can scrape items" do
CategoryListing.new(url: 'http://example.com/scraping_html/index.html').scrape
assert_equal ['item 1 title', 'item 2 title', 'item 3 title'], $scraped_data
end
end
class CategoryListing < ScraperTools::Page
def scrape
follow_links_to(CategoryPage, selector: '.categories a')
end
end
class CategoryPage < ScraperTools::Page
def scrape
follow_links_to(ItemPage, selector: '.items a')
end
end
class ItemPage < ScraperTools::Page
def scrape
$scraped_data << css('.title').text
end
end
end
|
zetter/scraper-tools
|
lib/scraper_tools/page.rb
|
<filename>lib/scraper_tools/page.rb
require 'nokogiri'
require 'faraday'
module ScraperTools
class Page
def initialize(options)
@url = options.fetch(:url)
@content = options.fetch(:content, nil)
@cache = options.fetch(:cache, ScraperTools.cache)
end
def follow_links_to(klass, options)
selector = options.fetch(:selector)
css(selector).each do |element|
link = URI.join(@url, element['href']).to_s
klass.new(url: link).scrape
end
end
def content
@cache.cache(@url) do
@content ||= response.body
end
end
def css(*args)
dom.css(*args)
end
private
def dom
@dom ||= Nokogiri::HTML(content)
end
def response
@response ||= Faraday.get(@url)
end
end
end
|
zetter/scraper-tools
|
test/units/test_page.rb
|
require "minitest/autorun"
require 'scraper_tools'
require 'support/fixtures'
require 'mocha/mini_test'
describe ScraperTools::Page do
include Fixtures
describe 'when intialized with a URL' do
before do
stub_get_requests
@page = ScraperTools::Page.new(url: 'http://example.com/test_page/index.html')
end
it 'returns the page content' do
expected_content = fixture('/test_page/index.html')
refute_empty expected_content
assert_equal expected_content, @page.content
end
it 'runs CSS selectors against the content' do
assert_equal 'Heading for test_page/index.html', @page.css('h1').text
end
it 'follows links to other pages' do
other_page_class = mock()
other_page_instance_1 = mock()
other_page_class.expects(:new).with(url: 'http://example.com/category_1.html').returns(other_page_instance_1)
other_page_instance_1.expects(:scrape)
other_page_instance_2 = mock()
other_page_class.expects(:new).with(url: 'http://example.com/category_2.html').returns(other_page_instance_2)
other_page_instance_2.expects(:scrape)
@page.follow_links_to(other_page_class, selector: 'a')
end
end
describe 'when intialized with content' do
before do
stub_get_requests
@page = ScraperTools::Page.new(url: 'http://example.net', content: '<a href="/blah.html">blah link</a>')
end
it 'returns the page content' do
assert_equal '<a href="/blah.html">blah link</a>', @page.content
end
it 'runs CSS selectors against the content' do
assert_equal 'blah link', @page.css('a').text
end
it 'follows links to other pages' do
other_page_class = mock()
other_page_instance_1 = mock()
other_page_class.expects(:new).with(url: 'http://example.net/blah.html').returns(other_page_instance_1)
other_page_instance_1.expects(:scrape)
@page.follow_links_to(other_page_class, selector: 'a')
end
end
end
|
zetter/scraper-tools
|
test/units/cache/test_redis.rb
|
require "minitest/autorun"
require 'scraper_tools'
describe ScraperTools::Cache::Redis do
before do
@client = stub(set: nil, get: nil)
@cache = ScraperTools::Cache::Redis.new(client: @client)
end
describe 'using the cache method' do
it "returns the result of the block and caches the value " do
@client.expects(:set).with('key', 'value_1_compressed')
Zlib::Deflate.expects(:deflate).with('value_1').returns('value_1_compressed')
result = @cache.cache('key') { 'value_1' }
assert_equal 'value_1', result
end
it "returns the cached value of the key" do
@client.stubs(:get).with('key').returns('value_1_compressed')
Zlib::Inflate.expects(:inflate).with('value_1_compressed').returns('value_1')
result = @cache.cache('key') { 'value_2' }
assert_equal 'value_1', result
end
it "does not execute the block when values are cached" do
@client.stubs(:get).with('key').returns('value_1_compressed')
Zlib::Inflate.expects(:inflate).with('value_1_compressed').returns('value_1')
@cache.cache('key') { raise 'not expected to be executed' }
end
end
end
|
zetter/scraper-tools
|
test/support/fixtures.rb
|
require 'pathname'
require 'webmock/minitest'
module Fixtures
class FixtureNotFoundError < StandardError; end
def fixture(path)
filename = File.dirname(__dir__) + '/support/fixtures' + path
if File.exists?(filename)
File.open(filename, 'rb') { |file| file.read }
else
raise FixtureNotFoundError.new("Tried to access fixture '#{path}' which does not exist at '#{filename}'.")
end
end
def stub_get_requests
stub_request(:get, /example\.com/).to_return do |request|
path_and_query = [request.uri.path, request.uri.query].compact.join('?')
{ body: fixture(path_and_query) }
end
end
end
|
zetter/scraper-tools
|
lib/scraper_tools.rb
|
module ScraperTools
class << self
attr_writer :cache
def cache
@cache || ScraperTools::Cache::Null.new
end
end
end
require 'scraper_tools/version'
require 'scraper_tools/page'
require 'scraper_tools/cache'
|
zetter/scraper-tools
|
lib/scraper_tools/cache.rb
|
module ScraperTools
module Cache
end
end
require 'scraper_tools/cache/null'
require 'scraper_tools/cache/redis'
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/refresher.rb
|
class ManageIQ::Providers::Aliyun::CloudManager::Refresher < ManageIQ::Providers::BaseManager::ManagerRefresher
def parse_legacy_inventory(ems)
ManageIQ::Providers::Aliyun::CloudManager::RefreshParser.ems_inv_to_hashes(ems, refresher_options)
end
def save_inventory(ems, target, _hashes_or_persister)
super
EmsRefresh.queue_refresh(ems.network_manager) if target.kind_of?(ManageIQ::Providers::BaseManager)
# EmsRefresh.queue_refresh(ems.ebs_storage_manager) if target.kind_of?(ManageIQ::Providers::BaseManager)
end
# List classes that will have post process method invoked
def post_process_refresh_classes
[::Vm]
end
end
|
wan374393747/manageiq-providers-aliyun
|
lib/manageiq-providers-aliyun.rb
|
<filename>lib/manageiq-providers-aliyun.rb
require "manageiq/providers/aliyun/engine"
require "manageiq/providers/aliyun/version"
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/inventory/collector.rb
|
class ManageIQ::Providers::Aliyun::Inventory::Collector < ManageIQ::Providers::Inventory::Collector
require_nested :CloudManager
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/regions.rb
|
<filename>app/models/manageiq/providers/aliyun/regions.rb
module ManageIQ
module Providers::Aliyun
module Regions
REGIONS = {
"cn-qingdao" => {
:name => "cn-qingdao",
:hostname => "ecs.aliyuncs.com",
:description => "China (Qingdao)"
},
"cn-beijing" => {
:name => "cn-beijing",
:hostname => "ecs.aliyuncs.com",
:description => "China (Beijing)"
},
"cn-zhangjiakou" => {
:name => "cn-zhangjiakou",
:hostname => "ecs.cn-zhangjiakou.aliyuncs.com",
:description => "China (Zhangjiakou)"
},
"cn-huhehaote" => {
:name => "cn-huhehaote",
:hostname => "ecs.cn-huhehaote.aliyuncs.com",
:description => "China (Hohhot)"
},
"cn-hangzhou" => {
:name => "cn-hangzhou",
:hostname => "ecs.aliyuncs.com",
:description => "China (Hangzhou)"
},
"cn-shanghai" => {
:name => "cn-shanghai",
:hostname => "ecs.aliyuncs.com",
:description => "China (Shanghai)"
},
"cn-shenzhen" => {
:name => "cn-shenzhen",
:hostname => "ecs.aliyuncs.com",
:description => "China (Shenzhen)"
}
}
def self.regions
additional_regions = Hash(Settings.ems.ems_aliyun.try!(:additional_regions)).stringify_keys
disabled_regions = Array(Settings.ems.ems_aliyun.try!(:disabled_regions))
REGIONS.merge(additional_regions).except(*disabled_regions)
end
def self.regions_by_hostname
regions.values.index_by { |v| v[:hostname] }
end
def self.all
regions.values
end
def self.names
regions.keys
end
def self.hostnames
regions_by_hostname.keys
end
def self.find_by_name(name)
regions[name]
end
def self.find_by_hostname(hostname)
regions_by_hostname[hostname]
end
end
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/inventory/persister/cloud_manager.rb
|
<filename>app/models/manageiq/providers/aliyun/inventory/persister/cloud_manager.rb<gh_stars>0
class ManageIQ::Providers::Aliyun::Inventory::Persister::CloudManager < ManageIQ::Providers::DummyProvider::Inventory::Persister
def initialize_inventory_collections
add_collection(cloud, :vms)
add_collection(cloud, :flavors)
end
def parent
manager.presence
end
def shared_options
{
:parent => parent
}
end
end
|
wan374393747/manageiq-providers-aliyun
|
lib/manageiq/providers/aliyun/engine.rb
|
module ManageIQ
module Providers
module Aliyun
class Engine < ::Rails::Engine
isolate_namespace ManageIQ::Providers::Aliyun
# NOTE: If you are going to make changes to autoload_paths, please make
# sure they are all strings. Rails will push these paths into the
# $LOAD_PATH.
#
# More info can be found in the ruby-lang bug:
#
# https://bugs.ruby-lang.org/issues/14372
#
# If you have no need to add any autoload_paths in this manageiq
# plugin, feel free to delete this section.
#
# Examples:
#
# config.autoload_paths << root.join("app", "models").to_s
# config.autoload_paths << root.join("lib", "my_provider").to_s
# config.autoload_paths << Rails.root.join("app", "models", "aliases").to_s
end
end
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/inventory/parser/cloud_manager.rb
|
<reponame>wan374393747/manageiq-providers-aliyun
class ManageIQ::Providers::Aliyun::Inventory::Parser::CloudManager < ManageIQ::Providers::DummyProvider::Inventory::Parser
def parse
flavors
vms
end
def flavors
collector.flavors.each do |flavor|
persister.flavors.build(
:name => flavor["name"],
:ems_ref => flavor["name"],
:cpus => flavor["cpus"],
:cpu_cores => 1,
:memory => flavor["memory"],
)
end
end
def vms
collector.vms.each do |vm|
flavor = persister.flavors.lazy_find(vm["instance_type"])
persister.vms.build(
:name => vm["name"],
:ems_ref => vm["uuid"],
:uid_ems => vm["uuid"],
:vendor => "unknown",
:location => "nowhere",
:flavor => flavor,
)
end
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/metrics_capture.rb
|
class ManageIQ::Providers::Aliyun::CloudManager::MetricsCapture < ManageIQ::Providers::BaseManager::MetricsCapture
VIM_STYLE_COUNTERS = {
"cpu_usage_rate_average" => {
:counter_key => "cpu_usage_rate_average",
:instance => "",
:capture_interval => "20",
:precision => 1,
:rollup => "average",
:unit_key => "percent",
:capture_interval_name => "realtime"
},
"disk_usage_rate_average" => {
:counter_key => "disk_usage_rate_average",
:instance => "",
:capture_interval => "20",
:precision => 2,
:rollup => "average",
:unit_key => "kilobytespersecond",
:capture_interval_name => "realtime"
},
"mem_usage_absolute_average" => {
:counter_key => "mem_usage_absolute_average",
:instance => "",
:capture_interval => "20",
:precision => 1,
:rollup => "average",
:unit_key => "percent",
:capture_interval_name => "realtime"
},
"net_usage_rate_average" => {
:counter_key => "net_usage_rate_average",
:instance => "",
:capture_interval => "20",
:precision => 2,
:rollup => "average",
:unit_key => "kilobytespersecond",
:capture_interval_name => "realtime"
}
}
def perf_collect_metrics(interval_name, start_time = nil, end_time = nil)
raise "No EMS defined" if target.ext_management_system.nil?
log_header = "[#{interval_name}] for: [#{target.class.name}], [#{target.id}], [#{target.name}]"
end_time ||= Time.now
end_time = end_time.utc
start_time ||= end_time - 4.hours # 4 hours for symmetry with VIM
start_time = start_time.utc
begin
target.ext_management_system.with_provider_connection do |connection|
[{target.ems_ref => VIM_STYLE_COUNTERS},
{target.ems_ref => fake_metrics(start_time, end_time)}]
end
rescue Exception => err
_log.error("#{log_header} Unhandled exception during perf data collection: [#{err}], class: [#{err.class}]")
_log.error("#{log_header} Timings at time of error: #{Benchmark.current_realtime.inspect}")
_log.log_backtrace(err)
raise
end
end
private
def fake_metrics(start_time, end_time)
timestamp = start_time
metrics = {}
while (timestamp < end_time)
metrics[timestamp] = {
'cpu_usage_rate_average' => rand(100).to_f,
'disk_usage_rate_average' => rand(100).to_f,
'mem_usage_rate_average' => rand(100).to_f,
'net_usage_rate_average' => rand(100).to_f,
}
timestamp += 20.seconds
end
metrics
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/availability_zone.rb
|
<gh_stars>0
class ManageIQ::Providers::Aliyun::CloudManager::AvailabilityZone < ::AvailabilityZone
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/builder.rb
|
class ManageIQ::Providers::Aliyun::Builder
class << self
def build_inventory(ems, target)
case target
when InventoryRefresh::TargetCollection
targeted_inventory(ems, target)
else
cloud_manager_inventory(ems, target)
end
end
private
def cloud_manager_inventory(ems, target)
collector_klass = ManageIQ::Providers::Aliyun::Inventory::Collector::CloudManager
persister_klass = ManageIQ::Providers::Aliyun::Inventory::Persister::CloudManager
parser_klass = ManageIQ::Providers::Aliyun::Inventory::Parser::CloudManager
inventory(ems, target, collector_klass, persister_klass, [parser_klass])
end
def targeted_inventory(ems, target)
collector_klass = ManageIQ::Providers::Aliyun::Inventory::Collector::TargetCollection
persister_klass = ManageIQ::Providers::Aliyun::Inventory::Persister::TargetCollection
parser_klass = ManageIQ::Providers::Aliyun::Inventory::Parser::CloudManager
inventory(ems, target, collector_klass, persister_klass, [parser_klass])
end
def inventory(manager, raw_target, collector_class, persister_class, parser_classes)
collector = collector_class.new(manager, raw_target)
persister = persister_class.new(manager, raw_target)
::ManageIQ::Providers::Aliyun::Inventory.new(persister, collector, parser_classes.map(&:new))
end
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager.rb
|
<reponame>wan374393747/manageiq-providers-aliyun
class ManageIQ::Providers::Aliyun::CloudManager < ManageIQ::Providers::CloudManager
require_nested :AvailabilityZone
require_nested :Flavor
require_nested :MetricsCapture
require_nested :MetricsCollectorWorker
require_nested :RefreshParser
require_nested :RefreshWorker
require_nested :Refresher
require_nested :Vm
supports :regions
include ManageIQ::Providers::Aliyun::ManagerMixin
def self.hostname_required?
# TODO: ExtManagementSystem is validating this
false
end
def self.ems_type
@ems_type ||= "aliyun".freeze
end
def self.description
@description ||= "Aliyun".freeze
end
def supported_auth_types
%w(default smartstate_docker)
end
def supports_authentication?(authtype)
supported_auth_types.include?(authtype.to_s)
end
def supported_catalog_types
%w(aliyun).freeze
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/refresh_worker.rb
|
<filename>app/models/manageiq/providers/aliyun/cloud_manager/refresh_worker.rb
class ManageIQ::Providers::Aliyun::CloudManager::RefreshWorker < MiqEmsRefreshWorker
require_nested :Runner
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/flavor.rb
|
<filename>app/models/manageiq/providers/aliyun/cloud_manager/flavor.rb
class ManageIQ::Providers::Aliyun::CloudManager::Flavor < ManageIQ::Providers::CloudManager::Flavor
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/vm.rb
|
<filename>app/models/manageiq/providers/aliyun/cloud_manager/vm.rb
class ManageIQ::Providers::Aliyun::CloudManager::Vm < ManageIQ::Providers::CloudManager::Vm
def provider_object(connection = nil)
connection ||= ext_management_system.connect
# find vm instance via connection and return it
# connection.find_instance(ems_ref)
# but we return just an object for now
OpenStruct.new
end
def raw_start
with_provider_object(&:start)
# Temporarily update state for quick UI response until refresh comes along
update_attributes!(:raw_power_state => "on")
end
def info
raw_info
end
def raw_info
env_vars = {
"PROVIDER_USERID" => "root",
"PROVIDER_PASSWORD" => "password",
}
extra_vars = {
:id => id,
:vmname => name,
}
playbook_path = ext_management_system.ansible_root.join("vm_info.yml")
result = Ansible::Runner.run(env_vars, extra_vars, playbook_path)
if result.return_code != 0
_log.error("Failed to get VM info: #{result.parsed_stdout.join("\n")}")
else
_log.info(result.parsed_stdout.join("\n"))
end
end
def long_running_playbook
env_vars = {
"PROVIDER_USERID" => "root",
"PROVIDER_PASSWORD" => "password",
}
extra_vars = {
:id => id,
:vmname => name,
}
playbook_path = ext_management_system.ansible_root.join("long_running_playbook.yml")
job = ManageIQ::Providers::AnsibleRunnerWorkflow.create_job(env_vars, extra_vars, playbook_path)
job.signal(:start)
job.miq_task
end
def raw_stop
with_provider_object(&:stop)
# Temporarily update state for quick UI response until refresh comes along
update_attributes!(:raw_power_state => "off")
end
def raw_pause
with_provider_object(&:pause)
# Temporarily update state for quick UI response until refresh comes along
update_attributes!(:raw_power_state => "paused")
end
def raw_suspend
with_provider_object(&:suspend)
# Temporarily update state for quick UI response until refresh comes along
update_attributes!(:raw_power_state => "suspended")
end
# TODO: this method could be the default in a baseclass
def self.calculate_power_state(raw_power_state)
# do some mapping on powerstates
# POWER_STATES[raw_power_state.to_s] || "terminated"
raw_power_state
end
end
|
wan374393747/manageiq-providers-aliyun
|
config/initializers/gettext.rb
|
<filename>config/initializers/gettext.rb
Vmdb::Gettext::Domains.add_domain(
'ManageIQ_Providers_Aliyun',
ManageIQ::Providers::Aliyun::Engine.root.join('locale').to_s,
:po
)
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/manager_mixin.rb
|
<gh_stars>0
module ManageIQ::Providers::Aliyun::ManagerMixin
extend ActiveSupport::Concern
included do
validates :provider_region, :inclusion => {:in => ->(_region) { ManageIQ::Providers::Aliyun::Regions.names }}
end
def description
ManageIQ::Providers::Aliyun::Regions.find_by_name(provider_region)[:description]
end
#
# Connections
#
def connect(options = {})
raise "no credentials defined" if missing_credentials?(options[:auth_type])
username = options[:user] || authentication_userid(options[:auth_type])
password = options[:pass] || authentication_password(options[:auth_type])
service = options[:service] || :Compute
proxy = options[:proxy_uri] || http_proxy_uri
region = options[:region] || provider_region
self.class.raw_connect(username, password, service, region, proxy)
end
def verify_credentials(auth_type = nil, options = {})
raise MiqException::MiqHostError, "No credentials defined" if missing_credentials?(auth_type)
return true if auth_type == "smartstate_docker"
self.class.connection_rescue_block do
with_provider_connection(options.merge(:auth_type => auth_type)) do |aliyun|
self.class.validate_connection(aliyun)
end
end
true
end
module ClassMethods
#
# Connections
#
def raw_connect(access_key_id, secret_access_key,service,region, proxy_uri = nil, validate = false)
require 'fog/aliyun'
connection = ::Fog::const_get(service).new(
:provider => "aliyun",
:aliyun_url => "https://ecs.aliyuncs.com/",
:aliyun_accesskey_id => access_key_id,
:aliyun_accesskey_secret => MiqPassword.try_decrypt(secret_access_key),
:aliyun_region_id => region
)
connection
end
def validate_connection(connection)
connection_rescue_block do
connection.regions.all.map(&:id)
end
end
def connection_rescue_block
yield
rescue => err
miq_exception = translate_exception(err)
raise unless miq_exception
_log.error("Error Class=#{err.class.name}, Message=#{err.message}")
raise miq_exception
end
def translate_exception(err)
MiqException::MiqHostError.new "#{err.message}"
end
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/inventory/persister/target_collection.rb
|
class ManageIQ::Providers::Aliyun::Inventory::Persister::TargetCollection < ManageIQ::Providers::DummyProvider::Inventory::Persister
def initialize_inventory_collections
add_collection(cloud, :flavors)
add_collection(cloud, :vms)
end
def targeted?
true
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/cloud_manager/metrics_collector_worker.rb
|
<reponame>wan374393747/manageiq-providers-aliyun<gh_stars>0
class ManageIQ::Providers::Aliyun::CloudManager::MetricsCollectorWorker < ManageIQ::Providers::BaseManager::MetricsCollectorWorker
require_nested :Runner
self.default_queue_name = "Aliyun"
def friendly_name
@friendly_name ||= "C&U Metrics Collector for Aliyun"
end
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/inventory/persister.rb
|
class ManageIQ::Providers::Aliyun::Inventory::Persister < ManageIQ::Providers::Inventory::Persister
require_nested :CloudManager
end
|
wan374393747/manageiq-providers-aliyun
|
app/models/manageiq/providers/aliyun/inventory/parser.rb
|
<reponame>wan374393747/manageiq-providers-aliyun<gh_stars>0
class ManageIQ::Providers::Aliyun::Inventory::Parser < ManageIQ::Providers::Inventory::Parser
require_nested :CloudManager
include Vmdb::Logging
end
|
wan374393747/manageiq-providers-aliyun
|
lib/manageiq/providers/aliyun.rb
|
<filename>lib/manageiq/providers/aliyun.rb<gh_stars>0
require "manageiq/providers/aliyun/engine"
|
davidlhayes/movie_server
|
app.rb
|
require 'bundler'
Bundler.require()
def fake_movie(name, release_year, description)
{:name => name.to_s, :release_year => release_year.to_s,
:description => description.to_s}.to_json
end
get '/' do
cross_origin
fake_movie('Sample Movie',2000,'This is just a sample')
end
get '/api/faker' do
cross_origin
if rand > 0.4
title = Faker::Name.first_name
else
title = Faker::Lorem.word.capitalize
end
if rand > 0.5
title += " " + Faker::Lorem.word.capitalize
end
if rand > 0.5
if rand > 0.5
title += " the"
end
title += " " + Faker::Lorem.word.capitalize
end
release_year =Faker::Number.between(1955,2012)
description = Faker::Lorem.paragraph(2)
fake_movie(title,release_year,description)
end
get '/api/aliens' do
cross_origin
fake_movie('Aliens',1986,'The planet from Alien (1979) has been colonized,' \
' but contact is lost. This time, the rescue team has impressive' \
' firepower, but will it be enough?')
end
get '/api/terminator' do
cross_origin
fake_movie('The Terminator',1984,'A human-looking indestructible cyborg is' \
' sent from 2029 to 1984 to assassinate a waitress, whose unborn son will' \
' lead humanity in a war against the machines, while a soldier from that' \
' war is sent to protect her at all costs.')
end
get '/api/oklahoma' do
cross_origin
fake_movie('Oklahoma!',1955,'In the Oklahoma territory at the turn of the' \
' twentieth century, two young cowboys vie with an evil ranch hand and' \
' a traveling peddler for the hearts of the women they love.')
end
|
shykes/ember.js
|
neuter.rb
|
require 'rake-pipeline'
module Neuter
DEBUG = false
class SpadeWrapper < Rake::Pipeline::FileWrapper
REQUIRE_RE = %r{^\s*require\(['"]([^'"]*)['"]\);?\s*}
# Keep track of required files
@@required = []
# Yes, it's called package because module is a reserved word
def package
@package ||= path.split('/lib/')[0].split('/').last.split('.js').last
end
def read
source = super
# bail if this class is used for an intermediate file (it is!)
return source if !path.include?("/lib/")
# Replace all requires with emptiness, and accumulate dependency sources
prepend = ''
source.gsub! REQUIRE_RE do |m|
req = $1
# Find a reason to fail
reason = @@required.include?(req) ? 'Already required' : false
reason ||= is_package_req(req) ? 'Required package' : false
reason ||= is_external_req(package, req) ? "External package for #{package}" : false
if reason
p "Skipped #{req} required in #{path} (#{reason})" if DEBUG
else
@@required << req
req_file = File.join(package, "lib", "#{req.gsub(package, '')}.js")
prepend = prepend + self.class.new(root, req_file, encoding).read
p "Required #{req_file} as #{req} in #{path} in package #{package}" if DEBUG
end
''
end
source = "(function(exports) {\n#{source}\n})({});\n\n"
"#{prepend}#{source}"
end
protected
def is_package_req(req)
!(req.include? '/')
end
def is_external_req(package, req)
!(req.split('/')[0] == package)
end
end
module Filters
class NeuterFilter < Rake::Pipeline::ConcatFilter
# Allows selective concat by passing packages array (or all if nil)
def initialize(packages=nil, string=nil, &block)
@packages = packages
@file_wrapper_class = SpadeWrapper
super(string, &block)
end
def generate_output(inputs, output)
inputs.each do |input|
if !(@packages.nil? || @packages.include?(input.path.split('/').first))
p "Not neutering: #{input.path}" if DEBUG
next
end
spade = SpadeWrapper.new(input.root, input.path, input.encoding)
p "Neutering #{input.path} into #{output.path}" if DEBUG
output.write spade.read
end
end
end
class SelectFilter < Rake::Pipeline::ConcatFilter
# Allows selective concat by passing packages array (or all if nil)
def initialize(packages=nil, string=nil, &block)
@packages = packages || []
super(string, &block)
end
def generate_output(inputs, output)
inputs.each do |input|
next unless @packages.include?(input.path)
output.write input.read
end
end
end
end
module Helpers
def neuter(*args, &block)
filter(Neuter::Filters::NeuterFilter, *args, &block)
end
def select(*args, &block)
filter(Neuter::Filters::SelectFilter, *args, &block)
end
end
end
Rake::Pipeline::DSL::PipelineDSL.send(:include, Neuter::Helpers)
|
frodrigo/gpx
|
lib/gpx/point.rb
|
<reponame>frodrigo/gpx
# frozen_string_literal: true
module GPX
# The base class for all points. Trackpoint and Waypoint both descend from this base class.
class Point < Base
D_TO_R = Math::PI / 180.0
attr_accessor :time, :elevation, :gpx_file, :speed, :extensions
attr_reader :lat, :lon
# When you need to manipulate individual points, you can create a Point
# object with a latitude, a longitude, an elevation, and a time. In
# addition, you can pass an XML element to this initializer, and the
# relevant info will be parsed out.
def initialize(opts = { lat: 0.0, lon: 0.0, elevation: 0.0, time: Time.now })
super()
@gpx_file = opts[:gpx_file]
if opts[:element]
elem = opts[:element]
@lat = elem['lat'].to_f
@lon = elem['lon'].to_f
@latr = (D_TO_R * @lat)
@lonr = (D_TO_R * @lon)
# '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?
@time = (
begin
Time.xmlschema(elem.at('time').inner_text)
rescue StandardError
nil
end)
@elevation = elem.at('ele').inner_text.to_f unless elem.at('ele').nil?
@speed = elem.at('speed').inner_text.to_f unless elem.at('speed').nil?
@extensions = elem.at('extensions') unless elem.at('extensions').nil?
else
@lat = opts[:lat]
@lon = opts[:lon]
@elevation = opts[:elevation]
@time = opts[:time]
@speed = opts[:speed]
@extensions = opts[:extensions]
end
end
# Returns the latitude and longitude (in that order), separated by the
# given delimeter. This is useful for passing a point into another API
# (i.e. the Google Maps javascript API).
def lat_lon(delim = ', ')
"#{lat}#{delim}#{lon}"
end
# Returns the longitude and latitude (in that order), separated by the
# given delimeter. This is useful for passing a point into another API
# (i.e. the Google Maps javascript API).
def lon_lat(delim = ', ')
"#{lon}#{delim}#{lat}"
end
# Latitude in radians.
def latr
@latr ||= (@lat * D_TO_R)
end
# Longitude in radians.
def lonr
@lonr ||= (@lon * D_TO_R)
end
# Set the latitude (in degrees).
def lat=(latitude)
@latr = (latitude * D_TO_R)
@lat = latitude
end
# Set the longitude (in degrees).
def lon=(longitude)
@lonr = (longitude * D_TO_R)
@lon = longitude
end
end
end
|
frodrigo/gpx
|
lib/gpx/gpx_file.rb
|
<filename>lib/gpx/gpx_file.rb
# frozen_string_literal: true
module GPX
class GPXFile < Base
attr_accessor :tracks,
:routes, :waypoints, :bounds, :lowest_point, :highest_point, :duration, :ns, :time, :name, :version, :creator, :description, :moving_duration
DEFAULT_CREATOR = "GPX RubyGem #{GPX::VERSION} -- http://dougfales.github.io/gpx/"
# This initializer can be used to create a new GPXFile from an existing
# file or to create a new GPXFile instance with no data (so that you can
# add tracks and points and write it out to a new file later).
# To read an existing GPX file, do this:
# gpx_file = GPXFile.new(:gpx_file => 'mygpxfile.gpx')
# puts "Speed: #{gpx_file.average_speed}"
# puts "Duration: #{gpx_file.duration}"
# puts "Bounds: #{gpx_file.bounds}"
#
# To read a GPX file from a string, use :gpx_data.
# gpx_file = GPXFile.new(:gpx_data => '<xml ...><gpx>...</gpx>)
# To create a new blank GPXFile instance:
# gpx_file = GPXFile.new
# Note that you can pass in any instance variables to this form of the initializer, including Tracks or Segments:
# some_track = get_track_from_csv('some_other_format.csv')
# gpx_file = GPXFile.new(:tracks => [some_track])
#
def initialize(opts = {})
super()
@duration = 0
@attributes = {}
@namespace_defs = []
@tracks = []
@time = nil
if opts[:gpx_file] || opts[:gpx_data]
if opts[:gpx_file]
gpx_file = opts[:gpx_file]
gpx_file = File.open(gpx_file) unless gpx_file.is_a?(File)
@xml = Nokogiri::XML(gpx_file)
else
@xml = Nokogiri::XML(opts[:gpx_data])
end
gpx_element = @xml.at('gpx')
@attributes = gpx_element.attributes
@namespace_defs = gpx_element.namespace_definitions
@version = gpx_element['version']
reset_meta_data
bounds_element = (
begin
@xml.at('metadata/bounds')
rescue StandardError
nil
end)
if bounds_element
@bounds.min_lat = get_bounds_attr_value(bounds_element, %w[min_lat minlat minLat])
@bounds.min_lon = get_bounds_attr_value(bounds_element, %w[min_lon minlon minLon])
@bounds.max_lat = get_bounds_attr_value(bounds_element, %w[max_lat maxlat maxLat])
@bounds.max_lon = get_bounds_attr_value(bounds_element, %w[max_lon maxlon maxLon])
else
get_bounds = true
end
@time = begin
Time.parse(@xml.at('metadata/time').inner_text)
rescue StandardError
nil
end
@name = begin
@xml.at('metadata/name').inner_text
rescue StandardError
nil
end
@description = begin
@xml.at('metadata/desc').inner_text
rescue StandardError
nil
end
@xml.search('trk').each do |trk|
trk = Track.new(element: trk, gpx_file: self)
update_meta_data(trk, get_bounds)
@tracks << trk
end
@waypoints = []
@xml.search('wpt').each { |wpt| @waypoints << Waypoint.new(element: wpt, gpx_file: self) }
@routes = []
@xml.search('rte').each { |rte| @routes << Route.new(element: rte, gpx_file: self) }
@tracks.delete_if(&:empty?)
calculate_duration
else
reset_meta_data
opts.each { |attr_name, value| instance_variable_set("@#{attr_name}", value) }
unless @tracks.nil? || @tracks.size.zero?
@tracks.each { |trk| update_meta_data(trk) }
calculate_duration
end
end
@tracks ||= []
@routes ||= []
@waypoints ||= []
end
def get_bounds_attr_value(el, possible_names)
result = nil
possible_names.each do |name|
result = el[name]
break unless result.nil?
end
(
begin
result.to_f
rescue StandardError
nil
end)
end
# Returns the distance, in kilometers, meters, or miles, of all of the
# tracks and segments contained in this GPXFile.
def distance(opts = { units: 'kilometers' })
case opts[:units]
when /kilometers/i
@distance
when /meters/i
(@distance * 1000)
when /miles/i
(@distance * 0.62)
end
end
# Returns the average speed, in km/hr, meters/hr, or miles/hr, of this
# GPXFile. The calculation is based on the total distance divided by the
# sum of duration of all segments of all tracks
# (not taking into accounting pause time).
def average_speed(opts = { units: 'kilometers' })
case opts[:units]
when /kilometers/i
distance / (moving_duration / 3600.0)
when /meters/i
(distance * 1000) / (moving_duration / 3600.0)
when /miles/i
(distance * 0.62) / (moving_duration / 3600.0)
end
end
# Crops any points falling within a rectangular area. Identical to the
# delete_area method in every respect except that the points outside of
# the given area are deleted. Note that this method automatically causes
# the meta data to be updated after deletion.
def crop(area)
reset_meta_data
keep_tracks = []
tracks.each do |trk|
trk.crop(area)
unless trk.empty?
update_meta_data(trk)
keep_tracks << trk
end
end
@tracks = keep_tracks
routes.each { |rte| rte.crop(area) }
waypoints.each { |wpt| wpt.crop(area) }
end
# Deletes any points falling within a rectangular area. The "area"
# parameter is usually an instance of the Bounds class. Note that this
# method cascades into similarly named methods of subordinate classes
# (i.e. Track, Segment), which means, if you want the deletion to apply
# to all the data, you only call this one (and not the one in Track or
# Segment classes). Note that this method automatically causes the meta
# data to be updated after deletion.
def delete_area(area)
reset_meta_data
keep_tracks = []
tracks.each do |trk|
trk.delete_area(area)
unless trk.empty?
update_meta_data(trk)
keep_tracks << trk
end
end
@tracks = keep_tracks
routes.each { |rte| rte.delete_area(area) }
waypoints.each { |wpt| wpt.delete_area(area) }
end
# Resets the meta data for this GPX file. Meta data includes the bounds,
# the high and low points, and the distance.
def reset_meta_data
@bounds = Bounds.new
@highest_point = nil
@lowest_point = nil
@distance = 0.0
@moving_duration = 0.0
end
# rubocop:disable Style/OptionalBooleanParameter
# Updates the meta data for this GPX file. Meta data includes the
# bounds, the high and low points, and the distance. This is useful when
# you modify the GPX data (i.e. by adding or deleting points) and you
# want the meta data to accurately reflect the new data.
def update_meta_data(trk, get_bounds = true)
@lowest_point = trk.lowest_point if @lowest_point.nil? || (!trk.lowest_point.nil? && (trk.lowest_point.elevation < @lowest_point.elevation))
@highest_point = trk.highest_point if @highest_point.nil? || (!trk.highest_point.nil? && (trk.highest_point.elevation > @highest_point.elevation))
@bounds.add(trk.bounds) if get_bounds
@distance += trk.distance
@moving_duration += trk.moving_duration
end
# Serialize the current GPXFile to a gpx file named <filename>.
# If the file does not exist, it is created. If it does exist, it is overwritten.
def write(filename, update_time = true)
@time = Time.now if @time.nil? || update_time
@name ||= File.basename(filename)
doc = generate_xml_doc
File.open(filename, 'w+') { |f| f.write(doc.to_xml) }
end
def to_s(update_time = true)
@time = Time.now if @time.nil? || update_time
doc = generate_xml_doc
doc.to_xml
end
# rubocop:enable Style/OptionalBooleanParameter
def inspect
"<#{self.class.name}:...>"
end
def recalculate_distance
@distance = 0
@tracks.each do |track|
track.recalculate_distance
@distance += track.distance
end
end
private
def attributes_and_nsdefs_as_gpx_attributes
# $stderr.puts @namespace_defs.inspect
gpx_header = {}
@attributes.each do |k, v|
k = "#{v.namespace.prefix}:#{k}" if v.namespace
gpx_header[k] = v.value
end
@namespace_defs.each do |nsd|
tag = 'xmlns'
tag += ":#{nsd.prefix}" if nsd.prefix
gpx_header[tag] = nsd.href
end
gpx_header
end
def generate_xml_doc
@version ||= '1.1'
version_dir = version.tr('.', '/')
gpx_header = attributes_and_nsdefs_as_gpx_attributes
gpx_header['version'] = @version.to_s unless gpx_header['version']
gpx_header['creator'] = DEFAULT_CREATOR unless gpx_header['creator']
gpx_header['xsi:schemaLocation'] = "http://www.topografix.com/GPX/#{version_dir} http://www.topografix.com/GPX/#{version_dir}/gpx.xsd" unless gpx_header['xsi:schemaLocation']
gpx_header['xmlns:xsi'] = 'http://www.w3.org/2001/XMLSchema-instance' if !gpx_header['xsi'] && !gpx_header['xmlns:xsi']
# $stderr.puts gpx_header.keys.inspect
# rubocop:disable Metrics/BlockLength
Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
xml.gpx(gpx_header) do
# version 1.0 of the schema doesn't support the metadata element, so push them straight to the root 'gpx' element
if @version == '1.0'
xml.name @name
xml.time @time.xmlschema
xml.bound(
minlat: bounds.min_lat,
minlon: bounds.min_lon,
maxlat: bounds.max_lat,
maxlon: bounds.max_lon
)
else
xml.metadata do
xml.name @name
xml.time @time.xmlschema
xml.bound(
minlat: bounds.min_lat,
minlon: bounds.min_lon,
maxlat: bounds.max_lat,
maxlon: bounds.max_lon
)
end
end
tracks&.each do |t|
xml.trk do
xml.name t.name
t.segments.each do |seg|
xml.trkseg do
seg.points.each do |p|
xml.trkpt(lat: p.lat, lon: p.lon) do
xml.time p.time.xmlschema unless p.time.nil?
xml.ele p.elevation unless p.elevation.nil?
xml << p.extensions.to_xml unless p.extensions.nil?
end
end
end
end
end
end
waypoints&.each do |w|
xml.wpt(lat: w.lat, lon: w.lon) do
xml.time w.time.xmlschema unless w.time.nil?
Waypoint::SUB_ELEMENTS.each do |sub_elem|
xml.send(sub_elem, w.send(sub_elem)) if w.respond_to?(sub_elem) && !w.send(sub_elem).nil?
end
end
end
routes&.each do |r|
xml.rte do
xml.name r.name
r.points.each do |p|
xml.rtept(lat: p.lat, lon: p.lon) do
xml.time p.time.xmlschema unless p.time.nil?
xml.ele p.elevation unless p.elevation.nil?
end
end
end
end
end
end
# rubocop:enable Metrics/BlockLength
end
# Calculates and sets the duration attribute by subtracting the time on
# the very first point from the time on the very last point.
def calculate_duration
@duration = 0
if @tracks.nil? || @tracks.size.zero? || @tracks[0].segments.nil? || @tracks[0].segments.size.zero?
return @duration
end
@duration = (@tracks[-1].segments[-1].points[-1].time - @tracks.first.segments.first.points.first.time)
rescue StandardError
@duration = 0
end
end
end
|
ar31an/back_to_anchor
|
lib/back_to_anchor/routing_url_for.rb
|
<gh_stars>0
ActionView::RoutingUrlFor.module_eval do
def url_for(options = nil)
case options
when String
options
when nil
super(only_path: _generate_paths_by_default)
when Hash
options = options.symbolize_keys
unless options.key?(:only_path)
options[:only_path] = only_path?(options[:host])
end
super(options)
when ActionController::Parameters
unless options.key?(:only_path)
options[:only_path] = only_path?(options[:host])
end
super(options)
when :back
_back_url
when :back_to_anchor
_back_to_anchor_url
when Array
components = options.dup
if _generate_paths_by_default
polymorphic_path(components, components.extract_options!)
else
polymorphic_url(components, components.extract_options!)
end
else
method = _generate_paths_by_default ? :path : :url
builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method)
case options
when Symbol
builder.handle_string_call(self, options)
when Class
builder.handle_class_call(self, options)
else
builder.handle_model_call(self, options)
end
end
end
end
|
ar31an/back_to_anchor
|
lib/back_to_anchor/url_helper.rb
|
<gh_stars>0
ActionView::Helpers::UrlHelper.module_eval do
def url_for(options = nil)
case options
when String
options
when :back
_back_url
when :back_to_anchor
_back_to_anchor_url
else
raise ArgumentError, "arguments passed to url_for can't be handled. Please require " \
"routes or provide your own implementation"
end
end
def _back_to_anchor_url
referrer = _filtered_referrer
if referrer
anchor_param = controller.request.query_parameters.dig(:to_anchor)
anchor_param ? "#{referrer}##{anchor_param}" : referrer
else
"javascript:history.back()"
end
end
protected :_back_to_anchor_url
end
|
ar31an/back_to_anchor
|
lib/back_to_anchor.rb
|
require "back_to_anchor/routing_url_for"
require "back_to_anchor/url_helper"
|
ar31an/back_to_anchor
|
back_to_anchor.gemspec
|
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "back_to_anchor/version"
Gem::Specification.new do |spec|
spec.name = "back_to_anchor"
spec.version = BackToAnchor::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.summary = %q{Back to Anchor!}
spec.description = %q{An alternative to link_to :back which also allows to go to previous page with anchor}
spec.homepage = "http://rubygems.org/gems/back_to_anchor"
spec.license = "MIT"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 2.0", ">= 2.0.1"
spec.add_development_dependency "rake", "~> 12.3", ">= 12.3.2"
spec.add_development_dependency "rspec", "~> 3.8"
spec.add_development_dependency "actionview", "~> 5.2", ">= 5.2.2.1"
spec.add_development_dependency "actionpack", "~> 5.2", ">= 5.2.2.1"
end
|
instacart/has_scope
|
lib/has_scope.rb
|
<filename>lib/has_scope.rb
module HasScope
TRUE_VALUES = ["true", true, "1", 1]
ALLOWED_TYPES = {
:array => [[ Array ]],
:hash => [[Hash, ActionController::Parameters]],
:boolean => [[ Object ], -> v { TRUE_VALUES.include?(v) }],
:default => [[ String, Numeric ]],
}
def self.included(base)
base.class_eval do
extend ClassMethods
class_attribute :scopes_configuration, :instance_writer => false
class_attribute :scopes_model_class, :instance_writer => false
self.scopes_configuration = {}
end
end
module ClassMethods
# Detects params from url and apply as scopes to your classes.
#
# == Options
#
# * <tt>:type</tt> - Checks the type of the parameter sent. If set to :boolean
# it just calls the named scope, without any argument. By default,
# it does not allow hashes or arrays to be given, except if type
# :hash or :array are set.
#
# * <tt>:only</tt> - In which actions the scope is applied. By default is :all.
#
# * <tt>:except</tt> - In which actions the scope is not applied. By default is :none.
#
# * <tt>:as</tt> - The key in the params hash expected to find the scope.
# Defaults to the scope name.
#
# * <tt>:using</tt> - If type is a hash, you can provide :using to convert the hash to
# a named scope call with several arguments.
#
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the scope should apply
#
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
# if the scope should NOT apply.
#
# * <tt>:default</tt> - Default value for the scope. Whenever supplied the scope
# is always called.
#
# * <tt>:allow_blank</tt> - Blank values are not sent to scopes by default. Set to true to overwrite.
#
# == Block usage
#
# has_scope also accepts a block. The controller, current scope and value are yielded
# to the block so the user can apply the scope on its own. This is useful in case we
# need to manipulate the given value:
#
# has_scope :category do |controller, scope, value|
# value != "all" ? scope.by_category(value) : scope
# end
#
# has_scope :not_voted_by_me, :type => :boolean do |controller, scope|
# scope.not_voted_by(controller.current_user.id)
# end
#
def has_scope(*scopes, &block)
options = scopes.extract_options!
options.symbolize_keys!
options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank, :in)
if options.key?(:in)
options[:as] = options[:in]
options[:using] = scopes
end
if options.key?(:using)
if options.key?(:type) && options[:type] != :hash
raise "You cannot use :using with another :type different than :hash"
else
options[:type] = :hash
end
options[:using] = Array(options[:using])
end
options[:only] = Array(options[:only])
options[:except] = Array(options[:except])
self.scopes_configuration = scopes_configuration.dup
scopes.each do |scope|
# When `with_scope_model` is used the scopes should only apply to a single model. Otherwise,
# the scope will apply to all models. To isolate scopes by model the scope_key combines the
# the name of the scope and the model it applies to, or nil if it applies to all models.
scope_key = {scope: scope, model: self.scopes_model_class}
scopes_configuration[scope_key] ||= { :as => scope, :type => :default, :block => block }
scopes_configuration[scope_key] = self.scopes_configuration[scope_key].merge(options)
end
end
def with_scope_model(model_class, &block)
self.scopes_model_class = model_class
class_eval &block
self.scopes_model_class = nil
end
end
protected
# Receives an object where scopes will be applied to.
#
# class GraduationsController < InheritedResources::Base
# has_scope :featured, :type => true, :only => :index
# has_scope :by_degree, :only => :index
#
# def index
# @graduations = apply_scopes(Graduation).all
# end
# end
#
def apply_scopes(target, hash=params)
return target unless scopes_configuration
scopes_configuration.each do |scope_key, options|
scope = scope_key[:scope]
model = scope_key[:model]
next unless !model || target <= model
next unless apply_scope_to_action?(options)
key = options[:as]
if hash.key?(key)
value, call_scope = hash[key], true
elsif options.key?(:default)
value, call_scope = options[:default], true
if value.is_a?(Proc)
value = value.arity == 0 ? value.call : value.call(self)
end
end
value = parse_value(options[:type], key, value)
value = normalize_blanks(value)
if call_scope && (value.present? || options[:allow_blank])
current_scopes[key] = value
target = call_scope_by_type(options[:type], scope, target, value, options)
end
end
target
end
# Set the real value for the current scope if type check.
def parse_value(type, key, value) #:nodoc:
klasses, parser = ALLOWED_TYPES[type]
if klasses.any? { |klass| value.is_a?(klass) }
parser ? parser.call(value) : value
end
end
# Screens pseudo-blank params.
def normalize_blanks(value) #:nodoc:
case value
when Array
value.select { |v| v.present? }
when Hash
value.select { |k, v| normalize_blanks(v).present? }.with_indifferent_access
when ActionController::Parameters
normalize_blanks(value.to_unsafe_h)
else
value
end
end
# Call the scope taking into account its type.
def call_scope_by_type(type, scope, target, value, options) #:nodoc:
block = options[:block]
if !block && !target.respond_to?(scope)
return target
end
if type == :boolean && !options[:allow_blank]
block ? block.call(self, target) : target.send(scope)
elsif value && options.key?(:using)
value = value.values_at(*options[:using])
block ? block.call(self, target, value) : target.send(scope, *value)
else
block ? block.call(self, target, value) : target.send(scope, value)
end
end
# Given an options with :only and :except arrays, check if the scope
# can be performed in the current action.
def apply_scope_to_action?(options) #:nodoc:
return false unless applicable?(options[:if], true) && applicable?(options[:unless], false)
if options[:only].empty?
options[:except].empty? || !options[:except].include?(action_name.to_sym)
else
options[:only].include?(action_name.to_sym)
end
end
# Evaluates the scope options :if or :unless. Returns true if the proc
# method, or string evals to the expected value.
def applicable?(string_proc_or_symbol, expected) #:nodoc:
case string_proc_or_symbol
when String
eval(string_proc_or_symbol) == expected
when Proc
string_proc_or_symbol.call(self) == expected
when Symbol
send(string_proc_or_symbol) == expected
else
true
end
end
# Returns the scopes used in this action.
def current_scopes
@current_scopes ||= {}
end
end
ActiveSupport.on_load :action_controller do
include HasScope
helper_method :current_scopes if respond_to?(:helper_method)
end
|
zcash-hackworks/zealous-logger
|
zealous-logger.podspec
|
#
# Be sure to run `pod lib lint zealous-logger.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'zealous-logger'
s.version = '1.0.0'
s.summary = 'Zealous Logger is a small, simple, discrete but yet enthusiastic logger'
s.description = <<-DESC
Zealous Logger is a small, simple, discrete but yet enthusiastic logger. Designed for those who need logs, but not snitches. We acknowledge that Application Logs are needed for troubleshooting and development purposes. That doesn't mean that you should choose between logging and your users' privacy. We believe that Privacy is a Human Right, so logs shouldn't leave your device unless you explicitly want to. We write this small library with that in mind.
DESC
s.homepage = 'https://github.com/zcash-hackworks/zealous-logger'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/zcash-hackworks/zealous-logger', :tag => s.version.to_s }
s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.12'
s.source_files = 'Sources/zealous-logger/**/*.{swift}'
s.swift_version = '5.1'
s.dependency 'CocoaLumberjack/Swift', '~> 3.7.0'
s.frameworks = 'OSLog'
s.test_spec 'Tests' do | test_spec |
test_spec.source_files = 'Tests/zealous-loggerTests/**/*.{swift}'
test_spec.dependency 'CocoaLumberjack/Swift', '~> 3.7.0'
end
end
|
NeatNerdPrime/beaker-puppet
|
lib/beaker-puppet/version.rb
|
<filename>lib/beaker-puppet/version.rb
module BeakerPuppet
VERSION = '1.22.2'
end
|
example42/puppet-ntp
|
spec/classes/ntp_spec.rb
|
require 'spec_helper'
describe 'ntp' do
let(:title) { 'ntp' }
let(:node) { 'rspec.example42.com' }
let :facts do
{
:ipaddress => '10.42.42.42',
:id => 'root',
:osfamily => 'Debian',
:kernel => 'Linux',
:operatingsystem => 'Debian',
:operatingsystemrelease => '7.8',
:operatingsystemmajrelease => '7',
:virtual => 'physical',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
:concat_basedir => '/dne',
# Strict variables
# :puppi_archivedir => nil,
# :puppi_workdir => nil,
# :ntp_server => nil,
}
end
describe 'Test standard installation' do
it { should contain_package('ntp').with_ensure('present') }
it { should contain_package('ntp').with_name('ntp') }
it { should contain_service('ntp').with_ensure('running') }
it { should contain_service('ntp').with_enable('true') }
it { should contain_file('ntp.conf').with_ensure('present') }
it { should contain_file('ntp.cron').with_ensure('absent') }
it 'should generate a valid default template' do
should contain_file('ntp.conf').with_content(/server 1.pool.ntp.org/)
end
end
describe 'Test installation of a specific version' do
let(:params) { {:version => '1.0.42' } }
it { should contain_package('ntp').with_ensure('1.0.42') }
end
describe 'Test standard installation with monitoring and firewalling' do
let(:params) { {:monitor => true , :firewall => true, :port => '42', :protocol => 'tcp' } }
it { should contain_package('ntp').with_ensure('present') }
it { should contain_service('ntp').with_ensure('running') }
it { should contain_service('ntp').with_enable('true') }
it { should contain_file('ntp.conf').with_ensure('present') }
it 'should monitor the process' do
should contain_monitor__process('ntp_process').with_enable(true)
end
it 'should place a firewall rule' do
should contain_firewall('ntp_tcp_42').with_enable(true)
end
end
describe 'Test server parameter as arrays' do
let(:params) { {:server => ['server1', 'server2'] } }
it 'should generate a valid default template' do
should contain_file('ntp.conf').with(
'content' => /server server1/,
'content' => /server server2/
)
end
end
describe 'Test server parameter as strings' do
let(:params) { {:server => 'server1,server2' } }
it 'should generate a valid default template' do
should contain_file('ntp.conf').with(
'content' => /server server1/,
'content' => /server server2/
)
end
end
context "on Debian" do
let :facts do
super().merge({
:operatingsystem => 'Debian',
:operatingsystemrelease => '7.8',
:operatingsystemmajrelease => '7',
})
end
describe 'Test install with cron runmode on Debian' do
let(:params) { {:runmode => 'cron', :server => ['server1', 'server2'] } }
it { should contain_package('ntp').with_ensure('present') }
it { should contain_package('ntp').with_name('ntpdate') }
it { should_not contain_service('ntp').with_ensure('stopped') }
it { should_not contain_service('ntp').with_enable('false') }
it { should contain_file('ntp.conf').with_ensure('present') }
it { should contain_file('ntp.cron').with_ensure('present') }
it 'should generate a valid default template' do
should contain_file('ntp.cron').with_content(/ntpd -q/)
end
end
end
describe 'Test decommissioning - absent' do
let(:params) { {:absent => true, :monitor => true , :firewall => true, :port => '42', :protocol => 'tcp'} }
it 'should remove Package[ntp]' do should contain_package('ntp').with_ensure('absent') end
it 'should not manage Service[ntp]' do should_not contain_service('ntp') end
it 'should remove ntp configuration file' do should contain_file('ntp.conf').with_ensure('absent') end
it 'should not monitor the process' do
should contain_monitor__process('ntp_process').with_enable(false)
end
it 'should remove a firewall rule' do
should contain_firewall('ntp_tcp_42').with_enable(false)
end
end
describe 'Test decommissioning - disable' do
let(:params) { {:disable => true, :monitor => true , :firewall => true, :port => '42', :protocol => 'tcp'} }
it { should contain_package('ntp').with_ensure('present') }
it 'should stop Service[ntp]' do should contain_service('ntp').with_ensure('stopped') end
it 'should not enable at boot Service[ntp]' do should contain_service('ntp').with_enable('false') end
it { should contain_file('ntp.conf').with_ensure('present') }
it 'should not monitor the process' do
should contain_monitor__process('ntp_process').with_enable(false)
end
it 'should remove a firewall rule' do
should contain_firewall('ntp_tcp_42').with_enable(false)
end
end
describe 'Test decommissioning - disableboot' do
let(:params) { {:disableboot => true, :monitor => true , :firewall => true, :port => '42', :protocol => 'tcp'} }
it { should contain_package('ntp').with_ensure('present') }
it { should_not contain_service('ntp').with_ensure('present') }
it { should_not contain_service('ntp').with_ensure('absent') }
it 'should not enable at boot Service[ntp]' do should contain_service('ntp').with_enable('false') end
it { should contain_file('ntp.conf').with_ensure('present') }
it 'should not monitor the process locally' do
should contain_monitor__process('ntp_process').with_enable(false)
end
it 'should keep a firewall rule' do
should contain_firewall('ntp_tcp_42').with_enable(true)
end
end
describe 'Test customizations - template' do
let(:params) { {:template => "ntp/spec.erb" , :options => { 'opt_a' => 'value_a' } } }
it 'should generate a valid template' do
should contain_file('ntp.conf').with_content(/fqdn: rspec.example42.com/)
end
it 'should generate a template that uses custom options' do
should contain_file('ntp.conf').with_content(/value_a/)
end
it 'should not use source parameters' do
should contain_file('ntp.conf').with_source(nil)
end
end
describe 'Test customizations - source' do
let(:params) { {:source => "puppet://modules/ntp/spec" , :source_dir => "puppet://modules/ntp/dir/spec" , :source_dir_purge => true, :template => '' } }
it 'should request a valid source ' do
should contain_file('ntp.conf').with_source("puppet://modules/ntp/spec")
end
it 'should request a valid source dir' do
should contain_file('ntp.dir').with_source("puppet://modules/ntp/dir/spec")
end
it 'should purge source dir if source_dir_purge is true' do
should contain_file('ntp.dir').with_purge(true)
end
it 'should not use template parameters' do
should contain_file('ntp.conf').with_content(nil)
end
end
describe 'Test customizations - custom class' do
let(:params) { {:my_class => "ntp::spec" } }
it 'should automatically include a custom class' do
should contain_file('ntp.conf').with_content(/fqdn: rspec.example42.com/)
end
end
describe 'Test service autorestart' do
it { should contain_file('ntp.conf').with_notify('Service[ntp]') }
end
describe 'Test service autorestart' do
let(:params) { {:service_autorestart => "no" } }
it 'should not automatically restart the service, when service_autorestart => false' do
should contain_file('ntp.conf').with_notify(nil)
end
end
describe 'Test Puppi Integration' do
let(:params) { {:puppi => true, :puppi_helper => "myhelper"} }
it 'should generate a puppi::ze define' do
should contain_puppi__ze('ntp').with_helper("myhelper")
end
end
describe 'Test Monitoring Tools Integration' do
let(:params) { {:monitor => true, :monitor_tool => "puppi" } }
it 'should generate monitor defines' do
should contain_monitor__process('ntp_process').with_tool("puppi")
end
end
describe 'Test Firewall Tools Integration' do
let(:params) { {:firewall => true, :firewall_tool => "iptables" , :protocol => "tcp" , :port => "42" } }
it 'should generate correct firewall define' do
should contain_firewall('ntp_tcp_42').with_tool("iptables")
end
end
describe 'Test OldGen Module Set Integration' do
let(:params) { {:monitor => "yes" , :monitor_tool => "puppi" , :firewall => "yes" , :firewall_tool => "iptables" , :puppi => "yes" , :port => "42" , :protocol => 'tcp' } }
it 'should generate monitor resources' do
should contain_monitor__process('ntp_process').with_tool("puppi")
end
it 'should generate firewall resources' do
should contain_firewall('ntp_tcp_42').with_tool("iptables")
end
it 'should generate puppi resources ' do
should contain_puppi__ze('ntp').with_ensure("present")
end
end
describe 'Test params lookup' do
let :facts do
super().merge({
:monitor => true,
})
end
let(:params) { { :port => '42' } }
it 'should honour top scope global vars' do
should contain_monitor__process('ntp_process').with_enable(true)
end
end
describe 'Test params lookup' do
let :facts do
super().merge({
:ntp_monitor => true,
})
end
let(:params) { { :port => '42' } }
it 'should honour module specific vars' do
should contain_monitor__process('ntp_process').with_enable(true)
end
end
describe 'Test params lookup' do
let :facts do
super().merge({
:monitor => false,
:ntp_monitor => true,
})
end
let(:params) { { :port => '42' } }
it 'should honour top scope module specific over global vars' do
should contain_monitor__process('ntp_process').with_enable(true)
end
end
describe 'Test params lookup' do
let :facts do
super().merge({
:monitor => false,
})
end
let(:params) { { :monitor => true , :firewall => true, :port => '42' } }
it 'should honour passed params over global vars' do
should contain_monitor__process('ntp_process').with_enable(true)
end
end
end
|
brdebr/AttndCtrl
|
db/migrate/20180603210723_add_timetable_to_timetable_unit.rb
|
class AddTimetableToTimetableUnit < ActiveRecord::Migration[5.1]
def change
add_reference :timetable_units, :timetable, foreign_key: true
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.