repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
Youshu31415926/igetui-ruby
|
lib/igetui.rb
|
require 'forwardable'
require 'net/http'
require 'uri'
require 'json'
require 'digest/md5'
require 'base64'
module IGeTui
class << self
extend Forwardable
API_URL = "http://sdk.open.api.igexin.com/apiex.htm"
attr_reader :pusher
def_delegators :pusher, :push_message_to_single
def_delegators :pusher, :push_message_to_list
def_delegators :pusher, :push_message_to_app
def_delegators :pusher, :stop
def_delegators :pusher, :get_client_id_status
def_delegators :pusher, :get_client_id
def_delegators :pusher, :get_content_id, :cancel_content_id
def pusher(app_id, api_key, master_secret)
@pusher = IGeTui::Pusher.new(API_URL, app_id, api_key, master_secret)
end
end
end
require "igetui/version"
require 'protobuf/GtReq.pb'
require "igetui/template"
require "igetui/validate"
require "igetui/message"
require "igetui/pusher"
require "igetui/client"
|
snanda85/snanda85.github.io
|
generate.rb
|
<gh_stars>0
require 'date'
require 'optparse'
options = {}
opts = OptionParser.new do |opts|
opts.banner = "Usage:\n\tgenerate.rb title category " +
"\n\nOptions:\n\tcategory\tblog, writeup"
end
opts.parse!
if ARGV.empty?
puts opts.banner
exit
end
options[:title] = ARGV.shift
options[:category] = ARGV.shift || "blog"
def slug(title)
title.downcase.gsub(/[^\w]/, " ").strip.gsub(/\s+/, '-')
end
template = '''---
layout: post
title: "%{title}"
categories:
- %{category}
---
Go-go-gadget blog post
'''
content = template % options
filename = "_posts/#{Date.today}-#{slug(options[:title])}.md"
File.open(filename, "w") do |file|
file.write(content)
end
system "subl -n . #{filename}"
puts "Crush it!"
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count/scope_reflection.rb
|
class PgTriggerCount
class ScopeReflection
attr_accessor :reflection, :scope
def initialize(reflection,options)
@reflection = reflection
@scope = options[:scope]
@scope_tables[k][:table] ||= options[:table]
@scope_tables[k][:foreign_key] ||= "#{options[:table].singularize}_id"
@scope_tables[k][:primary_key] ||= "id"
end
end
end
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count/generator.rb
|
require 'forwardable'
class PgTriggerCount
class Generator
attr_accessor :reflections
def initialize(reflections)
@reflections = [reflections].flatten.collect{|r|PgTriggerCount::Generator::Reflection.new(r)}
end
def counts_classes
reflections.collect{|reflection| reflection.counts_class}.uniq
end
def counted_table_generators
@reflections_by_counted_class ||= begin
reflections_by_counted_class = {}
reflections.each do |reflection|
if reflections_by_counted_class[reflection.counted_class]
reflections_by_counted_class[reflection.counted_class].add reflection
else
reflections_by_counted_class[reflection.counted_class] ||= PgTriggerCount::Generator::CountedTable.new(reflection)
end
end
reflections_by_counted_class
end
end
def generate_functions
counted_table_generators.values.collect{|g| g.generate_function}
end
def generate_drop_functions
counted_table_generators.values.collect{|g| g.generate_drop_function}
end
def generate_missing_triggers
counted_table_generators.values.reject(&:trigger_exists?).collect{|g| g.generate_trigger }
end
def reflections_by_counts_class
reflections_by_counts_class = {}
reflections.each do |reflection|
reflections_by_counts_class[reflection.counts_class] ||= []
reflections_by_counts_class[reflection.counts_class] << reflection
end
reflections_by_counts_class
end
def new_counts_tables
new_tables = counts_classes.reject{|klass|klass.table_exists?}.collect(&:table_name)
end
# FIXME We need to generate indexes!
def indexe_definitions
end
def new_counts_table_definitions
definitions = {}
reflections_by_counts_class.each do |counts_class,reflections|
next if counts_class.table_exists?
counter_columns = reflections.first.counter_class.columns_hash
definitions[counts_class.table_name] ||= {}
reflections.each do |reflection|
reflection.counts_keys.each do |key,keys|
definitions[counts_class.table_name][key] = {
:name => key,
:type => counter_columns[keys[:counter_key].to_s].type,
}
end
definitions[counts_class.table_name][reflection.count_column] = {
:name => reflection.count_column,
:type => :integer
}
end
end
definitions
end
def new_counts_column_definitions
definitions = {}
reflections_by_counts_class.each do |counts_class,reflections|
next unless counts_class.table_exists?
counter_columns = reflections.first.counter_class.columns_hash
# pp "ADAMDEBUG: ", counter_columns
# add missing key columns
reflections.collect(&:counts_keys).each do |keys|
keys = keys.values.first
next if counts_class.columns_hash[keys[:counts_key].to_s]
definitions[counts_class.table_name] ||= {}
definitions[counts_class.table_name][keys[:counts_key]] = {
:name => key,
:type => counter_columns[keys[:counter_key].to_s].type,
}
end
# add missing count columns
reflections.each do |reflection|
next if counts_class.columns_hash[reflection.count_column]
definitions[counts_class.table_name] ||= {}
definitions[counts_class.table_name][reflection.count_column] = {
:name => reflection.count_column,
:type => :integer,
}
end
end
definitions
end
# FIXME we need to get the current cache version
def generate_invalidate_cache_function
"
CREATE OR REPLACE FUNCTION invalidate_cache(model VARCHAR, key VARCHAR, id VARCHAR) RETURNS BOOL AS $$
DECLARE
cache_version VARCHAR;
cache_key VARCHAR;
pass BOOL;
BEGIN
-- Go get the cache_Version
cache_version := 0;
cache_key := model || '_' || cache_version || '_0:' || key || ':' || id;
INSERT INTO pg_trigger_cache_keys (foo) VALUES (cache_key);
PERFORM memcache_delete(cache_key);
RETURN true;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_trigger_cache_keys (foo) VALUES ('fail');
RETURN false;
END;
$$ LANGUAGE plpgsql;
"
end
def migration_vars(klass_name="CreatePgTriggerCount#{Time.now.to_i}")
{
:migration_name => klass_name,
:new_tables => self.new_counts_table_definitions,
:new_columns => self.new_counts_column_definitions,
:create_functions => self.generate_functions,
:drop_functions => self.generate_drop_functions,
:create_triggers => self.generate_missing_triggers,
:invalidate_cache => self.generate_invalidate_cache_function
}
end
def all_functions
generate_invalidate_cache_function <<
generate_missing_triggers.join("\n") <<
generate_functions.join("\n")
end
def load_all_functions
unless self.class.functions_loaded?
ActiveRecord::Base.connection.execute all_functions
self.class.functions_loaded = true
end
end
def self.functions_loaded?
@functions_loaded
end
def self.functions_loaded=(bool)
@functions_loaded = bool
end
end
end
|
wonko9/pg_trigger_count
|
tasks/pg_trigger_count_tasks.rake
|
<reponame>wonko9/pg_trigger_count<filename>tasks/pg_trigger_count_tasks.rake
require 'rubygems'
require 'rake'
require 'active_record'
# require "#{File.dirname(__FILE__)}/../../config/environment.rb"
namespace :pgtc do
desc 'Generate Functions'
task :generate_functions do
end
end
|
wonko9/pg_trigger_count
|
lib/active_record_extensions.rb
|
class PgTriggerCountError < StandardError; end
module ActiveRecord
class Base
def self.pg_trigger_count(count_column,options={})
options[:count_column] ||= count_column
options[:counted_class] ||= options[:class_name] if options[:class_name]
options[:counter_class] = self
reflection = PgTriggerCount::Reflection.new(options)
PgTriggerCount.add_counted_model(reflection.counted_class)
end
def self.define_pg_count_method(reflection)
define_method "#{reflection.count_method_name}" do
assoc = self.send(reflection.counts_association)
if assoc and assoc.send(reflection.count_column)
assoc.send(reflection.count_column)
else
reflection.update_count_for(self)
if reflection.record_cache?
reflection.counts_class.cached_index("by_#{reflection.counts_keys.keys.first}").invalidate(self.send(reflection.counter_keys.keys.first))
end
if (self.send(reflection.counts_association) && self.send(reflection.counts_association).reload) || self.send(reflection.counts_association,true)
self.send(reflection.counts_association).send(reflection.count_column)
else
# should this be 0?
0
end
end
end
end
def self.trigger_counts
@trigger_counts
end
def self.pgtc_generator
@pgtc_generator ||= PgTriggerCount::Generator.new(trigger_counts)
end
def self.trigger_exists?(trigger)
ActiveRecord::Base.connection.select_value("SELECT tgname from pg_trigger WHERE tgname='#{trigger}'")
end
end
end
|
wonko9/pg_trigger_count
|
test/generator_test.rb
|
<gh_stars>1-10
require File.dirname(__FILE__) + '/test_helper'
require 'active_record'
require 'rails_generator'
require 'rails_generator/scripts/generate'
require "#{File.dirname(__FILE__)}/../generators/pg_trigger_count/pg_trigger_count_generator"
class GeneratorTest < Test::Unit::TestCase
# should "probably rename this file and start testing for real" do
# flunk "hey buddy, you should probably rename this file and start testing for real"
# end
context "Basic Reflection" do
setup do
PgtcMigration::CreateTables.up
# Message.stubs(:connection).returns(stub(:execute => true))
@reflection = PgTriggerCount::Reflection.new(:count_column => :messages, :counter_class => "User")
@generator = PgTriggerCount::Generator::Reflection.new(@reflection)
end
should "work" do
sql = @generator.generate_sql
f = File.open("../tmp/pg_trig_reflection1.sql", "w")
f.write(sql)
end
teardown do
PgtcMigration::CreateTables.down
end
end
context "polymorphic" do
setup do
Message.stubs(:connection).returns(stub(:execute => true))
@reflection = PgTriggerCount::Reflection.new(:count_column => :messages, :counter_class => "User", :as => :sender)
@generator = PgTriggerCount::Generator::Reflection.new(@reflection)
end
should "work" do
sql = @generator.generate_sql
f = File.open("../tmp/pg_trig_reflection2.sql", "w")
f.write(sql)
end
end
context "full generator" do
setup do
PgtcMigration::CreateTables.up
@messages = PgTriggerCount::Reflection.new(:count_column => :messages, :counter_class => "User", :as => :sender)
@user_groups = PgTriggerCount::Reflection.new(:count_column => :groups, :counter_class => "User", :counted_class => "GroupMembership")
@group_users = PgTriggerCount::Reflection.new(:count_column => :users, :counter_class => "Group", :counted_class => "GroupMembership")
@generator = PgTriggerCount::Generator.new([@messages,@user_groups,@group_users])
end
teardown do
PgtcMigration::CreateTables.down
end
should "generate function" do
# pp "ADAMDEBUG: ", @generator.reflections.first.insert_count_sql
sql = @generator.generate_functions
f = File.open("../tmp/pg_trig.sql", "w")
f.write(sql)
f.write("\n\n")
# f.write(@generator.generate_trigger_safe)
end
should "new tables" do
assert_equal @generator.new_counts_table_definitions, {
"user_counts" => {
"user_id" => {:type=>:integer, :name=>"user_id"},
"groups_count" => {:type=>:integer, :name=>"groups_count"},
"messages_count" => {:type=>:integer, :name=>"messages_count"}
},
"group_counts"=> {
"users_count"=> {:type=>:integer, :name=>"users_count"},
"group_id" => {:type=>:integer, :name=>"group_id"}
}
}
end
context "missing columns" do
setup do
PgtcMigration::CreateTables.up
end
teardown do
PgtcMigration::CreateTables.down
end
should "new columns" do
assert_equal @generator.new_counts_column_definitions, {"user_counts"=>{"groups_count"=>{:type=>:integer, :name=>"groups_count"}}}
end
end
end
end
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count/old_generator.rb
|
<gh_stars>1-10
class PgTriggerCount::Generator
attr_accessor :by, :scope, :counts_table, :trig_name, :recalc_name,
:table_name, :invalidate_cache, :options, :count_column, :name
def initialize(table_name, options)
@table_name = table_name
@options = options
@by = [@options[:by]].flatten
@scope = @options[:scope]
@use_pgmemcache = @options.has_key?(:use_pgmemcache) ? @options[:use_pgmemcache] : true
@counts_table = "#{table_name}_counts"
@trig_name = "tcfunc_#{table_name}_by_" + (scope ? "#{scope.first}" : "#{by.join('_and_')}")
@recalc_name = "#{@trig_name}_recalc"
@count_column = options[:count_column] || 'cnt'
@name = options[:name] || "'#{scope ? scope.first : by.join(',')}' "
end
def invalidate_cache?
@use_pgmemcache
end
def count_key_prefix
"#{table_name}:#{scope ? scope.first : by.join(',')}"
end
def generate_drop_function
"DROP FUNCTION #{trig_name}() CASCADE"
end
def key_select
by.join(key_separator)
end
def scope_conditions
scope ? ' AND ' << scope[1].collect{|k,v|"#{k}='#{v}'"}.join(' AND ') : ''
end
def separator
'_'
end
def key_separator
"||'#{separator}'||"
end
def generate_trigger_function
new_update_where = "name=#{name} AND key=#{by.collect{|b|"NEW.#{b}"}.join(key_separator)}"
old_update_where = "name=#{name} AND key=#{by.collect{|b|"OLD.#{b}"}.join(key_separator)}"
if_cond = (by + (scope ? scope[1].keys : [])).collect{|b|"NEW.#{b} <> OLD.#{b}"}.join(' , ')
cache_key = "'#{count_key_prefix}:'||#{by.collect{|b|"NEW.#{b}"}.join(key_separator)}"
cache_sql = invalidate_cache? ? "
BEGIN
PERFORM memcache_delete(#{cache_key});
EXCEPTION WHEN OTHERS THEN -- Ignore errors
END;
-- INSERT INTO pg_trigger_cache_keys (key) VALUES ('#{count_key_prefix}:'||#{by.collect{|b|"NEW.#{b}"}.join(key_separator)});" : ''
<<-FUN
CREATE OR REPLACE FUNCTION #{trig_name}() RETURNS TRIGGER AS $#{trig_name}$
DECLARE
up_count integer;
new_count RECORD;
new_total integer;
cache_data varchar;
BEGIN
IF (TG_OP = 'DELETE') THEN
UPDATE #{counts_table} SET #{count_column}=#{count_column}-1 WHERE #{new_update_where};
ELSIF (TG_OP = 'INSERT') THEN
UPDATE #{counts_table} SET #{count_column}=#{count_column}+1 WHERE #{new_update_where};
ELSIF (TG_OP = 'UPDATE') THEN
IF #{if_cond} THEN
UPDATE #{counts_table} SET #{count_column}=#{count_column}+1 WHERE #{new_update_where};
UPDATE #{counts_table} SET #{count_column}=#{count_column}-1 WHERE #{old_update_where};
ELSE
RETURN NEW;
END IF;
END IF;
GET DIAGNOSTICS up_count = ROW_COUNT;
IF up_count = 0 THEN -- we couldn't update so now we have to pre-populate
SELECT #{trig_name}_recalc(#{by.collect{|b|"NEW.#{b}"}.join(',')}) INTO new_total;
END IF;
#{cache_sql}
RETURN NEW;
END;
$#{trig_name}$ LANGUAGE plpgsql;
FUN
end
def generate_recalc_function
func_conditions = by.collect{|b|"var_#{b} " + (b.to_s[-3,3] == '_id' ? 'bigint' : 'varchar')}.join(',')
conditions = by.collect{|b|"#{b}=var_#{b}"}.join(' AND ')
<<-SQL
CREATE OR REPLACE FUNCTION #{trig_name}_recalc(#{func_conditions}) RETURNS integer AS $$
DECLARE
new_count RECORD;
BEGIN
SELECT #{key_select} as key, #{name} as name, count(*) as #{count_column} FROM #{table_name}
WHERE #{conditions} #{scope_conditions}
GROUP BY #{by.join(',')} INTO new_count;
INSERT INTO #{counts_table} (key,name,#{count_column}) VALUES (new_count.key, new_count.name, new_count.#{count_column});
RETURN new_count.cnt;
END;
$$ LANGUAGE plpgsql;
SQL
end
def generate_trigger
<<-TRIG
CREATE TRIGGER #{trig_name}
AFTER INSERT OR UPDATE OR DELETE ON messages
FOR EACH ROW EXECUTE PROCEDURE #{trig_name}();
TRIG
end
end
|
wonko9/pg_trigger_count
|
generators/pg_trigger_count/pg_trigger_count_generator.rb
|
<gh_stars>1-10
require 'rails_generator'
class PgTriggerCountGenerator < Rails::Generator::NamedBase
def initialize(runtime_args, runtime_options = {})
super
end
def banner
"Usage: #{$0}"
end
def manifest
@generator = PgTriggerCount.generator
record do |m|
now = Time.now.to_i
if @generator.new_counts_table_definitions.any? or @generator.new_counts_column_definitions.any?
m.migration_template 'migration.rb', 'db/migrate', :assigns => @generator.migration_vars, :migration_file_name => "create_pg_trigger_count_#{now}"
end
end
end
end
|
wonko9/pg_trigger_count
|
test/pg_trigger_count_test.rb
|
<reponame>wonko9/pg_trigger_count
require File.dirname(__FILE__) + '/test_helper'
require 'ostruct'
class PgTriggerCountTest < Test::Unit::TestCase
# context "Basic Reflection" do
#
# setup do
# @reflection = PgTriggerCount::Reflection.new(:count_column => :messages, :counter_class => "User")
# end
#
# should "have right counter class" do
# assert_equal User, @reflection.counter_class
# end
#
# should "have right counted class" do
# assert_equal Message, @reflection.counted_class
# end
#
# should "have right counts class" do
# assert_equal UserCount, @reflection.counts_class
# end
#
# should "have right count column" do
# assert_equal "messages_count", @reflection.count_column
# end
#
# should "have right count method name" do
# assert_equal "messages_count", @reflection.count_method_name
# end
#
# should "have right counter_keys" do
# assert_equal @reflection.counter_keys, {"id"=>{:counter_key=>"id", :counts_key=>"user_id", :counted_key=>"user_id"}}
# end
#
# should "have table names" do
# assert_equal "messages", @reflection.counted_table
# assert_equal "users", @reflection.counter_table
# assert_equal "user_counts", @reflection.counts_table
# end
#
# end
context "reflection with as" do
setup do
@reflection = PgTriggerCount::Reflection.new(:count_column => :messages, :counter_class => "User", :as => :sender)
end
should "have right counter_keys" do
assert_equal @reflection.counter_keys, {"id"=>{:counter_key=>"id", :counts_key=>"user_id", :counted_key=>"sender_id"}}
end
end
context "full" do
setup do
setup_database
@n1 = Network.create
@u1 = User.create(:network => @n1)
@u2 = User.create(:network => @n1)
end
teardown do
teardown_database
end
should "have scope" do
@n1 = Network.find @n1.id
assert_equal 0, @n1.users_count
@u1.update_attribute :state, 'active'
@n1 = Network.find @n1.id
assert_equal 1, @n1.users_count
@u1.update_attribute :state, 'passive'
@n1 = Network.find @n1.id
assert_equal 0, @n1.users_count
end
should "handle updates" do
@m2 = Message.create(:sender => @u2)
assert_equal 1, @u2.messages_count
assert_equal 0, @u1.messages_count
@m2.sender = @u1
@m2.save
assert_equal 0, @u2.user_counts(true).messages_count
assert_equal 1, @u1.messages_count
end
should "inc dec message counts" do
@m1 = Message.create(:sender => @u1)
assert_equal 1, @u1.messages_count
@m1.destroy
@u1 = User.find @u1.id
assert_equal 0, @u1.messages_count
assert_equal 0, @u2.messages_count
end
end
end
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count/generator/counted_table.rb
|
<reponame>wonko9/pg_trigger_count<gh_stars>1-10
class PgTriggerCount::Generator
class CountedTable
attr_accessor :reflections
def initialize(reflections)
@reflections = [reflections].flatten.collect{|r|PgTriggerCount::Generator::Reflection.new(r)}
end
def add(reflection)
@reflections << reflection
end
def counted_class
reflections.first.counted_class
end
def function_name
"tcfunc_#{counted_class.table_name}"
end
def generate_drop_function
"DROP FUNCTION #{function_name}() CASCADE"
end
def begin_function_sql
"CREATE OR REPLACE FUNCTION #{function_name}() RETURNS TRIGGER AS $#{function_name}$
DECLARE
up_count1 integer;
up_count2 integer;
up_count3 integer;
up_count4 integer;
up_count5 integer;
inc_count integer;
scope_record RECORD;
BEGIN
"
end
def end_function_sql
"
RETURN NEW;
END;
$#{function_name}$ LANGUAGE plpgsql;
"
end
def generate_trigger
<<-TRIG
CREATE TRIGGER #{function_name}
AFTER INSERT OR UPDATE OR DELETE ON #{counted_class.table_name}
FOR EACH ROW EXECUTE PROCEDURE #{function_name}();
TRIG
end
def trigger_exists?
ActiveRecord::Base.trigger_exists?(function_name)
end
def drop_and_generate_trigger
"DROP TRIGGER #{function_name};
#{generate_trigger}"
end
def generate_function
begin_function_sql <<
reflections.collect{ |r| r.generate_sql }.join("\n") <<
end_function_sql
end
end
end
|
wonko9/pg_trigger_count
|
generators/pg_trigger_count/templates/migration.rb
|
<filename>generators/pg_trigger_count/templates/migration.rb<gh_stars>1-10
class <%= migration_name %> < ActiveRecord::Migration
def self.up
ActiveRecord::Base.connection.execute("create language 'plpgsql'") rescue ActiveRecord::StatementInvalid
<%- new_tables.each do |table_name, columns| -%>
create_table :<%= table_name %> do |t|
<%- columns.values.each do |column| -%>
t.column :<%=column[:name] %>, :<%=column[:type]%>
<%- end -%>
t.timestamps
end
<%- end -%>
<%- new_columns.each do |table_name, column| -%>
add_column :<%=table_name %>, :<%= column[:name] %>, :<%=column[:type]%>
<%- end -%>
<%- create_functions.each do |function| -%>
function = <<-SQL
<%= function %>
SQL
ActiveRecord::Base.connection.execute(function)
<%- end -%>
<%- create_triggers.each do |trigger| -%>
trigger = <<-SQL
<%= trigger %>
SQL
ActiveRecord::Base.connection.execute(trigger)
<%- end -%>
function = <<-SQL
<%= invalidate_cache %>
SQL
ActiveRecord::Base.connection.execute(function)
end
def self.down
<%- new_tables.each do |table_name, columns| -%>
drop_table :<%= table_name %>
<%- end -%>
<%- new_columns.each do |table_name, column| -%>
remove_column :<%=table_name %>, :<%= column[:name] %>
<%- end -%>
<%- drop_functions.each do |function| -%>
ActiveRecord::Base.connection.execute("<%= function %>")
<%- end -%>
end
end
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count/generator/reflection.rb
|
<reponame>wonko9/pg_trigger_count<gh_stars>1-10
require 'forwardable'
class PgTriggerCount::Generator
class Reflection
attr_accessor :reflection
def initialize(reflection)
@reflection = reflection
end
def quote(val)
ActiveRecord::Base.connection.quote(val)
end
def select_count_conditions(target="NEW")
conditions = scope.collect {|k,v|"#{counted_table}.#{k} IS NOT DISTINCT FROM #{quote(v)}"}
if target.is_a?(Hash)
target = target.dup.stringify_keys
conditions += counted_keys.collect do |key,keys|
"#{counted_table}.#{key} is not distinct from '#{target[keys[:counter_key].to_s]}'"
end
else
conditions += counted_keys.collect do |key,keys|
"#{counted_table}.#{key} is not distinct from #{target}.#{key}"
end
end
conditions.join(" AND ")
end
def select_count_sql(target="NEW",select_keys=nil)
group_by = ''
if select_keys
select_keys = "#{select_keys.join(',')},"
group_by = " GROUP BY #{counted_keys.keys.join(',')}"
end
"SELECT #{select_keys}count(*) as #{count_column} FROM #{counted_table}
WHERE #{select_count_conditions(target)}#{group_by}"
end
def insert_count_from_select_sql(target="NEW")
insert_keys = counted_keys.collect { |key,keys| keys[:counts_key] }
insert_keys += ["created_at","updated_at",count_column]
select_keys = counted_keys.keys + ["now()","now()"]
"INSERT INTO #{counts_table} (#{insert_keys.join(",")})
#{select_count_sql(target,select_keys)}"
end
def update_count_conditions(target="NEW",check_for_value=true)
if target.is_a?(Hash)
target = target.dup.stringify_keys
conditions = reflection.counts_keys.collect do |count_key, keys|
"#{reflection.counts_table}.#{count_key} IS NOT DISTINCT FROM '#{target[keys[:counter_key]]}'"
end
else
conditions = reflection.counts_keys.collect do |count_key, keys|
"#{reflection.counts_table}.#{count_key} IS NOT DISTINCT FROM #{target}.#{keys[:counted_key]}"
end
end
conditions << "#{reflection.counts_table}.#{reflection.count_column} IS NOT NULL" if check_for_value
conditions.join(" AND ")
end
def update_count_from_select_sql(target="NEW")
"UPDATE #{counts_table} SET #{count_column}=(#{select_count_sql(target)}), updated_at=now() WHERE #{update_count_conditions(target,false)};"
end
def insert_or_update_count(target="NEW")
"#{update_count_from_select_sql(target)}
IF NOT FOUND THEN
#{insert_count_from_select_sql(target)};
END IF;"
end
def increment_counts_sql(target,increment=1)
"UPDATE #{counts_table}
SET #{count_column}=#{count_column}#{increment < 0 ? '' : '+'}#{increment}
WHERE #{update_count_conditions(target)}"
end
def increment_counts_if_valid(target,increment=1)
return increment_counts_sql(target,increment) if scope.empty? and scope_tables.empty?
if_conditions = scope.collect { |key,val| "#{target}.#{key} IS NOT DISTINCT FROM #{quote(val)}"}.join(" AND ")
sql = ''
if scope_tables.any?
sql = scope_tables.values.collect {|s| "#{select_scoped_record(s)};" }.join("\n")
end
sql += "
IF #{if_conditions} THEN
#{increment_counts_sql(target,increment)};
END IF"
end
# NEW.#{key} <=> OLD.#{key}"
def record_changed_conditions
conditions = (reflection.counted_keys.keys + scope.keys).collect do |key|
"NEW.#{key} IS DISTINCT FROM OLD.#{key}"
end.join(" OR ")
conditions
end
def select_scoped_record(scope,target="NEW")
"SELECT * from #{scope[:table]} WHERE #{scope[:primary_key]} = #{target}.#{scope[:foreign_key]}"
end
def show_record_changed_conditions
conditions = (reflection.counted_keys.keys + scope.keys).collect do |key|
"'#{key}: '||coalesce(NEW.#{key}::text,'NULL') || 'IS DISTINCT FROM' || coalesce(OLD.#{key}::text,'NULL')"
end.join(" || ' ' ||")
conditions
end
def show_record_data(target="NEW")
conditions = (reflection.counted_keys.keys + scope.keys).collect do |key|
"'#{key}: ' || coalesce(#{target}.#{key}::text,'NULL')"
end.join(" || ' ' ||")
conditions
end
def debug
true
end
def sql_log_debug(op,message)
"INSERT INTO logs (log) VALUES ('#{op} counted:#{counted_class} counter:#{counter_class} ' || #{message});" if debug
end
def cache_invalidation_sql
key = counted_keys.keys.first
"BEGIN
IF (TG_OP = 'DELETE') THEN
PERFORM invalidate_cache('#{counts_class}','by_#{counts_keys.keys.first}',OLD.#{key}::text);
ELSE
PERFORM invalidate_cache('#{counts_class}','by_#{counts_keys.keys.first}',NEW.#{key}::text);
END IF;
EXCEPTION WHEN OTHERS THEN -- Ignore errors
END;"
end
def generate_sql
"
IF (TG_OP = 'DELETE') THEN
#{increment_counts_if_valid("OLD",-1)};
GET DIAGNOSTICS up_count1 = ROW_COUNT;
#{sql_log_debug('DELETE',"'rows: ' || up_count1::text || ' ' ||" + show_record_data('OLD'))}
ELSIF (TG_OP = 'INSERT') THEN
#{increment_counts_if_valid("NEW",1)};
GET DIAGNOSTICS up_count2 = ROW_COUNT;
#{sql_log_debug('INSERT',show_record_data('NEW') + "|| ' ' || 'rows: ' || up_count2::text")}
ELSIF (TG_OP = 'UPDATE') THEN
IF #{record_changed_conditions} THEN
#{increment_counts_if_valid("OLD",-1)};
GET DIAGNOSTICS up_count3 = ROW_COUNT;
#{sql_log_debug('UPDATE DEC',show_record_changed_conditions + " || ' rows:' || up_count3::text || ' ' || '" + increment_counts_sql("OLD",-1)+"'")}
#{increment_counts_if_valid("NEW",1)};
GET DIAGNOSTICS up_count4 = ROW_COUNT;
#{sql_log_debug('UPDATE INC',show_record_changed_conditions + " || ' rows:' || up_count4::text || ' ' || '" + increment_counts_sql("NEW",1)+"'")}
ELSE
#{sql_log_debug('UPDATE NO CHANGE',show_record_changed_conditions)}
END IF;
ELSE
#{sql_log_debug('NOOP',"TG_OP")}
END IF;
GET DIAGNOSTICS inc_count = ROW_COUNT;
IF TG_OP != 'DELETE' AND inc_count = 0 THEN -- we couldn't update so now we have to pre-populate
#{sql_log_debug('REFRESH',"'refresh'")}
#{insert_or_update_count}
END IF;
#{cache_invalidation_sql}
"
end
def method_missing(name,*args)
begin
reflection.send(name,*args)
rescue NameError => e
raise NameError.new("Method #{name} does not exist on #{self.class} or #{reflection.class}")
end
end
end
end
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count/reflection.rb
|
<filename>lib/pg_trigger_count/reflection.rb
class PgTriggerCount
class PgtcCallbacks
attr_accessor :reflection
def initialize(reflection)
@reflection = reflection
end
def after_save(record)
reflection.counts_class.cached_index("by_#{reflection.counts_keys.keys.first}").invalidate(record.send(reflection.counted_keys.keys.first))
end
end
class Reflection
attr_accessor :options, :counter_class, :counted_class, :counts_class, :count_column, :cache,
:count_method_name, :scope, :counter_keys, :counted_keys, :counts_keys, :scope_tables
def initialize(options)
@options = options
@count_column = "#{options[:count_column]}_count"
@counter_class = options[:counter_class].to_s.constantize
@counted_class = options[:counted_class] ? options[:counted_class].to_s.constantize : options[:count_column].to_s.classify.constantize
@count_method_name = options[:count_method_name] || count_column
@counts_class_name = "#{counter_class}_counts".classify
@cache = options[:cache] || defined?(CACHE) ? CACHE : nil
@scope = stringify_hash(options[:scope]) || {}
@scope_tables = {}
@counter_keys = {}
@counted_keys = {}
@counts_keys = {}
# Handle scopes that include other tables
@scope.each do |k,v|
if @scope[k].is_a?(Hash)
@scope_tables[k] = @scope.delete(k)
@scope_tables[k][:scope] ||= v
@scope_tables[k][:table] ||= k.pluralize
@scope_tables[k][:foreign_key] ||= "#{k.singularize}_id"
@scope_tables[k][:primary_key] ||= "id"
end
end
begin
@counts_class = options[:counts_class] || @counts_class_name.constantize
rescue NameError
@counts_class = Class.new(ActiveRecord::Base)
Object.const_set(@counts_class_name,@counts_class)
puts "ERROR: #{@counts_class_name} has not been created. Please run ./script/generate pg_trigger_count migration" unless @counts_class.table_exists?
end
if options[:as]
@counter_keys = {
'id' => {
:counter_key => 'id',
:counts_key => "#{counter_class.name.underscore}_id",
:counted_key => "#{options[:as]}_id",
}
}
@scope["#{options[:as]}_type"] = counter_class.to_s
else
@counter_keys = {
'id'=> {
:counter_key => 'id',
:counts_key => "#{counter_class.name.underscore}_id",
:counted_key => "#{counter_class.name.underscore}_id",
}
}
end
# setup lookups for each type of table
@counter_keys.each do |counter_key,keys|
@counted_keys[keys[:counted_key]] = keys
@counts_keys[keys[:counts_key]] = keys
end
if options[:record_cache] or not options.has_key?(:record_cache)
@record_cache = true if counts_class.respond_to?(:record_cache)
@use_pgmemcache = PgTriggerCount.use_pgmemcache?(connection) if connection
end
# set up active record reflection
counter_class.has_one counts_association, :class_name => counts_class.to_s unless respond_to? counts_class.table_name
if record_cache?
counts_class.record_cache :by => counts_keys.keys.first
counted_class.after_save PgtcCallbacks.new(self) if not use_pgmemcache?
end
counter_class.define_pg_count_method(self)
add_to_model_class
end
def stringify_hash(hash)
return hash unless hash.is_a?(Hash)
new_hash = {}
hash.each do |k,v|
if new_hash[k].is_a?(Hash)
new_hash[k.to_s] = stringify_hash(v)
else
new_hash[k.to_s] = v ? v.to_s : v
end
end
new_hash
end
def add_to_model_class
trigger_counts = counted_class.instance_variable_get("@trigger_counts") || []
trigger_counts << self
counted_class.instance_variable_set("@trigger_counts",trigger_counts)
end
def counts_association
counts_class.table_name
end
def record_cache?
@record_cache
end
def use_pgmemcache?
@use_pgmemcache
end
def cache_key_prefix
"'pgtc:#{counts_class}:'"
end
def count_by_keys
counted_keys.keys
end
def method_missing(name, *args)
name = name.to_s
if name =~ /^(.*)_table$/
self.send("#{$1}_class").table_name
else
raise NameError.new("Method #{name} does not exist")
end
end
def generator
@generator ||= PgTriggerCount::Generator::Reflection.new(self)
end
def update_count_for(record)
target = {}
counter_keys.keys.each{|k| target[k]=record.send(k) }
if (connection.update(generator.update_count_from_select_sql(target)) < 1)
connection.execute(generator.insert_count_from_select_sql(target))
end
end
def connection
counted_class.connection
end
end
end
|
wonko9/pg_trigger_count
|
test/test_helper.rb
|
<reponame>wonko9/pg_trigger_count
require 'rubygems'
require 'pp'
require 'test/unit'
require 'shoulda'
require 'mocha'
require 'erb'
require 'ostruct'
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.dirname(__FILE__) + "/../lib")
# $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
require 'pg_trigger_count'
# ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.establish_connection(
:adapter => "postgresql",
:host => "localhost",
:username => "postgres",
:database => "pg_trigger_count_test"
)
# ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.connection.client_min_messages = 'panic'
ActiveRecord::Migration.verbose = false
class Message < ActiveRecord::Base
belongs_to :network
belongs_to :sender, :polymorphic => true
end
class Network < ActiveRecord::Base
has_many :users
has_many :groups
has_many :messages
end
class User < ActiveRecord::Base
has_many :messages, :as => :sender
has_many :group_memberships
has_many :groups, :through => :group_memberships
belongs_to :network
end
class Group < ActiveRecord::Base
has_many :group_memberships
has_many :users, :through => :group_memberships
belongs_to :network
end
class GroupMembership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
Network.pg_trigger_count :users, :scope => {:state => :active}
Network.pg_trigger_count :messages
User.pg_trigger_count :messages, :as => :sender
class PgtcMigration
def self.generate_migration
@generator ||= PgTriggerCount.generator
vars = @generator.migration_vars("CreatePgTriggerCount")
b = binding
vars.each { |k,v| eval "#{k} = vars[:#{k}]", b }
ERB.new(File.read(File.dirname(__FILE__) +"/../generators/pg_trigger_count/templates/migration.rb"),nil,'-').result(b)
end
class CreateTables < ActiveRecord::Migration
def self.up
begin
create_table :logs do |t|
t.column :log, :string, :limit => 2000
t.timestamps
end
rescue ActiveRecord::StatementInvalid
end
create_table :networks do |t|
t.timestamps
end
create_table :users do |t|
t.integer :network_id
t.string :state
t.timestamps
end
create_table :messages do |t|
t.integer :network_id
t.integer :sender_id
t.string :sender_type
t.timestamps
end
create_table :groups do |t|
t.integer :network_id
t.string :state
t.timestamps
end
create_table :group_memberships do |t|
t.integer :user_id
t.integer :group_id
t.boolean :approved
t.timestamps
end
end
def self.down
drop_table :users
drop_table :messages
drop_table :groups
drop_table :group_memberships
drop_table :networks
end
end
class CreateUserCounts < ActiveRecord::Migration
def self.up
create_table :user_counts do |t|
t.column :user_id, :integer
t.column :messages_count, :integer
end
end
def self.down
drop_table :user_counts
end
end
end
class Test::Unit::TestCase
def fake_rails_root
File.dirname(__FILE__) + '/../tmp/rails_root'
end
def file_list
Dir.glob(File.join(fake_rails_root, "*"))
end
def setup_database
PgtcMigration::CreateTables.up
migration = PgtcMigration.generate_migration
eval migration
CreatePgTriggerCount.up
end
def teardown_database
PgtcMigration::CreateTables.down
CreatePgTriggerCount.down
end
end
|
wonko9/pg_trigger_count
|
lib/pg_trigger_count.rb
|
$:.unshift(File.dirname(__FILE__))
require 'active_record'
require 'active_support'
require 'active_record_extensions'
require 'pg_trigger_count/reflection'
require 'pg_trigger_count/generator'
require 'pg_trigger_count/generator/reflection'
require 'pg_trigger_count/generator/counted_table'
class PgTriggerCount
def self.use_pgmemcache?(connection)
return @use_pgmemcache if defined?(@use_pgmemcache)
begin
connection.execute("select memcache_get('test')")
@use_pgmemcache = true
rescue ActiveRecord::StatementInvalid => e
@use_pgmemcache = false
end
end
def self.add_counted_model(klass)
@counted_models ||= []
@counted_models << klass unless @counted_models.include?(klass)
end
def self.counted_models
@counted_models || []
end
def self.generator
PgTriggerCount::Generator.new(counted_models.collect(&:trigger_counts).flatten)
end
end
|
ivan1993br/autoproj-docker-enviroment
|
image/autoproj.buildconf/autoproj/overrides.rb
|
<gh_stars>0
# Under MIT License
#author <NAME>
# Write in this file customization code that will get executed after all the
# soures have beenloaded.
Autoproj.manifest.each_autobuild_package do |pkg|
pkg.define "CMAKE_EXPORT_COMPILE_COMMANDS", "ON" if pkg.kind_of?(Autobuild::CMake)
end
|
ivan1993br/autoproj-docker-enviroment
|
image/autoproj.buildconf/autoproj/init.rb
|
<reponame>ivan1993br/autoproj-docker-enviroment
# Under MIT License
#author <NAME>
# Write in this file customization code that will get executed before
# autoproj is loaded.
# Set the path to 'make'
# Autobuild.commands['make'] = '/path/to/ccmake'
# Set the parallel build level (defaults to the number of CPUs)
# Autobuild.parallel_build_level = 10
# Uncomment to initialize the environment variables to default values. This is
# useful to ensure that the build is completely self-contained, but leads to
# miss external dependencies installed in non-standard locations.
#
# set_initial_env
#
# Additionally, you can set up your own custom environment with calls to env_add
# and env_set:
#
# env_add 'PATH', "/path/to/my/tool"
# env_set 'CMAKE_PREFIX_PATH', "/opt/boost;/opt/xerces"
# env_set 'CMAKE_INSTALL_PATH', "/opt/orocos"
#
# NOTE: Variables set like this are exported in the generated 'env.sh' script.
#
require 'autobuild/import/git-lfs'
FileUtils.mkdir_p File.join(Autoproj.prefix, 'lib', 'python2.7', 'dist-packages')
FileUtils.mkdir_p File.join(Autoproj.prefix, 'lib', 'python2.7', 'site-packages')
Autoproj.env_add_path 'PYTHONPATH', File.join(Autoproj.prefix, 'lib', 'python2.7', 'dist-packages')
Autoproj.env_add_path 'PYTHONPATH', File.join(Autoproj.prefix, 'lib', 'python2.7', 'site-packages')
Autoproj.env_add_path 'LD_LIBRARY_PATH', File.join(Autoproj.prefix, 'lib')
Autoproj.config.set('build', File.join(Autoproj.root_dir, 'build')) unless Autoproj.config.get('build', nil)
Autoproj.config.set('source', 'src') unless Autoproj.config.source_dir
if Autoproj.config.user_shells.empty?
Autoproj.config.user_shells = ['bash']
end
(['sh'] + Autoproj.config.user_shells).each do |shell|
shell_helper = "setup.#{shell}"
FileUtils.touch File.join(Autoproj.prefix, shell_helper)
Autoproj.env_source_after(File.join(Autoproj.prefix, shell_helper), shell: shell)
end
#
require 'autoproj/gitorious'
Autoproj.gitorious_server_configuration('GITORIOUS', 'gitorious.org')
Autoproj.gitorious_server_configuration('GITHUB', 'github.com', :http_url => 'https://github.com')
|
twe4ked/terminal_game_engine
|
lib/terminal_game_engine/frame.rb
|
<filename>lib/terminal_game_engine/frame.rb
require 'io/console'
module TerminalGameEngine
class Frame
attr_reader :rows
def initialize(width, height)
@rows = height.times.map { ' ' * width }
end
def width
@rows.first.size
end
def height
@rows.size
end
def draw(x, y, sprite)
lines = sprite.split("\n")
lines.each_with_index do |line, i|
if line.size > 0 && y+lines.size <= self.height && y+i >= 0
# crop when drawing off left
if x < 0
line = line[x.abs..-1]
x = 0
end
# crop when drawing off right
if x+line.size-1 >= self.width
line = line[0..(self.width-1)-(x+line.size)]
end
@rows[y+i][x..x+line.size-1] = line
end
end
end
def draw_center(y, sprite)
sprite_width = sprite.split("\n").first.size
x = self.width / 2 - sprite_width / 2
draw x, y, sprite
end
def render
@rows.each_with_index do |row, i|
Frame.move_cursor 0, i
print row
end
end
def self.move_cursor(x, y)
print "\033[#{y+1};#{x+1}H"
end
def self.clear_screen
print "\033[2J"
end
def self.disable_cursor
print "\x1B[?25l"
end
def self.enable_cursor
print "\x1B[?25h"
end
def self.setup(disable_cursor: true)
clear_screen
disable_cursor if disable_cursor
$stdin.raw!
at_exit do
puts "\r"
enable_cursor if disable_cursor
$stdin.cooked!
system 'stty sane'
end
trap 'WINCH' do
clear_screen
end
end
end
end
|
xLeachimx/NeuralNetworks
|
ruby/neural_net.rb
|
<reponame>xLeachimx/NeuralNetworks
class Neuron
attr_reader :activation
attr_accessor :error
attr_accessor :connections
attr_accessor :bias
def initialize
@inputs = []
@connections = []
@bias = 0.0
@error = 0.0
end
def addInput input
@inputs.push(input)
end
def calcActivation
@activation = bias
@inputs.each do |i|
@activation += i
end
# sigmoid
@activation = 1/(1+(Math.exp(-activation))) #Run through sigmoid function
# hyperbolic
# @activation = Math.tanh(activation)
end
def reset
@activation = 0.0
@inputs = []
end
def addConnection to, weight
@connections.push([to,weight])
end
def fire
@connections.each do |connection|
connection[0].addInput(connection[1]*@activation)
end
end
def getTotalInput
total = @bias
@inputs.each do |i|
total += i
end
return total
end
end
class NeuralNetwork
# Precond:
# layers is an array of integers representing the size of the networks layers, in order
# Postcond:
# sets up an untrained, random neural network
def initialize layers, precision=10
@network = []
layers.each do |layer|
@network.push([])
layer.times do
@network[-1].push(Neuron.new)
end
end
@precision = precision
# random connection weights
@network.each_index do |i|
if i != (@network.size - 1)
@network[i].each do |sender|
@network[i+1].each do |receiver|
sender.addConnection(receiver,Random.rand().round(@precision))
# sender.addConnection(receiver,0.0)
end
end
end
end
end
def run inputs
clearNet
@network[0].each_index do |i|
@network[0][i].addInput(inputs[i])
end
@network.each do |layer|
layer.each do |neuron|
neuron.calcActivation
neuron.fire
end
end
end
def retrieveOutputRounded
output = []
@network[-1].each do |neuron|
output.push(neuron.activation.round)
end
return output
end
def retrieveOutputRaw
output = []
@network[-1].each do |neuron|
output.push(neuron.activation)
end
return output
end
def train expected, lr
# Calculate all the error factors
layer = @network[-1]
# output layer error
layer.each_index do |i|
layer[i].error = backpropFunction(layer[i].getTotalInput())*(expected[i]-layer[i].activation)
end
layers = @network[0,@network.length-1]
layers.reverse!
# reverse order inner and input layers error
layers.each do |layer|
layer.each do |neuron|
neuron.error = backpropFunction(neuron.getTotalInput())
total = 0.0
neuron.connections.each do |connection|
total += connection[1] * connection[0].error
end
neuron.error = neuron.error * total
end
end
# Add to weights
@network.each do |layer|
layer.each do |neuron|
next if neuron.connections == []
neuron.connections.each do |connection|
connection[1] += lr*neuron.activation*connection[0].error
end
neuron.bias += lr*neuron.error
end
end
end
def toString
result = ""
@network.each_index do |layer|
@network[layer].each_index do |neuron|
@network[layer][neuron].connections.each_index do |connect|
result += "#{layer}->#{neuron}->#{connect}:#{@network[layer][neuron].connections[connect][1]}"
result += "\n"
end
end
end
return result
end
private
def backpropFunction totalInput
# Sigmoid
return (Math.exp(totalInput)/((1+Math.exp(totalInput))**2))
# Hyperbolic
# return 1-(Math.tanh(totalInput)**2)
end
def clearNet
@network.each do |layer|
layer.each do |neuron|
neuron.reset
end
end
end
end
|
xLeachimx/NeuralNetworks
|
ruby/test.rb
|
<filename>ruby/test.rb
require_relative 'neural_net'
class TestCase
attr_accessor :input
attr_accessor :expectation
def initialize input, expectation
@input = input
@expectation = expectation
end
def expectationMatched output
return false if output.length != @expectation.length
output.each_index do |i|
return false if output[i] != @expectation[i]
end
return true
end
end
def test
net = NeuralNetwork.new([3,6,3,1])
cases = []
cases.push(TestCase.new([0,0,0],[0]))
cases.push(TestCase.new([1,0,0],[0]))
cases.push(TestCase.new([0,1,0],[0]))
cases.push(TestCase.new([1,1,0],[1]))
cases.push(TestCase.new([0,0,1],[0]))
cases.push(TestCase.new([1,0,1],[1]))
cases.push(TestCase.new([0,1,1],[1]))
cases.push(TestCase.new([1,1,1],[1]))
done = false
trials = 0
maxTrials = 1000
highest = 0.0
learningRate = 1
puts net.toString
retried = false
while !done do
learningRate = Random.rand()
trials += 1
count = 0.0
trains = []
cases.each do |c|
net.run(c.input)
# puts net.retrieveOutput
if c.expectationMatched(net.retrieveOutputRounded)
count += 1.0
else
trains.push(c)
# net.train(c.expectation,learningRate)
end
# net.train(c.expectation,learningRate)
end
accuracy = (count/cases.length)
if accuracy > highest
highest = accuracy
puts highest
end
break if count == cases.length
cases.each do |c|
net.train(c.expectation,learningRate)
end
if trials == maxTrials
net = NeuralNetwork.new([3,6,3,1])
trials = 0
puts "Retry"
end
end
puts trials
puts net.toString
end
test
|
bethesque/pact-consumer-minitest
|
spec/lib/pact/consumer/minitest_spec.rb
|
require "minitest/autorun"
require 'minitest'
require 'pact/consumer/minitest'
require 'mocha/mini_test'
require './spec/support/test'
describe Pact::Consumer::Minitest do
it "does not load RSpec" do
assert_equal(nil, defined?(::RSpec))
end
describe "hooks" do
before do
pact_test.reset
pact_test.expects(:pact_spec_hooks).returns(spec_hooks).at_least_once
spec_hooks.stubs(:before_all)
spec_hooks.stubs(:before_each)
spec_hooks.stubs(:after_each)
end
let(:spec_hooks) { Pact::Consumer::SpecHooks.new }
let(:pact_test) { TestTest.new }
describe "before_setup" do
it "ensures SpecHooks.before_all is only called once per suite" do
spec_hooks.expects(:before_all)
pact_test.before_setup
pact_test.before_setup
end
it "invokes SpecHooks.before_each" do
spec_hooks.expects(:before_each).with('TestTest')
pact_test.before_setup
end
end
describe "after_teardown" do
it "invokes SpecHooks.after_each" do
spec_hooks.expects(:after_each).with('TestTest')
pact_test.after_teardown
end
end
end
end
|
bethesque/pact-consumer-minitest
|
spec/support/client.rb
|
require 'httparty'
class Something
attr_reader :name
def initialize name
@name = name
end
def == other
other.is_a?(Something) && other.name == name
end
end
class MyServiceProviderClient
include HTTParty
base_uri 'http://my-service'
def get_something
name = JSON.parse(self.class.get("/something").body)['name']
Something.new(name)
end
end
|
bethesque/pact-consumer-minitest
|
example/zoo-app/spec/service_providers/animal_service_client_spec.rb
|
require_relative 'pact_helper'
require 'zoo_app/animal_service_client'
module ZooApp
describe AnimalServiceClient do
include Pact::Consumer::Minitest
before do
AnimalServiceClient.base_uri animal_service.mock_service_base_url
end
describe ".find_alligator_by_name" do
describe "when an alligator by the given name exists" do
before do
animal_service.given("there is an alligator named Mary").
upon_receiving("a request for an alligator").with(
method: :get,
path: '/alligators/Mary',
headers: {'Accept' => 'application/json'} ).
will_respond_with(
status: 200,
headers: {'Content-Type' => 'application/json;charset=utf-8'},
body: {name: 'Mary'}
)
end
it "returns the alligator" do
assert_equal(AnimalServiceClient.find_alligator_by_name("Mary"), ZooApp::Animals::Alligator.new(name: 'Mary'))
end
end
describe "when an alligator by the given name does not exist" do
before do
animal_service.given("there is not an alligator named Mary").
upon_receiving("a request for an alligator").with(
method: :get,
path: '/alligators/Mary',
headers: {'Accept' => 'application/json'} ).
will_respond_with(status: 404)
end
it "returns nil" do
assert_equal(AnimalServiceClient.find_alligator_by_name("Mary"), nil)
end
end
describe "when an error occurs retrieving the alligator" do
before do
animal_service.given("an error occurs retrieving an alligator").
upon_receiving("a request for an alligator").with(
method: :get,
path: '/alligators/Mary',
headers: {'Accept' => 'application/json'}).
will_respond_with(
status: 500,
headers: { 'Content-Type' => 'application/json;charset=utf-8'},
body: {error: 'Argh!!!'})
end
it "raises an error" do
error = ->{ AnimalServiceClient.find_alligator_by_name("Mary") }.must_raise AnimalServiceError
error.message.must_match /Argh/
end
end
end
end
end
|
bethesque/pact-consumer-minitest
|
spec/support/test.rb
|
module BaseTest
# Need this to support the 'super' calls
def before_setup; end
def after_teardown; end
end
module Pact
module Consumer
module Minitest
def reset
# Dirty hack to clear @@before_suite_hook_ran flag
# for tests
@@before_suite_hook_ran = false
end
end
end
end
class TestTest
include BaseTest
include Pact::Consumer::Minitest
end
module Pact
module Consumer
class SpecHooks
def after_suite
# Override - will try and actually shutdown mock servers otherwise
end
end
end
end
|
bethesque/pact-consumer-minitest
|
spec/integration/minitest_unit.rb
|
<gh_stars>1-10
require './spec/support/client.rb'
require 'minitest/autorun'
require 'minitest'
require 'pact/consumer/minitest'
Pact.service_consumer "My Other Service Consumer" do
has_pact_with "My Other Service Provider" do
mock_service :my_other_service_provider do
port 1235
end
end
end
class MyOtherServiceProviderClientTest < Minitest::Test
include Pact::Consumer::Minitest
def setup
my_other_service_provider.given("something exists").
upon_receiving("a request for something").with(method: :get, path: '/something', query: '').
will_respond_with(
status: 200,
headers: {'Content-Type' => 'application/json'},
body: {name: 'A small something'} )
MyServiceProviderClient.base_uri 'localhost:1235'
@subject = MyServiceProviderClient.new
end
def test_that_get_something_returns_something
assert_equal(@subject.get_something, Something.new('A small something'))
end
end
|
bethesque/pact-consumer-minitest
|
lib/pact/consumer/minitest/version.rb
|
module Pact
module Consumer
module Minitest
VERSION = "1.0.1"
end
end
end
|
bethesque/pact-consumer-minitest
|
tasks/test.rake
|
<filename>tasks/test.rake
require 'rake/testtask'
Rake::TestTask.new(:test) do |t|
t.pattern = "spec/lib/**/*_spec.rb"
end
Rake::TestTask.new (:integration) do |t|
t.pattern = "spec/integration/**/*.rb"
end
namespace :pact do
desc "Ensure pact file is written"
task 'test:pactfile' do
pact_path = './spec/pacts/my_service_consumer-my_service_provider.json'
FileUtils.rm_rf pact_path
Rake::Task['integration'].execute
fail "Did not find expected pact file at #{pact_path}" unless File.exist?(pact_path)
end
end
task :default => [:test, :integration, :'pact:test:pactfile']
|
bethesque/pact-consumer-minitest
|
lib/pact/consumer/minitest.rb
|
<filename>lib/pact/consumer/minitest.rb
require 'minitest'
require 'pact/consumer/minitest/version'
require 'pact/consumer'
require 'pact/consumer/spec_hooks'
module Pact
module Consumer
module Minitest
include Pact::Consumer::ConsumerContractBuilders
def pact_spec_hooks
@@pact_spec_hooks ||= Pact::Consumer::SpecHooks.new
end
module_function :pact_spec_hooks
def before_suite
unless defined?(@@before_suite_hook_ran) && @@before_suite_hook_ran
pact_spec_hooks.before_all
@@before_suite_hook_ran = true
end
end
def before_setup
super
before_suite
pact_spec_hooks.before_each self.class.name
end
def after_teardown
super
pact_spec_hooks.after_each self.class.name
end
end
end
end
after_suite_hook = Minitest.respond_to?(:after_run) ? :after_run : :after_tests
Minitest.send(after_suite_hook) do
Pact::Consumer::Minitest.pact_spec_hooks.after_suite
end
|
bethesque/pact-consumer-minitest
|
spec/integration/minitest_spec.rb
|
<reponame>bethesque/pact-consumer-minitest
require './spec/support/client.rb'
require 'minitest/autorun'
require 'minitest'
require 'pact/consumer/minitest'
Pact.service_consumer "My Service Consumer" do
has_pact_with "My Service Provider" do
mock_service :my_service_provider do
port 1234
end
end
end
describe MyServiceProviderClient do
include Pact::Consumer::Minitest
before do
MyServiceProviderClient.base_uri 'localhost:1234'
end
subject { MyServiceProviderClient.new }
describe "get_something" do
before do
my_service_provider.given("something exists").
upon_receiving("a request for something").with(method: :get, path: '/something', query: '').
will_respond_with(
status: 200,
headers: {'Content-Type' => 'application/json'},
body: {name: 'A small something'} )
end
it "returns a Something" do
assert_equal(subject.get_something, Something.new('A small something'))
end
end
end
|
bethesque/pact-consumer-minitest
|
example/zoo-app/lib/zoo_app/animal_service_client.rb
|
<filename>example/zoo-app/lib/zoo_app/animal_service_client.rb
require 'httparty'
require 'zoo_app/models/alligator'
module ZooApp
class AnimalServiceError < StandardError; end
class AnimalServiceClient
include HTTParty
base_uri 'animal-service.com'
def self.find_alligators
response = get("/alligators", :headers => {'Accept' => 'application/json'})
handle_response response do
parse_body(response).collect do | hash |
ZooApp::Animals::Alligator.new(hash)
end
end
end
def self.find_alligator_by_name name
response = get("/alligators/#{name}", :headers => {'Accept' => 'application/json'})
when_successful(response) do
ZooApp::Animals::Alligator.new(parse_body(response))
end
end
def self.when_successful response
if response.success?
yield
elsif response.code == 404
nil
else
raise AnimalServiceError.new(response.body)
end
end
def self.parse_body response
JSON.parse(response.body, {:symbolize_names => true})
end
end
end
|
worldline-spain/T21Mapping
|
T21Mapping.podspec
|
Pod::Spec.new do |s|
s.name = "T21Mapping"
s.version = "2.1.0"
s.summary = "T21Mapping is a simple class which wraps a generic mapping function."
s.author = "<NAME>"
s.platform = :ios
s.ios.deployment_target = "10.0"
s.source = { :git => "https://github.com/worldline-spain/T21Mapping.git", :tag => "2.1.0" }
s.source_files = "src/**/*.{swift}"
s.framework = "UIKit"
s.requires_arc = true
s.homepage = "https://github.com/worldline-spain/T21Mapping"
s.license = "https://github.com/worldline-spain/T21Mapping/blob/master/LICENSE"
s.swift_version = "5.0"
end
|
positronicninja/gnr_authorized_users
|
recipes/configure.rb
|
#
# Cookbook Name:: gnr_authorized_users
# Recipe:: configure
#
# Copyright 2016, Gryphon & Rook Inc
#
users = data_bag_item('ssh', 'users')
users.delete('id')
users.each do |name, ssh_key|
ssh_authorize_key name do
key ssh_key['key']
user ssh_key['user']
end
end
|
positronicninja/gnr_authorized_users
|
metadata.rb
|
name 'gnr_authorized_users'
maintainer '<NAME> Inc'
license 'All rights reserved'
description 'Configures authorized users'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
depends 'ssh_authorized_keys'
|
johngallagher/example-middleman-netlify-cms
|
config.rb
|
#Bootstrap is used to style bits of the demo. Remove it from the config, gemfile and stylesheets to stop using bootstrap
require "uglifier"
# Activate and configure extensions
# https://middlemanapp.com/advanced/configuration/#configuring-extensions
# Use '#id' and '.classname' as div shortcuts in slim
# http://slim-lang.com/
Slim::Engine.set_options shortcut: {
'#' => { tag: 'div', attr: 'id' }, '.' => { tag: 'div', attr: 'class' }
}
activate :autoprefixer do |prefix|
prefix.browsers = "last 2 versions"
end
activate :livereload
page '/*.xml', layout: false
page '/*.json', layout: false
page '/*.txt', layout: false
page "/partials/*", layout: false
page "/admin/*", layout: false
data.pages.each do |_filename, page|
# product is an array: [filename, {data}]
proxy "/#{page.fetch(:title).parameterize}/index.html", "page.html",
locals: { page: page },
layout: :page_detail,
ignore: true
end
activate :directory_indexes
helpers do
def background_image(image)
"background-image: url('" << image_path(image) << "')"
end
def nav_link(link_text, url, options = {})
options[:class] ||= "nav-link h5"
options[:class] << " active" if url == current_page.url
link_to(link_text, url, options)
end
def markdown(content)
Tilt['markdown'].new { content }.render
end
end
# Build-specific configuration
# https://middlemanapp.com/advanced/configuration/#environment-specific-settings
configure :build do
# Minify css on build
activate :minify_css
# Minify Javascript on build
activate :minify_javascript, ignore: "**/admin/**", compressor: ::Uglifier.new(mangle: true, compress: { drop_console: true }, output: {comments: :none})
# Use Gzip
activate :gzip
#Use asset hashes to use for caching
#activate :asset_hash
end
|
Betterment/site_prism
|
test_site/sections/people.rb
|
class People < SitePrism::Section
element :headline, 'h1'
element :dinosaur, '.dinosaur' #doesn't exist on the page
elements :individuals, '.person'
end
|
Betterment/site_prism
|
lib/site_prism/exceptions.rb
|
module SitePrism
class NoUrlForPage < StandardError; end
class NoUrlMatcherForPage < StandardError; end
class InvalidUrlMatcher < StandardError; end
class NoSelectorForElement < StandardError; end
class TimeoutException < StandardError; end
class TimeOutWaitingForElementVisibility < StandardError; end
class TimeOutWaitingForElementInvisibility < StandardError; end
end
|
Betterment/site_prism
|
spec/page_spec.rb
|
require 'spec_helper'
describe SitePrism::Page do
before do
allow(SitePrism::Waiter).to receive(:default_wait_time).and_return 0
end
it "should respond to load" do
expect(SitePrism::Page.new).to respond_to :load
end
it "should respond to set_url" do
expect(SitePrism::Page).to respond_to :set_url
end
it "should be able to set a url against it" do
class PageToSetUrlAgainst < SitePrism::Page
set_url "/bob"
end
page = PageToSetUrlAgainst.new
expect(page.url).to eq("/bob")
end
it "url should be nil by default" do
class PageDefaultUrl < SitePrism::Page; end
page = PageDefaultUrl.new
expect(PageDefaultUrl.url).to be_nil
expect(page.url).to be_nil
end
it "should not allow loading if the url hasn't been set" do
class MyPageWithNoUrl < SitePrism::Page; end
page_with_no_url = MyPageWithNoUrl.new
expect { page_with_no_url.load }.to raise_error
end
it "should allow loading if the url has been set" do
class MyPageWithUrl < SitePrism::Page
set_url "/bob"
end
page_with_url = MyPageWithUrl.new
expect { page_with_url.load }.to_not raise_error
end
it "should allow expansions if the url has them" do
class MyPageWithUriTemplate < SitePrism::Page
set_url "/users{/username}{?query*}"
end
page_with_url = MyPageWithUriTemplate.new
expect { page_with_url.load(username: 'foobar') }.to_not raise_error
expect(page_with_url.url(username: 'foobar', query: {'recent_posts' => 'true'})).to eq('/users/foobar?recent_posts=true')
expect(page_with_url.url(username: 'foobar')).to eq('/users/foobar')
expect(page_with_url.url).to eq('/users')
end
it "should allow to load html" do
class Page < SitePrism::Page; end
page = Page.new
expect { page.load('<html/>') }.to_not raise_error
end
it "should respond to set_url_matcher" do
expect(SitePrism::Page).to respond_to :set_url_matcher
end
it "url matcher should be nil by default" do
class PageDefaultUrlMatcher < SitePrism::Page; end
page = PageDefaultUrlMatcher.new
expect(PageDefaultUrlMatcher.url_matcher).to be_nil
expect(page.url_matcher).to be_nil
end
it "should be able to set a url matcher against it" do
class PageToSetUrlMatcherAgainst < SitePrism::Page
set_url_matcher /bob/
end
page = PageToSetUrlMatcherAgainst.new
expect(page.url_matcher).to eq(/bob/)
end
it "should raise an exception if displayed? is called before the matcher has been set" do
class PageWithNoMatcher < SitePrism::Page; end
expect { PageWithNoMatcher.new.displayed? }.to raise_error SitePrism::NoUrlMatcherForPage
end
it "should allow calls to displayed? if the url matcher has been set" do
class PageWithUrlMatcher < SitePrism::Page
set_url_matcher /bob/
end
page = PageWithUrlMatcher.new
expect { page.displayed? }.to_not raise_error
end
describe "with a full string URL matcher" do
class PageWithStringFullUrlMatcher < SitePrism::Page
set_url_matcher "https://joe:bump@bla.org:443/foo?bar=baz&bar=boof#myfragment"
end
let(:page) { PageWithStringFullUrlMatcher.new }
it "matches with all elements matching" do
swap_current_url("https://joe:bump@bla.org:443/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(true)
end
it "doesn't match with a non-matching fragment" do
swap_current_url("https://joe:bump@bla.org:443/foo?bar=baz&bar=boof#otherfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with a missing param" do
swap_current_url("https://joe:bump@bla.org:443/foo?bar=baz#myfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with wrong path" do
swap_current_url("https://joe:bump@bla.org:443/not_foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with wrong host" do
swap_current_url("https://joe:bump@blabber.org:443/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with wrong user" do
swap_current_url("https://joseph:bump@bla.org:443/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with wrong password" do
swap_current_url("https://joe:bean@bla.org:443/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with wrong scheme" do
swap_current_url("http://joe:bump@bla.org:443/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(false)
end
it "doesn't match with wrong port" do
swap_current_url("https://joe:bump@bla.org:8000/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(false)
end
end
context "with a minimal URL matcher" do
class PageWithStringMinimalUrlMatcher < SitePrism::Page
set_url_matcher "/foo"
end
let(:page) { PageWithStringMinimalUrlMatcher.new }
it "matches a complex URL by only path" do
swap_current_url("https://joe:<EMAIL>:443/foo?bar=baz&bar=boof#myfragment")
expect(page.displayed?).to eq(true)
end
end
context "with an implicit matcher" do
class PageWithImplicitUrlMatcher < SitePrism::Page
set_url "/foo"
end
let(:page) { PageWithImplicitUrlMatcher.new }
it "should default the matcher to the url" do
expect(page.url_matcher).to eq("/foo")
end
it "matches a realistic local dev URL" do
swap_current_url("http://localhost:3000/foo")
expect(page.displayed?).to eq(true)
end
end
context "with a parameterized URL matcher" do
class PageWithParameterizedUrlMatcher < SitePrism::Page
set_url_matcher "{scheme}:///foos{/id}"
end
let(:page) { PageWithParameterizedUrlMatcher.new }
describe "#displayed?" do
it "returns true without expected_mappings provided" do
swap_current_url("http://localhost:3000/foos/28")
expect(page.displayed?).to eq(true)
end
it "returns true with correct expected_mappings provided" do
swap_current_url("http://localhost:3000/foos/28")
expect(page.displayed?(id: 28)).to eq(true)
end
it "returns false with incorrect expected_mappings provided" do
swap_current_url("http://localhost:3000/foos/28")
expect(page.displayed?(id: 17)).to eq(false)
end
end
it "passes through incorrect expected_mappings from the be_displayed matcher" do
swap_current_url("http://localhost:3000/foos/28")
expect(page).not_to be_displayed id: 17
end
it "passes through correct expected_mappings from the be_displayed matcher" do
swap_current_url("http://localhost:3000/foos/28")
expect(page).to be_displayed id: 28
end
describe "#url_matches" do
it "returns mappings from the current_url" do
swap_current_url("http://localhost:3000/foos/15")
expect(page.url_matches).to eq "scheme" => "http", "id" => "15"
end
it "returns nil if current_url doesn't match the url_matcher" do
swap_current_url("http://localhost:3000/bars/15")
expect(page.url_matches).to eq nil
end
end
end
describe "with a regexp matcher" do
class PageWithRegexpUrlMatcher < SitePrism::Page
set_url_matcher %r{foos/(\d+)}
end
let(:page) { PageWithRegexpUrlMatcher.new }
describe "#url_matches" do
it "returns regexp MatchData" do
swap_current_url("http://localhost:3000/foos/15")
expect(page.url_matches).to be_kind_of(MatchData)
end
it "lets you get at the captures" do
swap_current_url("http://localhost:3000/foos/15")
expect(page.url_matches[1]).to eq "15"
end
it "returns nil if current_url doesn't match the url_matcher" do
swap_current_url("http://localhost:3000/bars/15")
expect(page.url_matches).to eq nil
end
end
end
it "should expose the page title" do
expect(SitePrism::Page.new).to respond_to :title
end
def swap_current_url(url)
allow(page).to receive(:page).and_return(double(current_url: url))
end
end
|
Betterment/site_prism
|
spec/sections_spec.rb
|
require 'spec_helper'
describe SitePrism::Page do
it "should respond to sections" do
expect(SitePrism::Page).to respond_to :sections
end
it "should create a matching existence method for sections" do
class SomePageWithSectionsThatNeedsTestingForExistence < SitePrism::Section
end
class YetAnotherPageWithSections < SitePrism::Page
section :some_things, SomePageWithSectionsThatNeedsTestingForExistence, '.bob'
end
page = YetAnotherPageWithSections.new
expect(page).to respond_to :has_some_things?
end
end
|
Betterment/site_prism
|
features/support/env.rb
|
<reponame>Betterment/site_prism
unless ENV['CI']
require 'simplecov'
SimpleCov.start
end
require 'capybara'
require 'capybara/dsl'
require 'capybara/cucumber'
require 'selenium-webdriver'
require 'rspec/collection_matchers'
$: << './test_site'
$: << './lib'
require 'site_prism'
require 'test_site'
require 'sections/people'
require 'sections/no_element_within_section'
require 'sections/container_with_element'
require 'sections/child'
require 'sections/parent'
require 'sections/search_result'
require 'pages/my_iframe'
require 'pages/home'
require 'pages/dynamic_page'
require 'pages/no_title'
require 'pages/page_with_people'
require 'pages/redirect'
require 'pages/section_experiments'
Capybara.configure do |config|
config.default_driver = :selenium
config.javascript_driver = :selenium
config.run_server = false
config.default_selector = :css
config.default_wait_time = 5
config.app_host = "file://" + File.dirname(__FILE__) + "/../../test_site/html"
#capybara 2.1 config options
config.match = :prefer_exact
config.ignore_hidden_elements = false
end
Capybara.register_driver :selenium do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
profile["browser.cache.disk.enable"] = false
profile["browser.cache.memory.enable"] = false
Capybara::Selenium::Driver.new(app, :browser => :firefox, profile: profile)
end
SitePrism.configure do |config|
config.use_implicit_waits = false
end
|
Betterment/site_prism
|
test_site/pages/section_experiments.rb
|
class TestSectionExperiments < SitePrism::Page
set_url '/section_experiments.htm'
section :parent_section, Parent, '.parent-div'
sections :search_results, SearchResult, '.search-results .search-result'
section :anonymous_section, '.anonymous-section' do
element :title, 'h1'
def upcase_title_text
title.text.upcase
end
end
sections :anonymous_sections, 'ul.anonymous-sections li' do
element :title, 'h1'
def downcase_title_text
title.text.downcase
end
end
end
|
Betterment/site_prism
|
test_site/pages/my_iframe.rb
|
class MyIframe < SitePrism::Page
element :some_text, 'span#some_text_in_an_iframe'
end
|
Betterment/site_prism
|
features/step_definitions/page_element_interaction_steps.rb
|
<gh_stars>0
Then /^I can get the page title$/ do
expect(@test_site.home.title).to eq "Home Page"
end
Then /^the page has no title$/ do
expect(@test_site.no_title.title).to eq ""
end
Then /^the page does not have element$/ do
@test_site.home.has_no_nonexistent_element?
expect(@test_site.home).to have_no_nonexistent_element
end
Then /^the page does not have elements$/ do
@test_site.home.has_no_nonexistent_elements?
expect(@test_site.home).to have_no_nonexistent_elements
end
Then /^I can see the welcome header$/ do
expect(@test_site.home).to have_welcome_header
expect(@test_site.home.welcome_header.text).to eq "Welcome"
end
Then /^I can see the welcome header with capybara query options$/ do
expect(@test_site.home).to have_welcome_header
expect(@test_site.home).to have_welcome_header :text => "Welcome"
expect { @test_site.home.welcome_header :text => "Welcome" }.to_not raise_error
end
Then /^the welcome header is not matched with invalid text$/ do
expect(@test_site.home).to have_no_welcome_header(:text => "This Doesn't Match!")
end
Then /^I can see the welcome message$/ do
expect(@test_site.home).to have_welcome_message
expect(@test_site.home.welcome_message.text).to eq "This is the home page, there is some stuff on it"
end
Then /^I can see the welcome message with capybara query options$/ do
expect(@test_site.home).to have_welcome_message
expect(@test_site.home).to have_welcome_message :text => "This is the home page, there is some stuff on it"
end
Then /^I can see the go button$/ do
expect(@test_site.home).to have_go_button
@test_site.home.go_button.click
end
Then /^I can see the link to the search page$/ do
expect(@test_site.home).to have_link_to_search_page
expect(@test_site.home.link_to_search_page['href']).to include 'search.htm'
end
Then /^I cannot see the missing squirrel$/ do
using_wait_time(0) do
expect(@test_site.home).to_not have_squirrel
end
end
Then /^I cannot see the missing other thingy$/ do
using_wait_time(0) do
expect(@test_site.home).not_to have_other_thingy
end
end
Then /^I can see the group of links$/ do
expect(@test_site.home).to have_lots_of_links
end
Then /^I can get the group of links$/ do
expect(@test_site.home.lots_of_links.collect {|link| link.text}).to eq ['a', 'b', 'c']
end
Then /^all expected elements are present$/ do
expect(@test_site.home).not_to be_all_there
end
Then /^an exception is raised when I try to deal with an element with no selector$/ do
expect {@test_site.no_title.has_element_without_selector?}.to raise_error SitePrism::NoSelectorForElement
expect {@test_site.no_title.element_without_selector}.to raise_error SitePrism::NoSelectorForElement
expect {@test_site.no_title.wait_for_element_without_selector}.to raise_error SitePrism::NoSelectorForElement
end
Then /^an exception is raised when I try to deal with elements with no selector$/ do
expect {@test_site.no_title.has_elements_without_selector?}.to raise_error SitePrism::NoSelectorForElement
expect {@test_site.no_title.elements_without_selector}.to raise_error SitePrism::NoSelectorForElement
expect {@test_site.no_title.wait_for_elements_without_selector}.to raise_error SitePrism::NoSelectorForElement
end
When /^I wait until a particular element is visible$/ do
@test_site.home.wait_until_some_slow_element_visible
end
When /^I wait for a specific amount of time until a particular element is visible$/ do
@test_site.home.wait_until_shy_element_visible(5)
end
Then /^the previously invisible element is visible$/ do
expect(@test_site.home).to have_shy_element
end
Then /^I get a timeout error when I wait for an element that never appears$/ do
expect {@test_site.home.wait_until_invisible_element_visible(1)}.to raise_error SitePrism::TimeOutWaitingForElementVisibility
end
When /^I wait while for an element to become invisible$/ do
@test_site.home.wait_until_retiring_element_invisible
end
Then /^the previously visible element is invisible$/ do
expect(@test_site.home.retiring_element).not_to be_visible
end
When /^I wait for a specific amount of time until a particular element is invisible$/ do
@test_site.home.wait_until_retiring_element_invisible(5)
end
Then /^I get a timeout error when I wait for an element that never disappears$/ do
expect {@test_site.home.wait_until_welcome_header_invisible(1)}.to raise_error SitePrism::TimeOutWaitingForElementInvisibility
end
Then /^I do not wait for an nonexistent element when checking for invisibility$/ do
start = Time.new
@test_site.home.wait_until_nonexistent_element_invisible(10)
expect(Time.new - start).to be < 1
end
When /^I wait for invisibility of an element embedded into a section which is removed$/ do
@test_site.home.remove_container_with_element_btn.click
end
Then /^I receive an error when a section with the element I am waiting for is removed$/ do
expect {@test_site.home.container_with_element.wait_until_embedded_element_invisible}.to raise_error Capybara::ElementNotFound
end
Then /^I can wait a variable time for elements to appear$/ do
@test_site.home.wait_for_lots_of_links
@test_site.home.wait_for_lots_of_links(0.1)
end
Then /^I can wait a variable time and pass specific parameters$/ do
@test_site.home.wait_for_lots_of_links(0.1, count: 2)
Capybara.using_wait_time 0.3 do
# intentionally wait and pass nil to force this to cycle
expect(@test_site.home.wait_for_lots_of_links(nil, count: 19810814)).to be false
end
end
|
Betterment/site_prism
|
lib/site_prism/waiter.rb
|
module SitePrism
class Waiter
def self.wait_until_true(wait_time_seconds=default_wait_time)
start_time = Time.now
loop do
return true if yield
break unless Time.now - start_time <= wait_time_seconds
sleep(0.05)
end
raise SitePrism::TimeoutException.new, "Timed out while waiting for block to return true."
end
def self.default_wait_time
@@default_wait_time
end
private
@@default_wait_time = Capybara.default_wait_time
end
end
|
Betterment/site_prism
|
spec/spec_helper.rb
|
<gh_stars>1-10
require 'capybara'
require 'capybara/dsl'
require 'selenium-webdriver'
$: << './test_site'
$: << './lib'
require 'site_prism'
require 'test_site'
require 'sections/people'
require 'sections/no_element_within_section'
require 'sections/container_with_element'
require 'pages/my_iframe'
require 'pages/home'
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = [:should, :expect]
end
end
class MyTest
def response
[200, {'Content-Length' => '9'}, ['MyTestApp']]
end
end
class MyTestApp
def call(env)
MyTest.new.response
end
end
Capybara.app = MyTestApp.new
|
Betterment/site_prism
|
lib/site_prism/version.rb
|
module SitePrism
VERSION = "2.6"
end
|
Betterment/site_prism
|
spec/element_spec.rb
|
<filename>spec/element_spec.rb
require 'spec_helper'
describe SitePrism::Page do
it "should respond to element" do
expect(SitePrism::Page).to respond_to :element
end
it "element method should generate existence check method" do
class PageWithElement < SitePrism::Page
element :bob, 'a.b c.d'
end
page = PageWithElement.new
expect(page).to respond_to :has_bob?
end
it "element method should generate method to return the element" do
class PageWithElement < SitePrism::Page
element :bob, 'a.b c.d'
end
page = PageWithElement.new
expect(page).to respond_to :bob
end
it "element method without css should generate existence check method" do
class PageWithElement < SitePrism::Page
element :thing, 'input#nonexistent'
end
page = PageWithElement.new
expect(page).to respond_to :has_no_thing?
end
it "should be able to wait for an element" do
class PageWithElement < SitePrism::Page
element :some_slow_element, 'a.slow'
end
page = PageWithElement.new
expect(page).to respond_to :wait_for_some_slow_element
end
it "should know if all mapped elements are on the page" do
class PageWithAFewElements < SitePrism::Page
element :bob, 'a.b c.d'
end
page = PageWithAFewElements.new
expect(page).to respond_to :all_there?
end
it "element method with xpath should generate existence check method" do
class PageWithElement < SitePrism::Page
element :bob, :xpath, '//a[@class="b"]//c[@class="d"]'
end
page = PageWithElement.new
expect(page).to respond_to :has_bob?
end
it "element method with xpath should generate method to return the element" do
class PageWithElement < SitePrism::Page
element :bob, :xpath, '//a[@class="b"]//c[@class="d"]'
end
page = PageWithElement.new
expect(page).to respond_to :bob
end
it "should be able to wait for an element defined with xpath selector" do
class PageWithElement < SitePrism::Page
element :some_slow_element, :xpath, '//a[@class="slow"]'
end
page = PageWithElement.new
expect(page).to respond_to :wait_for_some_slow_element
end
it "should know if all mapped elements defined by xpath selector are on the page" do
class PageWithAFewElements < SitePrism::Page
element :bob, :xpath, '//a[@class="b"]//c[@class="d"]'
end
page = PageWithAFewElements.new
expect(page).to respond_to :all_there?
end
end
|
Betterment/site_prism
|
features/step_definitions/wait_steps.rb
|
<reponame>Betterment/site_prism
Then /^when I wait for the element that takes a while to appear$/ do
@test_site.home.wait_for_some_slow_element
end
Then /^I successfully wait for it to appear$/ do
expect(@test_site.home).to have_some_slow_element
end
When /^I wait for a specifically short amount of time for an element to appear$/ do
@test_site.home.wait_for_some_slow_element(2)
end
Then /^the element I am waiting for doesn't appear in time$/ do
expect(@test_site.home).to_not be_all_there
end
Then /^when I wait for the section element that takes a while to appear$/ do
@test_site.section_experiments.parent_section.wait_for_slow_section_element
end
Then /^I successfully wait for the slow section element to appear$/ do
expect(@test_site.section_experiments.parent_section).to have_slow_section_element
end
|
Betterment/site_prism
|
lib/site_prism/page.rb
|
module SitePrism
class Page
include Capybara::DSL
include ElementChecker
extend ElementContainer
def page
@page || Capybara.current_session
end
def load(expansion_or_html = {})
if expansion_or_html.is_a? String
@page = Capybara.string(expansion_or_html)
else
expanded_url = url(expansion_or_html)
raise SitePrism::NoUrlForPage if expanded_url.nil?
visit expanded_url
end
end
def displayed?(*args)
expected_mappings = args.last.is_a?(::Hash) ? args.pop : {}
seconds = args.length > 0 ? args.first : Waiter.default_wait_time
raise SitePrism::NoUrlMatcherForPage if url_matcher.nil?
begin
Waiter.wait_until_true(seconds) { url_matches?(expected_mappings) }
rescue SitePrism::TimeoutException => e
return false
end
end
def url_matches(seconds = Waiter.default_wait_time)
if displayed?(seconds)
if url_matcher.kind_of?(Regexp)
url_matcher.match(page.current_url)
elsif url_matcher.respond_to?(:to_str)
matcher_template.mappings(page.current_url)
else
raise SitePrism::InvalidUrlMatcher
end
end
end
def self.set_url page_url
@url = page_url.to_s
end
def self.set_url_matcher page_url_matcher
@url_matcher = page_url_matcher
end
def self.url
@url
end
def self.url_matcher
@url_matcher || url
end
def url(expansion = {})
return nil if self.class.url.nil?
Addressable::Template.new(self.class.url).expand(expansion).to_s
end
def url_matcher
self.class.url_matcher
end
def secure?
!current_url.match(/^https/).nil?
end
private
def find_first *find_args
find *find_args
end
def find_all *find_args
all *find_args
end
def element_exists? *find_args
has_selector? *find_args
end
def element_does_not_exist? *find_args
has_no_selector? *find_args
end
def url_matches?(expected_mappings = {})
if url_matcher.kind_of?(Regexp)
!(page.current_url =~ url_matcher).nil?
elsif url_matcher.respond_to?(:to_str)
matcher_template.matches?(page.current_url, expected_mappings)
else
raise SitePrism::InvalidUrlMatcher
end
end
def matcher_template
@addressable_url_matcher ||= AddressableUrlMatcher.new(url_matcher)
end
end
end
|
diasks2/pragmatic_segmenter_gui
|
pragmatic_segmenter.rb
|
# encoding: utf-8
Shoes.setup do
gem 'pragmatic_segmenter', '0.3.3'
end
require 'pragmatic_segmenter'
LANGUAGE_CODES = {
'en' => 'English',
'de' => 'German',
'es' => 'Spanish',
'fr' => 'French',
'it' => 'Italian',
'ja' => 'Japanese',
'el' => 'Greek',
'ru' => 'Russian',
'ar' => 'Arabic',
'am' => 'Amharic',
'hi' => 'Hindi',
'hy' => 'Armenian',
'fa' => 'Persian',
'my' => 'Burmese',
'ur' => 'Urdu',
'nl' => 'Dutch',
'pl' => 'Polish',
'zh' => 'Chinese',
nil => 'Other'
}
Shoes.app(title: "Pragmatic Segmenter") do
background "#fff"
border("#F27A24", strokewidth: 6)
stack(margin: 12) do
flow do
para "Choose the UTF-8 text file you would like to segment:"
end
flow do
@select_file = button "Choose File"
end
flow do
para "Enter the file path and name of the new file that will be created (i.e. /Desktop/segmented_text.txt):"
end
flow do
@file_output_path = edit_line width: 500
end
flow do
para "Select a Language:"
end
flow do
@language = list_box items: LANGUAGE_CODES.values
end
flow do
@push = button "Create Segmented File"
end
@note = para ''
@push.click do
@note.replace ''
@text = File.open(@file_input_path, "r:UTF-8", &:read)
File.open(@file_output_path.text(), 'w') { |f| f.write(PragmaticSegmenter::Segmenter.new(text: @text, language: LANGUAGE_CODES.key(@language.text())).segment.join("\n")) }
@note.replace "Finished"
end
@select_file.click do
@file_input_path = ask_open_file
end
end
end
|
citrusbyte/openshift-sinatra-redis
|
app.rb
|
<filename>app.rb
require 'sinatra'
require 'redis'
configure do
REDIS_HOST = ENV['OPENSHIFT_REDIS_HOST']
REDIS_PORT = ENV['OPENSHIFT_REDIS_PORT']
REDIS_PW = ENV['REDIS_PASSWORD']
REDIS = Redis.new(:host => REDIS_HOST, :port => REDIS_PORT, :password => <PASSWORD>)
end
get '/' do
"the time where this server lives is #{Time.now}
<br /><br />check out your <a href=\"/agent\">user_agent</a>
<br />Check out the load <a href=\"/count\">count</a>"
end
get '/agent' do
"you're using #{request.user_agent}<br />
Return to <a href=\"/\">top</a>"
end
get '/count' do
REDIS.incr("count")
count = REDIS.get("count").to_s
"This page has been loaded #{count} times<br />
Return to <a href=\"/\">top</a>"
end
|
asfktz/rails-sample-app
|
app/helpers/application_helper.rb
|
<filename>app/helpers/application_helper.rb
module ApplicationHelper
def full_title(page_title = '')
base_title = 'Ruby on Rails Tutorial Sample App'
unless page_title.empty?
return page_title + ' | ' + base_title
end
return base_title
end
end
|
asfktz/rails-sample-app
|
test/models/user_test.rb
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(
name: 'bob',
email: '<EMAIL>',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
)
end
test "should be valid" do
assert @user.valid?
end
test "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6;
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5;
assert_not @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid?
end
test "email should not be too long" do
def create_email(length:)
address = "@example.com"
name = "a" * (length - address.length)
name + address
end
@user.email = create_email(length: 255)
assert @user.valid?
@user.email = create_email(length: 256)
assert_not @user.valid?
end
test "email validation should accept valid addresses" do
valid_addresses = %w[
<EMAIL>
<EMAIL>
<EMAIL>-<EMAIL>
<EMAIL>
<EMAIL>
]
valid_addresses.each do |email|
@user.email = email
assert @user.valid?, "#{email.inspect} should be valid"
end
end
test "email validation should reject invalid addresses" do
valid_addresses = %w[
<EMAIL>
user_at_foo.org
<EMAIL>.
<EMAIL>
<EMAIL>@bar+baz.com
]
valid_addresses.each do |email|
@user.email = email
assert_not @user.valid?, "#{email.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
end
|
asfktz/rails-sample-app
|
try.rb
|
class Person
def greet
puts 'koko'
end
end
class Bob < Person
10.times do
greet
end
end
|
KritR/Bitcoin-Spigot
|
main.rb
|
<gh_stars>0
#!/usr/bin/env ruby
#################################
# INCLUDING REQUIREMENTS #
#################################
require 'rubygems'
require 'watir-webdriver'
require 'io/console'
require 'open-uri'
require 'tmpdir'
require 'rmagick'
require 'base64'
require 'net/http'
require 'rtesseract'
require 'CSV'
require 'nokogiri'
require 'timeout'
include Magick
#################################
#DEFINING METHODS AND VARIABLES #
#################################
# DEFINING BIG VARIABLES
@url = 'faucet.bitcoinzebra.com'
$proxyList = []
$addressList = []
$b
#$doc = Nokogiri::HTML(open("http://www.socks-proxy.net/"))
$updateTime = Time.now
def superLoopedyLooper
#updateProxies
CSV.foreach('bitcoinaddresses.csv') do |line|
$addressList << line[1]
end
CSV.foreach('proxyList.csv') do |line|
$proxyList << line[0]
end
while true do
for iter in 0..$proxyList.length
puts iter
proxyAddr = $proxyList[iter]
btcAddress = $addressList[iter]
profile = Selenium::WebDriver::Firefox::Profile.new
profile['network.proxy.socks_version'] = 4
proxy = Selenium::WebDriver::Proxy.new(:socks => proxyAddr)
profile.proxy = proxy
# You have to do a little more to use the specific profile
driver = Selenium::WebDriver.for :firefox, :profile => profile
$b = Watir::Browser.new(driver)
$b.goto (@url + "/preferences")
countr = 0
ready = false
while(!ready and countr<10)
ready = $b.title.chomp == 'Bitcoin Zebra - Preferences'
puts ready
countr += 1
puts countr
sleep(1)
end
if !ready
$b.close
next
end
=begin
begin
Timeout::timeout(10){
while true
onPage = $b.title.chomp == 'Bitcoin Zebra - Preferences'
puts onPage
if(onPage)
break
end
sleep 1
end
}
rescue Timeout::Error => msg
puts $b.title
puts $b.title.chomp == 'Bitcoin Zebra - Preferences'
puts "Recovered from Timeout"
$b.close
next
end
=end
sleep 1 until $b.select_list(:id => "BodyPlaceholder_CaptchaTypeDropdown").exists?
$b.select_list(:id => "BodyPlaceholder_CaptchaTypeDropdown").select "Recaptcha"
$b.input(:id => 'BodyPlaceholder_UpdateButton').click
# $b.cookies.add("user",cookie,{path: '/',domain: 'faucet.bitcoinzebra.com'})
sleep 5
$b.goto @url
# cookie = "BitcoinAddress="+btcAddress+"&CaptchaType=0"
# puts cookie
# $b.cookies.add('user',cookie,:secure => false, :path => "/", :domain => 'faucet.bitcoinzebra.com')
#$b.cookies.add("user",cookie,:path => '/',:domain => 'faucet.bitcoinzebra.com')
# $b.refresh
=begin
begin
Timeout::timeout(10) do
sleep 1 until ($b.title == 'Bitcoin Zebra - Free Bitcoin Faucet')
end
rescue
puts "RECOVERED"
$b.close
next
end
=end
countr = 0
ready = false
while(!ready and countr<10)
ready = $b.title.chomp == 'Bitcoin Zebra - Free Bitcoin Faucet'
puts ready
countr += 1
puts countr
sleep(1)
end
if !ready
$b.close
next
end
# COMPLETE THE ADDRESS FILLUP
#sleep 1 until $b.text_field(:id => 'BodyPlaceholder_BitcoinAddressTextbox').exists?
$b.text_field(:id => 'BodyPlaceholder_BitcoinAddressTextbox').set(btcAddress)
sleep 1 until $b.input(:id => 'feedButton').exists?
$b.input(:id => 'feedButton').click
# DEAL WITH THE CAPTCHAs
sleep 1 until $b.image(:id => "recaptcha_challenge_image").exists?
puts " We're ready for the Captcha "
left = $b.execute_script("return $('#recaptcha_challenge_image').offset().left").to_i
top = $b.execute_script("return $('#recaptcha_challenge_image').offset().top").to_i
height = $b.execute_script("return $('#recaptcha_challenge_image').innerHeight()").to_i
width = $b.execute_script("return $('#recaptcha_challenge_image').innerWidth()").to_i
screenshot = Image.read_inline($b.screenshot.base64).first
captcha_image = screenshot.crop(left, top, width, height).write("ss_crop.png")
=begin
if checkForText height,width,captcha_image
# INSERT TESSERACT SOLVER HERE
captchaSolution = solveUsingOCR screenshot
if(captchaSolution.empty? or not (captchaSolution.downcase.include? "enter" or captchaSolution.downcase.include? "answer") )
captchaSolution = solveUsingService captcha_image
elsif captchaSolution.downcase.include? "="
captchaSolution.split("=")[2]
elsif captchaSolution.downcase.include? "answer"
captchaSolution.downcase.split("answer").[2].delete(":","=").chomp
end
else
captchaSolution = solveUsingService captcha_image
end
=end
captchaSolution = solveUsingService captcha_image
sleep 1 until $b.text_field(:id => 'recaptcha_response_field').exists?
$b.text_field(:id => 'recaptcha_response_field').set(captchaSolution)
submit
end
if ($updateTime+(60*60) <=> Time.now) < 0
sleep 10 until (($updateTime+(60*60) <=> Time.now) < 0)
end
$updateTime = Time.now
end
end
=begin
def updateProxies
$doc = Nokogiri::HTML(open("http://www.socks-proxy.net/"))
newProxies = []
for x in 0..200
if x % 8 == 0
newProxies << $doc.xpath("//td")[x].text + ":" + $doc.xpath("//td")[x+1].text
else
next
end
end
newProxies.delete_if {|proxy| $usedProxies.include? proxy }
$proxyList.clear
$proxyList.concat newProxies
end
=end
#SETTING UP ENVIRONMENT
=begin
def checkForText (width, height, image)
for x in 1..width
for y in (height-25)..height
color = image.pixel_color(x,y)
red = color.red/257
green = color.green/257
blue = color.blue/257
max = [red,green,blue].max
min = [red,green,blue].min
if(max-min > 10)
#puts red
#puts green
#puts blue
#puts (x.to_s + " : " + y.to_s)
#puts "false"
return false
end
end
end
return true
end
def solveUsingOCR (image)
image.crop(left,top+height-25,width,25).contrast(1).sharpen(1).level(0.1,0.4,).write("ss_double_crop.png")
#x..write "meepo.png"
rimg = RTesseract.new("ss_double_crop.png")
puts rimg
return rimg.to_s
end
=end
def solveUsingService (image)
uri = URI('http://2captcha.com/in.php')
captcha_base64 = Base64.encode64(image.to_blob)
req = Net::HTTP::Post.new(uri)
req.set_form_data('method' => 'base64', 'key' => @apiKey, 'body' => captcha_base64)
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
captchaID = ''
case res
when Net::HTTPSuccess, Net::HTTPRedirection
captchaID = res.body.partition('|')[2]
else
res.value
# INSERT ERROR CODE HERE
end
resURI = URI('http://2captcha.com/res.php')
params = { :key => @apiKey, :action => 'get', :id => captchaID}
resURI.query = URI.encode_www_form(params)
solved = false
until solved do
res = Net::HTTP.get_response(resURI)
if res.is_a?(Net::HTTPSuccess) and (res.body != 'CAPCHA_NOT_READY')
puts res.body
solved = true
else
sleep 2
end
end
return res.body.partition('|')[2]
end
def submit
sleep 1 until $b.input(:class => 'submit-button').exists?
$b.input(:class => 'submit-button').click
sleep 2
$b.close
end
#################################
# END OF METHOD DECLARATION #
#################################
#################################
# RUNNING OF ACTUAL SCRIPT #
#################################
superLoopedyLooper
#submit
#################################
# END OF ACTUAL SCRIPT #
#################################
|
MatheusFalcao/adm
|
lib/tasks/creat_admin.rake
|
<gh_stars>0
namespace :creat_admin do
@usr = User.new
@usr.email = "<EMAIL>"
@usr.password = "<PASSWORD>"
@usr.save
end
|
MatheusFalcao/adm
|
config/routes.rb
|
Rails.application.routes.draw do
# Back admin routes start
namespace :admin do
resources :users
# Admin root
root to: 'application#index'
end
# Back admin routes end
# Front routes start
devise_for :users, only: [:session, :registration], path: 'session',
path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }
# Application root
root to: 'application#home'
# Front routes end
get "contact" => 'application#contact'
get "noslider" => 'application#noslider'
end
|
bufferapp/buffer-ruby-deprecated
|
buffer.gemspec
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/buffer/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.description = "Buffer API wrapper for Ruby"
gem.summary = "Buffer API wrapper for Ruby"
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "buffer"
gem.require_paths = ["lib"]
gem.version = Buffer::VERSION
gem.add_dependency "faraday"
gem.add_dependency "multi_json"
gem.add_dependency "i18n"
gem.add_dependency "active_support"
gem.add_development_dependency "rspec", "~> 2.7"
gem.add_development_dependency "simplecov"
gem.add_development_dependency "webmock"
end
|
bufferapp/buffer-ruby-deprecated
|
spec/buffer_spec.rb
|
require 'helper'
describe Buffer::Client do
describe 'new' do
it 'accepts a token' do
client = Buffer::Client.new 'some_token'
client.token.should eq('some_token')
end
it 'rejects an integer token' do
lambda { client = Buffer::Client.new 123 }.should raise_error
end
it 'rejects an array token' do
lambda { client = Buffer::Client.new [123, 'hello'] }.should raise_error
end
it 'rejects an hash token' do
lambda { client = Buffer::Client.new :test => 123 }.should raise_error
end
end
describe 'api' do
subject do
Buffer::Client.new 'some_token'
end
it 'is a method' do
subject.respond_to?(:api).should be_true
end
describe 'api :get' do
before do
stub_get('user.json').
with(:query => {:access_token => 'some_token'}).
to_return(
:body => fixture('user.json'),
:headers => {:content_type => 'application/json; charset=utf-8'})
stub_get('non_existent.json').
with(:query => {:access_token => 'some_token'}).
to_return(
:body => '',
:headers => {:content_type => 'application/json; charset=utf-8'})
stub_get('mangled.json').
with(:query => {:access_token => 'some_token'}).
to_return(
:body => '{dfpl:[}233]',
:headers => {:content_type => 'application/json; charset=utf-8'})
end
it 'makes correct request to user.json with access token' do
subject.api :get, 'user.json'
a_get('user.json').
with(:query => {:access_token => 'some_token'}).
should have_been_made
end
it 'makes correct request when passed user' do
subject.api :get, 'user'
a_get('user.json').
with(:query => {:access_token => 'some_token'}).
should have_been_made
end
it 'returns correct parsed object' do
res = subject.api :get, 'user'
target = begin
MultiJson.load fixture('user.json')
end
res.should eq(target)
end
it 'returns nil from non existent endpoint' do
res = subject.api :get, 'non_existent'
res.should eq(nil)
end
it 'returns nil from mangled data' do
res = subject.api :get, 'mangled'
res.should eq(nil)
end
end
describe 'api :post' do
before do
stub_post('updates/create.json').
with(
:query => {:access_token => 'some_token'},
:body => {
"media"=>{"link"=>"http://google.com"},
"profile_ids"=>[
"4eb854340acb04e870000010",
"4eb9276e0acb04bb81000067"],
"text"=>"This is an example update"}).
to_return(
:body => fixture('success.json'),
:status => 200)
stub_post('updates/creatify.json').
with(
:query => {:access_token => 'some_token'},
:body => {
"media"=>{"link"=>"http://google.com"},
"profile_ids"=>[
"4eb854340acb04e870000010",
"4eb9276e0acb04bb81000067"],
"text"=>"This is an example update"}).
to_return(
:status => 200)
stub_request(
:post,
"https://api.bufferapp.com/1/updates/create.json?access_token=some_token").
with(:body => {"profile_ids"=>["fdf", "1"], "text"=>["a237623", "asb"]},
:headers => {
'Accept'=>'*/*',
'Content-Type'=>'application/x-www-form-urlencoded',
'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})
end
it 'should make the correct POST to updates/create.json' do
subject.api :post,
'updates/create.json',
:text => "This is an example update",
:profile_ids => [
'4eb854340acb04e870000010',
'4eb9276e0acb04bb81000067'],
:media => {:link => "http://google.com"}
a_post('updates/create.json').
with(
:query => {:access_token => 'some_token'},
:body => fixture_contents('create_body.txt')).
should have_been_made
end
it 'should return a correctly parsed object' do
res = subject.api :post,
'updates/create.json',
:text => "This is an example update",
:profile_ids => [
'4eb854340acb04e870000010',
'4eb9276e0acb04bb81000067'],
:media => {:link => "http://google.com"}
res['success'].should be_true
end
it 'should return nil from non existent endpoint' do
res = subject.api :post,
'updates/creatify.json',
:text => "This is an example update",
:profile_ids => [
'4eb854340acb04e870000010',
'4eb9276e0acb04bb81000067'],
:media => {:link => "http://google.com"}
res.should eq(nil)
end
it 'should return nil when passes crap' do
res = subject.api :post,
'updates/create.json',
:text => [:a237623, 'asb'],
:profile_ids => ['fdf', '1']
res.should eq(nil)
end
end
end
describe 'get' do
subject do
Buffer::Client.new 'some_token'
end
it 'is a method' do
subject.respond_to?(:get).should be_true
end
before do
stub_get('user.json').
with(:query => {:access_token => 'some_token'}).
to_return(
:body => fixture('user.json'),
:headers => {:content_type => 'application/json; charset=utf-8'})
end
it 'makes correct request to user.json with access token' do
subject.get 'user.json'
a_get('user.json').
with(:query => {:access_token => 'some_token'}).
should have_been_made
end
it 'makes correct request when passed user' do
subject.get 'user'
a_get('user.json').
with(:query => {:access_token => 'some_token'}).
should have_been_made
end
end
describe 'post' do
subject do
Buffer::Client.new 'some_token'
end
it 'is a method' do
subject.respond_to?(:post).should be_true
end
before do
stub_post('updates/create.json').
with(
:query => {:access_token => 'some_token'},
:body => {
"media"=>{"link"=>"http://google.com"},
"profile_ids"=>[
"4eb854340acb04e870000010",
"4eb9276e0acb04bb81000067"],
"text"=>"This is an example update"}).
to_return(
:body => fixture('success.json'),
:status => 200)
end
it 'should make the correct POST to updates/create.json' do
subject.post 'updates/create.json',
:text => "This is an example update",
:profile_ids => ['4eb854340acb04e870000010', '4eb9276e0acb04bb81000067'],
:media => {:link => "http://google.com"}
a_post('updates/create.json').
with(
:query => {:access_token => 'some_token'},
:body => fixture_contents('create_body.txt')).
should have_been_made
end
end
end
describe Buffer::User do
describe 'new' do
it 'accepts a token' do
user = Buffer::User.new 'some_token'
user.token.should eq('some_token')
end
it 'rejects an integer token' do
lambda { user = Buffer::User.new 123 }.should raise_error
end
it 'rejects an array token' do
lambda { user = Buffer::User.new [123, 'hello'] }.should raise_error
end
it 'rejects an hash token' do
lambda { user = Buffer::User.new :test => 123 }.should raise_error
end
end
describe 'helpers' do
subject do
Buffer::User.new 'some_token'
end
before do
stub_get('user.json').
with(:query => {:access_token => 'some_token'}).
to_return(
:body => fixture('user.json'),
:headers => {:content_type => 'application/json; charset=utf-8'})
end
it 'respond with correct id' do
subject.id.should eq('1234')
end
it 'do not respond to eye_color' do
lambda { color = subject.eye_color }.should raise_error
end
it 'respond to get' do
lambda { user = subject.get 'user' }.should_not raise_error
end
end
describe 'cache' do
subject do
Buffer::User.new 'some_token'
end
before do
stub_get('user.json').
with(:query => {:access_token => 'some_token'}).
to_return(
:body => fixture('user.json'),
:headers => {:content_type => 'application/json; charset=utf-8'})
end
describe 'access' do
before do
subject.id
end
it 'is used after accessing id once' do
id = subject.id
a_get('user.json').
should_not have_been_made
end
end
describe 'invalidation' do
before do
subject.id
end
it 'forces server access' do
subject.invalidate
id = subject.id
a_get('user.json').
with(:query => {:access_token => '<PASSWORD>'}).
should have_been_made.times(2)
end
end
end
end
|
bufferapp/buffer-ruby-deprecated
|
spec/helper.rb
|
<gh_stars>0
require 'simplecov'
SimpleCov.start do
add_filter 'spec'
end
require 'rspec'
require 'webmock/rspec'
require 'multi_json'
require 'buffer'
# Taken from https://github.com/sferik/twitter/blob/master/spec/helper.rb
# for stubbing & mocking HTTP requests
def endpoint
'https://api.bufferapp.com/1/'
end
def a_get(path)
a_request(:get, endpoint + path)
end
def a_post(path)
a_request(:post, endpoint + path)
end
def stub_get(path)
stub_request(:get, endpoint + path)
end
def stub_post(path)
stub_request(:post, endpoint + path)
end
def fixture_path
File.expand_path("../fixtures", __FILE__)
end
def fixture(file)
File.new(fixture_path + '/' + file)
end
def fixture_contents(file)
File.open(fixture_path + '/' + file) { |f| f.read }
end
|
bufferapp/buffer-ruby-deprecated
|
lib/buffer.rb
|
<reponame>bufferapp/buffer-ruby-deprecated<gh_stars>0
require 'buffer/version'
require 'faraday'
require 'multi_json'
require 'addressable/uri'
require 'active_support/core_ext'
module Buffer
class Client
attr_reader :token
# Initialize a new Buffer::Client
#
# Also sets up a Faraday connection object
#
# token - string access token for use with all API requests
def initialize(token)
if token.kind_of? String
@token = token
else
raise ArgumentError, "token must be a string"
end
@conn = Faraday.new :url => 'https://api.bufferapp.com/1/'
@addr = Addressable::URI.new
end
# get is a shorthand method for api :get
#
# uri - string endpoint uri
def get(uri)
api :get, uri
end
# post is a shorthand method for api :post
#
# uri - string endpoint uri
# data - hash or array for POST body
def post(uri, data = {})
api :post, uri, data
end
# api is the root method of the Client, handling all requests.
#
# type - HTTP verb, :get or :post
# url - enpoint uri, with or without .json
# data - hash or array of data to be sent in POST body
def api(type, uri, data = {})
uri << '.json' unless uri =~ /\.json$/
res = if type == :get
@conn.get uri, :access_token => @token
elsif type == :post
@conn.post do |req|
req.url uri, :access_token => @token
req.body = data.to_query
end
end
# Return nil if the body is less that 2 characters long,
# ie. '{}' is the minimum valid JSON, or if the decoder
# raises an exception when passed mangled JSON
begin
MultiJson.load res.body if res.body && res.body.length >= 2
rescue
end
end
end
class User < Client
def initialize(token)
super
invalidate
end
private
# user is a method for handling the cache of the user
# data from the Buffer API.
#
# Returns a hash of user data.
def user
@cache[:user] ||= get 'user'
end
public
# invalidate wipes the cache so that future requests
# rebuild it from server data
def invalidate
@cache = {}
end
# method_missing steps in to enable the helper methods
# by trying to get a particular key from self.user
#
# Returns the user data or the result of super
def method_missing(method, *args, &block)
user[method.to_s] || super
end
def respond_to?(name)
user.key_exist? name
end
end
end
|
wardhus/puppet-caddy
|
spec/classes/package_spec.rb
|
<gh_stars>0
require 'spec_helper'
describe 'caddy::package' do
context 'with default values for all parameters' do
let(:facts) do
{
os: {
family: 'RedHat',
name: 'RedHat',
release: { major: '6' },
architecture: 'x86_64'
}
}
end
it { is_expected.to compile.with_all_deps }
it do
is_expected.to contain_exec('install caddy')
end
it do
is_expected.to contain_exec('extract caddy')
end
it do
is_expected.to contain_file('/usr/local/bin/caddy').with(
'mode' => '0755',
'owner' => 'root',
'group' => 'root',
'require' => 'Exec[extract caddy]'
)
end
end
end
|
robst/thread_watcher
|
lib/thread_watcher.rb
|
require "thread_watcher/version"
require "thread_watcher/thread_formatter"
require "thread_watcher/thread_holder"
require "thread_watcher/process_watch"
module ThreadWatcher
require 'singleton'
class Monitor
include Singleton
def initialize
@process_watch = ThreadWatcher::ProcessWatch.new
end
def run options = {}, &block
@process_watch.run options, &block
end
def self.run options = {}, &block
instance.run options, &block
end
def kill! id
@process_watch.kill! id
end
def self.kill! id
instance.kill! id
end
def restart id
@process_watch.restart id
end
def self.restart id
instance.restart id
end
def status
@process_watch.status
end
def self.status
instance.status
end
end
end
|
robst/thread_watcher
|
lib/thread_watcher/process_watch.rb
|
module ThreadWatcher
class ProcessWatch
attr_accessor :threads
def initialize
@threads = {}
@current_id = 1
start_cleaning_job
end
def run options = {}, &block
options = options.merge(id: next_id)
thread_holder = ThreadHolder.new(block, options)
thread_holder.start!
@threads[thread_holder.id] = thread_holder
thread_holder.id
end
def kill id
return if @threads[id].nil?
return if @threads[id].options[:keep_alive]
@threads[id].stop!
@threads.delete id
end
def kill! id
return if @threads[id].nil?
@threads[id].options[:keep_alive] = false
kill id
''
end
def restart id
return if @threads[id].nil?
@threads[id].restart!
''
end
def clear!
@threads.each do |key, thread|
next if thread.alive?
kill key
end
end
def status
ThreadFormatter.headline
@threads.each do |key, thread|
ThreadFormatter.data thread
end
''
end
private
def next_id
@current_id += 1
@current_id
end
def start_cleaning_job
run(name: 'Cleaning Jobs', keep_alive: true) { while true; self.clear!; sleep(60); end; }
end
end
end
|
robst/thread_watcher
|
lib/thread_watcher/thread_holder.rb
|
module ThreadWatcher
class ThreadHolder
attr_accessor :thread, :id, :options, :block, :start_time
def initialize block, options
@block = block
@options = available_options.merge options
set_id
end
def start!
initialize_starttime
@thread = Thread.new{ block.call }
end
def stop!
@thread.kill
end
def restart!
stop!
start!
end
def alive?
@thread.alive?
end
def runtime
time_to_i - start_time
end
def time_to_i
Time.now.to_i
end
private
def available_options
{ name: :noname, keep_alive: false }
end
def initialize_starttime
@start_time = time_to_i
end
def set_id
@id = options[:id]
end
end
end
|
robst/thread_watcher
|
lib/thread_watcher/thread_formatter.rb
|
<gh_stars>1-10
module ThreadWatcher
class ThreadFormatter
def self.headline
self.output "|ID\t\t|Running?\t|Runtime in Seconds\t|Name"
end
def self.data thread
self.output "|#{thread.id}\t|#{thread.alive?}\t\t|\t#{thread.runtime}\t\t|#{thread.options[:name]}"
end
def self.output content
puts content
end
end
end
|
komagata/mycask
|
Casks/imote.rb
|
<gh_stars>1-10
class Imote < Cask
url 'http://www.mkdsoftware.com/downloads/iMote_2.3.2.dmg'
homepage 'http://www.mkdsoftware.com/imote/'
version 'latest'
app 'iMote.app'
uninstall 'iMote.app'
sha256 :no_check
end
|
komagata/mycask
|
brew-mycask.rb
|
<gh_stars>1-10
require 'formula'
class BrewMycask < Formula
homepage 'https://github.com/komagata/mycask/'
url 'https://github.com/komagata/mycask.git'
def install
end
end
|
jsantos/relative_time
|
test/indonesian_relative_time_test.rb
|
<reponame>jsantos/relative_time
require 'test_helper'
describe RelativeTime do
let(:date) { Time.now }
let(:minute) { 60 }
let(:hour) { 60 * minute }
let(:day) { 24 * hour }
let(:week) { 7 * day }
let(:month) { 4 * week }
let(:year) { 12 * month }
describe '#in_words' do
describe 'with from date' do
let(:date_from) { Time.now + 1 * hour }
it { RelativeTime.in_words(date, date_from, locale: :id).must_equal '1 jam yang lalu' }
describe 'with both DateTime type' do
let(:date) { DateTime.new(2017, 1, 15, 11, 0) }
let(:date_from) { DateTime.new(2017, 1, 18, 15, 0) }
it { RelativeTime.in_words(date, date_from, locale: :id).must_equal '3 hari yang lalu' }
end
describe 'date_from DateTime type' do
let(:date_from) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from, locale: :id).must_equal '1 hari yang lalu' }
end
describe 'date DataTime type' do
let(:date) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from, locale: :id).must_equal 'dalam 23 jam' }
end
end
describe 'when difference in seconds' do
it { RelativeTime.in_words(date, locale: :id).must_equal 'kurang dari 1 menit' }
it { RelativeTime.in_words(date - 10, locale: :id).must_equal 'kurang dari 1 menit' }
it { RelativeTime.in_words(date + 10, locale: :id).must_equal 'kurang dari 1 menit' }
it { RelativeTime.in_words(date - 59, locale: :id).must_equal 'kurang dari 1 menit' }
it { RelativeTime.in_words(date + 59, locale: :id).must_equal 'kurang dari 1 menit' }
end
describe 'when difference in minutes' do
it { RelativeTime.in_words(date - 70, locale: :id).must_equal '1 menit yang lalu' }
it { RelativeTime.in_words(date + 70, locale: :id).must_equal 'dalam 1 menit' }
it { RelativeTime.in_words(date - 1 * minute, locale: :id).must_equal '1 menit yang lalu' }
it { RelativeTime.in_words(date - 3 * minute, locale: :id).must_equal '3 menit yang lalu' }
it { RelativeTime.in_words(date - 20 * minute, locale: :id).must_equal '20 menit yang lalu' }
it { RelativeTime.in_words(date - 59 * minute, locale: :id).must_equal '59 menit yang lalu' }
it { RelativeTime.in_words(date + 1 * minute, locale: :id).must_equal 'dalam 1 menit' }
it { RelativeTime.in_words(date + 3 * minute, locale: :id).must_equal 'dalam 3 menit' }
it { RelativeTime.in_words(date + 20 * minute, locale: :id).must_equal 'dalam 20 menit' }
it { RelativeTime.in_words(date + 59 * minute, locale: :id).must_equal 'dalam 59 menit' }
end
describe 'when difference in hours' do
it { RelativeTime.in_words(date - 70 * minute, locale: :id).must_equal '1 jam yang lalu' }
it { RelativeTime.in_words(date + 70 * minute, locale: :id).must_equal 'dalam 1 jam' }
it { RelativeTime.in_words(date - 60 * minute, locale: :id).must_equal '1 jam yang lalu' }
it { RelativeTime.in_words(date + 60 * minute, locale: :id).must_equal 'dalam 1 jam' }
it { RelativeTime.in_words(date - 1 * hour, locale: :id).must_equal '1 jam yang lalu' }
it { RelativeTime.in_words(date - 3 * hour, locale: :id).must_equal '3 jam yang lalu' }
it { RelativeTime.in_words(date - 10 * hour, locale: :id).must_equal '10 jam yang lalu' }
it { RelativeTime.in_words(date - 23 * hour, locale: :id).must_equal '23 jam yang lalu' }
it { RelativeTime.in_words(date + 1 * hour, locale: :id).must_equal 'dalam 1 jam' }
it { RelativeTime.in_words(date + 3 * hour, locale: :id).must_equal 'dalam 3 jam' }
it { RelativeTime.in_words(date + 10 * hour, locale: :id).must_equal 'dalam 10 jam' }
it { RelativeTime.in_words(date + 23 * hour, locale: :id).must_equal 'dalam 23 jam' }
end
describe 'when difference in days' do
it { RelativeTime.in_words(date - 24 * hour, locale: :id).must_equal '1 hari yang lalu' }
it { RelativeTime.in_words(date + 24 * hour, locale: :id).must_equal 'dalam 1 hari' }
it { RelativeTime.in_words(date - 1 * day, locale: :id).must_equal '1 hari yang lalu' }
it { RelativeTime.in_words(date - 3 * day, locale: :id).must_equal '3 hari yang lalu' }
it { RelativeTime.in_words(date - 6 * day, locale: :id).must_equal '6 hari yang lalu' }
it { RelativeTime.in_words(date + 1 * day, locale: :id).must_equal 'dalam 1 hari' }
it { RelativeTime.in_words(date + 3 * day, locale: :id).must_equal 'dalam 3 hari' }
it { RelativeTime.in_words(date + 6 * day, locale: :id).must_equal 'dalam 6 hari' }
end
describe 'when difference in weeks' do
it { RelativeTime.in_words(date - 7 * day, locale: :id).must_equal '1 minggu yang lalu' }
it { RelativeTime.in_words(date + 7 * day, locale: :id).must_equal 'dalam 1 minggu' }
it { RelativeTime.in_words(date - 8 * day, locale: :id).must_equal '1 minggu yang lalu' }
it { RelativeTime.in_words(date + 8 * day, locale: :id).must_equal 'dalam 1 minggu' }
it { RelativeTime.in_words(date - 1 * week, locale: :id).must_equal '1 minggu yang lalu' }
it { RelativeTime.in_words(date - 3 * week, locale: :id).must_equal '3 minggu yang lalu' }
it { RelativeTime.in_words(date + 1 * week, locale: :id).must_equal 'dalam 1 minggu' }
it { RelativeTime.in_words(date + 3 * week, locale: :id).must_equal 'dalam 3 minggu' }
end
describe 'when difference in months' do
it { RelativeTime.in_words(date - 4 * week, locale: :id).must_equal '1 bulan yang lalu' }
it { RelativeTime.in_words(date + 4 * week, locale: :id).must_equal 'dalam 1 bulan' }
it { RelativeTime.in_words(date - 6 * week, locale: :id).must_equal '1 bulan yang lalu' }
it { RelativeTime.in_words(date + 6 * week, locale: :id).must_equal 'dalam 1 bulan' }
it { RelativeTime.in_words(date - 1 * month, locale: :id).must_equal '1 bulan yang lalu' }
it { RelativeTime.in_words(date - 11 * month, locale: :id).must_equal '11 bulan yang lalu' }
it { RelativeTime.in_words(date + 1 * month, locale: :id).must_equal 'dalam 1 bulan' }
it { RelativeTime.in_words(date + 11 * month, locale: :id).must_equal 'dalam 11 bulan' }
end
describe 'when difference in years' do
it { RelativeTime.in_words(date - 12 * month, locale: :id).must_equal '1 tahun yang lalu' }
it { RelativeTime.in_words(date + 12 * month, locale: :id).must_equal 'dalam 1 tahun' }
it { RelativeTime.in_words(date - 14 * month, locale: :id).must_equal '1 tahun yang lalu' }
it { RelativeTime.in_words(date + 14 * month, locale: :id).must_equal 'dalam 1 tahun' }
it { RelativeTime.in_words(date - 1 * year, locale: :id).must_equal '1 tahun yang lalu' }
it { RelativeTime.in_words(date - 11 * year, locale: :id).must_equal '11 tahun yang lalu' }
it { RelativeTime.in_words(date + 1 * year, locale: :id).must_equal 'dalam 1 tahun' }
it { RelativeTime.in_words(date + 11 * year, locale: :id).must_equal 'dalam 11 tahun' }
end
end
end
|
jsantos/relative_time
|
test/turkish_relative_time_test.rb
|
require 'test_helper'
describe RelativeTime do
let(:date) { Time.now }
let(:minute) { 60 }
let(:hour) { 60 * minute }
let(:day) { 24 * hour }
let(:week) { 7 * day }
let(:month) { 4 * week }
let(:year) { 12 * month }
describe '#in_words' do
describe 'with from date' do
let(:date_from) { Time.now + 1 * hour }
it { RelativeTime.in_words(date, date_from, locale: :tr).must_equal '1 saat önce' }
describe 'with both DateTime type' do
let(:date) { DateTime.new(2017, 1, 15, 11, 0) }
let(:date_from) { DateTime.new(2017, 1, 18, 15, 0) }
it { RelativeTime.in_words(date, date_from, locale: :tr).must_equal '3 gün önce' }
end
describe 'date_from DateTime type' do
let(:date_from) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from, locale: :tr).must_equal '1 gün önce' }
end
describe 'date DataTime type' do
let(:date) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from, locale: :tr).must_equal '23 saat içinde' }
end
end
describe 'when difference in seconds' do
it { RelativeTime.in_words(date, locale: :tr).must_equal '1 dakikadan daha az' }
it { RelativeTime.in_words(date - 10, locale: :tr).must_equal '1 dakikadan daha az' }
it { RelativeTime.in_words(date + 10, locale: :tr).must_equal '1 dakikadan daha az' }
it { RelativeTime.in_words(date - 59, locale: :tr).must_equal '1 dakikadan daha az' }
it { RelativeTime.in_words(date + 59, locale: :tr).must_equal '1 dakikadan daha az' }
end
describe 'when difference in minutes' do
it { RelativeTime.in_words(date - 70, locale: :tr).must_equal '1 dakika önce' }
it { RelativeTime.in_words(date + 70, locale: :tr).must_equal '1 dakika içinde' }
it { RelativeTime.in_words(date - 1 * minute, locale: :tr).must_equal '1 dakika önce' }
it { RelativeTime.in_words(date - 3 * minute, locale: :tr).must_equal '3 dakika önce' }
it { RelativeTime.in_words(date - 20 * minute, locale: :tr).must_equal '20 dakika önce' }
it { RelativeTime.in_words(date - 59 * minute, locale: :tr).must_equal '59 dakika önce' }
it { RelativeTime.in_words(date + 1 * minute, locale: :tr).must_equal '1 dakika içinde' }
it { RelativeTime.in_words(date + 3 * minute, locale: :tr).must_equal '3 dakika içinde' }
it { RelativeTime.in_words(date + 20 * minute, locale: :tr).must_equal '20 dakika içinde' }
it { RelativeTime.in_words(date + 59 * minute, locale: :tr).must_equal '59 dakika içinde' }
end
describe 'when difference in hours' do
it { RelativeTime.in_words(date - 70 * minute, locale: :tr).must_equal '1 saat önce' }
it { RelativeTime.in_words(date + 70 * minute, locale: :tr).must_equal '1 saat içinde' }
it { RelativeTime.in_words(date - 60 * minute, locale: :tr).must_equal '1 saat önce' }
it { RelativeTime.in_words(date + 60 * minute, locale: :tr).must_equal '1 saat içinde' }
it { RelativeTime.in_words(date - 1 * hour, locale: :tr).must_equal '1 saat önce' }
it { RelativeTime.in_words(date - 3 * hour, locale: :tr).must_equal '3 saat önce' }
it { RelativeTime.in_words(date - 10 * hour, locale: :tr).must_equal '10 saat önce' }
it { RelativeTime.in_words(date - 23 * hour, locale: :tr).must_equal '23 saat önce' }
it { RelativeTime.in_words(date + 1 * hour, locale: :tr).must_equal '1 saat içinde' }
it { RelativeTime.in_words(date + 3 * hour, locale: :tr).must_equal '3 saat içinde' }
it { RelativeTime.in_words(date + 10 * hour, locale: :tr).must_equal '10 saat içinde' }
it { RelativeTime.in_words(date + 23 * hour, locale: :tr).must_equal '23 saat içinde' }
end
describe 'when difference in days' do
it { RelativeTime.in_words(date - 24 * hour, locale: :tr).must_equal '1 gün önce' }
it { RelativeTime.in_words(date + 24 * hour, locale: :tr).must_equal '1 gün içinde' }
it { RelativeTime.in_words(date - 1 * day, locale: :tr).must_equal '1 gün önce' }
it { RelativeTime.in_words(date - 3 * day, locale: :tr).must_equal '3 gün önce' }
it { RelativeTime.in_words(date - 6 * day, locale: :tr).must_equal '6 gün önce' }
it { RelativeTime.in_words(date + 1 * day, locale: :tr).must_equal '1 gün içinde' }
it { RelativeTime.in_words(date + 3 * day, locale: :tr).must_equal '3 gün içinde' }
it { RelativeTime.in_words(date + 6 * day, locale: :tr).must_equal '6 gün içinde' }
end
describe 'when difference in weeks' do
it { RelativeTime.in_words(date - 7 * day, locale: :tr).must_equal '1 hafta önce' }
it { RelativeTime.in_words(date + 7 * day, locale: :tr).must_equal '1 hafta içinde' }
it { RelativeTime.in_words(date - 8 * day, locale: :tr).must_equal '1 hafta önce' }
it { RelativeTime.in_words(date + 8 * day, locale: :tr).must_equal '1 hafta içinde' }
it { RelativeTime.in_words(date - 1 * week, locale: :tr).must_equal '1 hafta önce' }
it { RelativeTime.in_words(date - 3 * week, locale: :tr).must_equal '3 hafta önce' }
it { RelativeTime.in_words(date + 1 * week, locale: :tr).must_equal '1 hafta içinde' }
it { RelativeTime.in_words(date + 3 * week, locale: :tr).must_equal '3 hafta içinde' }
end
describe 'when difference in months' do
it { RelativeTime.in_words(date - 4 * week, locale: :tr).must_equal '1 ay önce' }
it { RelativeTime.in_words(date + 4 * week, locale: :tr).must_equal '1 ay içinde' }
it { RelativeTime.in_words(date - 6 * week, locale: :tr).must_equal '1 ay önce' }
it { RelativeTime.in_words(date + 6 * week, locale: :tr).must_equal '1 ay içinde' }
it { RelativeTime.in_words(date - 1 * month, locale: :tr).must_equal '1 ay önce' }
it { RelativeTime.in_words(date - 11 * month, locale: :tr).must_equal '11 ay önce' }
it { RelativeTime.in_words(date + 1 * month, locale: :tr).must_equal '1 ay içinde' }
it { RelativeTime.in_words(date + 11 * month, locale: :tr).must_equal '11 ay içinde' }
end
describe 'when difference in years' do
it { RelativeTime.in_words(date - 12 * month, locale: :tr).must_equal '1 yıl önce' }
it { RelativeTime.in_words(date + 12 * month, locale: :tr).must_equal '1 yıl içinde' }
it { RelativeTime.in_words(date - 14 * month, locale: :tr).must_equal '1 yıl önce' }
it { RelativeTime.in_words(date + 14 * month, locale: :tr).must_equal '1 yıl içinde' }
it { RelativeTime.in_words(date - 1 * year, locale: :tr).must_equal '1 yıl önce' }
it { RelativeTime.in_words(date - 11 * year, locale: :tr).must_equal '11 yıl önce' }
it { RelativeTime.in_words(date + 1 * year, locale: :tr).must_equal '1 yıl içinde' }
it { RelativeTime.in_words(date + 11 * year, locale: :tr).must_equal '11 yıl içinde' }
end
end
end
|
jsantos/relative_time
|
lib/relative_time.rb
|
require 'relative_time/in_words'
require 'relative_time/version'
module RelativeTime
def self.in_words(date_to, date_from = Time.now, locale: :en)
InWords.new(locale: locale).(date_to, date_from)
end
end
|
jsantos/relative_time
|
lib/relative_time/in_words.rb
|
require 'i18n'
require 'i18n/backend/pluralization'
module RelativeTime
class InWords
def self.setup
return if @setup
I18n.load_path << Dir[File.expand_path("#{__dir__}/../../config/locales") + '/*.yml']
I18n.load_path << Dir[File.expand_path("#{__dir__}/../../config/locales") + '/*.rb']
I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)
@setup = true
end
def initialize(locale: :en)
self.class.setup
I18n.locale = locale
end
def call(date_to, date_from)
diff = date_from.to_time - date_to.to_time
return I18n.t('relative.less_than_a_minute') if diff.abs.round <= 59
date_string = resolution(diff.abs.round)
diff >= 0 ? I18n.t('relative.ago', date_string: date_string) : I18n.t('relative.in', date_string: date_string)
end
private
MINUTE = 60
HOUR = 60 * MINUTE
DAY = 24 * HOUR
WEEK = 7 * DAY
MONTH = 4 * WEEK
YEAR = 12 * MONTH
def resolution(diff)
if diff >= YEAR
I18n.t('relative.years', count: (diff / YEAR).round)
elsif diff >= MONTH
I18n.t('relative.months', count: (diff / MONTH).round)
elsif diff >= WEEK
I18n.t('relative.weeks', count: (diff / WEEK).round)
elsif diff >= DAY
I18n.t('relative.days', count: (diff / DAY).round)
elsif diff >= HOUR
I18n.t('relative.hours', count: (diff / HOUR).round)
else
I18n.t('relative.minutes', count: (diff / MINUTE).round)
end
end
end
end
|
jsantos/relative_time
|
test/russian_relative_time_test.rb
|
require 'test_helper'
describe RelativeTime do
let(:date) { Time.now }
let(:minute) { 60 }
let(:hour) { 60 * minute }
let(:day) { 24 * hour }
let(:week) { 7 * day }
let(:month) { 4 * week }
let(:year) { 12 * month }
describe '#in_words' do
describe 'with from date' do
let(:date_from) { Time.now + 1 * hour }
it { RelativeTime.in_words(date, date_from, locale: :ru).must_equal 'час назад' }
describe 'with both DateTime type' do
let(:date) { DateTime.new(2017, 1, 15, 11, 0) }
let(:date_from) { DateTime.new(2017, 1, 18, 15, 0) }
it { RelativeTime.in_words(date, date_from, locale: :ru).must_equal '3 дня назад' }
end
describe 'date_from DateTime type' do
let(:date_from) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from, locale: :ru).must_equal 'день назад' }
end
describe 'date DataTime type' do
let(:date) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from, locale: :ru).must_equal 'через 23 часа' }
end
end
describe 'when difference in seconds' do
it { RelativeTime.in_words(date, locale: :ru).must_equal 'меньше минуты назад' }
it { RelativeTime.in_words(date - 10, locale: :ru).must_equal 'меньше минуты назад' }
it { RelativeTime.in_words(date + 10, locale: :ru).must_equal 'меньше минуты назад' }
it { RelativeTime.in_words(date - 59, locale: :ru).must_equal 'меньше минуты назад' }
it { RelativeTime.in_words(date + 59, locale: :ru).must_equal 'меньше минуты назад' }
end
describe 'when difference in minutes' do
it { RelativeTime.in_words(date - 70, locale: :ru).must_equal 'минуту назад' }
it { RelativeTime.in_words(date + 70, locale: :ru).must_equal 'через минуту' }
it { RelativeTime.in_words(date - 1 * minute, locale: :ru).must_equal 'минуту назад' }
it { RelativeTime.in_words(date - 3 * minute, locale: :ru).must_equal '3 минуты назад' }
it { RelativeTime.in_words(date - 20 * minute, locale: :ru).must_equal '20 минут назад' }
it { RelativeTime.in_words(date - 59 * minute, locale: :ru).must_equal '59 минут назад' }
it { RelativeTime.in_words(date + 1 * minute, locale: :ru).must_equal 'через минуту' }
it { RelativeTime.in_words(date + 3 * minute, locale: :ru).must_equal 'через 3 минуты' }
it { RelativeTime.in_words(date + 20 * minute, locale: :ru).must_equal 'через 20 минут' }
it { RelativeTime.in_words(date + 59 * minute, locale: :ru).must_equal 'через 59 минут' }
end
describe 'when difference in hours' do
it { RelativeTime.in_words(date - 70 * minute, locale: :ru).must_equal 'час назад' }
it { RelativeTime.in_words(date + 70 * minute, locale: :ru).must_equal 'через час' }
it { RelativeTime.in_words(date - 60 * minute, locale: :ru).must_equal 'час назад' }
it { RelativeTime.in_words(date + 60 * minute, locale: :ru).must_equal 'через час' }
it { RelativeTime.in_words(date - 1 * hour, locale: :ru).must_equal 'час назад' }
it { RelativeTime.in_words(date - 3 * hour, locale: :ru).must_equal '3 часа назад' }
it { RelativeTime.in_words(date - 10 * hour, locale: :ru).must_equal '10 часов назад' }
it { RelativeTime.in_words(date - 23 * hour, locale: :ru).must_equal '23 часа назад' }
it { RelativeTime.in_words(date + 1 * hour, locale: :ru).must_equal 'через час' }
it { RelativeTime.in_words(date + 3 * hour, locale: :ru).must_equal 'через 3 часа' }
it { RelativeTime.in_words(date + 10 * hour, locale: :ru).must_equal 'через 10 часов' }
it { RelativeTime.in_words(date + 23 * hour, locale: :ru).must_equal 'через 23 часа' }
end
describe 'when difference in days' do
it { RelativeTime.in_words(date - 24 * hour, locale: :ru).must_equal 'день назад' }
it { RelativeTime.in_words(date + 24 * hour, locale: :ru).must_equal 'через день' }
it { RelativeTime.in_words(date - 1 * day, locale: :ru).must_equal 'день назад' }
it { RelativeTime.in_words(date - 3 * day, locale: :ru).must_equal '3 дня назад' }
it { RelativeTime.in_words(date - 6 * day, locale: :ru).must_equal '6 дней назад' }
it { RelativeTime.in_words(date + 1 * day, locale: :ru).must_equal 'через день' }
it { RelativeTime.in_words(date + 3 * day, locale: :ru).must_equal 'через 3 дня' }
it { RelativeTime.in_words(date + 6 * day, locale: :ru).must_equal 'через 6 дней' }
end
describe 'when difference in weeks' do
it { RelativeTime.in_words(date - 7 * day, locale: :ru).must_equal 'неделю назад' }
it { RelativeTime.in_words(date + 7 * day, locale: :ru).must_equal 'через неделю' }
it { RelativeTime.in_words(date - 8 * day, locale: :ru).must_equal 'неделю назад' }
it { RelativeTime.in_words(date + 8 * day, locale: :ru).must_equal 'через неделю' }
it { RelativeTime.in_words(date - 1 * week, locale: :ru).must_equal 'неделю назад' }
it { RelativeTime.in_words(date - 3 * week, locale: :ru).must_equal '3 недели назад' }
it { RelativeTime.in_words(date + 1 * week, locale: :ru).must_equal 'через неделю' }
it { RelativeTime.in_words(date + 3 * week, locale: :ru).must_equal 'через 3 недели' }
end
describe 'when difference in months' do
it { RelativeTime.in_words(date - 4 * week, locale: :ru).must_equal 'месяц назад' }
it { RelativeTime.in_words(date + 4 * week, locale: :ru).must_equal 'через месяц' }
it { RelativeTime.in_words(date - 6 * week, locale: :ru).must_equal 'месяц назад' }
it { RelativeTime.in_words(date + 6 * week, locale: :ru).must_equal 'через месяц' }
it { RelativeTime.in_words(date - 1 * month, locale: :ru).must_equal 'месяц назад' }
it { RelativeTime.in_words(date - 3 * month, locale: :ru).must_equal '3 месяца назад' }
it { RelativeTime.in_words(date - 11 * month, locale: :ru).must_equal '11 месяцев назад' }
it { RelativeTime.in_words(date + 1 * month, locale: :ru).must_equal 'через месяц' }
it { RelativeTime.in_words(date + 3 * month, locale: :ru).must_equal 'через 3 месяца' }
it { RelativeTime.in_words(date + 11 * month, locale: :ru).must_equal 'через 11 месяцев' }
end
describe 'when difference in years' do
it { RelativeTime.in_words(date - 12 * month, locale: :ru).must_equal 'год назад' }
it { RelativeTime.in_words(date + 12 * month, locale: :ru).must_equal 'через год' }
it { RelativeTime.in_words(date - 14 * month, locale: :ru).must_equal 'год назад' }
it { RelativeTime.in_words(date + 14 * month, locale: :ru).must_equal 'через год' }
it { RelativeTime.in_words(date - 1 * year, locale: :ru).must_equal 'год назад' }
it { RelativeTime.in_words(date - 3 * year, locale: :ru).must_equal '3 года назад' }
it { RelativeTime.in_words(date - 11 * year, locale: :ru).must_equal '11 лет назад' }
it { RelativeTime.in_words(date + 1 * year, locale: :ru).must_equal 'через год' }
it { RelativeTime.in_words(date + 3 * year, locale: :ru).must_equal 'через 3 года' }
it { RelativeTime.in_words(date + 11 * year, locale: :ru).must_equal 'через 11 лет' }
end
end
end
|
jsantos/relative_time
|
test/relative_time_test.rb
|
require 'test_helper'
describe RelativeTime do
let(:date) { Time.now }
let(:minute) { 60 }
let(:hour) { 60 * minute }
let(:day) { 24 * hour }
let(:week) { 7 * day }
let(:month) { 4 * week }
let(:year) { 12 * month }
describe '#in_words' do
describe 'with from date' do
let(:date_from) { Time.now + 1 * hour }
it { RelativeTime.in_words(date, date_from).must_equal 'an hour ago' }
describe 'with both DateTime type' do
let(:date) { DateTime.new(2017, 1, 15, 11, 0) }
let(:date_from) { DateTime.new(2017, 1, 18, 15, 0) }
it { RelativeTime.in_words(date, date_from).must_equal '3 days ago' }
end
describe 'date_from DateTime type' do
let(:date_from) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from).must_equal 'a day ago' }
end
describe 'date DataTime type' do
let(:date) { DateTime.now + 1 }
it { RelativeTime.in_words(date, date_from).must_equal 'in 23 hours' }
end
end
describe 'when difference in seconds' do
it { RelativeTime.in_words(date).must_equal 'less than a minute' }
it { RelativeTime.in_words(date - 10).must_equal 'less than a minute' }
it { RelativeTime.in_words(date + 10).must_equal 'less than a minute' }
it { RelativeTime.in_words(date - 59).must_equal 'less than a minute' }
it { RelativeTime.in_words(date + 59).must_equal 'less than a minute' }
end
describe 'when difference in minutes' do
it { RelativeTime.in_words(date - 70).must_equal 'a minute ago' }
it { RelativeTime.in_words(date + 70).must_equal 'in a minute' }
it { RelativeTime.in_words(date - 1 * minute).must_equal 'a minute ago' }
it { RelativeTime.in_words(date - 3 * minute).must_equal '3 minutes ago' }
it { RelativeTime.in_words(date - 20 * minute).must_equal '20 minutes ago' }
it { RelativeTime.in_words(date - 59 * minute).must_equal '59 minutes ago' }
it { RelativeTime.in_words(date + 1 * minute).must_equal 'in a minute' }
it { RelativeTime.in_words(date + 3 * minute).must_equal 'in 3 minutes' }
it { RelativeTime.in_words(date + 20 * minute).must_equal 'in 20 minutes' }
it { RelativeTime.in_words(date + 59 * minute).must_equal 'in 59 minutes' }
end
describe 'when difference in hours' do
it { RelativeTime.in_words(date - 70 * minute).must_equal 'an hour ago' }
it { RelativeTime.in_words(date + 70 * minute).must_equal 'in an hour' }
it { RelativeTime.in_words(date - 60 * minute).must_equal 'an hour ago' }
it { RelativeTime.in_words(date + 60 * minute).must_equal 'in an hour' }
it { RelativeTime.in_words(date - 1 * hour).must_equal 'an hour ago' }
it { RelativeTime.in_words(date - 3 * hour).must_equal '3 hours ago' }
it { RelativeTime.in_words(date - 10 * hour).must_equal '10 hours ago' }
it { RelativeTime.in_words(date - 23 * hour).must_equal '23 hours ago' }
it { RelativeTime.in_words(date + 1 * hour).must_equal 'in an hour' }
it { RelativeTime.in_words(date + 3 * hour).must_equal 'in 3 hours' }
it { RelativeTime.in_words(date + 10 * hour).must_equal 'in 10 hours' }
it { RelativeTime.in_words(date + 23 * hour).must_equal 'in 23 hours' }
end
describe 'when difference in days' do
it { RelativeTime.in_words(date - 24 * hour).must_equal 'a day ago' }
it { RelativeTime.in_words(date + 24 * hour).must_equal 'in a day' }
it { RelativeTime.in_words(date - 1 * day).must_equal 'a day ago' }
it { RelativeTime.in_words(date - 3 * day).must_equal '3 days ago' }
it { RelativeTime.in_words(date - 6 * day).must_equal '6 days ago' }
it { RelativeTime.in_words(date + 1 * day).must_equal 'in a day' }
it { RelativeTime.in_words(date + 3 * day).must_equal 'in 3 days' }
it { RelativeTime.in_words(date + 6 * day).must_equal 'in 6 days' }
end
describe 'when difference in weeks' do
it { RelativeTime.in_words(date - 7 * day).must_equal 'a week ago' }
it { RelativeTime.in_words(date + 7 * day).must_equal 'in a week' }
it { RelativeTime.in_words(date - 8 * day).must_equal 'a week ago' }
it { RelativeTime.in_words(date + 8 * day).must_equal 'in a week' }
it { RelativeTime.in_words(date - 1 * week).must_equal 'a week ago' }
it { RelativeTime.in_words(date - 3 * week).must_equal '3 weeks ago' }
it { RelativeTime.in_words(date + 1 * week).must_equal 'in a week' }
it { RelativeTime.in_words(date + 3 * week).must_equal 'in 3 weeks' }
end
describe 'when difference in months' do
it { RelativeTime.in_words(date - 4 * week).must_equal 'a month ago' }
it { RelativeTime.in_words(date + 4 * week).must_equal 'in a month' }
it { RelativeTime.in_words(date - 6 * week).must_equal 'a month ago' }
it { RelativeTime.in_words(date + 6 * week).must_equal 'in a month' }
it { RelativeTime.in_words(date - 1 * month).must_equal 'a month ago' }
it { RelativeTime.in_words(date - 11 * month).must_equal '11 months ago' }
it { RelativeTime.in_words(date + 1 * month).must_equal 'in a month' }
it { RelativeTime.in_words(date + 11 * month).must_equal 'in 11 months' }
end
describe 'when difference in years' do
it { RelativeTime.in_words(date - 12 * month).must_equal 'a year ago' }
it { RelativeTime.in_words(date + 12 * month).must_equal 'in a year' }
it { RelativeTime.in_words(date - 14 * month).must_equal 'a year ago' }
it { RelativeTime.in_words(date + 14 * month).must_equal 'in a year' }
it { RelativeTime.in_words(date - 1 * year).must_equal 'a year ago' }
it { RelativeTime.in_words(date - 11 * year).must_equal '11 years ago' }
it { RelativeTime.in_words(date + 1 * year).must_equal 'in a year' }
it { RelativeTime.in_words(date + 11 * year).must_equal 'in 11 years' }
end
end
end
|
jsantos/relative_time
|
test/version_test.rb
|
<filename>test/version_test.rb
require 'test_helper'
describe RelativeTime do
it { refute_nil ::RelativeTime::VERSION }
end
|
tektite-software/ruby_utils
|
lib/tektite_ruby_utils/present.rb
|
# PresentClass should behave just as NilClass, but the opposite. It represents
# that a value exists but does not represent any specific vallue or type; it
# is ambiguous. present should be seen as the opposite of nil.
class PresentClass
attr_accessor :type
# +type+ should be either nil (for ambiguous) or
# the class of the object represented.
# PresentClass.new(type: String)
# => present
# PresentClass.new(type: String).type
# => String
# present.type
# => nil
def initialize(options = {})
type = options[:type]
@type = type
end
# Makes present appear and behave like nil in the console. To see the
# object id, use +.object_id+. To see the value of an attribute
# such as +@type+, use the attribute getter method, such as .type.
def inspect
'present'
end
# To avoid confusing the present Object with the value of the
# object represented, attempting to convert the present Object
# to any other type raises an error.
# present can not be converted to an Integer.
def to_i
raise AmbiguousValueError
end
# present can not be converted to an Array.
def to_a
raise AmbiguousValueError
end
# present can not be converted to a String.
def to_s
raise AmbiguousValueError
end
# Return true if the object type is defined.
def type_known?
@type.nil? ? false : true
end
end
# Error class communicating that because PresentClass is ambiguous, it should
# not be converted to other data types to avoid confusion between `present`
# and the actual value represented.
class AmbiguousValueError < StandardError
# Creates new error instance. Default message is below, overriding not
# recommended.
# +msg+ explains why the error is raised; similar to why you can't
# divide by zero.
def initialize(msg = 'Value exists, but is unspecified, unknown, or secret.')
super
end
end
# Add some methods concerning present and PresentClass
# to all objects by extending Object.
class Object
# Allow .present? method on all objects
def present?
!nil?
end
# Return a new PresentClass object with @type defined
# as the type of the object.
def present_with_type
PresentClass.new(type: self.class)
end
# Aliases :present_with_class to :present_with_type
alias present_with_class present_with_type
end
# Extend Array with some helper methods.
class Array
# Returns true if all elements are present, false if one is nil
def all_present?
each do |e|
return false if e.nil?
end
true
end
# Returns an array with a boolean representing each element's presence
def each_present?
result = []
each_with_index do |e, i|
result[i] = if e.nil?
false
else
true
end
end
result
end
# Replaces non-nil elements with present
def mask_present
result = []
each_with_index do |e, i|
result[i] = (present if e.present?)
end
result
end
end
# Extend Hash with some helper methods.
class Hash
# Returns true if all values are present, otherwise false
def all_present?
each do |_key, value|
return false if value.nil?
end
true
end
# Returns a hash with the values of the original hash replaced with
# true if the value is present and false if nil.
def each_present?
result = {}
each do |key, value|
result[key] = value.present?
end
result
end
# Returns a hash with non-nil values of the original hash
# replaced with present.
def mask_present
result = {}
each do |key, value|
result[key] = value.present? ? present : nil
end
result
end
end
# Initializes a new constant with a frozen instance of PresentClass.
PRESENT = PresentClass.new.freeze
# +present+ returns PRESENT constant.
def present
PRESENT
end
# Add Present constant to Module in case PRESENT is
# overriden or corrupted in the global namespace.
module TektiteRubyUtils
# Set TektiteRubyUtils::Present equal to PRESENT
Present = PRESENT
end
|
tektite-software/ruby_utils
|
test/present_test.rb
|
require 'test_helper'
describe 'Global methods and constants' do
it 'must have the PRESENT constant' do
PRESENT.wont_be_nil
end
it 'must have PRESENT be a PresentClass' do
PRESENT.must_be_instance_of PresentClass
end
it 'must have a `present` method which equals PRESENT' do
present.must_be_same_as PRESENT
end
it 'present must return "present" when inspected' do
PRESENT.inspect.must_equal "present"
present.inspect.must_equal "present"
PresentClass.new.inspect.must_equal "present"
end
end
describe PresentClass do
before do
@present_string = PresentClass.new(type: String)
end
it 'should not be convertable to other types' do
-> { present.to_i }.must_raise AmbiguousValueError
-> { present.to_a }.must_raise AmbiguousValueError
-> { present.to_s }.must_raise AmbiguousValueError
end
it 'should by default return nil for @type' do
present.type.must_be_nil
end
it 'should return a class when type is defined' do
@present_string.type.must_be_kind_of Class
end
describe 'when calling type_known?' do
it 'should return false by default' do
present.type_known?.must_equal false
end
it 'should return true when the type is defined' do
@present_string.type_known?.must_equal true
end
end
end
describe Object do
before do
@test_string = 'This is a test'
@test_nil = nil
end
it 'should respond to present?' do
@test_string.must_respond_to :present?
end
describe 'when .present? is called' do
it 'should return true when not nil' do
@test_string.present?.must_equal true
end
it 'should return false when nil' do
@test_nil.present?.must_equal false
end
end
describe 'when .present_with_type is called' do
it 'should return a PresentClass object' do
@test_string.present_with_type.must_be_instance_of PresentClass
end
it 'should return a PresentClass not equal to PRESENT' do
@test_string.present_with_type.wont_be_same_as present
end
it 'should have a .type defined on the returned object' do
@test_string.present_with_type.type.must_equal String
end
end
end
describe Array do
before do
@test_array = [1, 2, 3, 4, nil, 5]
@test_array_2 = [1, 2, 3]
end
it 'should react properly to .all_present?' do
@test_array.all_present?.must_equal false
@test_array_2.all_present?.must_equal true
end
it 'should react properly to .each_present?' do
@test_array.each_present?.must_be_instance_of Array
@test_array.each_present?.must_equal [true, true, true, true, false, true]
@test_array_2.each_present?.must_equal [true, true, true]
end
it 'should react properly to .mask_present' do
@test_array.mask_present.must_be_instance_of Array
@test_array.mask_present.must_equal [
present, present, present, present, nil, present
]
@test_array_2.mask_present.must_equal [present, present, present]
end
it 'should not change original array' do
@test_array.mask_present
@test_array.all_present?
@test_array.each_present?
@test_array.must_equal [1, 2, 3, 4, nil, 5]
end
end
describe Hash do
before do
@test_hash = Hash(one: 1, two: 2, three: nil)
@test_hash_2 = Hash(alpha: nil, bravo: 'two')
@test_hash_3 = Hash(first: 1, second: 2)
end
it 'should react properly to .all_present?' do
@test_hash.all_present?.must_equal false
@test_hash_2.all_present?.must_equal false
@test_hash_3.all_present?.must_equal true
end
it 'should react properly to .each_present?' do
@test_hash.each_present?.must_be_instance_of Hash
@test_hash.each_present?.must_equal Hash(one: true, two: true, three: false)
@test_hash_2.each_present?.must_equal Hash(alpha: false, bravo: true)
end
it 'should react properly to .mask_present' do
@test_hash.mask_present.must_be_instance_of Hash
@test_hash.mask_present.must_equal Hash(
one: present, two: present, three: nil
)
@test_hash_2.mask_present.must_equal Hash(alpha: nil, bravo: present)
end
it 'should not change original hash' do
@test_hash.mask_present
@test_hash.all_present?
@test_hash.each_present?
@test_hash.must_equal Hash(one: 1, two: 2, three: nil)
end
end
describe 'TektiteRubyUtils::Present' do
it 'should be equal to PRESENT' do
TektiteRubyUtils::Present.must_be_same_as PRESENT
end
end
|
tektite-software/ruby_utils
|
lib/tektite_ruby_utils.rb
|
require 'tektite_ruby_utils/version'
require 'tektite_ruby_utils/present'
# See above files.
module TektiteRubyUtils
# See above files
end
|
tektite-software/ruby_utils
|
test/test_helper.rb
|
<filename>test/test_helper.rb
require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'tektite_ruby_utils'
require 'minitest/autorun'
# require 'minitest/spec'
# require 'minitest/mock'
require 'minitest/pride'
|
tektite-software/ruby_utils
|
lib/tektite_ruby_utils/version.rb
|
module TektiteRubyUtils
# Uses semantic versioning
VERSION = '0.1.0'.freeze
end
|
tektite-software/ruby_utils
|
tektite_ruby_utils.gemspec
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tektite_ruby_utils/version'
Gem::Specification.new do |spec|
spec.name = 'tektite_ruby_utils'
spec.version = TektiteRubyUtils::VERSION
spec.authors = ['Tektite Software', '<NAME>']
spec.email = ['<EMAIL>']
spec.summary = 'Extensions and utilities for Ruby'
spec.description = 'Adds additional functionality to Ruby,
such as PresentClass (opposite of NilClass).'
spec.homepage = 'https://github.com/tektite-software/ruby_utils'
spec.license = 'MIT'
spec.files = `git ls-files -z`
.split("\x0")
.reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.12'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'minitest', '~> 5.0'
end
|
thoughtbot/wrapped
|
spec/wrapped_spec.rb
|
<filename>spec/wrapped_spec.rb
require 'spec_helper'
require 'delegate'
describe Wrapped, 'conversion' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
let(:delegator) { SimpleDelegator.new(value).wrapped }
it "converts the value to a Present" do
expect(just).to be_instance_of(Present)
end
it "converts the nil to a Blank" do
expect(nothing).to be_instance_of(Blank)
end
it "converts a simple delegator to a Present" do
expect(delegator).to be_instance_of(Present)
expect(delegator.unwrap).to be_instance_of(SimpleDelegator)
end
end
describe Wrapped, 'accessing' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'produces the value of the wrapped object' do
expect(just.unwrap).to eq(value)
end
it 'raises an exception when called on the wrapped nil' do
expect { nothing.unwrap }.to raise_error(IndexError)
end
end
describe Wrapped, 'callbacks' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'calls the proper callback for a wrapped value' do
result = false
just.present {|v| result = v}
expect(result).to be_truthy
end
it 'calls the proper callback for a wrapped nil' do
result = false
nothing.blank {result = true}
expect(result).to be_truthy
end
it 'ignores the other callback for a wrapped value' do
result = true
just.blank { result = false }
expect(result).to be_truthy
end
it 'ignores the other callback for a wrapped nil' do
result = true
nothing.present { result = false }
expect(result).to be_truthy
end
it 'chains for wrapped values' do
result = false
just.present { result = true }.blank { result = false }
expect(result).to be_truthy
end
it 'chains for wrapped nils' do
result = false
nothing.present { result = false }.blank { result = true }
expect(result).to be_truthy
end
end
describe Wrapped, 'enumerable' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'acts over the value for #each on a wrapped value' do
result = -1
just.each {|v| result = v }
expect(result).to eq(value)
end
it 'produces itself for #each' do
expect(just.each).to eq(just)
end
it 'skips the block for #each on a wrapped nil' do
result = -1
nothing.each {|v| result = v }
expect(result).to eq(-1)
end
it 'produces blank for a wrapped nil on #each' do
expect(nothing.each).to eq(nothing)
end
it 'maps over the value for a wrapped value' do
expect(just.map {|n| n + 1}).to eq((value+1).wrapped)
end
it 'map produces blank' do
expect(nothing.map {|n| n + 1}).to be_instance_of(Blank)
end
it 'aliases map to collect' do
expect(just.method(:collect)).to be_alias_of(just.method(:map))
expect(nothing.method(:collect)).to be_alias_of(nothing.method(:map))
end
it 'select produces present for a value matching the block' do
expect(just.select { |n| n == value }).to eq(just)
end
it 'select produces blank for a value that does not match the block' do
expect(just.select { |n| n != value }).to be_instance_of(Blank)
end
it 'select products blank for a blank' do
expect(nothing.select { true }).to be_instance_of(Blank)
end
it 'aliases select to find_all' do
expect(just.method(:find_all)).to be_alias_of(just.method(:select))
expect(nothing.method(:find_all)).to be_alias_of(nothing.method(:select))
end
it 'reject produces present for a value matching the block' do
expect(just.reject { |n| n != value }).to eq(just)
end
it 'reject produces blank for a value that does not match the block' do
expect(just.reject { |n| n == value }).to be_instance_of(Blank)
end
it 'reject products blank for a blank' do
expect(nothing.reject { true }).to be_instance_of(Blank)
end
it 'grep produces present for a value matching the pattern' do
expect("hello".wrapped.grep(/ello$/)).to eq("hello".wrapped)
end
it 'grep produces blank for a value that does not match the pattern' do
expect("hello".wrapped.grep(/^ello/)).to be_instance_of(Blank)
end
it 'grep products blank for a blank' do
expect(nothing.grep(/.*/)).to be_instance_of(Blank)
end
end
describe Wrapped, 'queries' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'knows whether it is present' do
expect(just).to be_present
expect(nothing).not_to be_present
end
it 'knows whether it is blank' do
expect(just).not_to be_blank
expect(nothing).to be_blank
end
end
describe Wrapped, 'unwrap_or' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'produces the value for a wrapped value with an argument' do
expect(just.unwrap_or(-1)).to eq(value)
end
it 'produces the argument for a wrapped nil with an argument' do
expect(nothing.unwrap_or(-1)).to eq(-1)
end
it 'produces the value for a wrapped value with a block' do
expect(just.unwrap_or { value + 1 }).to eq(value)
end
it 'produces the block result for a wrapped nil with a block' do
expect(nothing.unwrap_or { 2 }).to eq(2)
end
end
describe Wrapped, 'monadic' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'produces the value from #flat_map for a wrapped value' do
expect(just.flat_map {|n| (n+1).wrapped }.unwrap).to eq(value+1)
end
it 'produces blank from #flat_map for a wrapped nil' do
expect(nothing.flat_map {|n| (n+1).wrapped}).to be_blank
end
end
describe Wrapped, 'functor' do
let(:value) { 1 }
let(:just) { 1.wrapped }
let(:nothing) { nil.wrapped }
it 'unwraps, applies the block, then re-wraps for a wrapped value' do
expect(just.fmap {|n| n+1}.unwrap).to eq(value+1)
end
it 'produces the blank for a wrapped nil' do
expect(nothing.fmap {|n| n+1}).to be_blank
end
it 'obeys the functor law: fmap id == id' do
expect(fmap(id).(just)).to eq(id.(just))
end
it 'obeys the functor law: fmap (f . g) == fmap f . fmap g' do
expect(fmap(compose(null, const(nil))).(just)).
to eq(compose(fmap(null), fmap(const(nil))).(just))
end
def fmap(f)
lambda { |x| x.fmap(&f) }
end
def const(x)
lambda { |_| x }
end
def id
lambda { |x| x }
end
def compose(f, g)
lambda { |x| f.call(g.call(x)) }
end
def null
lambda {|x| x.nil? }
end
end
describe Wrapped, 'equality' do
it 'is equal with the same wrapped value' do
expect(1.wrapped).to eq(1.wrapped)
end
it 'is not equal with a different wrapped value' do
expect(1.wrapped).not_to eq(2.wrapped)
end
it 'is equal with two wrapped nils' do
expect(nil.wrapped).to eq(nil.wrapped)
end
it 'is not equal with a wrapped nil and a wrapped value' do
expect(nil.wrapped).not_to eq(1.wrapped)
end
it 'is not equal with a wrapped value and a wrapped nil' do
expect(1.wrapped).not_to eq(nil.wrapped)
end
it 'is not equal with a present value and un unwrapped value' do
expect(1.wrapped).not_to eq(1)
end
it 'is not equal with a blank value and an unwrapped value' do
expect(nil.wrapped).not_to eq(1)
end
end
|
thoughtbot/wrapped
|
lib/wrapped/present.rb
|
<filename>lib/wrapped/present.rb
# A class that represents a wrapped value. This class holds something that is
# not nil.
class Present
include Enumerable
# Use Object#wrapped and NilClass#wrapped instead.
def initialize(value) # :nodoc:
@value = value
end
# Produce the value, unwrapped.
#
# If a block is given apply the block to the value and produce that.
#
# > w.unwrap_or(0)
# > w.unwrap_or("hello") {|s| "Hi, #{s}" }
def unwrap_or(_default = nil)
unwrap
end
# Invoke the block on the value, unwrapped. This method produces the wrapped
# value again, making it chainable. See `blank' for its companion.
#
# > w.present {|s| puts "Hello, #{s}" }.blank { puts "Do I know you?" }
def present(&block)
block.call(unwrap)
self
end
# Do nothing then produce the wrapped value, making it chainable. See
# `present' for its companion.
#
# > w.blank { puts "Symbol not found" }.present {|s| puts users[s]}
def blank(&ignored)
self
end
# Produces itself.
#
# If a block is passed, it is run against the unwrapped value.
#
# This class mixes in Enumerable, which is controlled by this method.
#
# > w.each {|n| puts "Found #{n}" }
def each
yield unwrap if block_given?
self
end
# Produces itself if the block evaluates to true. Produces Blank if the block
# evaluates to false.
def select
super.first.wrapped
end
alias_method :find_all, :select
# Produces itself if the block evaluates to false. Produces Blank if the block
# evaluates to true.
def reject
super.first.wrapped
end
# Produces itself if the unwrapped value matches the given expression.
# Produces Blank otherwise.
def grep(*)
super.first.wrapped
end
# The raw value. I doubt you need this method.
def unwrap
@value
end
# True; this is an instance of a wrapped value.
def present?
true
end
# False; this does not wrap a nil.
def blank?
false
end
# Run a block against the unwrapped value, producing the result of the block.
#
# > w.flat_map {|n| n+1 }
#
# Also, you can use this like you would use >>= in Haskell. This and wrapped
# make it a monad.
#
# > w.flat_map {|n| (n+1).wrapped }
def flat_map
yield unwrap
end
# Run a block within the wrapper. This produces a wrapped value.
#
# > w.fmap {|n| n+1 }
#
# This makes it a functor.
def fmap
Present.new(yield unwrap)
end
alias_method :collect, :fmap
alias_method :map, :fmap
# Is this wrapped value equal to the given wrapped value?
#
# > 1.wrapped == 1.wrapped
# > nil.wrapped == 2.wrapped
def ==(other)
other.is_a?(Present) && unwrap == other.unwrap_or(nil)
end
end
|
thoughtbot/wrapped
|
wrapped.gemspec
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "wrapped/version"
Gem::Specification.new do |s|
s.name = "wrapped"
s.version = Wrapped::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "http://github.com/mike-burns/wrapped"
s.license = 'BSD'
s.summary = %q{The maybe functor for Ruby}
s.description = %q{The unchecked nil is a dangerous concept leading to NoMethodErrors at runtime. It would be better if you were forced to explictly unwrap potentially nil values. This library provides mechanisms and convenience methods for making this more possible.}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_development_dependency("rspec", "~> 3.1.0")
s.add_development_dependency("rake")
end
|
thoughtbot/wrapped
|
lib/wrapped.rb
|
require 'wrapped/version'
require 'wrapped/injection'
|
thoughtbot/wrapped
|
spec/spec_helper.rb
|
require 'wrapped'
RSpec::Matchers.define :be_alias_of do |source_method|
match do |target_method|
block = lambda { |n| n + 1 }
target_method.call(&block) == source_method.call(&block)
end
end
|
thoughtbot/wrapped
|
lib/wrapped/blank.rb
|
<filename>lib/wrapped/blank.rb
# The class represents a lack of something.
class Blank
include Enumerable
# It is an error (specifically, an IndexError) to use this method.
def unwrap
raise IndexError.new("Blank has no value")
end
# Produce the value that is passed in.
#
# > w.unwrap_or(0)
def unwrap_or(default = nil)
if block_given?
yield
else
default
end
end
# Does nothing, returning itself. This is chainable. See blank for its
# companion.
#
# w.present.blank { puts "Missing" }
def present
self
end
# Call the block then return itself. This is chainable. See present for its
# companion.
#
# w.blank { puts "I got nothing" }.present {|n| puts "got #{n}" }
def blank(&block)
block.call
self
end
# Produce the empty list.
#
# This class mixes in the Enumerable module, which relies on this.
#
# > w.each {|n| puts n }
def each
self
end
# Produces itself.
def select
self
end
alias_method :find_all, :select
# Produces itself.
def reject
self
end
# Produces itself.
def grep(*)
self
end
# False; this is not an instance of a wrapped value.
def present?
false
end
# True; this is an instance of nothing.
def blank?
true
end
# Do nothing, returning itself.
#
# > w.flat_map {|n| n+1 }
def flat_map
self
end
# Do nothing, returning itself.
#
# > w.fmap {|n| n+1 }
def fmap
self
end
alias_method :collect, :fmap
alias_method :map, :fmap
# Is this wrapped value equal to the given wrapped value? All blank values
# are equal to each other.
#
# > nil.wrapped == nil.wrapped
# > 1.wrapped == nil.wrapped
def ==(other)
other.is_a?(Blank)
end
end
|
thoughtbot/wrapped
|
lib/wrapped/injection.rb
|
<gh_stars>10-100
require 'wrapped/present'
require 'wrapped/blank'
class BasicObject
# Wrap the object, forcing the user to be aware of the potential for a nil
# value by unwrapping it.
#
# See the Present class for details on how to unwrap it.
def wrapped
::Present.new(self)
end
end
class NilClass
# Wrap the nil, which is exactly the whole point. At this point the user must
# explictly deal with the nil, aware that it exists.
#
# See the Blank class and the README for details on how to work with this.
def wrapped
Blank.new
end
end
|
GrapeColor/telechannel
|
telechannel.rb
|
require 'bundler/setup'
require 'stringio'
require 'yaml'
require 'discordrb'
require 'discordrb/webhooks'
class Telechannel
MESSAGES_FILE = File.expand_path('../messages.yml', __FILE__)
MESSAGES_LIST = File.open(MESSAGES_FILE, 'r') { |f| YAML.load(f) }
REQUIRE_PERMIT = {
manage_webhooks: "ウェブフックの管理",
read_messages: "メッセージを読む",
send_messages: "メッセージを送信",
manage_messages: "メッセージの管理",
embed_links: "埋め込みリンク",
read_message_history: "メッセージ履歴を読む",
add_reactions: "リアクションの追加",
}
def initialize(bot_token)
@confirm_queue = Hash.new { |hash, key| hash[key] = [] } # 接続承認待ちチャンネル
@link_pairs = Hash.new { |hash, key| hash[key] = {} } # 接続済み
@webhook_relations = Hash.new
@related_messages = Hash.new { |hash, key| hash[key] = {} } # 転送メッセージの関係性
@error_channels = [] # Webhook取得に失敗したサーバー一覧
@bot = Discordrb::Commands::CommandBot.new(
token: bot_token,
prefix: "/",
help_command: false,
)
# BOT初期化処理
@bot.ready do
@bot.game = "/connect でヘルプ表示"
resume_links
end
# コネクション作成
@bot.command(:connect) do |event, p_channel_id|
next unless check_permission(event.channel, event.author)
next unless p_channel = get_arg_channel(event.channel, p_channel_id)
new_link(event.channel, p_channel, event.author)
nil
end
# コネクション削除
@bot.command(:disconnect) do |event, p_channel_id|
next unless check_permission(event.channel, event.author)
next unless p_channel = get_arg_channel(event.channel, p_channel_id)
remove_link(event.channel, p_channel, event.author)
nil
end
# 接続中のチャンネルを表示
@bot.command(:connecting) do |event|
next unless check_permission(event.channel, event.author)
listing_links(event)
nil
end
# BOTに必要な権限の検証
@bot.command(:connectable) do |event|
next unless check_permission(event.channel, event.author)
test_permittion(event.channel)
nil
end
# メッセージイベント
@bot.message do |event|
transfer_message(event)
nil
end
# メッセージ削除イベント
@bot.message_delete do |event|
destroy_message(event.id)
nil
end
# メッセージ編集イベント
@bot.message_edit do |event|
edited_message(event)
nil
end
# ウェブフック更新イベント
@bot.webhook_update do |event|
check_webhooks(event.channel)
nil
end
# 招待コマンド
@bot.mention do |event|
next if event.content !~ /^<@!?\d+> *invite/
channel = event.author.pm
channel.send_embed do |embed|
invite = MESSAGES_LIST[:invite]
embed.color = invite[:color]
embed.title = invite[:title]
embed.description = invite[:description]
end
end
# デバッグコマンド
@bot.mention(in: ENV['ADMIN_CHANNEL_ID'].to_i, from: ENV['ADMIN_USER_ID'].to_i) do |event|
next if event.content !~ /^<@!?\d+> admin (.+)/
$stdout = StringIO.new
begin
value = eval("pp(#{$1})")
log = $stdout.string
rescue => exception
log = exception
end
$stdout = STDOUT
event.send_message("**STDOUT**")
log.to_s.scan(/.{1,#{2000 - 8}}/m) do |split|
event.send_message("```\n#{split}\n```")
end
event.send_message("**RETURN VALUE**")
value.to_s.scan(/.{1,#{2000 - 8}}/m) do |split|
event.send_message("```\n#{split}\n```")
end
end
end
# BOT起動
def run(async = false)
@bot.run(async)
end
private
# 実行権限チェック
def check_permission(channel, member)
return if member.bot_account?
return true if channel.private?
return unless member.is_a?(Discordrb::Member)
member.permission?(:manage_channels, channel)
end
# 引数のチャンネルを取得
def get_arg_channel(channel, p_channel_id)
# ヘルプ表示(パラメータなし)
if p_channel_id.nil?
channel.send_embed do |embed|
help = MESSAGES_LIST[:help]
embed.color = help[:color]
embed.title = help[:title]
embed.description = help[:description]
end
return
end
# チャンネルが指定されていない
if p_channel_id !~ /^(\d+)$/ && p_channel_id !~ /^<#(\d+)>$/
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ チャンネルIDを指定してください"
embed.description = "コマンドのパラメータにチャンネルID、またはチャンネルメンションを指定してください。"
end
return
end
# チャンネルIDを解決できるか
begin
p_channel = @bot.channel($1)
rescue
p_channel = nil
end
if p_channel.nil?
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 指定されたチャンネルが見つかりません"
embed.description = "指定したチャンネルが存在しないか、BOTが導入されていません。"
end
return
end
# チャンネルが同一ではないか
if channel == p_channel
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 指定されたチャンネルはこのチャンネルです"
embed.description = "このチャンネル自身に対して接続することはできません。"
end
return
end
p_channel
end
#================================================
# 新しい接続
def new_link(channel, p_channel, user)
# 接続可能か検証
return unless link_validation(channel, p_channel, user)
# 接続方法選択
if p_channel.private? || channel.private?
receive = p_channel.private?
send = channel.private?
elsif p_channel.category?
receive = true
send = false
else
receive, send = link_select(channel, p_channel, user)
end
return unless receive || send
# 相手チャンネル上のメンバーデータ
p_member = @bot.member(p_channel.server, user.id) unless p_channel.private?
# 相手チャンネル上で権限を持つか
p_permit = p_member && p_member.permission?(:manage_channels, channel)
# 相手チャンネル上で権限を持たないとき
unless p_permit
p_member, confirm_ch = link_confirmation(channel, p_channel)
return if p_member.nil?
end
# 双方向接続・一方向接続(送信側)の場合
if send
return unless link_create_other(channel, p_channel, p_permit)
end
# 自チャンネルのリンクを作成
if !receive || create_link(channel, p_channel)
link_success(channel, p_channel, receive, send, user, p_member)
else
link_failure(channel, p_channel, send, confirm_ch)
end
end
# 接続済み検証
def link_validation(channel, p_channel, user)
return if @confirm_queue[channel.id].include?(p_channel.id)
receive = @link_pairs[p_channel.id].has_key?(channel.id)
send = @link_pairs[channel.id].has_key?(p_channel.id)
unless receive || send
receive = @link_pairs[p_channel.id].has_key?(channel.parent_id)
send = @link_pairs[channel.parent_id].has_key?(p_channel.id)
end
if receive || send
channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "ℹ️ すでに接続されています"
embed.description = "**#{gen_channel_disp(channel, p_channel)}** と "
if receive && send
embed.description += "**双方向接続** されています。"
else
embed.description += "**一方向接続(#{send ? "送" : "受" }信側)** されています。"
end
embed.description += "\n\n切断は `/disconnect #{p_channel.id}` で行えます。"
end
return
end
if channel.private? && p_channel.private?
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ プライベートチャンネル同士は接続できません"
embed.description = "ダイレクトメッセージや、グループチャット同士を接続することはできません。"
end
return
end
true
end
# 接続方式の選択
def link_select(channel, p_channel, user)
message = channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "🆕 ##{p_channel.name} との接続方法を選んでください(1分以内)"
embed.description = "↔️ **双方向接続**\n 相手チャンネルと互いにメッセージを送信します\n\n"
embed.description += "⬅️ **一方向接続(受信側)**\n相手チャンネルのメッセージをこのチャンネルへ送信します\n\n"
embed.description += "➡️ **一方向接続(送信側)**\nこのチャンネルのメッセージを相手チャンネルへ送信します"
end
message.create_reaction("↔️")
message.create_reaction("⬅️")
message.create_reaction("➡️")
# 選択待ち
receive = nil
send = nil
await_event = @bot.add_await!(Discordrb::Events::ReactionAddEvent, { timeout: 60 }) do |event|
next if event.message != message || event.user != user
case event.emoji.name
when "↔️"; send, receive = true, true
when "➡️"; send, receive = true, false
when "⬅️"; send, receive = false, true
else; next
end
true
end
message.delete
return if await_event.nil? # イベントタイムアウト
return receive, send
end
# 接続承認処理
def link_confirmation(channel, p_channel)
message = channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "ℹ️ 相手チャンネルでコマンドを実行してください(10分以内)"
embed.description = "**#{gen_channel_disp(channel, p_channel)}**"
embed.description += " で以下のコマンドを実行してください。\n```/connect #{channel.id}```"
end
# 承認コマンド入力待ち
p_member = nil
confirm_ch = nil
@confirm_queue[p_channel.id] << channel.id
await_event = @bot.add_await!(Discordrb::Events::MessageEvent, { timeout: 600 }) do |event|
next if event.content != "/connect #{channel.id}"
if event.channel != p_channel
next unless event.channel.parent_id
next if event.channel.category != p_channel
end
p_member = event.author
next unless p_channel.private? || p_member.permission?(:manage_channels, p_channel)
confirm_ch = event.channel
true
end
@confirm_queue[p_channel.id].delete(channel.id)
message.delete
# イベントタイムアウト
if await_event.nil?
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続待ちがタイムアウトしました"
embed.description = "**#{gen_channel_disp(channel, p_channel)}**"
embed.description += " で10分以内に権限を持ったメンバーによる指定コマンドの実行がありませんでした。\n"
embed.description += "最初からコマンドを実行しなおしてください。"
end
return
end
return p_member, confirm_ch
end
# 相手側のリンクを作成
def link_create_other(channel, p_channel, p_permit)
unless create_link(p_channel, channel)
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 相手チャンネルと接続できませんでした"
embed.description = "**#{gen_channel_disp(channel, p_channel)}** でウェブフックを作成できませんでした。\n"
embed.description += "チャンネルのウェブフックの作成数が上限(10個)に達していないか、"
embed.description += "BOTの権限が十分か確認し、最初からコマンドを実行しなおしてください。"
end
# 承認コマンドを要求していた場合
if confirm_ch
confirm_ch.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 相手チャンネルと接続できませんでした"
embed.description = "**このチャンネル** でウェブフックを作成できませんでした。\n"
embed.description += "チャンネルのウェブフックの作成数が上限(10個)に達していないか、"
embed.description += "BOTの権限が十分か確認し、最初からコマンドを実行しなおしてください。"
end
end
return
end
true
end
# 接続成功(自チャンネルでのWebhook作成成功)
def link_success(channel, p_channel, receive, send, user, p_user)
channel.send_embed do |embed|
embed.color = 0x77b255
embed.title = "✅ 相手チャンネルと接続しました"
embed.description = "**#{gen_channel_disp(channel, p_channel)}** と "
if receive && send
embed.description += "**双方向接続** しました。"
else
embed.description += "**一方向接続(#{send ? "送" : "受" }信側)** しました。"
end
embed.description += "\n\n切断は `/disconnect #{p_channel.id}` で行えます。"
embed.footer = Discordrb::Webhooks::EmbedFooter.new(
text: user.distinct,
icon_url: user.avatar_url
)
end
return if p_channel.category?
p_channel.send_embed do |embed|
embed.color = 0x77b255
embed.title = "✅ 相手チャンネルと接続しました"
embed.description = "**#{gen_channel_disp(p_channel, channel)}** と "
if receive && send
embed.description += "**双方向接続** しました。"
else
embed.description += "**一方向接続(#{send ? "受" : "送" }信側)** しました。"
end
embed.description += "\n\n切断は `/disconnect #{channel.id}` で行えます。"
embed.footer = Discordrb::Webhooks::EmbedFooter.new(
text: p_user.distinct,
icon_url: p_user.avatar_url
)
end
end
# 接続失敗(自チャンネルでのWebhook作成失敗)
def link_failure(channel, p_channel, send, confirm_ch)
destroy_link(p_channel, channel) if send # 相手チャンネルのリンクをロールバック
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 相手チャンネルと接続できませんでした"
embed.description = "**このチャンネル** でウェブフックを作成できませんでした。\n"
embed.description += "チャンネルのウェブフックの作成数が上限(10個)に達していないか、"
embed.description += "BOTの権限が十分か確認し、最初からコマンドを実行しなおしてください。"
end
# 承認コマンドを要求していた場合
if confirm_ch
confirm_ch.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 相手チャンネルと接続できませんでした"
embed.description = "**#{gen_channel_disp(p_channel, channel)}** でウェブフックを作成できませんでした。\n"
embed.description += "チャンネルのウェブフックの作成数が上限(10個)に達していないか、"
embed.description += "BOTの権限が十分か確認し、最初からコマンドを実行しなおしてください。"
end
end
end
#================================================
# 接続の切断
def remove_link(channel, p_channel, user)
unless @link_pairs[channel.id].has_key?(p_channel.id) || @link_pairs[p_channel.id].has_key?(channel.id)
category = channel.category if channel.parent_id
unless category || @link_pairs[category.id].has_key?(p_channel.id) || @link_pairs[p_channel.id].has_key?(category.id)
channel.send_embed do |embed|
embed.color = 0xffcc4d
embed.title = "⚠️ 指定されたチャンネルは接続していません"
embed.description = "接続には以下のコマンドを使用してください。\n"
embed.description += "```/connect [チャンネルID or チャンネルメンション]```"
end
return
end
end
destroy_link(category || channel, p_channel)
destroy_link(p_channel, category || channel)
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "**#{gen_channel_disp(channel, p_channel)}**"
embed.description += " と接続が切断されました。"
embed.footer = Discordrb::Webhooks::EmbedFooter.new(
text: user.distinct,
icon_url: user.avatar_url
)
end
return if p_channel.category?
p_channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "**#{gen_channel_disp(p_channel, category || channel)}**"
embed.description += " と接続が切断されました。"
embed.footer = Discordrb::Webhooks::EmbedFooter.new(
text: user.distinct,
icon_url: user.avatar_url
)
end
end
#================================================
# 接続の再開
def resume_links
@bot.servers.each do |_, server|
server.text_channels.each {|channel| resume_channel_links(channel) }
end
end
# 指定サーバーの接続再開
def resume_channel_links(channel)
begin
webhooks = channel.webhooks
rescue
@error_channels << channel.id
return
end
webhooks.each do |webhook|
next if webhook.owner != @bot.profile
begin
p_channel = @bot.channel(webhook.name[/Telehook<(\d+)>/, 1])
rescue
webhook.delete("Other a channel have been lost.")
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "相手チャンネルが見つからないため、接続が切断されました。"
end
next
end
next unless p_channel
# 重複ウェブフックを削除
if @link_pairs[p_channel.id].has_key?(channel.id)
webhook.delete if webhook != @link_pairs[p_channel.id][channel.id]
next
end
@webhook_relations[webhook.id] = p_channel.id
@link_pairs[p_channel.id][channel.id] = webhook
end
true
end
#================================================
# 接続作成(p_channel ⇒ channel[webhook])
def create_link(channel, p_channel)
if @error_channels.delete(channel.id)
return unless resume_channel_links(channel)
end
begin
webhook = channel.create_webhook(
"Telehook<#{p_channel.id}>",
@webhook_icon,
"To receive messages from other a channel."
)
rescue; return; end
@webhook_relations[webhook.id] = p_channel.id
@link_pairs[p_channel.id][channel.id] = webhook
end
# 接続削除
def destroy_link(channel, p_channel)
webhook = @link_pairs[p_channel.id].delete(channel.id)
return if webhook.nil?
begin
webhook.delete("To disconnect from other a channel.")
rescue; nil; end
@webhook_relations.delete(webhook.id)
true
end
# 接続相手喪失
def lost_link(channel, p_channel_id)
@link_pairs[channel.id].delete(p_channel_id)
webhook = @link_pairs[p_channel_id].delete(channel.id)
return if webhook.nil?
begin
webhook.delete("Other a channel have been lost.")
rescue; nil; end
@webhook_relations.delete(webhook.id)
end
#================================================
# メッセージ転送
def transfer_message(event, send_list = {})
return if event.author.bot_account?
channel = event.channel
message = event.message
if send_list.empty?
send_list.merge!(@link_pairs[channel.id]) if @link_pairs.has_key?(channel.id)
send_list.merge!(@link_pairs[channel.parent_id]) if @link_pairs.has_key?(channel.parent_id)
end
return if send_list.empty?
posts = []
send_list.each do |p_channel_id, p_webhook|
begin
p_channel = @bot.channel(p_channel_id)
rescue
lost_link(channel, p_channel_id)
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "相手チャンネルが見つからないため、接続が切断されました。"
end
next
end
posts << Thread.new { post_webhook(channel, p_channel, p_webhook, message) }
end
posts.each {|post| post.join }
end
# Webhookへの送信処理
def post_webhook(channel, p_channel, p_webhook, message)
client = Discordrb::Webhooks::Client.new(id: p_webhook.id, token: p_webhook.token)
# メッセージ送信
unless message.content.empty?
await = chase_message(p_channel, p_webhook, message)
execute = execute_webhook(channel, p_channel, client, message.author, message.content, await)
await.join
execute.join
end
# 添付ファイル(CDNのURL)送信
unless message.attachments.empty?
content = message.attachments.map do |attachment|
attachment.spoiler? ? "||#{attachment.url}||" : attachment.url
end.join("\n")
await = chase_message(p_channel, p_webhook, message)
execute = execute_webhook(channel, p_channel, client, message.author, content, await)
await.join
execute.join
end
end
# メッセージ追跡
def chase_message(p_channel, p_webhook, message)
Thread.new do
@bot.add_await!(Discordrb::Events::MessageEvent, { timeout: 60, from: p_webhook.id }) do |event|
next if event.author.name !~ /^#{message.author.distinct}/
next if event.message.id < message.id
@related_messages[message.id][event.message.id] = p_channel.id
true
end
end
end
# Webhook実行
def execute_webhook(channel, p_channel, client, author, content, await)
Thread.new do
begin
client.execute do |builder|
builder.avatar_url = author.avatar_url
builder.username = gen_webhook_username(channel, p_channel, author)
builder.content = content
end
rescue RestClient::NotFound
await.kill # メッセージ追跡スレッドを終了
destroy_link(channel, p_channel)
destroy_link(p_channel, channel)
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "**#{gen_channel_disp(channel, p_channel)}**"
embed.description += " のウェブフックが見つからないため、接続が切断されました。"
end unless channel.category?
p_channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description += "**このチャンネル** のウェブフックが見つからないため、接続が切断されました。"
end
rescue
await.kill # メッセージ追跡スレッドを終了
end
end
end
# 関係するメッセージの削除
def destroy_message(message_id)
return unless p_messages = @related_messages.delete(message_id)
p_messages.each do |p_message_id, p_channel_id|
begin
Discordrb::API::Channel.delete_message(@bot.token, p_channel_id, p_message_id)
rescue; next; end
end
end
# 関係するメッセージの編集
def edited_message(event)
return unless p_messages = @related_messages.delete(event.message.id)
send_list = p_messages.map do |p_message_id, p_channel_id|
begin
response = Discordrb::API::Channel.messages(@bot.token, p_channel_id, 2)
p_message = Discordrb::Message.new(JSON.parse(response)[0], @bot)
rescue; next; end
next if p_message.id != p_message_id
p_message.delete
# 添付ファイル付きメッセージの本文を削除
p_message = Discordrb::Message.new(JSON.parse(response)[1], @bot)
p_message.delete if p_messages.has_key?(p_message.id)
# 相手ウェブフックを取得
p_webhook = @link_pairs[event.channel.id][p_channel_id]
p_webhook = @link_pairs[event.channel.parent_id][p_channel_id] unless p_webhook
[p_channel_id, p_webhook]
end.compact.to_h
transfer_message(event, send_list)
end
#================================================
# ウェブフックの変更を検証
def check_webhooks(channel)
begin
webhooks = channel.webhooks
rescue
@link_pairs.each {|key, _| key.delete(channel.id) }
@error_channels << channel.id
return
end
webhooks.each do |webhook|
next if webhook.owner != @bot.profile
p_channel_id = @webhook_relations[webhook.id]
next if webhook.name =~ /Telehook<#{p_channel_id}>/
begin
p_channel = @bot.channel(p_channel_id)
rescue
lost_link(channel, p_channel_id)
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "ウェブフックの名前が変更されたため、接続を切断しました。"
end
next
end
destroy_link(channel, p_channel)
destroy_link(p_channel, channel)
channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "**#{gen_channel_disp(channel, p_channel)}**"
embed.description += " と接続していたウェブフックの名前が変更されたため、接続を切断しました。"
end
next if p_channel.category?
p_channel.send_embed do |embed|
embed.color = 0xbe1931
embed.title = "⛔ 接続が切断されました"
embed.description = "**#{gen_channel_disp(p_channel, channel)}**"
embed.description += " のウェブフックが見つからないため、接続が切断されました。"
end
end
end
#================================================
# 接続済みリストを表示
LINK_MODE_ICONS = { mutual: "↔️", receive: "⬅️", send: "➡️" }
def listing_links(event)
channel = event.channel
link_list = {}
gen_link_list(link_list, channel)
gen_link_list(link_list, channel.category) if channel.parent_id
if link_list.empty?
channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "ℹ️ 接続中のチャンネルはありません"
end
return
end
channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "ℹ️ 接続中のチャンネル一覧"
embed.description = "↔️ 双方向接続 ⬅️ 一方向接続(受信側) ➡️ 一方向接続(送信側)\n"
link_list.each do |p_channel_id, item|
embed.description += "\n#{LINK_MODE_ICONS[item[:mode]]} #{item[:name]} 🆔 `#{p_channel_id}`"
end
end
end
def gen_link_list(link_list, channel)
@link_pairs[channel.id].each do |p_channel_id, p_webhook|
begin
p_channel = @bot.channel(p_channel_id)
rescue; next; end
link_list[p_channel.id] = { name: gen_channel_disp(channel, p_channel), mode: :send }
link_list[p_channel.id][:mode] = :mutual if @link_pairs[p_channel.id][channel.id]
end
@link_pairs.each do |p_channel_id, pair_data|
next if link_list.has_key?(p_channel_id)
if pair_data.find {|channel_id, _| channel_id == channel.id }
begin
p_channel = @bot.channel(p_channel_id)
rescue; next; end
link_list[p_channel.id] = { name: gen_channel_disp(channel, p_channel), mode: :receive }
end
end
end
#================================================
# 権限の検証
def test_permittion(channel)
if channel.private?
channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "ℹ️ 一方向接続(送信側)のみ使用できます"
end
return
end
bot_member = channel.server.member(@bot.profile.id)
channel.send_embed do |embed|
embed.color = 0x3b88c3
embed.title = "ℹ️ BOTに必要な権限一覧"
embed.description = ""
REQUIRE_PERMIT.each do |action, summary|
embed.description += bot_member.permission?(action, channel) ? "✅" : "⚠️"
embed.description += " #{summary}\n"
end
end
end
#================================================
# 相手チャンネル表示取得
def gen_channel_disp(channel, p_channel)
if p_channel.server == channel.server
return p_channel.category? ? "カテゴリ: #{p_channel.name}" : p_channel.mention
end
server_name = if p_channel.pm?
"DMチャンネル: "
elsif p_channel.group?
"グループチャット: "
elsif p_channel.category?
"#{p_channel.server.name} カテゴリ: "
else
"#{p_channel.server.name}: #"
end
"#{server_name}#{p_channel.name}"
end
# Webhookのユーザー名生成
def gen_webhook_username(channel, p_channel, user)
if channel.server == p_channel.server
return "#{user.distinct} (#{channel.category? ? "カテゴリ: " : "#"}#{channel.name})"
end
server_name = if channel.pm?
"DMチャンネル: "
elsif channel.group?
"グループチャット: "
elsif channel.category?
"#{channel.server.name} カテゴリ: "
else
"#{channel.server.name}: #"
end
"#{user.distinct} (#{server_name}#{channel.name})"
end
end
|
GrapeColor/telechannel
|
execution.rb
|
require 'dotenv/load'
require './telechannel'
telechannel = Telechannel.new(ENV['TELECHANNEL_TOKEN'])
telechannel.run
|
GrapeColor/telechannel
|
telechannel_old.rb
|
require 'bundler/setup'
require 'discordrb'
require 'discordrb/webhooks/client'
class Telechannel
WEBHOOK_NAME_REG = /^Telehook<(\d+)>$/
EMBED_COLOR = 0xea596e
def initialize(bot_token)
@bot = Discordrb::Commands::CommandBot.new(
token: bot_token,
prefix: "/",
help_command: false,
webhook_commands: false,
ignore_bots: true
)
@link_queues = Hash.new { |hash, key| hash[key] = {} } # 接続待機
@link_pairs = Hash.new { |hash, key| hash[key] = {} } # 接続済み
# BOT初期化処理
@bot.ready do
@bot.game = "#{@bot.prefix}connect"
end
# コマンド共通属性
@command_attrs = {
permission_message: "⚠️ **#{@bot.prefix}%name%** コマンドの実行には **チャンネル管理** 権限が必要です",
required_permissions: [:manage_channels]
}
# コネクション作成
@bot.command(:connect, @command_attrs) do |event, p_channel_id|
if p_channel_id.nil?
view_help(event)
next
end
if p_channel_id !~ /^\d+$/
event.send_message("⚠️ チャンネルIDを指定してください")
next
end
add_link(event.channel, p_channel_id.to_i)
nil
end
# コネクション削除
@bot.command(:disconnect, @command_attrs) do |event, p_channel_id|
if p_channel_id.nil?
view_help(event)
next
end
if p_channel_id !~ /^\d+$/
event.send_message("⚠️ チャンネルIDを指定してください")
next
end
remove_link(event.channel, p_channel_id.to_i)
nil
end
# 接続中のチャンネルを表示
@bot.command(:connecting, @command_attrs) do |event|
resume_links(event.channel)
event.send_embed do |embed|
embed.color = EMBED_COLOR
embed.title = "接続中のチャンネル一覧"
pair_list = get_pair_list(event.channel)
if pair_list.empty?
embed.description = "(接続中のチャンネルはありません)"
else
embed.description = ""
pair_list.each do |pair|
embed.description += "#{pair[:server_name]} ##{pair[:channel_name]} : **`#{pair[:channel_id]}`**\n"
end
end
end
end
# メッセージイベント
@bot.message do |event|
next unless event.channel.text?
next if event.content.start_with?(@bot.prefix)
send_content(event)
nil
end
# Webhook更新イベント
@bot.webhook_update do |event|
check_links(event.channel)
nil
end
# チャンネル削除イベント
@bot.channel_delete do |event|
lost_links(event.id)
nil
end
# 招待コマンド
@bot.mention do |event|
next if event.content !~ /^<@!?#{@bot.profile.id}> ?invite/
channel = event.author.pm
channel.send_embed do |embed|
embed.color = EMBED_COLOR
embed.title = "Telechannel に興味をもっていただき、ありがとうございます!"
embed.description = <<DESC
このBOTは簡単なコマンド操作でチャンネル間の相互チャットを実現できるBOTです。
BOTの使用方法・導入方法は[こちら](https://github.com/GrapeColor/telechannel/blob/master/README.md)のリンクをご覧ください。
DESC
end
end
# デバッグコマンド
@bot.mention(in: ENV['ADMIN_CHANNEL_ID'].to_i, from: ENV['ADMIN_USER_ID'].to_i) do |event|
next if event.content !~ /^<@!?\d+> admin (.+)/
begin
value = eval($1)
rescue => exception
value = exception
end
event << "```\n#{value}\n```"
end
end
# BOT起動
def run(async = false)
@bot.run(async)
end
private
# ヘルプを表示
def view_help(event)
event.send_embed do |embed|
embed.color = EMBED_COLOR
embed.title = "Telechannel の使い方"
embed.description = <<DESC
コマンドで簡単に他サーバー、他チャンネルと接続できるBOTです。
**`#{@bot.prefix}connect [相手のチャンネルID]`** : 指定されたチャンネルと接続します
**`#{@bot.prefix}disconnect [相手のチャンネルID]`** : 指定されたチャンネルを切断します
**`#{@bot.prefix}connecting`** : このチャンネルに接続されているチャンネルを表示します
このチャンネルと接続するには、
相手のチャンネルで **`#{@bot.prefix}connect #{event.channel.id}`** を実行してください。
[詳しい使用方法](https://github.com/GrapeColor/telechannel/blob/master/README.md)
DESC
end
end
# ペアまたはキューに登録
def add_link(channel, p_channel_id, no_msg = false)
# チャンネル取得
p_channel = get_p_channel(p_channel_id, channel && !no_msg)
return unless p_channel
if p_channel.id == channel.id
channel.send_message("⚠️ **指定されたチャンネルはこのチャンネルです**") unless no_msg
return
end
# 登録済み確認
if @link_queues[channel.id][p_channel.id]
channel.send_message(
"ℹ️ 既に **#{p_channel.server.name} ##{p_channel.name}** との接続を待っています\n" +
"相手チャンネルで次のコマンドを実行してください **`#{@bot.prefix}connect #{channel.id}`**"
) unless no_msg
return
end
if @link_pairs[channel.id][p_channel.id]
channel.send_message("ℹ️ **指定されたチャンネルは接続済みです**") unless no_msg
return
end
# ウェブフックを作成
webhook = get_webhook(channel, p_channel)
return unless webhook
# キューを取り出す
p_webhook = @link_queues[p_channel.id].delete(channel.id)
if p_webhook.nil?
# キューに登録
@link_queues[channel.id][p_channel.id] = webhook
channel.send_message(
"ℹ️ **#{p_channel.server.name} ##{p_channel.name}** との接続を待っています\n" +
"相手チャンネルで次のコマンドを実行してください **`#{@bot.prefix}connect #{channel.id}`**"
) unless no_msg
else
# ペアに登録
@link_pairs[channel.id][p_channel.id] = p_webhook
@link_pairs[p_channel.id][channel.id] = webhook
channel.send_message(
"✅ **#{p_channel.server.name} ##{p_channel.name}** と接続されました\n" +
"切断するには次のコマンドを実行してください **`#{@bot.prefix}disconnect #{p_channel.id}`**"
) unless no_msg
p_channel.send_message(
"✅ **#{channel.server.name} ##{channel.name}** と接続されました\n" +
"切断するには次のコマンドを実行してください **`#{@bot.prefix}disconnect #{channel.id}`**"
) unless no_msg
end
p_channel
end
# ペアまたはキューの削除
def remove_link(channel, p_channel_id, no_msg = false)
# チャンネル取得
p_channel = get_p_channel(p_channel_id)
if p_channel && p_channel.id == channel.id
channel.send_message("⚠️ **指定されたチャンネルはこのチャンネルです**") unless no_msg
return
end
p_webhook = @link_pairs[channel.id].delete(p_channel_id)
# キューの削除
if p_webhook.nil?
webhook = @link_queues[channel.id].delete(p_channel_id)
if webhook
begin; webhook.delete
rescue; nil; end
if p_channel
channel.send_message("ℹ️ **#{p_channel.server.name} ##{p_channel.name}** の接続待ちがキャンセルされました") unless no_msg
else
channel.send_message("ℹ️ 接続待ちがキャンセルされました") unless no_msg
end
else
channel.send_message("⚠️ **指定されたチャンネルは接続されていません**") unless no_msg
# 未登録のWebhookを削除
channel.webhooks.each do |webhook|
next if webhook.owner.id != @bot.profile.id
next if webhook.name !~ WEBHOOK_NAME_REG || $1.to_i != p_channel_id
webhook.delete
end
end
return p_channel
end
# ペアの削除
webhook = @link_pairs[p_channel_id].delete(channel.id)
if webhook
begin; webhook.delete
rescue; nil; end
if p_channel
channel.send_message("⛔ **#{p_channel.server.name} ##{p_channel.name}** と切断されました") unless no_msg
else
channel.send_message("⛔ 接続相手と切断されました") unless no_msg
end
end
begin; p_webhook.delete
rescue; nil; end
if p_channel
p_channel.send_message("⛔ **#{channel.server.name} ##{channel.name}** と切断されました") unless no_msg
end
p_channel
end
# すべての接続を切断
def remove_all_links(channel)
# ペア情報を元にWebhookを削除
if @link_pairs.has_key?(channel.id)
@link_pairs[channel.id].each do |p_channel_id, p_webhook|
remove_link(channel, p_channel_id)
end
end
# チャンネルのWebhookを削除
channel.webhooks.each do |webhook|
webhook.delete if webhook.owner.id == @bot.profile.id
end
end
# チャンネルIDの接続先をすべて切断
def lost_links(channel_id)
return unless @link_pairs.has_key?(channel.id)
@link_pairs[channel_id].each do |p_channel_id, p_webhook|
p_channel = get_p_channel(p_channel_id)
remove_link(p_channel, channel_id)
end
end
# 接続確認
def check_links(channel)
webhook_ids = channel.webhooks.map do |webhook|
webhook.name =~ WEBHOOK_NAME_REG
[webhook.id, $1.to_i]
end.to_h
return unless @link_pairs.has_key?(channel.id)
@link_pairs[channel.id].each do |p_channel_id, p_webhook|
webhook = @link_pairs[p_channel_id][channel.id]
unless webhook_ids.has_key?(webhook.id) && webhook_ids[webhook.id] == p_channel_id
remove_link(channel, p_channel_id)
end
end
end
# メッセージ送信
def send_content(event)
channel = event.channel
message = event.message
resume_links(channel)
return unless @link_pairs.has_key?(channel.id)
@link_pairs[channel.id].each do |p_channel_id, p_webhook|
client = Discordrb::Webhooks::Client.new(id: p_webhook.id, token: p_webhook.token)
if message.author.respond_to?(:display_name)
display_name = message.author.display_name
else
display_name = message.author.username
end
begin
# メッセージ送信
if !message.content.strip.empty?
client.execute do |builder|
builder.avatar_url = message.author.avatar_url
builder.username = "#{display_name} (@#{channel.server.name} ##{channel.name})"
builder.content += message.content
end
end
# 添付ファイル(CDNのURL)送信
if !message.attachments.empty?
client.execute do |builder|
builder.avatar_url = message.author.avatar_url
builder.username = "#{display_name} (@#{channel.server.name} ##{channel.name})"
builder.content = "(添付ファイル)\n"
message.attachments.each do |attachment|
builder.content += attachment.spoiler? ? "📎 ||#{attachment.url}||\n" : "📎 #{attachment.url}\n"
end
end
end
rescue RestClient::NotFound
remove_link(channel, p_channel_id)
end
end
end
# 接続再構築
def resume_links(channel)
return if @link_pairs.has_key?(channel.id) || @link_queues.has_key?(channel.id)
channel.webhooks.each do |webhook|
next if webhook.owner.id != @bot.profile.id
next if webhook.name !~ WEBHOOK_NAME_REG
p_channel_id = $1.to_i
# キュー登録
p_channel = add_link(channel, p_channel_id, true)
unless p_channel
remove_link(channel, p_channel_id)
next
end
# ペア登録
p_channel.webhooks.each do |webhook|
next if webhook.owner.id != @bot.profile.id
next if webhook.name !~ WEBHOOK_NAME_REG || $1.to_i != channel.id
add_link(p_channel, channel.id, true)
end
end
end
# 相手チャンネルを取得
def get_p_channel(p_channel_id, channel = nil)
begin
p_channel = @bot.channel(p_channel_id)
rescue Discordrb::Errors::NoPermission
channel.send_message("⚠️ **指定されたチャンネルにBOTが導入されていません**") if channel
return nil
end
if p_channel.nil?
channel.send_message("⚠️ **指定されたチャンネルは存在しません**") if channel
return nil
end
p_channel
end
# Webhookの取得または作成
def get_webhook(channel, p_channel)
# 既存のWebhookを取得
begin
webhooks = channel.webhooks.select do |webhook|
webhook.name =~ WEBHOOK_NAME_REG
$1.to_i == p_channel.id && webhook.owner.id == @bot.profile.id
end
rescue Discordrb::Errors::NoPermission
channel.send_message("⚠️ BOTに **ウェブフックの管理** 権限が必要です")
return nil
end
# Webhookを作成
if webhooks.empty?
begin
webhook = channel.create_webhook("Telehook<#{p_channel.id}>")
rescue Discordrb::Errors::NoPermission
channel.send_message("⚠️ BOTに **ウェブフックの管理** 権限が必要です")
return nil
end
return webhook
end
webhooks.first
end
# 接続済みリスト取得
def get_pair_list(channel)
return [] unless @link_pairs.has_key?(channel.id)
@link_pairs[channel.id].map do |p_channel_id, p_webhook|
p_channel = get_p_channel(p_channel_id)
next unless p_channel
{ server_name: p_channel.server.name, channel_name: p_channel.name, channel_id: p_channel.id }
end
end
end
|
githubteacher/example-githubapiscripts
|
gh_unsub.rb
|
#!/usr/bin/env ruby
require 'octokit'
pass_re = /^password: "(.*)"$/
token = '***** GET A TOKEN *****'
c = Octokit::Client.new(:access_token => token)
user_login = c.user.login
puts "Finding your mentions...\n"
notifications = 50.times.map {|x| c.notifications(:page => x+1)}.take_while {|x| x.count > 1}.inject([]) {|acc,x| acc.concat(x); acc}
repos = notifications.map {|x| x.repository.full_name}.sort.uniq
puts "Fetching contributors from #{repos.count} repos...\n"
contrib = repos.map do |x|
begin
contrib = c.contributors(x)
raise "wtf" unless contrib.is_a?(Array)
ret = [x, contrib]
rescue
## NB: When you fetch from a repo that has never been contributed to
## by anyone, the API throws a 404
ret = [x, []]
end
end
to_unsub = contrib.select {|x| ! x[1].any? {|y| y[:login] == user_login } }.map {|x| x[0]}
if (ARGV[0] == "-f")
puts "Unsubscribing from #{to_unsub.count} repos..."
to_unsub.each {|x| puts x; c.delete_subscription(x) }
else
puts "\nYou should unsubscribe from:"
to_unsub.each {|x| puts "#{x} - https://github.com/#{x}" }
puts "\nRerun with -f to unsubscribe"
end
|
githubteacher/example-githubapiscripts
|
migrate_repo.rb
|
<reponame>githubteacher/example-githubapiscripts
require "json"
require "typhoeus"
require "pp"
# MigrateRepo usage instructions:
#
# The way this is used at REDACTEDBYREQUEST for migrating from GitHub to GHE is by
# creating a separate organization with no members called "migration",
# adding that as the target organization, and then once the migration
# has finished, moving it over to the intended location.
#
# The reason why we do it this way is so that people who are auto-
# subscribed to the intended organization are not spammed by potentially
# thousands of comments in the source repository.
#
# The sleep time is arbitrarily chosen based on empirical evidence that
# lower times cause huge backups in resque jobs.
#
# Generally speaking, the source api host will be api.github.com, the
# source host will be github.com and the source prefix will be empty.
#
# The target api host and the target host will be your GHE deployment
# domain. Your target prefix will be "/api/v3".
#
# There is a known failure case on comments where the basis commit was
# lost in a force push. In this case, it will say "Server Error" and
# will move on to the next comment. This is unfortunately expected in
# many circumstances. Any write requests to the target will be spit
# out at the end of the run and you can choose to keep the output for
# posterity or to discard it if you really don't care.
#
# Don't use this tool on existing repos. It is intended to be used
# on repos that are moved over for the first time from another
# GitHub organization.
class MigrateRepo
HOOK_URLS = []
SOURCE_ORGANIZATION = ""
SOURCE_API_HOST = ""
SOURCE_HOST = ""
SOURCE_PREFIX = ""
TARGET_ORGANIZATION = ""
TARGET_API_HOST = ""
TARGET_HOST = ""
TARGET_PREFIX = ""
SLEEP_TIME = 1
def self.migrate(source_auth_token, target_auth_token, repo)
source = GithubHost.new(
:host => SOURCE_HOST,
:api_host => SOURCE_API_HOST,
:prefix => SOURCE_PREFIX,
:token => source_auth_token,
:org => SOURCE_ORGANIZATION,
:repo => repo,
)
target = GithubHost.new(
:host => TARGET_HOST,
:api_host => TARGET_API_HOST,
:prefix => TARGET_PREFIX,
:token => target_auth_token,
:org => TARGET_ORGANIZATION,
:repo => repo,
)
old_repo = source.request(
"/repos/#{SOURCE_ORGANIZATION}/#{repo}",
:method => :get,
)
# Create the repo and add hooks, content
self.create_repo(target, old_repo)
self.add_hooks(target, HOOK_URLS)
self.push_content(source, target)
# Create a mapping of all pull requests from number to content
pulls = self.pull_requests(source)
pull_map = pulls.inject({}){|h, p| h[p["number"]] = p; h}
self.issues(source).each do |old_issue|
puts "Processing issue #{old_issue["number"]}"
# Create the issue
issue = self.add_issue(target, old_issue)
# Check to see if it has a pull request
has_pull = pull_map.include?(old_issue["number"])
# Get all comments in the issue
comments = self.comments(source, old_issue, has_pull)
# Add the pull request iff one exists on the original issue
if has_pull
self.add_pull(target, pull_map[old_issue["number"]], issue)
end
# Add each comment
comments.each do |comment|
if comment["commit_id"]
# A commit id means that this is a PR comment
self.add_pull_comment(target, issue, comment)
else
# This is an issue comment
self.add_issue_comment(target, issue, comment)
end
# Sleep for a little bit after each comment.
# This is to reduce resque burden and resolve random other issues
# around out-of-order comments that have been seen without this.
sleep(SLEEP_TIME)
end
# Finally, close the issue if the original one was already closed
if old_issue["state"] != "open"
self.close_issue(target, issue, old_issue["state"])
end
end
pp target.failures
end
def self.create_repo(target, old_repo)
target.request(
"/orgs/#{target.org}/repos",
:method => :post,
:body => {
"name" => target.repo,
"description" => old_repo["description"],
"private" => true,
}.to_json,
)
end
def self.add_hooks(target, hooks)
HOOK_URLS.each do |hook_url|
target.request(
"/repos/#{target.org}/#{target.repo}/hooks",
:method => :post,
:body => {
"name" => "web",
"active" => true,
"config" => {
"url" => hook_url,
"content_type" => "json",
},
}.to_json,
)
end
end
def self.push_content(source, target)
Dir.mktmpdir(source.repo) do |dir|
`git clone --mirror git@#{source.host}:#{source.org}/#{source.repo}.git #{dir}`
`git --git-dir=#{dir} remote add target git@#{target.host}:#{target.org}/#{target.repo}.git`
`git --git-dir=#{dir} push --all target`
`git --git-dir=#{dir} push --tags target`
end
end
def self.add_issue(target, old_issue)
issue = target.request(
"/repos/#{target.org}/#{target.repo}/issues",
:method => :post,
:body => {
:title => old_issue["title"],
:body => annotated_body(old_issue),
}.to_json,
)
end
def self.close_issue(target, issue, state)
# Close the issue
target.request(
"/repos/#{target.org}/#{target.repo}/issues/#{issue["number"]}",
:method => :patch,
:body => {
:state => state,
}.to_json,
)
end
def self.add_issue_comment(target, issue, comment)
target.request(
"/repos/#{target.org}/#{target.repo}/issues/#{issue["number"]}/comments",
:method => :post,
:body => {
:body => annotated_body(comment),
}.to_json,
)
end
def self.add_pull(target, old_pull, new_issue)
if old_pull["state"] == "open"
# If the PR is open, assume the refs are present
base = old_pull["base"]["ref"]
head = old_pull["head"]["ref"]
else
# If the PR is closed, fall back to SHA
base = old_pull["base"]["sha"]
head = old_pull["head"]["sha"]
end
pull = target.request(
"/repos/#{target.org}/#{target.repo}/pulls",
:method => :post,
:body => {
:issue => new_issue["number"],
:base => base,
:head => head,
}.to_json,
)
end
def self.add_pull_comment(target, issue, comment)
target.request(
"/repos/#{target.org}/#{target.repo}/pulls/#{issue["number"]}/comments",
:method => :post,
:body => {
:body => annotated_body(comment),
:commit_id => comment["original_commit_id"],
:path => comment["path"],
:position => comment["original_position"],
}.to_json,
)
end
def self.annotated_body(original)
author = original["user"]["login"]
timestamp = original["created_at"]
body = original["body"]
"Originally posted by #{author} at #{timestamp}:\n\n#{body}"
end
def self.issues(source)
open = source.get_all(
"/repos/#{source.org}/#{source.repo}/issues",
:params => {
:state => "open",
},
)
closed = source.get_all(
"/repos/#{source.org}/#{source.repo}/issues",
:params => {
:state => "closed",
},
)
(open + closed).sort{|a, b| a["created_at"] <=> b["created_at"]}
end
def self.pull_requests(source)
open = source.get_all(
"/repos/#{source.org}/#{source.repo}/pulls",
:params => {
:state => "open",
},
)
closed = source.get_all(
"/repos/#{source.org}/#{source.repo}/pulls",
:params => {
:state => "closed",
},
)
(open + closed).sort{|a, b| a["created_at"] <=> b["created_at"]}
end
def self.comments(source, issue, has_pull)
comments = source.get_all(
"/repos/#{source.org}/#{source.repo}/issues/#{issue["number"]}/comments",
:params => {
:sort => 'created',
},
)
if has_pull
comments += source.get_all(
"/repos/#{source.org}/#{source.repo}/pulls/#{issue["number"]}/comments",
:params => {
:sort => 'created',
},
)
end
comments.sort{|a, b| a["created_at"] <=> b["created_at"]}
end
class GithubHost
attr_reader :host, :org, :failures, :repo
def initialize(options = {})
@auth_token = options[:token]
@api_host = options[:api_host]
@host = options[:host]
@prefix = options[:prefix]
@org = options[:org]
@repo = options[:repo]
@failures = []
end
def request(path, options = {})
tries = 0
response = nil
while tries <= 3
tries += 1
options[:headers] = {"Authorization" => "token #{@auth_token}"}
request = Typhoeus::Request.new(
"https://#{@api_host}#{@prefix}#{path}",
options,
)
response = request.run
if response.code < 300
return response.body.empty? ? "" : JSON.parse(response.body)
end
end
puts "Error: #{response.body}"
@failures << [path, options, response.code]
nil
end
def get_all(path, options = {})
page = 1
all_items = []
while true
items = request(
path,
:method => :get,
:params => options[:params].merge({:page => page}),
)
break if items.empty?
all_items += items
page += 1
end
all_items
end
end
end
if ARGV.length < 3
puts "ruby migrate_repo.rb <source_auth_token> <target_auth_token> <repo_name>"
else
MigrateRepo.migrate(ARGV[0], ARGV[1], ARGV[2])
end
|
githubteacher/example-githubapiscripts
|
get-user.rb
|
<filename>get-user.rb<gh_stars>1-10
require 'Octokit'
# Fetch a user
user = Octokit.user 'githubteacher'
puts user.name
# => "<NAME>"
puts user.fields
puts user.id
puts user.email
# => <Set: {:login, :id, :gravatar_id, :type, :name, :company, :blog, :location, :email, :hireable, :bio, :public_repos, :followers, :following, :created_at, :updated_at, :public_gists}>
puts user[:company]
# => "GitHub, Inc."
user.rels[:gists].href
# => "https://api.github.com/users/githubteacher/gists"
|
ericboehs/to_slug
|
spec/to_slug_spec.rb
|
# coding: utf-8
require 'to_slug'
describe String, "to_slug" do
it "as an option can use space as a delimiter preserving spaces" do
"This is a string".to_slug(:delimiter=>" ").should == "this is a string"
end
it "replaces spaces with dashes" do
"This is a string".to_slug.should == "this-is-a-string"
end
it "converts accented characters to a close ASCII alternative" do
"aëiòú".to_slug.should == "aeiou"
end
it "converts lots of accented characters to a close ASCII alternative" do
"thîs ís a nåsty strïng éëê. ýůçký".to_slug.should == "this-is-a-nasty-string-eee-yucky"
end
it "converts a single accented character to a close ACII alternative" do
"å".to_slug.should == "a"
end
it "converts scores to dashes" do
"This is an example to_slug".to_slug.should == "this-is-an-example-to-slug"
end
it "with the option :preserve_underscore doesn't convert scores to dashes" do
"This is an example to_slug".to_slug(:preserve_underscore => true).should == "this-is-an-example-to_slug"
end
it "with the option :preserve_underscore handles multiple underscores" do
"This is an example to_______slug".to_slug(:preserve_underscore => true).should == "this-is-an-example-to_slug"
end
it "converts periods to dashes" do
"This.is.an.example.string".to_slug.should == "this-is-an-example-string"
end
it "removes leading/trailing whitespace" do
" this is a string ".to_slug.should == "this-is-a-string"
end
it "removes leading punctuation" do
"!!*% This is leading to somewhere cool".to_slug.should == "this-is-leading-to-somewhere-cool"
end
it "removes single quotes" do
"This is a 'quoted' string".to_slug.should == "this-is-a-quoted-string"
end
it "removes double quotes" do
'This is a "quoted" string'.to_slug.should == "this-is-a-quoted-string"
end
it "handles multiple spaces" do
"I like to put extra spaces. See".to_slug.should == "i-like-to-put-extra-spaces-see"
end
it "preserves dashes" do
"I like Mrs - on my salad".to_slug.should == "i-like-mrs-on-my-salad"
end
it "downcases all characters" do
"THIS IS SPARTAAAaaa".to_slug.should == "this-is-spartaaaaaa"
end
it "accepts empty strings" do
"".to_slug.should == ""
end
it "remains a String class" do
"I am a string class yo!".to_slug.should be_kind_of(String)
end
it "removes html entities" do
"I love my mom & dad; they made me cake".to_slug.should == "i-love-my-mom-dad-they-made-me-cake"
end
# Test all the accents
it "converts accents for the letter A" do
"À Á Â Ã Ā Ă Ȧ Ả Ä Å Ǎ Ȁ Ȃ Ą Ạ Ḁ Ầ Ấ Ẫ Ẩ Ằ Ắ Ẵ Ẳ Ǡ Ǟ Ǻ Ậ Ặ".to_slug.should == "a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a"
end
it "converts accents for the letter AE" do
"Æ Ǽ Ǣ".to_slug.should == "ae-ae-ae"
end
it "converts accents for the letter B" do
"Ḃ Ɓ Ḅ Ḇ Ƃ Ƅ".to_slug.should == "b-b-b-b-b-b"
end
it "converts accents for the letter C" do
"C Ć Ĉ Ċ Č Ƈ Ç Ḉ".to_slug.should == "c-c-c-c-c-c-c-c"
end
it "converts accents for the letter D" do
"D Ḋ Ɗ Ḍ Ḏ Ḑ Ḓ Ď Đ Ɖ Ƌ".to_slug.should == "d-d-d-d-d-d-d-d-d-d-d"
end
it "converts accents for the letter E" do
"È É Ê Ẽ Ē Ĕ Ė Ë Ẻ Ě Ȅ Ȇ Ẹ Ȩ Ę Ḙ Ḛ Ề Ế Ễ Ể Ḕ Ḗ Ệ Ḝ Ǝ Ɛ".to_slug.should == "e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e"
end
it "converts accents for the letter F" do
"Ḟ Ƒ".to_slug.should == "f-f"
end
it "converts accents for the letter G" do
"Ǵ Ĝ Ḡ Ğ Ġ Ǧ Ɠ Ģ Ǥ".to_slug.should == "g-g-g-g-g-g-g-g-g"
end
it "converts accents for the letter H" do
"Ĥ Ḣ Ḧ Ȟ Ƕ Ḥ Ḩ Ḫ Ħ".to_slug.should == "h-h-h-h-h-h-h-h-h"
end
it "converts accents for the letter I" do
"Ì Í Î Ĩ Ī Ĭ İ Ï Ỉ Ǐ Ị Į Ȉ Ȋ Ḭ Ɨ Ḯ".to_slug.should == "i-i-i-i-i-i-i-i-i-i-i-i-i-i-i-i-i"
end
it "converts accents for the letter IJ" do
"IJ".to_slug.should == "ij"
end
it "converts accents for the letter J" do
"Ĵ".to_slug.should == "j"
end
it "converts accents for the letter K" do
"Ḱ Ǩ Ḵ Ƙ Ḳ Ķ".to_slug.should == "k-k-k-k-k-k"
end
it "converts accents for the letter L" do
"Ĺ Ḻ Ḷ Ļ Ḽ Ľ Ŀ Ł Ḹ".to_slug.should == "l-l-l-l-l-l-l-l-l"
end
it "converts accents for the letter M" do
"Ḿ Ṁ Ṃ Ɯ".to_slug.should == "m-m-m-m"
end
it "converts accents for the letter N" do
"Ǹ Ń Ñ Ṅ Ň Ŋ Ɲ Ṇ Ņ Ṋ Ṉ Ƞ".to_slug.should == "n-n-n-n-n-n-n-n-n-n-n-n"
end
it "converts accents for the letter O" do
"Ò Ó Ô Õ Ō Ŏ Ȯ Ö Ỏ Ő Ǒ Ȍ Ȏ Ơ Ǫ Ọ Ɵ Ø Ồ Ố Ỗ Ổ Ȱ Ȫ Ȭ Ṍ Ṏ Ṑ Ṓ Ờ Ớ Ỡ Ở Ợ Ǭ Ộ Ǿ Ɔ".to_slug.should == "o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o"
end
it "converts accents for the letter OE" do
"Œ".to_slug.should == "oe"
end
it "converts accents for the letter P" do
"Ṕ Ṗ Ƥ".to_slug.should == "p-p-p"
end
it "converts accents for the letter R" do
"Ŕ Ṙ Ř Ȑ Ȓ Ṛ Ŗ Ṟ Ṝ Ʀ".to_slug.should == "r-r-r-r-r-r-r-r-r-r"
end
it "converts accents for the letter S" do
"Ś Ŝ Ṡ Š Ṣ Ș Ş Ṥ Ṧ Ṩ".to_slug.should == "s-s-s-s-s-s-s-s-s-s"
end
it "converts accents for the letter T" do
"Ṫ Ť Ƭ Ʈ Ṭ Ț Ţ Ṱ Ṯ Ŧ".to_slug.should == "t-t-t-t-t-t-t-t-t-t"
end
it "converts accents for the letter U" do
"Ù Ú Û Ũ Ū Ŭ Ü Ủ Ů Ű Ǔ Ȕ Ȗ Ư Ụ Ṳ Ų Ṷ Ṵ Ṹ Ṻ Ǜ Ǘ Ǖ Ǚ Ừ Ứ Ữ Ử Ự".to_slug.should == "u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u"
end
it "converts accents for the letter V" do
"Ṽ Ṿ Ʋ".to_slug.should == "v-v-v"
end
it "converts accents for the letter W" do
"Ẁ Ẃ Ŵ Ẇ Ẅ Ẉ".to_slug.should == "w-w-w-w-w-w"
end
it "converts accents for the letter X" do
"Ẋ Ẍ".to_slug.should == "x-x"
end
it "converts accents for the letter Y" do
"Ỳ Ý Ŷ Ỹ Ȳ Ẏ Ÿ Ỷ Ƴ Ỵ".to_slug.should == "y-y-y-y-y-y-y-y-y-y"
end
it "converts accents for the letter Z" do
"Ź Ẑ Ż Ž Ȥ Ẓ Ẕ Ƶ".to_slug.should == "z-z-z-z-z-z-z-z"
end
it "converts accents for the letter a" do
"à á â ã ā ă ȧ ä ả å ǎ ȁ ȃ ą ạ ḁ ẚ ầ ấ ẫ ẩ ằ ắ ẵ ẳ ǡ ǟ ǻ ậ ặ".to_slug.should == "a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a"
end
it "converts accents for the letter ae" do
"æ ǽ ǣ".to_slug.should == "ae-ae-ae"
end
it "converts accents for the letter b" do
"ḃ ɓ ḅ ḇ ƀ ƃ ƅ".to_slug.should == "b-b-b-b-b-b-b"
end
it "converts accents for the letter c" do
"ć ĉ ċ č ƈ ç ḉ".to_slug.should == "c-c-c-c-c-c-c"
end
it "converts accents for the letter d" do
"ḋ ɗ ḍ ḏ ḑ ḓ ď đ ƌ ȡ".to_slug.should == "d-d-d-d-d-d-d-d-d-d"
end
it "converts accents for the letter e" do
"è é ê ẽ ē ĕ ė ë ẻ ě ȅ ȇ ẹ ȩ ę ḙ ḛ ề ế ễ ể ḕ ḗ ệ ḝ ɛ".to_slug.should == "e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e-e"
end
it "converts accents for the letter f" do
"ḟ ƒ".to_slug.should == "f-f"
end
it "converts accents for the letter g" do
"ǵ ĝ ḡ ğ ġ ǧ ɠ ģ ǥ".to_slug.should == "g-g-g-g-g-g-g-g-g"
end
it "converts accents for the letter h" do
"ĥ ḣ ḧ ȟ ƕ ḩ ḫ ẖ ħ".to_slug.should == "h-h-h-h-h-h-h-h-h"
end
it "converts accents for the letter i" do
"ì í î ĩ ī ĭ ı ï ỉ ǐ į į ȋ ḭ ɨ ḯ".to_slug.should == "i-i-i-i-i-i-i-i-i-i-i-i-i-i-i-i"
end
it "converts accents for the letter ij" do
"ij".to_slug.should == "ij"
end
it "converts accents for the letter j" do
"ĵ ǰ".to_slug.should == "j-j"
end
it "converts accents for the letter k" do
"ḱ ǩ ƙ ḳ ķ".to_slug.should == "k-k-k-k-k"
end
it "converts accents for the letter l" do
"ĺ ḻ ḷ ļ ḽ ľ ŀ ł ƚ ḹ ȴ".to_slug.should == "l-l-l-l-l-l-l-l-l-l-l"
end
it "converts accents for the letter m" do
"ḿ ṁ ṃ ɯ".to_slug.should == "m-m-m-m"
end
it "converts accents for the letter n" do
"ǹ ń ñ ṅ ň ŋ ɲ ṇ ņ ṋ ṉ ʼn ȵ".to_slug.should == "n-n-n-n-n-n-n-n-n-n-n-n-n"
end
it "converts accents for the letter o" do
"ò ó ô õ ō ŏ ȯ ö ỏ ő ǒ ȍ ȏ ơ ǫ ọ ɵ ø ồ ố ỗ ổ ȱ ȫ ȭ ṍ ṏ ṑ ṓ ờ ớ ỡ ở ợ ǭ ộ ǿ ɔ".to_slug.should == "o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o"
end
it "converts accents for the letter oe" do
"œ".to_slug.should == "oe"
end
it "converts accents for the letter p" do
"ṕ ṗ ƥ".to_slug.should == "p-p-p"
end
it "converts accents for the letter r" do
"ŕ ṙ ř ȑ ȓ ṛ ŗ ṟ ṝ".to_slug.should == "r-r-r-r-r-r-r-r-r"
end
it "converts accents for the letter s" do
"ś ŝ ṡ š ṣ ș ş ṥ ṧ ṩ ß ſ ẛ".to_slug.should == "s-s-s-s-s-s-s-s-s-s-s-s-s"
end
it "converts accents for the letter t" do
"ṫ ẗ ť ƭ ʈ ƫ ṭ ț ţ ṱ ṯ ŧ ȶ".to_slug.should == "t-t-t-t-t-t-t-t-t-t-t-t-t"
end
it "converts accents for the letter u" do
"ù ú û ũ ū ŭ ü ủ ů ű ǔ ȕ ȗ ư ụ ṳ ų ṷ ṵ ṹ ṻ ǖ ǜ ǘ ǖ ǚ ừ ứ ữ ử ự".to_slug.should == "u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u"
end
it "converts accents for the letter v" do
"ṽ ṿ".to_slug.should == "v-v"
end
it "converts accents for the letter w" do
"ẁ ẃ ŵ ẇ ẅ ẘ ẉ".to_slug.should == "w-w-w-w-w-w-w"
end
it "converts accents for the letter x" do
"ẋ ẍ".to_slug.should == "x-x"
end
it "converts accents for the letter y" do
"ỳ ý ŷ ỹ ȳ ẏ ÿ ỷ ẙ ƴ ỵ".to_slug.should == "y-y-y-y-y-y-y-y-y-y-y"
end
it "converts accents for the letter z" do
"ź ẑ ż ž ȥ ẓ ẕ ƶ".to_slug.should == "z-z-z-z-z-z-z-z"
end
it "removes unknown accents" do
"this Ð Þ Ə Ɣ Ɩ Ƣ Ƨ Ʃ Ʊ Ʒ Ǯ Ƹ Ȝ ƿ Ȣ ð þ ə ɣ ɩ ƣ ƨ ʃ is ƪ ʊ ʒ ǯ ƹ ƺ ȝ Ƿ ȣ DZ Dz dz a DŽ Dž dž LJ Lj lj NJ Nj nj ĸ ƍ ƛ ƾ ƻ Ƽ ƽ string".to_slug.should == "this-is-a-string"
end
end
|
ericboehs/to_slug
|
lib/to_slug.rb
|
# coding: utf-8
class String # This reopns the string class
# Define a new method to convert the string to be url friendly
def to_slug(options={})
# This is the input as there are no arguments passed.
string = self
delimiter = options[:delimiter].nil? ? "-" : options[:delimiter]
# Define which accents map to which ascii characters
accents = {
# Uppercase
'A' => %w(À Á Â Ã Ā Ă Ȧ Ả Ä Å Ǎ Ȁ Ȃ Ą Ạ Ḁ Ầ Ấ Ẫ Ẩ Ằ Ắ Ẵ Ẳ Ǡ Ǟ Ǻ Ậ Ặ),
'AE' => %w(Æ Ǽ Ǣ),
'B' => %w(Ḃ Ɓ Ḅ Ḇ Ƃ Ƅ),
'C' => %w(C Ć Ĉ Ċ Č Ƈ Ç Ḉ),
'D' => %w(D Ḋ Ɗ Ḍ Ḏ Ḑ Ḓ Ď Đ Ɖ Ƌ),
'E' => %w(È É Ê Ẽ Ē Ĕ Ė Ë Ẻ Ě Ȅ Ȇ Ẹ Ȩ Ę Ḙ Ḛ Ề Ế Ễ Ể Ḕ Ḗ Ệ Ḝ Ǝ Ɛ),
'F' => %w(Ḟ Ƒ),
'G' => %w(Ǵ Ĝ Ḡ Ğ Ġ Ǧ Ɠ Ģ Ǥ),
'H' => %w(Ĥ Ḣ Ḧ Ȟ Ƕ Ḥ Ḩ Ḫ Ħ),
'I' => %w(Ì Í Î Ĩ Ī Ĭ İ Ï Ỉ Ǐ Ị Į Ȉ Ȋ Ḭ Ɨ Ḯ),
'IJ' => %w(IJ),
'J' => %w(Ĵ),
'K' => %w(Ḱ Ǩ Ḵ Ƙ Ḳ Ķ),
'L' => %w(Ĺ Ḻ Ḷ Ļ Ḽ Ľ Ŀ Ł Ḹ),
'M' => %w(Ḿ Ṁ Ṃ Ɯ),
'N' => %w(Ǹ Ń Ñ Ṅ Ň Ŋ Ɲ Ṇ Ņ Ṋ Ṉ Ƞ),
'O' => %w(Ò Ó Ô Õ Ō Ŏ Ȯ Ö Ỏ Ő Ǒ Ȍ Ȏ Ơ Ǫ Ọ Ɵ Ø Ồ Ố Ỗ Ổ Ȱ Ȫ Ȭ Ṍ Ṏ Ṑ Ṓ Ờ Ớ Ỡ Ở Ợ Ǭ Ộ Ǿ Ɔ),
'OE' => %w(Œ),
'P' => %w(Ṕ Ṗ Ƥ),
'R' => %w(Ŕ Ṙ Ř Ȑ Ȓ Ṛ Ŗ Ṟ Ṝ Ʀ),
'S' => %w(Ś Ŝ Ṡ Š Ṣ Ș Ş Ṥ Ṧ Ṩ),
'T' => %w(Ṫ Ť Ƭ Ʈ Ṭ Ț Ţ Ṱ Ṯ Ŧ),
'U' => %w(Ù Ú Û Ũ Ū Ŭ Ü Ủ Ů Ű Ǔ Ȕ Ȗ Ư Ụ Ṳ Ų Ṷ Ṵ Ṹ Ṻ Ǜ Ǘ Ǖ Ǚ Ừ Ứ Ữ Ử Ự),
'V' => %w(Ṽ Ṿ Ʋ),
'W' => %w(Ẁ Ẃ Ŵ Ẇ Ẅ Ẉ),
'X' => %w(Ẋ Ẍ),
'Y' => %w(Ỳ Ý Ŷ Ỹ Ȳ Ẏ Ÿ Ỷ Ƴ Ỵ),
'Z' => %w(Ź Ẑ Ż Ž Ȥ Ẓ Ẕ Ƶ),
# Lowercase
'a' => %w(à á â ã ā ă ȧ ä ả å ǎ ȁ ȃ ą ạ ḁ ẚ ầ ấ ẫ ẩ ằ ắ ẵ ẳ ǡ ǟ ǻ ậ ặ),
'ae' => %w(æ ǽ ǣ),
'b' => %w(ḃ ɓ ḅ ḇ ƀ ƃ ƅ),
'c' => %w(ć ĉ ċ č ƈ ç ḉ),
'd' => %w(ḋ ɗ ḍ ḏ ḑ ḓ ď đ ƌ ȡ),
'e' => %w(è é ê ẽ ē ĕ ė ë ẻ ě ȅ ȇ ẹ ȩ ę ḙ ḛ ề ế ễ ể ḕ ḗ ệ ḝ ɛ),
'f' => %w(ḟ ƒ),
'g' => %w(ǵ ĝ ḡ ğ ġ ǧ ɠ ģ ǥ),
'h' => %w(ĥ ḣ ḧ ȟ ƕ ḩ ḫ ẖ ħ),
'i' => %w(ì í î ĩ ī ĭ ı ï ỉ ǐ į į ȋ ḭ ɨ ḯ),
'ij' => %w(ij),
'j' => %w(ĵ ǰ),
'k' => %w(ḱ ǩ ƙ ḳ ķ),
'l' => %w(ĺ ḻ ḷ ļ ḽ ľ ŀ ł ƚ ḹ ȴ),
'm' => %w(ḿ ṁ ṃ ɯ),
'n' => %w(ǹ ń ñ ṅ ň ŋ ɲ ṇ ņ ṋ ṉ ʼn ȵ),
'o' => %w(ò ó ô õ ō ŏ ȯ ö ỏ ő ǒ ȍ ȏ ơ ǫ ọ ɵ ø ồ ố ỗ ổ ȱ ȫ ȭ ṍ ṏ ṑ ṓ ờ ớ ỡ ở ợ ǭ ộ ǿ ɔ),
'oe' => %w(œ),
'p' => %w(ṕ ṗ ƥ),
'r' => %w(ŕ ṙ ř ȑ ȓ ṛ ŗ ṟ ṝ),
's' => %w(ś ŝ ṡ š ṣ ș ş ṥ ṧ ṩ ß ſ ẛ),
't' => %w(ṫ ẗ ť ƭ ʈ ƫ ṭ ț ţ ṱ ṯ ŧ ȶ),
'u' => %w(ù ú û ũ ū ŭ ü ủ ů ű ǔ ȕ ȗ ư ụ ṳ ų ṷ ṵ ṹ ṻ ǖ ǜ ǘ ǖ ǚ ừ ứ ữ ử ự),
'v' => %w(ṽ ṿ),
'w' => %w(ẁ ẃ ŵ ẇ ẅ ẘ ẉ),
'x' => %w(ẋ ẍ),
'y' => %w(ỳ ý ŷ ỹ ȳ ẏ ÿ ỷ ẙ ƴ ỵ),
'z' => %w(ź ẑ ż ž ȥ ẓ ẕ ƶ),
# Not sure what to do with these
'' => %w(Ð Þ Ə Ɣ Ɩ Ƣ Ƨ Ʃ Ʊ Ʒ Ǯ Ƹ Ȝ ƿ Ȣ ð þ ə ɣ ɩ ƣ ƨ ʃ ƪ ʊ ʒ ǯ ƹ ƺ ȝ Ƿ ȣ DZ Dz dz DŽ Dž dž LJ Lj lj NJ Nj nj ĸ ƍ ƛ ƾ ƻ Ƽ ƽ)
}
# Replace each accent in the string
#accents.each do |replacement, accent|
# accent.each do |character|
# string = string.gsub(character, replacement)
# end
#end
accents.each do |replacement, accent|
regex = Regexp.new("[#{accent.join("|")}]")
string = string.gsub(regex, replacement)
end
# Strip any HTML decimal/hexadecimal entites
string = string.gsub(
/ # begin matching a string
& # an ampersand
[^ ] # Match any character except whitespace -- enables matching of hex or decimal
[0-9A-F] # a hex digit
{1,4} # 1 to 4 of them
; # a semicolon
/xi, # / = end matching; x = allow spaces/comments; i = ignore case; , = end argument
'' # replace matches with nothing (remove matches)
)
# Convert periods to dashs
string = string.gsub(/[.]/,"-")
unless options[:preserve_underscore]
# Convert underscores to dashs
string = string.gsub(/[_]/, "-")
end
# Remove any characters that aren't alphanumeric (or a dash)
string = string.gsub(/[^a-zA-Z0-9 \-_]/,"")
# Convert multiple spaces to a single space
string = string.gsub(/[ ]+/," ")
# Give a little trim around the edges (leading/trailing whitespace)
string.strip!
# Replace single spaces with a URL friendly dash (-)
string = string.gsub(/ /,"#{delimiter}")
# Do a greedy replace on multiple dashes
string = string.gsub(/-+/,"-")
# Do a greedy replace on multiple underscores
string = string.gsub(/_+/,"_")
# CASE. EVERYTHING. DOWN. (and return since it's the last line)
string = string.downcase
end
end
|
ericboehs/to_slug
|
to_slug.gemspec
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "to_slug/version"
Gem::Specification.new do |s|
s.name = "to_slug"
s.version = ToSlug::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/ericboehs/to_slug"
s.summary = %q{Adds a to_slug method to ruby's String class}
s.description = %q{This gem makes URL friendly strings out of not so pretty strings.}
s.rubyforge_project = "to_slug"
s.add_development_dependency "rspec", "~> 2.4.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
|
cervinka/jira-worklog
|
lib/jira/worklog/cli.rb
|
<gh_stars>0
require 'commander/import'
program :name, 'jira-worklog'
program :version, '0.0.1'
program :description, 'Add worklog to JIRA using REST API'
# program :help_formatter, :compact
global_option '-u', '--user USERNAME', 'JIRA login username'
global_option '-p', '--password PASSWORD', 'JIRA login password'
global_option '-b', '--url-base BASE_URL', 'JIRA base URL. ie: https://jira.example.com/rest/api/2/'
command :issues do |c|
c.syntax = 'jira-worklog issues [options]'
c.summary = 'List available issues'
# c.description = ''
c.example 'list issues', 'jira-worklog issues -u USERNAME -p PASSWORD -b BASE_URL'
c.action do |_args, options|
url_base, user, password = get_credentials(options)
api = APIClient.new(url_base,user, password)
# api = Jira::Worklog::APIClient.new(url_base,user, password)
api.issues.each do |issue|
puts "#{issue[:key]} (issue_id #{issue[:id]}) - #{issue[:summary]}"
end
end
end
command :add do |c|
c.syntax = 'jira-worklog add [options]'
c.summary = 'Add new worklog entries to JIRA'
c.description= <<DESCRIPTION
- input file must contain 4 columns and each column is required (additional rows are ignored)
- 1st column: issue key or id
- 2nd column: date (start time is set to 7am automatically)
- 3rd column: duration in hours
- 4th column: comment
DESCRIPTION
c.example 'description', 'jira-worklog add -u USER -p PASSWORD -b BASE_URL --xlsx FILE.XLSX'
c.option '--xlsx FILE', 'Add new entries to JIRA workog from xlsx file'
c.action do |_args, options|
raise '--xlsx is mandatory parameter' unless options.xlsx
url_base, user, password = get_credentials(options)
api = APIClient.new(url_base, user, password)
worklogs = load_from_xlsx(options.xlsx)
worklog_ids = []
worklogs.each do |worklog|
worklog_id = api.add_worklog(worklog)
worklog_ids << worklog_id
puts "#{formatted_duration(worklog[:duration])} - (id: #{worklog_id}) #{worklog[:date]} #{worklog[:issue]} #{worklog[:comment]}"
end
puts '-' * 60
puts "#{formatted_duration(worklogs.inject(0) { |sum, worklog| sum + worklog[:duration] })} inserted"
puts "New ids: #{worklog_ids.join(',')}"
end
end
command :delete do |c|
c.syntax = 'jira-worklog delete ISSUE WORKLOG_IDS'
c.summary = 'Delete worklog entries by ids (comma separated)'
c.example 'delete worklogs', 'jira-worklog delete -u USER -p PASSWORD -b BASE_URL WORKLOG1_ID,WORKLOG2_ID,...'
c.action do |args, options|
issue = args[0].to_s
raise 'please specify issue key or id' if issue.nil?
ids = args[1].to_s.split(',')
raise 'please specify worklog ids (comma separated)' if ids.empty?
url_base, user, password = get_credentials(options)
api = APIClient.new(url_base, user, password)
ids.each do |worklog_id|
puts "Deleting worklog ##{worklog_id}"
api.delete_worklog(issue, worklog_id)
end
end
end
command :list do |c|
c.syntax = 'jira-worklog list [options]'
c.summary = 'List worklog entries for given issue'
c.description = ''
c.example 'list worklogs for given issue', 'jira-worklog list -u USER -p PASSWORD -b BASE_URL --issue ISSUE_ID_OR_KEY'
c.option '--issue ISSUE', 'JIRA Issue Key or Id (use "issues" command to list available issues)'
c.action do |_args, options|
raise '--issue is mandatory parameter' unless options.issue
url_base, user, password = get_credentials(options)
api = APIClient.new(url_base, user, password)
worklogs = api.worklogs(options.issue)
worklog_ids = []
worklogs.each do |worklog|
puts "#{formatted_duration(worklog[:duration])} - (id: #{worklog[:id]}) #{worklog[:date]} #{worklog[:comment]}"
worklog_ids << worklog[:id]
end
puts '-' * 60
puts "#{formatted_duration(worklogs.inject(0) { |sum, worklog| sum + worklog[:duration] })} total"
puts "Worklog ids: #{worklog_ids.join(',')}"
end
end
def load_from_xlsx(filename)
doc = SimpleXlsxReader.open(filename)
doc.sheets # => [<#SXR::Sheet>, ...]
sheet = doc.sheets.first
puts "Loading from sheet: #{sheet.name}"
worklogs = []
sheet.rows.each.with_index do |row, idx|
issue, date, duration, comment = row[0], row[1], row[2], row[3]
duration = Float(duration) rescue 0
if issue && !issue.nil? && !issue.empty? && date.is_a?(Date) && duration > 0 && comment && !comment.nil? && !comment.empty?
worklogs << ({issue: issue, date: date, duration: duration * 3600, comment: comment})
else
puts "Skipping row ##{idx + 1}: #{row.inspect}"
end
end
worklogs
end
def formatted_duration(total_seconds)
hours = total_seconds / (60 * 60)
minutes = (total_seconds / 60) % 60
seconds = total_seconds % 60
'%2d:%02d:%02d' % [hours, minutes, seconds]
end
def get_credentials(options)
user = options.user || ask('JIRA user: ')
password = options.password || ask('JIRA password: ') { |q| q.echo = '*' }
url_base = options.url_base
raise('--url_base is mandatory option') if url_base.nil? || url_base.empty?
[url_base, user, password]
end
|
cervinka/jira-worklog
|
lib/jira/worklog.rb
|
<reponame>cervinka/jira-worklog
require 'rubygems'
require 'json'
require 'rest-client'
require 'simple_xlsx_reader'
require 'jira/worklog/version'
require 'jira/worklog/api_client'
module Jira
module Worklog
# Your code goes here...
end
end
|
cervinka/jira-worklog
|
lib/jira/worklog/version.rb
|
<filename>lib/jira/worklog/version.rb
module Jira
module Worklog
VERSION = '0.1.1'
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.