repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
majesty2450/whip
|
lib/whip/cli/parser.rb
|
<gh_stars>0
require_relative "option"
require_relative "flag"
require_relative "argument"
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
class Whip::CLI::Parser
def initialize (options)
@options = options
end
def tokenize (args = ARGV)
tokens = Array.new
args.each do |arg|
if arg[0] == "-" && arg[1] == "-"
#tokens.push(Whip::CLI::Flag.new(arg[2..-1]))
tokens.push(Whip::CLI::Flag.new(arg))
elsif arg[0] == "-"
#tokens.push(Whip::CLI::Flag.new(arg[1..-1]))
tokens.push(Whip::CLI::Flag.new(arg))
else
tokens.push(Whip::CLI::Argument.new(arg))
end
end
return tokens
end
def parse (tokens = tokenize)
matches = Array.new
tokens.each_with_index do |token, index|
@options.each do |option|
if option.match(token)
option.fill(tokens, index)
matches.push(option)
end
end
end
blocked = nil
matches.each do |match|
if blocked && match.blocking
match.blockedAction(matches, self)
else
match.action(matches, self)
if match.blocking
blocked = match
end
end
end
end
def options
return @options
end
end
|
majesty2450/whip
|
lib/whip/cli/flag.rb
|
<gh_stars>0
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
class Whip::CLI::Flag
def initialize (name)
@name = name
end
def name
@name
end
def == (other)
if other.class.method_defined?("name") && other.name == @name
return true
else
return false
end
end
end
|
majesty2450/whip
|
lib/whip/cli/option.rb
|
<filename>lib/whip/cli/option.rb
require_relative "flag"
require_relative "argument"
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
class Whip::CLI::Option
def initialize (flags, description, blocking = false)
@flags = flags
@args = Array.new
@used_flag = nil
@description = description
@blocking = blocking
end
def match (token)
@flags.each do |flag|
if flag == token
return true
end
end
return false
end
def fill (tokens, index)
@used_flag = tokens[index]
tokens = tokens[(index + 1)..-1]
tokens.each do |token|
if Whip::CLI::Flag == token.class
break
else
@args.push(token)
end
end
end
def flags
return @flags
end
def args
return @args
end
def description
return @description
end
def blocking
return @blocking
end
def action (matches, parser)
raise NotImplementedError
end
def blockedAction (matches, parser)
puts "ERROR: Blocked Option (" + @used_flag.name + ")"
end
end
|
majesty2450/whip
|
lib/whip/cli/argument.rb
|
<filename>lib/whip/cli/argument.rb
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
class Whip::CLI::Argument
def initialize (value)
@value = value
end
def value
@value
end
def == (other)
if other.class.method_defined?("value") && other.value == @value
return true
else
return false
end
end
end
|
majesty2450/whip
|
lib/whip/token.rb
|
<filename>lib/whip/token.rb
module Whip end
# Base token class
class Whip::Token
def initialize (pos)
@starts = pos
@ends = pos
end
def ends= (pos)
@ends = pos
end
def ends
@ends
end
def starts
@starts
end
end
|
majesty2450/whip
|
lib/whip/watcher.rb
|
<reponame>majesty2450/whip
require_relative "file"
require_relative "watch"
require_relative "compiler"
module Whip end
# Watches files for changes in themselves or their dependencies, then parses
# and compiles it and fixes dependencies
class Whip::Watcher
def initialize (files)
@watches = Array.new
files.each do |file|
@watches.push(Whip::Watch.new(file))
end
end
def watch
puts "Watching, Press 'Ctrl-C' to stop..."
while true
@watches.each do |watch|
if watch.check
watch.changeDeps(Whip::Compiler.new.compile(watch.file))
watch.modified
puts ">>> Modified! " + watch.file.path
end
end
end
end
end
|
dgamboaestrada/rails-skeleton
|
src/spec/controllers/users_controller_spec.rb
|
<reponame>dgamboaestrada/rails-skeleton<filename>src/spec/controllers/users_controller_spec.rb
require 'rails_helper'
require 'faker'
require 'json_matchers/rspec'
RSpec.describe UsersController, type: :controller do
# This should return the minimal set of attributes required to create a valid
# User. As you add validations to User, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
{
"email": Faker::Internet.email,
"password": "password"
}
}
let(:invalid_attributes) {
{
"email": "invalid email",
"password": "password"
}
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# UsersController. Be sure to keep this updated too.
let(:valid_session) { { } }
describe "GET #index" do
it "returns a success response" do
FactoryBot.create(:user)
get :index, params: { :format => :json }
expect(response).to be_successful
expect(response.body).to match_response_schema('users')
end
end
describe "GET #show" do
it "returns a success response" do
user = FactoryBot.create(:user)
get :show, params: { :format => 'json', id: user.id.to_param }
expect(response).to be_successful
expect(response.body).to match_response_schema('user')
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new User" do
expect {
post :create, params: { :format => 'json', user: valid_attributes }
}.to change(User, :count).by(1)
expect(response).to have_http_status(201)
expect(response.body).to match_response_schema('user_create')
end
end
context "with invalid params" do
it "returns a 422 (Unprocessable Entity response)" do
post :create, params: { :format => 'json', user: invalid_attributes }
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
{
email: Faker::Internet.email
}
}
it "updates the requested user" do
user = User.create! valid_attributes
put :update, params: { :format => 'json', id: user.to_param, user: new_attributes }
user.reload
expect(response).to be_successful
expect(user.email).to eq(new_attributes[:email])
end
end
context "with invalid params" do
it "returns a 422 (Unprocessable Entity response)" do
user = User.create! valid_attributes
put :update, params: { :format => 'json', id: user.to_param, user: invalid_attributes }
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe "DELETE #destroy" do
it "destroys the requested user" do
user = User.create! valid_attributes
expect {
delete :destroy, params: { :format => 'json', id: user.to_param }
}.to change(User, :count).by(-1)
end
end
end
|
dgamboaestrada/rails-skeleton
|
src/app/controllers/users_controller.rb
|
class UsersController < InheritedResources::Base
before_action :set_user, only: %i[show update destroy]
def index
@users = User.order(params[:sort]).per_page_kaminari(params[:page]).per params[:limit]
respond_to do |format|
format.json { render json: @users }
end
end
def show
respond_to do |format|
format.json { render json: @user }
end
end
def create
@user = User.create(
email: user_params[:email],
password: user_params[:password],
)
respond_to do |format|
if @user.valid?
format.json { render :show, status: :created, location: @user }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def update
@user.update(user_params)
respond_to do |format|
if @user.valid?
format.json { render json: @user, status: :ok, location: @user }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def destroy
@user.destroy
respond_to do |format|
format.json { head :no_content }
end
end
private
def user_params
params.require(:user).permit(:email, :password)
end
def set_user
@user = User.find(params[:id])
end
end
|
dgamboaestrada/rails-skeleton
|
src/app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
before_action :apijson_pagination, if: :json_request? # action to jwt authorization
before_action :set_locale # Setting the Locale from param
skip_before_action :verify_authenticity_token, if: :json_request? # Skip csrf to api
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def json_request?
request.format.json?
end
def underscore_params_key_transform
underscore_params = params.clone
params.each do |key, value|
underscore_params[key.underscore] = value
end
underscore_params
end
def apijson_pagination
if params[:page].present?
params[:limit] = params[:page][:size] if params[:page][:size].present?
params[:page] = if params[:page][:number].present?
params[:page][:number]
else
1
end
end
params[:sort] = '-id' if params[:sort].blank?
end
end
|
mvali95/logster
|
lib/logster/configuration.rb
|
<reponame>mvali95/logster
# frozen_string_literal: true
module Logster
class Configuration
attr_accessor(
:allow_grouping,
:application_version,
:current_context,
:env_expandable_keys,
:enable_custom_patterns_via_ui,
:enable_js_error_reporting,
:environments,
:rate_limit_error_reporting,
:web_title,
:maximum_message_size_bytes
)
attr_writer :subdirectory
def initialize
# lambda |env,block|
@current_context = lambda { |_, &block| block.call }
@environments = [:development, :production]
@subdirectory = nil
@env_expandable_keys = []
@enable_custom_patterns_via_ui = false
@rate_limit_error_reporting = true
@enable_js_error_reporting = true
@maximum_message_size_bytes = 60_000
@allow_grouping = false
if defined?(::Rails) && defined?(::Rails.env) && ::Rails.env.production?
@allow_grouping = true
end
end
def subdirectory
@subdirectory || '/logs'
end
end
end
|
mvali95/logster
|
lib/logster/version.rb
|
# frozen_string_literal: true
module Logster
VERSION = "2.4.2"
end
|
mvali95/logster
|
lib/logster/redis_store.rb
|
<gh_stars>0
# frozen_string_literal: true
require 'json'
require 'logster/base_store'
require 'logster/redis_rate_limiter'
module Logster
class RedisStore < BaseStore
attr_accessor :redis, :max_backlog, :redis_raw_connection
attr_writer :redis_prefix
def initialize(redis = nil)
super()
@redis = redis || Redis.new
@max_backlog = 1000
@redis_prefix = nil
@redis_raw_connection = nil
end
def save(message)
if keys = message.solved_keys
keys.each do |solved|
return true if @redis.hget(solved_key, solved)
end
end
apply_max_size_limit(message)
@redis.multi do
@redis.hset(grouping_key, message.grouping_key, message.key)
@redis.rpush(list_key, message.key)
update_message(message)
end
trim
check_rate_limits(message.severity)
true
end
def delete(msg)
@redis.multi do
@redis.hdel(hash_key, msg.key)
@redis.hdel(env_key, msg.key)
@redis.hdel(grouping_key, msg.grouping_key)
@redis.lrem(list_key, -1, msg.key)
end
end
def bulk_delete(message_keys, grouping_keys)
@redis.multi do
@redis.hdel(hash_key, message_keys)
@redis.hdel(env_key, message_keys)
@redis.hdel(grouping_key, grouping_keys)
message_keys.each do |k|
@redis.lrem(list_key, -1, k)
end
end
end
def replace_and_bump(message, save_env: true)
# TODO make it atomic
exists = @redis.hexists(hash_key, message.key)
return false unless exists
@redis.multi do
@redis.hset(hash_key, message.key, message.to_json(exclude_env: true))
@redis.hset(env_key, message.key, message.env_json) if save_env
@redis.lrem(list_key, -1, message.key)
@redis.rpush(list_key, message.key)
end
check_rate_limits(message.severity)
true
end
def similar_key(message)
@redis.hget(grouping_key, message.grouping_key)
end
def count
@redis.llen(list_key)
end
def solve(message_key)
if (message = get(message_key)) && (keys = message.solved_keys)
# add a time so we can expire it
keys.each do |s_key|
@redis.hset(solved_key, s_key, Time.now.to_f.to_i)
end
end
clear_solved
end
def latest(opts = {})
limit = opts[:limit] || 50
severity = opts[:severity]
before = opts[:before]
after = opts[:after]
search = opts[:search]
with_env = opts.key?(:with_env) ? opts[:with_env] : true
start, finish = find_location(before, after, limit)
return [] unless start && finish
results = []
direction = after ? 1 : -1
begin
keys = @redis.lrange(list_key, start, finish) || []
break unless keys && (keys.count > 0)
rows = bulk_get(keys, with_env: with_env)
temp = []
rows.each do |row|
break if before && before == row.key
row = nil if severity && !severity.include?(row.severity)
row = filter_search(row, search)
temp << row if row
end
if direction == -1
results = temp + results
else
results += temp
end
start += limit * direction
finish += limit * direction
finish = -1 if finish > -1
end while rows.length > 0 && results.length < limit && start < 0
results
end
def clear
RedisRateLimiter.clear_all(@redis)
@redis.del(solved_key)
@redis.del(list_key)
keys = @redis.smembers(protected_key) || []
if keys.empty?
@redis.del(hash_key)
@redis.del(env_key)
else
protected = @redis.mapped_hmget(hash_key, *keys)
protected_env = @redis.mapped_hmget(env_key, *keys)
@redis.del(hash_key)
@redis.del(env_key)
@redis.mapped_hmset(hash_key, protected)
@redis.mapped_hmset(env_key, protected_env)
sorted = protected
.values
.map { |string|
Message.from_json(string) rescue nil
}
.compact
.sort
.map(&:key)
@redis.pipelined do
sorted.each do |message_key|
@redis.rpush(list_key, message_key)
end
end
end
end
# Delete everything, included protected messages
# (use in tests)
def clear_all
@redis.del(list_key)
@redis.del(protected_key)
@redis.del(hash_key)
@redis.del(env_key)
@redis.del(grouping_key)
@redis.del(solved_key)
@redis.del(ignored_logs_count_key)
Logster::PATTERNS.each do |klass|
@redis.del(klass.set_name)
end
@redis.keys.each do |key|
@redis.del(key) if key.include?(Logster::RedisRateLimiter::PREFIX)
@redis.del(key) if key.start_with?(ip_rate_limit_key(""))
end
end
def get(message_key, load_env: true)
json = @redis.hget(hash_key, message_key)
return nil unless json
message = Message.from_json(json)
if load_env
message.env = get_env(message_key) || {}
end
message
end
def get_all_messages
bulk_get(@redis.lrange(list_key, 0, -1))
end
def bulk_get(message_keys, with_env: true)
envs = @redis.mapped_hmget(env_key, *message_keys) if with_env
@redis.hmget(hash_key, message_keys).map! do |json|
message = Message.from_json(json)
if with_env
env = envs[message.key]
if !message.env || message.env.size == 0
env = env && env.size > 0 ? ::JSON.parse(env) : {}
message.env = env
end
end
message
end
end
def get_env(message_key)
json = @redis.hget(env_key, message_key)
return if !json || json.size == 0
JSON.parse(json)
end
def protect(message_key)
if message = get(message_key)
message.protected = true
update_message(message)
end
end
def unprotect(message_key)
if message = get(message_key)
message.protected = false
update_message(message)
else
raise "Message already deleted"
end
end
def solved
@redis.hkeys(solved_key) || []
end
def register_rate_limit_per_minute(severities, limit, &block)
register_rate_limit(severities, limit, 60, block)
end
def register_rate_limit_per_hour(severities, limit, &block)
register_rate_limit(severities, limit, 3600, block)
end
def redis_prefix
return 'default'.freeze if !@redis_prefix
@prefix_is_proc ||= @redis_prefix.respond_to?(:call)
@prefix_is_proc ? @redis_prefix.call : @redis_prefix
end
def rate_limits
@rate_limits ||= {}
end
def insert_pattern(set_name, pattern)
@redis.sadd(set_name, pattern)
end
def remove_pattern(set_name, pattern)
@redis.srem(set_name, pattern)
end
def get_patterns(set_name)
@redis.smembers(set_name)
end
def increment_ignore_count(pattern)
@redis.hincrby(ignored_logs_count_key, pattern, 1)
end
def remove_ignore_count(pattern)
@redis.hdel(ignored_logs_count_key, pattern)
end
def get_all_ignore_count
@redis.hgetall(ignored_logs_count_key)
end
def rate_limited?(ip_address, perform: false, limit: 60)
key = ip_rate_limit_key(ip_address)
limited = @redis.exists(key)
if perform && !limited
@redis.setex key, limit, ""
end
limited
end
protected
def clear_solved(count = nil)
ignores = Set.new(@redis.hkeys(solved_key) || [])
if ignores.length > 0
start = count ? 0 - count : 0
message_keys = @redis.lrange(list_key, start, -1) || []
bulk_get(message_keys).each do |message|
unless (ignores & (message.solved_keys || [])).empty?
delete message
end
end
end
end
def trim
if @redis.llen(list_key) > max_backlog
removed_keys = []
while removed_key = @redis.lpop(list_key)
unless @redis.sismember(protected_key, removed_key)
rmsg = get removed_key
@redis.hdel(hash_key, rmsg.key)
@redis.hdel(env_key, rmsg.key)
@redis.hdel(grouping_key, rmsg.grouping_key)
break
else
removed_keys << removed_key
end
end
removed_keys.reverse.each do |key|
@redis.lpush(list_key, key)
end
end
end
def update_message(message)
@redis.hset(hash_key, message.key, message.to_json(exclude_env: true))
@redis.hset(env_key, message.key, message.env_json)
if message.protected
@redis.sadd(protected_key, message.key)
else
@redis.srem(protected_key, message.key)
end
end
def find_message(list, message_key)
limit = 50
start = 0
finish = limit - 1
found = nil
while found == nil
items = @redis.lrange(list, start, finish)
break unless items && items.length > 0
found = items.index(message_key)
break if found
start += limit
finish += limit
end
found
end
def find_location(before, after, limit)
start = -limit
finish = -1
return [start, finish] unless before || after
found = nil
find = before || after
while !found
items = @redis.lrange(list_key, start, finish)
break unless items && items.length > 0
found = items.index(find)
if items.length < limit
found += limit - items.length if found
break
end
break if found
start -= limit
finish -= limit
end
if found
if before
offset = -(limit - found)
else
offset = found + 1
end
start += offset
finish += offset
finish = -1 if finish > -1
return nil if start > -1
end
[start, finish]
end
def get_search(search)
exclude = false
if String === search && search[0] == "-"
exclude = true
search = search.sub("-", "")
end
[search, exclude]
end
def filter_search(row, search)
search, exclude = get_search(search)
return row unless row && search
if exclude
row if !(row =~ search) && filter_env!(row, search, exclude)
else
row if row =~ search || filter_env!(row, search)
end
end
def filter_env!(message, search, exclude = false)
if Array === message.env
array_env_matches?(message, search, exclude)
else
if exclude
!env_matches?(message.env, search)
else
env_matches?(message.env, search)
end
end
end
def env_matches?(env, search)
return false unless env && search
env.values.any? do |value|
if Hash === value
env_matches?(value, search)
else
case search
when Regexp
value.to_s =~ search
when String
value.to_s =~ Regexp.new(search, Regexp::IGNORECASE)
else
false
end
end
end
end
def array_env_matches?(message, search, exclude)
matches = message.env.select do |env|
if exclude
!env_matches?(env, search)
else
env_matches?(env, search)
end
end
return false if matches.empty?
message.env = matches
message.count = matches.size
true
end
def check_rate_limits(severity)
rate_limits_to_check = rate_limits[self.redis_prefix]
return if !rate_limits_to_check
rate_limits_to_check.each { |rate_limit| rate_limit.check(severity) }
end
def solved_key
@solved_key ||= "__LOGSTER__SOLVED_MAP"
end
def list_key
@list_key ||= "__LOGSTER__LATEST"
end
def hash_key
@hash_key ||= "__LOGSTER__MAP"
end
def env_key
@env_key ||= "__LOGSTER__ENV_MAP"
end
def protected_key
@saved_key ||= "__LOGSTER__SAVED"
end
def grouping_key
@grouping_key ||= "__LOGSTER__GMAP"
end
def ignored_logs_count_key
@ignored_logs_count_key ||= "__LOGSTER__IGNORED_LOGS_COUNT_KEY__MAP"
end
def ip_rate_limit_key(ip_address)
"__LOGSTER__IP_RATE_LIMIT_#{ip_address}"
end
private
def apply_max_size_limit(message)
size = message.to_json(exclude_env: true).bytesize
env_size = message.env_json.bytesize
max_size = Logster.config.maximum_message_size_bytes
if size + env_size > max_size
# env is most likely the reason for the large size
# truncate it so the overall size is < the limit
if Array === message.env
# the - 1 at the end ensures the size goes a little bit below the limit
truncate_at = (message.env.size.to_f * max_size.to_f / (env_size + size)).to_i - 1
truncate_at = 1 if truncate_at < 1
message.env = message.env[0...truncate_at]
end
end
end
def register_rate_limit(severities, limit, duration, callback)
severities = [severities] unless severities.is_a?(Array)
redis = (@redis_raw_connection && @redis_prefix) ? @redis_raw_connection : @redis
rate_limiter = RedisRateLimiter.new(
redis, severities, limit, duration, Proc.new { redis_prefix }, callback
)
rate_limits[self.redis_prefix] ||= []
rate_limits[self.redis_prefix] << rate_limiter
rate_limiter
end
end
end
|
mvali95/logster
|
test/logster/test_pattern.rb
|
require_relative '../test_helper'
require 'logster/redis_store'
require 'logster/pattern'
class TestPattern < Minitest::Test
class FakePattern < Logster::Pattern
def self.set_name
"__LOGSTER__fake_patterns_set".freeze
end
end
Logster::PATTERNS << FakePattern
class TestRedisStore < Logster::BaseStore
def get_patterns(set_name)
["/differentstore/"]
end
end
def setup
Logster.store = Logster::RedisStore.new
Logster.store.clear_all
end
def teardown
Logster.store.clear_all
Logster.store = nil
end
def test_parse_pattern_works_correctly
assert_equal(/osama/i, klass.parse_pattern(/osama/i))
assert_equal(/osama/i, klass.parse_pattern("/osama/i"))
assert_equal(/osama/, klass.parse_pattern("/osama/"))
assert_equal(/osama/, klass.parse_pattern("osama"))
assert_equal(/[a-zA-Z]/, klass.parse_pattern("[a-zA-Z]"))
assert_equal(/[a-zA-Z]/, klass.parse_pattern("/[a-zA-Z]/"))
assert_nil(klass.parse_pattern("/osama"))
assert_nil(klass.parse_pattern("["))
assert_nil(klass.parse_pattern("/[/"))
end
def test_validity_checks_are_correct
assert(klass.valid?(/osama/))
refute(klass.valid?(//))
refute(klass.valid?(//i))
refute(klass.valid?(/ /))
end
def test_find_all_works_correctly
patterns = ["/test/i", "tttt", "[d-y].*"]
patterns.each { |p| FakePattern.new(p).save }
results = FakePattern.find_all
assert_equal(3, results.size)
assert_includes(results, /test/i)
assert_includes(results, /tttt/)
assert_includes(results, /[d-y].*/)
results = FakePattern.find_all(raw: true)
assert_equal(3, results.size)
assert_includes(results, "/test/i")
assert_includes(results, "/tttt/")
assert_includes(results, "/[d-y].*/")
end
def test_find_all_can_take_an_instance_of_store
results = FakePattern.find_all(store: TestRedisStore.new)
assert_equal(1, results.size)
assert_equal(/differentstore/, results.first)
end
def test_find_works_correctly
FakePattern.new("/wwwlll/").save
record = FakePattern.find("wwwlll")
assert_equal(/wwwlll/, record.pattern)
record = FakePattern.find(/wwwlll/)
assert_equal(/wwwlll/, record.pattern)
assert_nil(FakePattern.find("dfsdfsdf"))
assert_nil(FakePattern.find(nil))
end
def test_patterns_get_parsed_on_initialize
assert_equal(/mypattern/, FakePattern.new("mypattern").pattern)
assert_equal(/111333/, FakePattern.new(/111333/).pattern)
end
def test_save_works_correctly
bad_patterns = ["/bruken", nil, "[a-z", "/(osa|sss{1/"]
bad_patterns.each do |p|
assert_raises(Logster::Pattern::PatternError) do
FakePattern.new(p).save
end
end
assert_equal(0, FakePattern.find_all.size)
good_patterns = ["/logster/i", /logster/, "sssd", "(ccx|tqe){1,5}", "logster"]
good_patterns.each do |p|
FakePattern.new(p).save
end
results = FakePattern.find_all
assert_equal(4, results.size) # 4 because /logster/ and logster are the same
good_patterns_regex = [/logster/i, /logster/, /sssd/, /(ccx|tqe){1,5}/]
results.each do |p|
assert_includes(good_patterns_regex, p)
end
end
def test_modify_works_correctly
record = FakePattern.new(/logster/)
record.save
record.modify("/LoGsTEr/")
all_patterns = FakePattern.find_all
assert_equal(1, all_patterns.size)
assert_equal(/LoGsTEr/, all_patterns.first)
assert_equal(/LoGsTEr/, record.pattern)
end
def test_modify_doesnt_remove_old_pattern_when_new_is_bad
record = FakePattern.new(/LoGsTEr/)
record.save
assert_raises(Logster::Pattern::PatternError) do
record.modify("/badReg")
end
all_patterns = FakePattern.find_all
assert_equal(1, all_patterns.size)
assert_equal(/LoGsTEr/, all_patterns.first)
assert_equal(/LoGsTEr/, record.pattern)
end
def test_destroy_works_correctly
record = FakePattern.new(/somepattern/)
record.save
patterns = FakePattern.find_all
assert_equal(1, patterns.size)
assert_equal(/somepattern/, patterns.first)
record.destroy
assert_equal(0, FakePattern.find_all.size)
end
private
def klass
Logster::Pattern
end
end
|
mvali95/logster
|
lib/logster/base_store.rb
|
<reponame>mvali95/logster
# frozen_string_literal: true
module Logster
class BaseStore
attr_accessor :level, :max_retention, :skip_empty, :ignore, :allow_custom_patterns
def initialize
@max_retention = 60 * 60 * 24 * 7
@skip_empty = true
@allow_custom_patterns = false
@patterns_cache = Logster::Cache.new
end
# Save a new message at the front of the latest list.
def save(message)
not_implemented
end
# Modify the saved message to the given one (identified by message.key) and bump it to the top of the latest list
def replace_and_bump(message, save_env: true)
not_implemented
end
# Check if another message with the same grouping_key is already stored.
# Returns the similar message's message.key
def similar_key(message)
not_implemented
end
# The number of messages currently stored.
def count
not_implemented
end
# Delete all unprotected messages in the store.
def clear
not_implemented
end
# Delete all messages, including protected messages.
def clear_all
not_implemented
end
# Get a message by its message_key
def get(message_key, load_env: true)
not_implemented
end
# Get a group of messages by their message_keys
def bulk_get(message_keys)
not_implemented
end
# Get all messages that you have in the store
def get_all_messages
not_implemented
end
# Get a message's env by its message_key
def get_env(message_key)
not_implemented
end
# Mark a message as protected; i.e. it is not deleted by the #clear method
def protect(message_key)
not_implemented
end
def delete(message_key)
not_implemented
end
# Delete messages associated with given message_keys
def bulk_delete(message_keys, grouping_keys)
not_implemented
end
# Clear the protected mark for a message.
def unprotect(message_key)
not_implemented
end
# Solve a particular message, causing all old messages with matching version and backtrace
# to be deleted (report should delete any solved messages when called)
def solve(message_key)
not_implemented
end
# Registers a rate limit on the given severities of logs
def register_rate_limit(severities, limit, duration, &block)
not_implemented
end
# Checks all the existing rate limiters to check if any has been exceeded
def check_rate_limits(severity)
not_implemented
end
# takes a string as `pattern` and places it under the set `set_name`
def insert_pattern(set_name, pattern)
not_implemented
end
# takes a string as `pattern` and removes it from the set `set_name`
def remove_pattern(set_name, pattern)
not_implemented
end
# returns an array of strings each of which must be convertible to regexp
def get_patterns(set_name)
not_implemented
end
# increments the number of messages that have been suppressed by a pattern
def increment_ignore_count(pattern)
end
# removes number of suppressed messages by a pattern
def remove_ignore_count(pattern)
end
# returns a hash that maps patterns to the number of messages they
# have suppressed
def get_all_ignore_count
{}
end
def rate_limited?(ip_address, perform: false, limit: 60)
not_implemented
end
def report(severity, progname, msg, opts = {})
return if (!msg || (String === msg && msg.empty?)) && skip_empty
return if level && severity < level
message = Logster::Message.new(severity, progname, msg, opts[:timestamp], count: opts[:count])
env = opts[:env] || {}
backtrace = opts[:backtrace]
if Hash === env && env[:backtrace]
# Special - passing backtrace through env
backtrace = env.delete(:backtrace)
end
message.populate_from_env(env)
if backtrace
if backtrace.respond_to? :join
backtrace = backtrace.join("\n")
end
message.backtrace = backtrace
else
message.backtrace = caller.join("\n")
end
return if ignore && ignore.any? do |pattern|
if message =~ pattern
val = Regexp === pattern ? pattern.inspect : pattern.to_s
increment_ignore_count(val)
true
end
end
if Logster.config.enable_custom_patterns_via_ui || allow_custom_patterns
custom_ignore = @patterns_cache.fetch do
Logster::SuppressionPattern.find_all(store: self)
end
return if custom_ignore.any? do |pattern|
if message =~ pattern
increment_ignore_count(pattern.inspect)
true
end
end
end
similar = nil
if Logster.config.allow_grouping
key = self.similar_key(message)
similar = get(key, load_env: false) if key
end
if similar
if similar.count < Logster::MAX_GROUPING_LENGTH
similar.env = get_env(similar.key) || {}
end
save_env = similar.merge_similar_message(message)
replace_and_bump(similar, save_env: save_env)
similar
else
save message
message
end
end
def clear_suppression_patterns_cache
@patterns_cache.clear
end
private
def not_implemented
raise "Not Implemented"
end
end
end
|
mvali95/logster
|
test/logster/test_message.rb
|
<reponame>mvali95/logster
require_relative '../test_helper'
require 'logster/message'
class TestMessage < MiniTest::Test
def test_merge_similar
msg1 = Logster::Message.new(0, '', 'test', 10)
msg1.populate_from_env(a: "1", b: "2")
msg2 = Logster::Message.new(0, '', 'test', 20)
msg2.populate_from_env(a: "2", c: "3")
assert_equal(msg2.grouping_key, msg1.grouping_key)
msg1.merge_similar_message(msg2)
assert_equal(20, msg1.timestamp)
assert_equal(10, msg1.first_timestamp)
assert Array === msg1.env
assert_equal(msg1.env.size, 2)
assert({ a: "1", b: "2" } <= msg1.env[0])
assert({ "a" => "2", "c" => "3" } <= msg1.env[1])
end
def test_merge_adds_timestamp_to_env
time1 = Time.new(2010, 1, 1, 1, 1).to_i
msg1 = Logster::Message.new(0, '', 'test', time1)
msg1.env = { a: "aa", b: "bb" }
time2 = Time.new(2011, 1, 1, 1, 1).to_i
msg2 = Logster::Message.new(0, '', 'test', time2)
msg2.env = { e: "ee", f: "ff" }
msg1.merge_similar_message(msg2)
assert_equal(time1, msg1.env[0]["time"])
assert_equal(time2, msg1.env[1]["time"])
end
def test_merge_messages_both_with_array_envs
msg1 = Logster::Message.new(0, '', 'test', 10)
msg1.env = [{ a: "aa", b: "bb" }, { c: "cc", d: "dd" }]
msg2 = Logster::Message.new(0, '', 'test', 20)
msg2.env = [{ e: "ee", f: "ff" }, { g: "gg", h: "hh" }]
msg1.merge_similar_message(msg2)
# new env should be an array, but it should never have
# another array of envs within itself (hence flatten(1))
assert_equal(msg1.env.size, 4)
assert_equal(msg1.env.map(&:keys).flatten(1).map(&:to_s), %w{a b c d e f g h})
assert_equal(msg1.env.map(&:values).flatten(1).map(&:to_s), %w{aa bb cc dd ee ff gg hh})
end
def test_merge_messages_one_with_array_envs
msg1 = Logster::Message.new(0, '', 'test', 10)
msg1.env = [{ a: "aa", b: "bb" }, { c: "cc", d: "dd" }]
msg2 = Logster::Message.new(0, '', 'test', 20)
msg2.env = { e: "ee", f: "ff" }
msg1.merge_similar_message(msg2)
assert_equal(msg1.env.size, 3)
assert_equal(msg1.env.map(&:keys).flatten(1).map(&:to_s), %w{a b c d e f time})
assert_equal(msg1.env.map(&:values).flatten(1).map(&:to_s), %w{aa bb cc dd ee ff 20})
end
def test_adds_application_version
Logster.config.application_version = "abc"
msg = Logster::Message.new(0, '', 'test', 10)
msg.populate_from_env({})
assert_equal("abc", msg.env["application_version"])
ensure
Logster.config.application_version = nil
end
def test_merging_sums_count_for_both_messages
msg1 = Logster::Message.new(0, '', 'test', 10, count: 15)
msg2 = Logster::Message.new(0, '', 'test', 20, count: 13)
msg2.env = {}
assert_equal(msg1.grouping_key, msg2.grouping_key)
save_env = msg1.merge_similar_message(msg2)
assert(save_env)
assert_equal(msg1.count, 15 + 13)
end
def test_messages_with_bad_encoding_dont_break_logster
hash = {
severity: 0,
progname: "test",
message: "invalid encoding",
env: {
a: "bad_value",
b: ["bad_value"]
}
}
json = hash.to_json.gsub("bad_value", "45\xC0\xBE")
message = Logster::Message.from_json(json)
message.to_json # test failure would be this raising exception
message.env = JSON.parse(json)["env"]
message.to_json
end
def test_populate_from_env_works_on_array
msg = Logster::Message.new(0, '', 'test', 10)
hash = { "custom_key" => "key" }
msg.populate_from_env([hash])
assert Array === msg.env
assert_equal(msg.env.size, 1)
assert hash <= msg.env[0]
end
def test_ensure_env_samples_dont_exceed_50
msg1 = Logster::Message.new(0, '', 'test', 10, count: 50)
msg1.env = [{ a: 1 }]
msg2 = Logster::Message.new(0, '', 'test', 20, count: 13)
msg2.env = { b: 2 }
assert_equal(msg1.grouping_key, msg2.grouping_key)
save_env = msg1.merge_similar_message(msg2)
refute(save_env)
assert_equal(63, msg1.count) # update count
assert_equal([{ a: 1 }], msg1.env) # but don't merge msg2's env into msg1's
end
def test_message_to_h_respects_params
msg = Logster::Message.new(0, "", "test")
test_hash = { test_key: "this is a test" }
msg.env = test_hash
assert_equal(test_hash, msg.to_h[:env])
assert_nil(msg.to_h(exclude_env: true)[:env])
end
def test_message_to_json_respects_params
msg = Logster::Message.new(0, "", "test")
test_hash = { test_key: "this is a test" }
msg.env = test_hash
assert_includes(msg.to_json, test_hash.to_json)
refute_includes(msg.to_json(exclude_env: true), test_hash.to_json)
end
def test_title_is_truncated_when_too_large
msg = Logster::Message.new(0, "", "a" * 1000)
# 3 is the ... at the end to indicate truncated message
assert_equal(600 + 3, msg.message.size)
end
def test_env_is_not_merged_into_similar_message_if_size_will_be_too_large
default = Logster.config.maximum_message_size_bytes
Logster.config.maximum_message_size_bytes = 1000
message = Logster::Message.new(Logger::INFO, "test", "message", count: 13)
env = [{ key1: "this is my first key", key2: "this is my second key" }] * 13
message.env = env
message2 = Logster::Message.new(Logger::INFO, "test", "message")
message2.env = env.first
message.merge_similar_message(message2)
# env isn't merged, but count is incremented
assert_equal(13, message.env.size)
assert_equal(14, message.count)
ensure
Logster.config.maximum_message_size_bytes = default
end
end
|
mvali95/logster
|
lib/logster/ignore_pattern.rb
|
<filename>lib/logster/ignore_pattern.rb
module Logster
class IgnorePattern
def initialize(message_pattern = nil, env_patterns = nil)
@msg_match = message_pattern
@env_match = env_patterns
end
def self.from_message_and_request_uri(msg, request)
IgnorePattern.new(msg, REQUEST_URI: request)
end
def matches?(message)
if @msg_match
return false unless compare(message.message, @msg_match)
end
if @env_match
return false unless compare(message.env, @env_match)
end
true
end
def to_s
"<#Logster::IgnorePattern, msg_match: #{@msg_match.inspect}, env_match: #{@env_match.inspect}>"
end
private
def compare(message, pattern)
return false unless message && pattern
case pattern
when Regexp
message.to_s =~ pattern
when String
message.to_s =~ Regexp.new(Regexp.escape(pattern), Regexp::IGNORECASE)
when Hash
if Hash === message
compare_hash(message, pattern)
else
false
end
else
false
end
end
def compare_hash(message_hash, pattern_hash)
return false unless message_hash
pattern_hash.each do |key, value|
return false unless compare(get_indifferent(message_hash, key), value)
end
true
end
def get_indifferent(hash, key)
return hash[key] if hash[key]
return hash[key.to_s] if hash[key.to_s]
# no key.to_sym please, memory leak in Ruby < 2.2
nil
end
end
end
|
mvali95/logster
|
lib/logster/message.rb
|
<reponame>mvali95/logster
require 'digest/sha1'
require 'securerandom'
module Logster
MAX_GROUPING_LENGTH = 50
MAX_MESSAGE_LENGTH = 600
class Message
LOGSTER_ENV = "_logster_env".freeze
ALLOWED_ENV = %w{
HTTP_HOST
REQUEST_URI
REQUEST_METHOD
HTTP_USER_AGENT
HTTP_ACCEPT
HTTP_REFERER
HTTP_X_FORWARDED_FOR
HTTP_X_REAL_IP
hostname
process_id
application_version
}
attr_accessor :timestamp, :severity, :progname, :key, :backtrace, :count, :protected, :first_timestamp
attr_reader :message, :env
def initialize(severity, progname, message, timestamp = nil, key = nil, count: 1)
@timestamp = timestamp || get_timestamp
@severity = severity
@progname = progname
@message = truncate_message(message)
@key = key || SecureRandom.hex
@backtrace = nil
@count = count || 1
@protected = false
@first_timestamp = nil
end
def to_h(exclude_env: false)
h = {
message: @message,
progname: @progname,
severity: @severity,
timestamp: @timestamp,
key: @key,
backtrace: @backtrace,
count: @count,
protected: @protected
}
h[:first_timestamp] = @first_timestamp if @first_timestamp
h[:env] = @env unless exclude_env
h
end
def message=(m)
@message = truncate_message(m)
end
def to_json(opts = nil)
exclude_env = Hash === opts && opts.delete(:exclude_env)
JSON.fast_generate(to_h(exclude_env: exclude_env), opts)
end
def self.from_json(json)
parsed = ::JSON.parse(json)
msg = new(parsed["severity"],
parsed["progname"],
parsed["message"],
parsed["timestamp"],
parsed["key"])
msg.backtrace = parsed["backtrace"]
msg.env = parsed["env"]
msg.count = parsed["count"]
msg.protected = parsed["protected"]
msg.first_timestamp = parsed["first_timestamp"]
msg
end
def env=(env)
@env_json = nil
@env = self.class.scrub_params(env)
end
def self.hostname
@hostname ||= `hostname`.strip! rescue "<unknown>"
end
def populate_from_env(env)
env ||= {}
if Array === env
env = env.map do |single_env|
self.class.default_env.merge(single_env)
end
else
env = self.class.default_env.merge(env)
end
@env_json = nil
@env = Message.populate_from_env(env)
end
def self.default_env
env = {
"hostname" => hostname,
"process_id" => Process.pid
}
env["application_version"] = Logster.config.application_version if Logster.config.application_version
env
end
# in its own method so it can be overridden
def grouping_hash
return { message: self.message, severity: self.severity, backtrace: self.backtrace }
end
# todo - memoize?
def grouping_key
Digest::SHA1.hexdigest JSON.fast_generate grouping_hash
end
# todo - memoize?
def solved_keys
if Array === env
versions = env.map { |single_env| single_env["application_version"] }
else
versions = env["application_version"]
end
if versions && backtrace && backtrace.length > 0
versions = [versions] if String === versions
versions.map do |version|
Digest::SHA1.hexdigest "#{version} #{backtrace}"
end
end
end
def is_similar?(other)
self.grouping_key == other.grouping_key
end
def merge_similar_message(other)
self.first_timestamp ||= self.timestamp
self.timestamp = [self.timestamp, other.timestamp].max
self.count += other.count || 1
return false if self.count > Logster::MAX_GROUPING_LENGTH
size = self.to_json(exclude_env: true).bytesize + self.env_json.bytesize
extra_env_size = other.env_json.bytesize
return false if size + extra_env_size > Logster.config.maximum_message_size_bytes
other_env = JSON.load JSON.fast_generate other.env
if Hash === other_env && !other_env.key?("time")
other_env["time"] = other.timestamp
end
if Hash === self.env && !self.env.key?("time")
self.env["time"] = self.first_timestamp
end
if Array === self.env
Array === other_env ? self.env.concat(other_env) : self.env << other_env
else
Array === other_env ? self.env = [self.env, *other_env] : self.env = [self.env, other_env]
end
@env_json = nil
true
end
def self.populate_from_env(env)
if Array === env
env.map do |single_env|
self.populate_env_helper(single_env)
end
else
self.populate_env_helper(env)
end
end
def self.populate_env_helper(env)
env[LOGSTER_ENV] ||= begin
unless env.include? "rack.input"
# Not a web request
return env
end
scrubbed = default_env
request = Rack::Request.new(env)
params = {}
request.params.each do |k, v|
if k.include? "password"
params[k] = "[redacted]"
elsif Array === v
params[k] = v[0..20]
else
params[k] = v && v[0..100]
end
end
scrubbed["params"] = params if params.length > 0
ALLOWED_ENV.map { |k|
scrubbed[k] = env[k] if env[k]
}
scrubbed
end
end
def <=>(other)
time = self.timestamp <=> other.timestamp
return time if time && time != 0
self.key <=> other.key
end
def =~(pattern)
case pattern
when Hash
IgnorePattern.new(nil, pattern).matches? self
when String
IgnorePattern.new(pattern, nil).matches? self
when Regexp
IgnorePattern.new(pattern, nil).matches? self
when IgnorePattern
pattern.matches? self
else
nil
end
end
def env_json
@env_json ||= (self.env || {}).to_json
end
def self.scrub_params(params)
if Array === params
params.map! { |p| scrub_params(p) }
params
elsif Hash === params
params.each do |k, v|
params[k] = scrub_params(v)
end
params
elsif String === params
scrubbed = params.scrub if !params.valid_encoding?
scrubbed || params
else
params
end
end
protected
def truncate_message(msg)
return msg unless msg
msg.size <= MAX_MESSAGE_LENGTH ? msg : msg[0...MAX_MESSAGE_LENGTH] + "..."
end
def get_timestamp
(Time.new.to_f * 1000).to_i
end
end
end
|
mvali95/logster
|
lib/logster/pattern.rb
|
<filename>lib/logster/pattern.rb<gh_stars>0
module Logster
class Pattern
class PatternError < StandardError; end
def self.set_name
raise "Please override the `set_name` method and specify and a name for this set"
end
def self.parse_pattern(string)
return string if Regexp === string
return unless String === string
if string[0] == "/"
return unless string =~ /\/(.+)\/(.*)/
string = $1
flag = Regexp::IGNORECASE if $2 && $2.include?("i")
end
Regexp.new(string, flag)
rescue RegexpError
nil
end
def self.find_all(raw: false, store: Logster.store)
patterns = store.get_patterns(set_name) || []
unless raw
patterns.map! do |p|
parse_pattern(p)
end
end
patterns.compact!
patterns
end
def self.find(pattern, store: Logster.store)
pattern = parse_pattern(pattern).inspect
return nil unless pattern
pattern = find_all(raw: true, store: store).find { |p| p == pattern }
return nil unless pattern
new(pattern)
end
def self.valid?(pattern)
return false unless Regexp === pattern
pattern_size = pattern.inspect.size
pattern_size > 3 && pattern_size < 500
end
def initialize(pattern, store: Logster.store)
self.pattern = pattern
@store = store
end
def valid?
self.class.valid?(pattern)
end
def to_s
pattern.inspect
end
def save(args = {})
ensure_valid!
@store.insert_pattern(set_name, self.to_s)
end
def modify(new_pattern)
new_pattern = self.class.parse_pattern(new_pattern)
raise PatternError.new unless self.class.valid?(new_pattern)
destroy
self.pattern = new_pattern
save
end
def destroy
@store.remove_pattern(set_name, self.to_s)
end
def pattern
@pattern
end
private
def pattern=(new_pattern)
@pattern = self.class.parse_pattern(new_pattern)
end
def set_name
self.class.set_name
end
def ensure_valid!
raise PatternError.new("Invalid pattern") unless valid?
end
end
end
|
mvali95/logster
|
lib/logster/cache.rb
|
module Logster
class Cache
def initialize(age = 2)
@age = age
@hash = { created_at: Process.clock_gettime(Process::CLOCK_MONOTONIC) }
end
def fetch
if !@hash.key?(:data) || @hash[:created_at] + @age < Process.clock_gettime(Process::CLOCK_MONOTONIC)
@hash[:data] = yield
@hash[:created_at] = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
@hash[:data]
end
def clear
@hash.delete(:data)
end
end
end
|
mvali95/logster
|
test/logster/test_logger.rb
|
<filename>test/logster/test_logger.rb
require_relative '../test_helper'
require 'logster/logger'
require 'logger'
class TestStore
attr_accessor :calls
def report(*args)
(@calls ||= []) << args
end
end
class TestLogger < Minitest::Test
def setup
@store = TestStore.new
@logger = Logster::Logger.new(@store)
end
def test_only_logs_valid_encoding
@logger.add(4, "a \xE4 test", "prog")
_, _, message = @store.calls[0]
assert_equal true, message.valid_encoding?
end
def test_per_thread_override
@logger.override_level = 2
@logger.add(0, "test", "prog", backtrace: "backtrace", env: { a: "x" })
Thread.new do
@logger.add(0, "test", "prog", backtrace: "backtrace", env: { a: "x" })
end.join
@logger.override_level = nil
@logger.add(0, "test", "prog", backtrace: "backtrace", env: { a: "x" })
assert_equal 2, @store.calls.length
end
def test_backtrace
@logger.add(0, "test", "prog", backtrace: "backtrace", env: { a: "x" })
assert_equal "backtrace", @store.calls[0][3][:backtrace]
end
def test_chain
io = StringIO.new
@logger.chain Logger.new(io)
@logger.warn "boom"
assert_match(/W,.*boom/, io.string)
end
def test_backtrace_with_chain
@other_store = TestStore.new
@logger.chain(Logster::Logger.new(@other_store))
@logger.add(0, "test", "prog", backtrace: "backtrace", env: { a: "x" })
[@store, @other_store].each do |store|
assert_equal "backtrace", store.calls[0][3][:backtrace]
end
end
def test_add_with_one_argument
@logger.add(2) { "test" }
@logger.add(2)
assert_equal 2, @store.calls.length
assert_equal "test", @store.calls.first[2]
end
class NewLogger < Logster::Logger; end
def test_inherited_logger_backtrace_with_chain
@other_store = TestStore.new
@logger = NewLogger.new(@store)
@logger.chain(Logster::Logger.new(@other_store))
@logger.add(0, "test", "prog", backtrace: "backtrace", env: { a: "x" })
[@store, @other_store].each do |store|
assert_equal "backtrace", store.calls[0][3][:backtrace]
end
end
def test_progname_parameter
@logger.add(0, "test")
progname = @store.calls[0][1]
assert_nil progname
end
class PlayLogger
attr_accessor :skip_store
def initialize(tester)
@tester = tester
end
def add(s, m, p, &block)
@tester.assert(skip_store)
end
end
def test_chain_with_ignore
@logger.chain PlayLogger.new(self)
@logger.skip_store = true
@logger.warn("testing")
end
end
|
mvali95/logster
|
test/logster/test_redis_store.rb
|
<gh_stars>0
require_relative '../test_helper'
require 'logster/redis_store'
require 'rack'
class TestRedisStore < Minitest::Test
def setup
@store = Logster::RedisStore.new(Redis.new)
@store.clear_all
end
def teardown
@store.clear_all
end
def test_delete
env = { test_env: "this is env" }
msg = @store.report(Logger::WARN, "test", "testing", env: env)
@store.delete(msg)
latest = @store.latest
assert_equal(0, latest.length)
assert_nil(@store.get_env(msg.key))
end
def test_latest
@store.report(Logger::WARN, "test", "IGNORE")
@store.report(Logger::WARN, "test", "This is a warning")
@store.report(Logger::WARN, "test", "This is another warning")
latest = @store.latest(limit: 2)
assert_equal(2, latest.length)
assert_equal("This is a warning", latest[0].message)
assert_equal("This is another warning", latest[1].message)
assert_equal(Logger::WARN, latest[1].severity)
assert_equal("test", latest[1].progname)
assert(!latest[1].key.nil?)
end
def test_latest_after
10.times do |i|
@store.report(Logger::WARN, "test", "A#{i}")
end
message = @store.latest[-1]
3.times do |i|
@store.report(Logger::WARN, "test", i.to_s)
end
message = @store.latest(after: message.key, limit: 3)[0]
assert_equal("0", message.message)
end
def test_latest_before
10.times do
@store.report(Logger::WARN, "test", "A")
end
10.times do
@store.report(Logger::WARN, "test", "B")
end
10.times do
@store.report(Logger::WARN, "test", "C")
end
messages = @store.latest(limit: 10)
assert_equal("C", messages[0].message)
assert_equal(10, messages.length)
messages = @store.latest(limit: 10, before: messages[0].key)
assert_equal("B", messages[0].message)
assert_equal(10, messages.length)
messages = @store.latest(limit: 10, before: messages[0].key)
assert_equal("A", messages[0].message)
assert_equal(10, messages.length)
end
def test_get
a_env = { "a_message" => "A MESSAGE" }
a_message = @store.report(Logger::WARN, "test", "A", env: a_env)
b_message = @store.report(Logger::WARN, "test", "B")
@store.report(Logger::WARN, "test", "C")
a_message = @store.get(a_message.key)
assert_equal("A", a_message.message)
assert_equal("B", b_message.message)
assert(a_env <= a_message.env)
a_message = @store.get(a_message.key, load_env: false)
assert_equal("A", a_message.message)
assert_nil(a_message.env)
end
def test_save_saves_env_separately
env = { "myenv" => "thisisenv" }
message = @store.report(Logger::WARN, "test", "title", env: env)
message = @store.get(message.key, load_env: false)
assert_nil(message.env)
message = @store.get(message.key)
assert(env <= message.env)
assert(env <= @store.get_env(message.key))
end
def test_bulk_get
keys = []
5.times do |n|
env = n == 0 ? nil : { "test_#{n}" => "envsss" }
keys << @store.report(Logger::WARN, "progname", "test_#{n}", env: env).key
end
messages = @store.bulk_get(keys)
5.times do |n|
msg = messages[n]
assert_equal("test_#{n}", msg.message)
if n == 0
assert_equal(Logster::Message.default_env, msg.env)
else
assert({ "test_#{n}" => "envsss" } <= msg.env)
end
end
end
def test_get_env
env = { "my_little_env" => "some value" }
message = @store.report(Logger::WARN, "test", "A", env: env)
assert(env <= @store.get_env(message.key))
assert_nil(@store.get_env("nonexistentkey"))
end
def test_replace_and_bump
old_env = { "old_env" => "old value" }
message = @store.report(Logger::WARN, "test", "A", env: old_env)
unsaved_env = { "unsaved_env" => "lost value" }
message.env = unsaved_env
@store.replace_and_bump(message, save_env: false)
message = @store.get(message.key)
assert(old_env <= message.env)
refute(unsaved_env <= message.env)
saved_env = { "saved_env" => "saved value!" }
message.env = saved_env
@store.replace_and_bump(message)
message = @store.get(message.key)
assert(saved_env == message.env)
end
def test_merging_performance
Logster.config.allow_grouping = true
backtrace = "fake backtrace"
env = { "some_env" => "some env" }
another_env = { "another_env" => "more env" }
yet_another_env = { "moaar_env" => "more env" }
@store.report(Logger::WARN, "", "title", backtrace: backtrace, env: env, count: 49)
message = @store.report(Logger::WARN, "", "title", backtrace: backtrace, env: another_env)
assert_instance_of(Array, message.env)
assert_equal(2, message.env.size)
assert(env <= message.env[0])
assert(another_env <= message.env[1])
message = @store.report(Logger::WARN, "", "title", backtrace: backtrace, env: yet_another_env)
# we don't need to load env from redis cause we don't
# need to merge new env samples if count is 50 or more
assert_nil(message.env)
ensure
Logster.config.allow_grouping = false
end
def test_backlog
env = { "backlog_test" => "BACKLOG" }
@store.max_backlog = 1
deleted_msg = @store.report(Logger::WARN, "test", "A")
@store.report(Logger::WARN, "test", "A")
@store.report(Logger::WARN, "test", "A")
@store.report(Logger::WARN, "test", "B", env: env)
latest = @store.latest
assert_equal(1, latest.length)
assert_equal("B", latest[0].message)
assert(env <= latest[0].env)
assert_nil(@store.get(deleted_msg.key))
assert_nil(@store.get_env(deleted_msg.key))
end
def test_save_unsave
@store.max_backlog = 3
@store.report(Logger::WARN, "test", "A")
b_message = @store.report(Logger::WARN, "test", "B")
@store.protect b_message.key
c_message = @store.report(Logger::WARN, "test", "C")
@store.protect c_message.key
@store.report(Logger::WARN, "test", "D")
latest = @store.latest
assert_equal(3, latest.length)
assert_equal("B", latest[0].message)
assert_equal("C", latest[1].message)
assert_equal(true, latest[1].protected)
assert_equal("D", latest[2].message)
# Saved messages still accessible by key
assert_equal("B", @store.get(b_message.key).message)
assert_equal(true, @store.get(b_message.key).protected)
# Unsave does not delete message if still recent
@store.unprotect c_message.key
assert_equal("C", @store.get(c_message.key).message)
assert_equal(false, @store.get(c_message.key).protected)
end
def test_clear
env = { "clear_env" => "cllleear" }
@store.max_backlog = 25
a_message = @store.report(Logger::WARN, "test", "A", timestamp: Time.now - (24 * 60 * 60), env: env)
@store.protect a_message.key
20.times do
@store.report(Logger::WARN, "test", "B", env: env)
end
c_message = @store.report(Logger::WARN, "test", "C", timestamp: Time.now + (24 * 60 * 60), env: env)
@store.protect c_message.key
d_message = @store.report(Logger::WARN, "test", "D", env: env)
10.times do
@store.report(Logger::WARN, "test", "E", env: env)
end
latest = @store.latest
assert_equal(25, latest.length)
@store.clear
# Protected messages are still accessible by their key
assert_equal("C", @store.get(c_message.key).message)
assert(env <= @store.get_env(c_message.key))
# Unprotected messages are gone
assert_nil(@store.get(d_message.key))
assert_nil(@store.get_env(d_message.key))
# The latest list is rebuilt with protected messages, earliest first
# Including messages that previously fell off (A)
latest = @store.latest
assert_equal(2, latest.length)
assert_equal("A", latest[0].message)
assert_equal("C", latest[1].message)
assert(env <= latest[0].env)
assert(env <= latest[1].env)
end
def test_hash_cleanup
@store.max_backlog = 2
a_message = @store.report(Logger::WARN, "test", "A")
@store.report(Logger::WARN, "test", "B")
@store.report(Logger::WARN, "test", "C")
assert_nil(@store.get(a_message.key))
end
def test_filter_latest
@store.report(Logger::INFO, "test", "A")
@store.report(Logger::WARN, "test", "B")
messages = @store.latest
assert_equal(2, messages.length)
messages = @store.latest(after: messages.last.key)
assert_equal(0, messages.length)
10.times do
@store.report(Logger::INFO, "test", "A")
end
@store.report(Logger::ERROR, "test", "C")
10.times do
@store.report(Logger::INFO, "test", "A")
end
latest = @store.latest(severity: [Logger::ERROR, Logger::WARN], limit: 2)
assert_equal(2, latest.length)
assert_equal("B", latest[0].message)
assert_equal("C", latest[1].message)
@store.report(Logger::ERROR, "test", "E")
# respects after
latest = @store.latest(severity: [Logger::ERROR, Logger::WARN], limit: 2, after: latest[1].key)
assert_equal(1, latest.length)
end
def test_search
@store.report(Logger::INFO, "test", "ABCDEFG")
@store.report(Logger::INFO, "test", "TUVWXYZ")
messages = @store.latest
assert_equal(2, messages.length)
latest = @store.latest(search: "TUVWXYZ")
assert_equal(1, latest.length)
assert_equal("TUVWXYZ", latest[0].message)
end
def test_search_exclude_results
@store.report(Logger::INFO, "test", "ABCDEFG")
@store.report(Logger::INFO, "test", "TUVWXYZ")
messages = @store.latest
assert_equal(2, messages.length)
latest = @store.latest(search: "-ABCD")
assert_equal(1, latest.length)
assert_equal("TUVWXYZ", latest[0].message)
end
def test_regex_search
@store.report(Logger::INFO, "test", "pattern_1")
@store.report(Logger::INFO, "test", "pattern_2")
messages = @store.latest
assert_equal(2, messages.length)
latest = @store.latest(search: /^pattern_[1]$/)
assert_equal(1, latest.length)
end
def test_env_search
@store.report(Logger::INFO, "test", "message ABCD", env: { cluster: "business5" })
@store.report(Logger::INFO, "test", "message WXYZ", env: { cluster: "business7" })
messages = @store.latest
assert_equal(2, messages.length)
latest = @store.latest(search: "business5")
assert_equal(1, latest.length)
assert_equal("message ABCD", latest[0].message)
latest = @store.latest(search: "-business5")
assert_equal(1, latest.length)
assert_equal("message WXYZ", latest[0].message)
latest = @store.latest(search: /business/)
assert_equal(2, latest.length)
assert_equal(["message ABCD", "message WXYZ"], latest.map(&:message).sort)
end
def test_array_env_search_preserve_env
m1_original_env = [{ cluster: "business5" }, { cluster: "standard3" }]
m2_original_env = [{ cluster: "business2" }, { cluster: "standard7" }]
@store.report(Logger::INFO, "test", "message ABCD", env: m1_original_env, count: 2)
@store.report(Logger::INFO, "test", "message WXYZ", env: m2_original_env, count: 2)
messages = @store.latest
assert_equal(2, messages.length)
m1_key = messages[0].key
m2_key = messages[1].key
messages = @store.latest(search: "business")
assert_equal(2, messages.size)
# any hashes that don't match should be stripped from the env
# array but only temporarily until it's sent to the client
# env array should remain untouched in redis memory
assert_equal(["business5"], messages[0].env.map { |env| env["cluster"] })
assert_equal(1, messages[0].count)
assert_equal(["business2"], messages[1].env.map { |env| env["cluster"] })
assert_equal(1, messages[1].count)
m1 = @store.get(m1_key)
m2 = @store.get(m2_key)
# original env should preserved in redis memory
assert_equal(["business5", "standard3"], m1.env.map { |env| env["cluster"] })
assert_equal(["business2", "standard7"], m2.env.map { |env| env["cluster"] })
end
def test_both_env_and_title_match_search
@store.report(Logger::INFO, "test", "message", env: [{ cluster: "business15" }])
@store.report(Logger::INFO, "test", "message2", env: { cluster: "business15" })
messages = @store.latest
assert_equal(2, messages.size)
messages = @store.latest(search: "-business15")
assert_equal(0, messages.size)
end
def test_data_kept_intact_on_report_when_env_matches_an_ignore_pattern
begin
Logster.config.allow_grouping = true
backtrace = caller
message = @store.report(Logger::WARN, "", "my error", env: { whatever: "something", backtrace: backtrace })
@store.ignore = [
Logster::IgnorePattern.new("business")
]
@store.report(Logger::WARN, "", "my error", env: { cluster: "business17", backtrace: backtrace })
message = @store.get(message.key)
assert(Array === message.env)
assert_equal(2, message.env.size)
# message2 shouldn't vanish even if
# its env matches an ignore pattern
# however it should be merged with message1
assert_equal("business17", message.env[1]["cluster"])
ensure
# reset so it doesn't affect other tests
@store.ignore = nil
Logster.config.allow_grouping = false
end
end
def test_array_env_negative_search
@store.report(Logger::INFO, "test", "message ABCD", env: [{ cluster: "business5" }, { cluster: "standard3" }], count: 2)
@store.report(Logger::INFO, "test", "message WXYZ", env: [{ cluster: "business2" }, { cluster: "standard7" }], count: 2)
messages = @store.latest
assert_equal(2, messages.length)
messages = @store.latest(search: "-business")
assert_equal(2, messages.size)
assert_equal(["standard3"], messages[0].env.map { |env| env["cluster"] })
assert_equal(1, messages[0].count)
assert_equal(["standard7"], messages[1].env.map { |env| env["cluster"] })
assert_equal(1, messages[1].count)
end
def test_negative_search_MUST_not_match_title_in_order_to_include_message
@store.report(Logger::INFO, "test", "message ABCD", env: [{ cluster: "business5" }, { cluster: "standard3" }], count: 2)
messages = @store.latest(search: "-ABCD")
assert_equal(0, messages.size) # cause title has ABCD
end
def test_positive_search_looks_at_title_OR_env
@store.report(Logger::INFO, "test", "message", env: [{ cluster: "business5 ABCDEFG" }, { cluster: "standard3" }], count: 2)
messages = @store.latest(search: "ABCDEFG")
assert_equal(1, messages.size)
assert_equal(1, messages[0].env.size)
assert_equal("business5 ABCDEFG", messages[0].env[0]["cluster"])
end
def test_backtrace
@store.report(Logger::INFO, "test", "pattern_1")
message = @store.latest(limit: 1).first
assert_match("test_backtrace", message.backtrace)
end
def test_ignore
@store.ignore = [/^test/]
@store.report(Logger::INFO, "test", "test it")
@store.report(Logger::INFO, "test", " test it")
assert_equal(1, @store.latest.count)
end
def test_solve
Logster.config.application_version = "abc"
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1")
m = @store.report(Logger::WARN, "application", "test error2", backtrace: "backtrace1")
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace2")
assert_equal(3, @store.latest.count)
@store.solve(m.key)
assert_equal(1, @store.latest.count)
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1")
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1", env: { "application_version" => "xyz" })
assert_equal(2, @store.latest.count)
ensure
Logster.config.application_version = nil
end
def test_solve_grouped
Logster.config.allow_grouping = true
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1", env: { "application_version" => "xyz" })
m = @store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1", env: { "application_version" => "efg" })
assert_equal(1, @store.latest.count)
@store.solve(m.key)
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1", env: { "application_version" => "xyz" })
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1", env: { "application_version" => "efg" })
assert_equal(0, @store.latest.count)
ensure
Logster.config.allow_grouping = false
end
def test_clears_solved
m = @store.report(Logger::WARN, "application", "test error2", backtrace: "backtrace1", env: { "application_version" => "abc" })
@store.solve(m.key)
assert_equal(1, @store.solved.length)
@store.clear
assert_equal(0, @store.solved.length)
end
def test_solving_with_some_missing_version
m = @store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1", env: { "application_version" => "xyz" })
@store.report(Logger::WARN, "application", "test error1", backtrace: "backtrace1")
@store.solve(m.key)
assert_equal(1, @store.latest.count)
end
def test_env
env = Rack::MockRequest.env_for("/test").merge(
"HTTP_HOST" => "www.site.com",
"HTTP_USER_AGENT" => "SOME WHERE"
)
orig = env.dup
orig["test"] = "tests"
orig["test1"] = "tests1"
Logster.add_to_env(env, "test", "tests")
Logster.add_to_env(env, "test1", "tests1")
orig.delete_if do |k, v|
!%w{
HTTP_HOST
REQUEST_METHOD
HTTP_USER_AGENT
test
test1
}.include? k
end
@store.report(Logger::INFO, "test", "test", env: env)
env = @store.latest.last.env
env.delete "hostname"
env.delete "process_id"
assert_equal(orig, env)
end
def test_custom_ignore_patterns_work_with_per_store_config
Logster.config.enable_custom_patterns_via_ui = false
@store.allow_custom_patterns = true
Logster::SuppressionPattern.new("/testtesttest/", store: @store).save
@store.report(Logger::INFO, "test", "testtesttesttest")
latest = @store.latest
assert_equal(0, latest.size)
@store.allow_custom_patterns = false
@store.report(Logger::INFO, "test", "testtesttesttest")
latest = @store.latest
assert_equal(1, latest.size)
assert_equal("testtesttesttest", latest.first.message)
end
def test_suppressed_logs_are_counted
@store.ignore = [/store ignore/, Logster::IgnorePattern.new(/ignore pattern/), "an ignore string"]
@store.allow_custom_patterns = true
Logster::SuppressionPattern.new(/sup pattern/, store: @store).save
2.times do
@store.report(Logger::INFO, "test", "this is store ignore")
@store.report(Logger::INFO, "test", "this is ignore pattern")
@store.report(Logger::INFO, "test", "this is sup pattern")
@store.report(Logger::INFO, "test", "this is an ignore string")
end
ignore_pattern = Logster::IgnorePattern.new(/ignore pattern/)
hash = @store.get_all_ignore_count
assert_equal("2", hash[ignore_pattern.to_s])
assert_equal("2", hash[/sup pattern/.inspect])
assert_equal("2", hash[/store ignore/.inspect])
assert_equal("2", hash["an ignore string"])
@store.remove_ignore_count(ignore_pattern.to_s)
hash = @store.get_all_ignore_count
assert_nil(hash[ignore_pattern.to_s])
end
def test_rate_limits
%w{minute hour}.each do |duration|
begin
called = false
assert_instance_of(
Logster::RedisRateLimiter,
@store.public_send("register_rate_limit_per_#{duration}", Logger::WARN, 0) do
called = true
end
)
@store.report(Logger::WARN, "test", "test")
assert called
ensure
reset_redis
end
end
end
def test_rate_limits_only_checks_when_message_is_bumped_or_saved
Logster.config.allow_grouping = true
Logster.config.application_version = 'abc'
@store.ignore = [/^ActiveRecord::RecordNotFound/]
rate_limit = @store.register_rate_limit_per_minute(Logger::WARN, 0)
message = @store.report(Logger::WARN, 'message 1', "Error!", backtrace: 'here')
assert_equal(1, rate_limit.retrieve_rate)
@store.report(Logger::WARN, 'message 1', "Error!", backtrace: 'here')
assert_equal(2, rate_limit.retrieve_rate)
@store.solve(message.key)
@store.report(Logger::WARN, 'message 1', "Error!", backtrace: 'here')
assert_equal(2, rate_limit.retrieve_rate)
@store.report(Logger::WARN, 'message 2', "Error!")
assert_equal(3, rate_limit.retrieve_rate)
@store.report(Logger::WARN, 'message 3', "ActiveRecord::RecordNotFound")
assert_equal(3, rate_limit.retrieve_rate)
ensure
Logster.config.allow_grouping = false
Logster.config.application_version = nil
reset_redis
end
def test_rate_limits_with_prefix
begin
time = Time.now
Timecop.freeze(time)
current_namespace = 'first'
@store.redis_prefix = Proc.new { current_namespace }
called_first = 0
called_second = 0
@store.register_rate_limit_per_minute(Logger::WARN, 0) { called_first += 1 }
@store.report(Logger::WARN, "test", "test")
assert_equal(1, called_first)
current_namespace = 'second'
@store.register_rate_limit_per_minute(Logger::WARN, 0) { called_second += 1 }
@store.report(Logger::WARN, "test", "test")
assert_equal(1, called_first)
assert_equal(1, called_second)
Timecop.freeze(time + 10) do
current_namespace = 'first'
@store.report(Logger::WARN, "test", "test")
assert_equal(2, called_first)
assert_equal(1, called_second)
end
ensure
reset_redis
end
end
def test_suppression_patterns_are_cached
@store.allow_custom_patterns = true
rec = Logster::SuppressionPattern.new(/forest/, store: @store)
rec.save
@store.report(Logger::INFO, "test", "littleforest")
latest = @store.latest
assert_equal(0, latest.size)
rec.destroy(clear_cache: false)
@store.report(Logger::INFO, "test", "anotherforest")
assert_equal(0, @store.latest.size)
Process.stub :clock_gettime, Process.clock_gettime(Process::CLOCK_MONOTONIC) + 3 do
@store.report(Logger::INFO, "test", "myforest")
latest = @store.latest
assert_equal(1, latest.size)
assert_equal("myforest", latest.first.message)
end
end
def test_store_trims_too_big_envs
default = Logster.config.maximum_message_size_bytes
Logster.config.maximum_message_size_bytes = 1000
message = Logster::Message.new(Logger::INFO, "test", "message")
env = [{ key1: "this is my first key", key2: "this is my second key" }] * 40
message.env = env
@store.save(message)
trimmed_message = @store.latest.first
assert_equal(13, trimmed_message.env.size)
size = message.to_json(exclude_env: true).bytesize + message.env_json.bytesize
assert_operator(1000, :>, size)
ensure
Logster.config.maximum_message_size_bytes = default
end
private
def reset_redis
@store.clear_all
end
end
|
Nabster2104/MyFirstLib
|
MyFirstLib.podspec
|
<reponame>Nabster2104/MyFirstLib
Pod::Spec.new do |s|
s.name = "MyFirstLib"
s.version = "1.0.7"
s.summary = "This is my First Lib"
s.description = "This is my First Lib, check it out."
s.homepage = "https://github.com/Nabster2104/"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "<NAME>" => "<EMAIL>" }
s.platform = :ios, "9.3"
s.source = { :git => "https://github.com/Nabster2104/MyFirstLib.git", :tag => s.version }
s.source_files = "MyFirstLib/**/*"
s.exclude_files = "MyFirstLib/**/*.plist"
s.swift_version = '4.2'
s.ios.deployment_target = '9.3'
s.dependency 'Alamofire', '4.8.0'
end
|
ready4god2513/readable_message
|
lib/readable_message.rb
|
require "readable_message/version"
module ReadableMessage
class Formatter
def initialize(message, *args)
@message = message
@messages = args.concat([:class, :message, :backtrace, :inspect]).flatten.collect { |arg|
Message.new(@message, arg)
}
end
def to_s
wrapper { body }
end
private
def body
@messages.each { |msg| puts msg.to_s unless msg.to_s.nil? }
end
def wrapper
puts "*" * 80
yield if block_given?
puts "*" * 80
end
end
class Message
def initialize(str, method)
@str, @method = str, method
end
def to_s
@str.send(@method).to_s if @str.respond_to?(@method.to_sym)
end
end
end
class Object
def to_readable(*args)
ReadableMessage::Formatter.new(self, args).to_s
end
end
|
ready4god2513/readable_message
|
spec/readable_message_spec.rb
|
<filename>spec/readable_message_spec.rb
require "spec_helper"
describe ReadableMessage do
subject { "my string" }
it { should respond_to(:to_readable) }
end
|
ready4god2513/readable_message
|
spec/spec_helper.rb
|
require "rubygems"
require "bundler/setup"
require "readable_message"
RSpec.configure do |config|
config.color_enabled = true
config.formatter = "documentation"
end
|
cwoz117/cookbooks
|
recipes/default.rb
|
package 'bind'
package 'bind-utils'
service 'named' do
action [:start, :enable]
end
file '/etc/named.conf' do
mode 0755
user 'named'
group 'named'
end
|
cwoz117/cookbooks
|
test/integration/default/default_test.rb
|
describe package 'bind' do
it {should be_installed}
end
describe service 'named' do
it {should be_enabled}
end
describe file '/etc/named.conf' do
it {should exist}
end
|
immersionroom/vee
|
scratch/homebrew_deps.rb
|
require 'json'
$:.unshift('/usr/local/Library/Homebrew')
require 'global'
require 'formula'
f = Formulary.factory('ffmpeg')
info = f.to_hash
info['dependencies'] = deps = {}
f.deps.each {|dep|
dep_class = 'build' if dep.build?
dep_class ||= 'optional' if dep.optional?
dep_class ||= 'required'
deps[dep.to_s] = {
:class => dep_class,
:installed => (dep.to_formula.version if dep.installed?),
}
}
puts JSON.pretty_generate(info)
|
espenhogbakk/chamber
|
app/models/user.rb
|
<reponame>espenhogbakk/chamber
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name
validates_presence_of :email, :first_name, :last_name
has_many :messages, :dependent => :destroy
has_many :participants
has_many :rooms, :through => :participants, :dependent => :destroy
def serializable_hash(options = nil)
{
id: id,
first_name: first_name,
last_name: last_name,
full_name: full_name,
email: email,
}
end
def full_name
"#{first_name} #{last_name}"
end
end
|
espenhogbakk/chamber
|
app/controllers/attachments_controller.rb
|
<filename>app/controllers/attachments_controller.rb
class AttachmentsController < ApplicationController
before_filter :authenticate_user!
def index
@attachments = Attachment.all
respond_to do |format|
format.json { render json: @attachments }
end
end
def show
@attachment = Attachment.find(params[:id])
respond_to do |format|
format.json { render json: @attachment }
end
end
def new
@attachment = Attachment.new
respond_to do |format|
format.json { render json: @attachment }
end
end
def edit
@attachment = Attachment.find(params[:id])
end
def create
@attachment = Attachment.new(message_id: params[:message_id], attachment: params[:attachment])
respond_to do |format|
if @attachment.save
format.json { render json: @attachment, status: :created, location: @attachment }
else
format.json { render json: @attachment.errors, status: :unprocessable_entity }
end
end
end
def update
@attachment = Attachment.find(params[:id])
respond_to do |format|
if @attachment.update_attributes(params[:attachment])
format.json { head :ok }
else
format.json { render json: @attachment.errors, status: :unprocessable_entity }
end
end
end
def destroy
@attachment = Attachment.find(params[:id])
@attachment.destroy
respond_to do |format|
format.json { head :ok }
end
end
end
|
espenhogbakk/chamber
|
app/controllers/participants_controller.rb
|
class ParticipantsController < ApplicationController
before_filter :authenticate_user!
def index
if params.include? :room_id
room = Room.find(params[:room_id])
@participants = room.participants
else
@participants = Participant.all
end
respond_to do |format|
format.json { render json: @participants }
end
end
# GET /participants/1
# GET /participants/1.json
def show
@participant = Participant.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @participant }
end
end
# GET /participants/1/edit
def edit
@participant = Participant.find(params[:id])
end
# PUT /participants/1
# PUT /participants/1.json
def update
@participant = Participant.find(params[:id])
respond_to do |format|
if @participant.update_attributes(params[:participant])
format.html { redirect_to @participant, notice: 'Participant was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @participant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /participants/1
# DELETE /participants/1.json
def destroy
if params.include? :room_id
# If room is is sent, delete by user_id
room = Room.find(params[:room_id])
@participant = room.participants.where(user_id: params[:id]).first
else
@participant = Participant.find(params[:id])
end
@participant.destroy
respond_to do |format|
format.html { redirect_to root_url }
format.json { head :ok }
end
end
end
|
espenhogbakk/chamber
|
app/models/roster.rb
|
<reponame>espenhogbakk/chamber
class Roster < SuperModel::Base
include SuperModel::Redis::Model
include SuperModel::Timestamp::Model
attributes :count
belongs_to :user
validates_presence_of :user_id
belongs_to :room
indexes :user_id
class << self
def subscribe
Juggernaut.subscribe do |event, data|
data.default = {}
user_id = data["meta"]["user_id"]
room_id = data["meta"]["room_id"]
next unless user_id &&
case event
when :subscribe
event_subscribe(user_id, room_id)
when :unsubscribe
event_unsubscribe(user_id)
end
end
end
protected
def event_subscribe(user_id, room_id)
user = find_by_user_id(user_id) || self.new(user_id: user_id, room_id: room_id)
user.increment!
end
def event_unsubscribe(user_id)
user = find_by_user_id(user_id)
user && user.decrement!
end
end
def count
read_attribute(:count) || 0
end
def increment!
self.count += 1
save!
end
def decrement!
self.count -= 1
self.count > 0 ? save! : destroy
end
end
|
espenhogbakk/chamber
|
test/unit/helpers/room_helper_test.rb
|
<reponame>espenhogbakk/chamber
require 'test_helper'
class RoomHelperTest < ActionView::TestCase
end
|
espenhogbakk/chamber
|
app/controllers/app_controller.rb
|
<filename>app/controllers/app_controller.rb
class AppController < ApplicationController
before_filter :authenticate_user!
def index
# TODO Move this to a scope
# TODO Include them if the current_user is a participant of the room
@rooms = Room.where(invite_only: [nil, false])
end
end
|
espenhogbakk/chamber
|
app/observers/roster_observer.rb
|
<filename>app/observers/roster_observer.rb
class RosterObserver < ActiveRecord::Observer
observe :roster
def after_create(roster)
publish :create, roster
end
def after_update(roster)
publish :update, roster
end
def after_destroy(roster)
publish :destroy, roster
end
private
def publish(action, roster)
Juggernaut.publish "rooms:#{roster.room_id}:roster", {
action: action,
roster: roster
}
end
end
|
espenhogbakk/chamber
|
app/observers/participant_observer.rb
|
class ParticipantObserver < ActiveRecord::Observer
observe :participant
def after_create(participant)
publish :create, participant
end
def after_update(participant)
publish :update, participant
end
def after_destroy(participant)
publish :destroy, participant
end
private
def publish(action, participant)
Juggernaut.publish "rooms:#{participant.room.id}:participants", {
action: action,
participant: participant
}
end
end
|
espenhogbakk/chamber
|
config/routes.rb
|
<reponame>espenhogbakk/chamber<gh_stars>0
Chamber::Application.routes.draw do
devise_for :users
resources :users
resources :messages
resources :rooms do
resources :messages
resources :participants
end
resources :attachments
resources :app
root :to => "app#index"
end
|
espenhogbakk/chamber
|
app/controllers/rooms_controller.rb
|
<gh_stars>0
class RoomsController < ApplicationController
before_filter :authenticate_user!
before_filter :find_room, :only =>[:show, :update, :destroy, :edit]
def index
@rooms = Room.all
respond_to do |format|
format.html
format.json { render json: @rooms }
end
end
def show
if @room.participants.where(user_id: current_user.id).empty?
@room.participants.create(user_id: current_user.id)
end
end
def new
@room = Room.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @room }
end
end
def create
@room = Room.new(params[:room])
respond_to do |format|
if @room.save
format.html { redirect_to @room, notice: 'Message was successfully created.' }
format.json { render json: @room, status: :created, location: @room }
else
format.html { render action: "new" }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
# GET /rooms/1/edit
def edit
end
# PUT /rooms/1
# PUT /rooms/1.json
def update
respond_to do |format|
if @room.update_attributes(params[:room])
format.html { redirect_to @room, notice: 'Room was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rooms/1
# DELETE /rooms/1.json
def destroy
@room.destroy
respond_to do |format|
format.html { redirect_to rooms_url }
format.json { head :ok }
end
end
private
def find_room
@room = Room.find(params[:id])
end
end
|
espenhogbakk/chamber
|
db/migrate/20120203202458_relate_message_to_user.rb
|
class RelateMessageToUser < ActiveRecord::Migration
def change
change_table :messages do |t|
t.references :user
end
end
end
|
espenhogbakk/chamber
|
app/models/message.rb
|
class Message < ActiveRecord::Base
has_one :attachment
belongs_to :user
belongs_to :room
validates_presence_of :body, :room_id, :user_id
def serializable_hash(options = nil)
{
id: id,
body: body,
room: room,
user: user,
updated_at: updated_at,
created_at: created_at,
attachment: attachment,
}
end
end
|
espenhogbakk/chamber
|
db/migrate/20120205133842_add_attachment_to_attachment.rb
|
<reponame>espenhogbakk/chamber<gh_stars>0
class AddAttachmentToAttachment < ActiveRecord::Migration
def self.up
change_table :attachments do |t|
t.has_attached_file :attachment
end
end
def self.down
drop_attached_file :attachments, :attachment
end
end
|
espenhogbakk/chamber
|
db/migrate/20120207173255_add_invite_only_to_rooms.rb
|
class AddInviteOnlyToRooms < ActiveRecord::Migration
def change
add_column :rooms, :invite_only, :boolean
end
end
|
espenhogbakk/chamber
|
db/migrate/20120204121918_create_participants.rb
|
class CreateParticipants < ActiveRecord::Migration
def change
create_table :participants do |t|
t.references :room
t.references :user
t.timestamps
end
add_index :participants, :room_id
add_index :participants, :user_id
end
end
|
espenhogbakk/chamber
|
app/observers/message_observer.rb
|
class MessageObserver < ActiveRecord::Observer
observe :message
def after_create(message)
publish :create, message
end
def after_update(message)
publish :update, message
end
def after_destroy(message)
publish :destroy, message
end
private
def publish(action, message)
Juggernaut.publish "rooms:#{message.room.id}:messages", {
action: action,
message: message
}
end
end
|
espenhogbakk/chamber
|
app/models/room.rb
|
class Room < ActiveRecord::Base
has_many :messages, :dependent => :destroy
has_many :participants
has_many :users, :through => :participants
attr_accessible :id, :name, :topic, :invite_only
end
|
espenhogbakk/chamber
|
app/views/rooms/show.json.jbuilder
|
<gh_stars>0
json.(@room, :id, :name, :messages)
|
espenhogbakk/chamber
|
db/migrate/20120203144249_create_attachments.rb
|
class CreateAttachments < ActiveRecord::Migration
def change
create_table :attachments do |t|
t.references :message
t.timestamps
end
end
def self.up
change_table :attachments do |t|
t.has_attached_file :file
end
end
def self.down
drop_attached_file :attachments, :file
end
end
|
espenhogbakk/chamber
|
app/models/attachment.rb
|
class Attachment < ActiveRecord::Base
has_attached_file :attachment
belongs_to :message
#validates_presence_of :message_id
def attachment_url
self.attachment.url
end
def serializable_hash(options = nil)
{
id: id,
message_id: message_id,
updated_at: updated_at,
created_at: created_at,
attachment_url: attachment_url,
attachment_content_type: attachment_content_type,
attachment_file_size: attachment_file_size,
}
end
end
|
espenhogbakk/chamber
|
app/helpers/app_helper.rb
|
module AppHelper
# def script_template(name, id = nil)
# id ||= name
# id += "_template"
# id = id.camelize(:lower)
# content_tag(:script, :type => "text/template", :id => id) do
# render :partial => name
# end
# end
#
# def meta_tag(name, value)
# %(<meta name="#{name}" content="#{Rack::Utils.escape_html(value)}"/>).html_safe
# end
end
|
espenhogbakk/chamber
|
app/models/participant.rb
|
class Participant < ActiveRecord::Base
belongs_to :room
belongs_to :user
def serializable_hash(options = nil)
{
id: id,
room: room,
user: user,
updated_at: updated_at,
created_at: created_at
}
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/stack.rb
|
<reponame>iamjoshbinder/irwebmachine<gh_stars>1-10
class IRWebmachine::Stack
def initialize(stack = [])
@stack = stack
@index = 0
@tracer = IRWebmachine::Tracer.new
@tracer.events = ["call", "return"]
@tracer.targets = [Webmachine::Resource::Callbacks]
end
def push(*args)
@stack.push(*args)
end
alias_method :<<, :push
def pop
@stack.pop
end
def last
@stack.last
end
def tracer
@tracer
end
def previous
@index -= 1 if @index != 0
@stack[@index]
end
def exhausted?
@tracer.finished?
end
def continue
if @index < @stack.size - 1
@index += 1
else
@index += 1 if @stack.size != 0
@stack << tracer.continue
end
@stack[@index]
end
def next
frame = nil
while frame.nil? || !frame.event?(:call)
frame = continue
end
frame
end
def to_a
@stack.dup
end
def to_graph
graph = Graph.new
@stack.each do |frame|
if frame.event?(:call)
graph.edge(frame.to_s)
end
end
graph
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine.rb
|
<filename>lib/irwebmachine.rb<gh_stars>1-10
module IRWebmachine
require "uri/query_params"
require "graph"
require_relative "irwebmachine/application"
require_relative "irwebmachine/traced_request"
require_relative "irwebmachine/frame"
require_relative "irwebmachine/tracer"
require_relative "irwebmachine/stack"
require_relative "irwebmachine/version"
def self.app=(app)
@app = Application.new app
end
def self.app
@app
end
end
|
iamjoshbinder/irwebmachine
|
test/fixtures/resource.rb
|
<gh_stars>1-10
class Resource < Webmachine::Resource
def content_types_provided
[["plain/text", :to_text]]
end
def content_types_accepted
[["*/*", :accept]]
end
def allowed_methods
%w(GET POST DELETE PUT)
end
# POST
def process_post
response.body = "POST OK"
end
# GET
def to_text
response.body = "GET OK"
end
# PUT
def accept
response.body = "PUT OK"
end
# DELETE
def delete_resource
response.body = "DELETE OK"
end
def finish_request
response.headers['X-Request-Query'] = request.query
response.headers['X-Request-Headers'] = request.headers
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/traced_request.rb
|
<reponame>iamjoshbinder/irwebmachine<gh_stars>1-10
class IRWebmachine::TracedRequest
def initialize(app)
@app = app
@req = nil
@res = nil
@stack = IRWebmachine::Stack.new
end
def stack
@stack
end
def dispatch(*args)
dispatch!(*args)
while frame = @stack.tracer.continue
@stack << frame
end
@res
end
def dispatch!(type, path, params = {}, headers = {}, body = "")
uri = URI::HTTP.build(host: "localhost", path: path)
uri.query_params.merge!(params)
@req = Webmachine::Request.new type.upcase, uri, headers, body
@res = Webmachine::Response.new
@stack.tracer.trace do
@app.dispatcher.dispatch(@req, @res)
end
@res
end
def to_a
[@req.method, @req.uri.path, @req.query, @req.headers, @req.body]
end
end
|
iamjoshbinder/irwebmachine
|
test/setup.rb
|
<filename>test/setup.rb
require "bundler/setup"
require "webmachine"
require "irwebmachine"
require "json"
require "test/unit"
Dir["test/fixtures/*.rb"].each do |file|
require "./#{file}"
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/pry.rb
|
<filename>lib/irwebmachine/pry.rb
module IRWebmachine::Pry
require "pry"
require_relative "pry/print_stack"
require_relative "pry/enter_stack"
require_relative "pry/nav"
end
def app
IRWebmachine.app || raise(RuntimeError, "No app set. Use IRWebmachine.app= to set one.", [])
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/pry/enter_stack.rb
|
<reponame>iamjoshbinder/irwebmachine
class IRWebmachine::Pry::EnterStack < Pry::ClassCommand
match 'enter-stack'
group 'irwebmachine'
description 'Enters the context of a method on the call stack for a webmachine request.'
banner <<-BANNER
enter-stack BREAKPOINT
Enters into the context of a method on the call stack for a webmachine
request. BREAKPOINT can be retrieved from the print-stack command.
BANNER
def setup
@app = target.eval "app"
@pry = Pry.new :commands => IRWebmachine::Pry::Nav
@req = IRWebmachine::TracedRequest.new @app.unbox
end
def process
@req.dispatch! *@app.last_request
repl @req.stack.continue
end
private
def repl(frame)
until hit?
if breakpoint =~ frame.to_s
@hit = true
else
if @req.stack.exhausted?
raise Pry::CommandError, 'No matching breakpoint.'
else
frame = @req.stack.continue
end
end
end
case @pry.repl(frame.context)
when nil
# no-op (exit).
when :next
repl @req.stack.next
when :continue
repl @req.stack.continue
when :previous
repl @req.stack.previous
end
end
def hit?
@hit
end
def breakpoint
@breakpoint ||= Regexp.new(args.first.to_s)
end
end
set = Pry::CommandSet.new
set.commands["enter-stack"] = IRWebmachine::Pry::EnterStack
Pry.commands.import(set)
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/pry/nav.rb
|
<reponame>iamjoshbinder/irwebmachine
module IRWebmachine::Pry
Nav = Pry::CommandSet.new do
command("continue") { throw(:breakout, :continue) }
alias_command "c", "continue"
command("next") { throw(:breakout, :next) }
alias_command "n", "next"
command("prev") { throw(:breakout, :previous) }
alias_command "p", "prev"
end
end
IRWebmachine::Pry::Nav.import(Pry.commands)
|
iamjoshbinder/irwebmachine
|
test/irwebmachine_application_test.rb
|
<filename>test/irwebmachine_application_test.rb
require_relative "setup"
class IRWebmachine::ApplicationTest < Test::Unit::TestCase
def setup
IRWebmachine.app = app
@app = IRWebmachine.app
end
def test_get
res = @app.get "/mock_application"
assert_equal "GET OK", res.body
end
def test_post
res = @app.post "/mock_application"
assert_equal "POST OK", res.body
end
def test_delete
res = @app.delete "/mock_application"
assert_equal "DELETE OK", res.body
end
def test_put
res = @app.put "/mock_application"
assert_equal "PUT OK", res.body
end
def test_query
%w(get post delete put).each do |verb|
res = @app.send(verb, "/mock_application", {"foo" => "bar"})
assert_equal({"foo" => "bar"}, res.headers['X-Request-Query'])
end
end
def test_headers
%w(get post delete put).each do |verb|
res = @app.send(verb, "/mock_application", {}, {'Answer' => '42'})
assert_equal({'Answer' => '42'}, res.headers['X-Request-Headers'])
end
end
private
def app
Webmachine::Application.new do |app|
app.routes do
add ["mock_application"], Resource
end
end
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/application.rb
|
<filename>lib/irwebmachine/application.rb
class IRWebmachine::Application
def initialize(app)
@app = to_app app
@req = nil
@res = nil
end
def unbox
@app
end
def last_response
@res || raise(RuntimeError, "No active request.", [])
end
def last_request
@req || raise(RuntimeError, "No active request.", [])
end
%w(get post delete put).each do |type|
define_method(type) do |*args|
@req = IRWebmachine::TracedRequest.new @app
@res = @req.dispatch(*[type, *args])
end
end
private
def to_app(obj)
is_module = obj.is_a? Module
is_resource = is_module && obj.ancestors.include?(Webmachine::Resource)
if is_resource
Webmachine::Application.new do |app|
app.routes do
add ["*"], obj
end
end
else
obj
end
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/irb.rb
|
<reponame>iamjoshbinder/irwebmachine
module IRWebmachine::IRB
require 'irb'
require_relative "irb/bundle"
end
module IRB::ExtendCommandBundle
include IRWebmachine::IRB::Bundle
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/frame.rb
|
class IRWebmachine::Frame
def initialize(binding,event)
@binding = binding
@event = event
@file = binding.eval "__FILE__"
@lineno = binding.eval "__LINE__"
@method = binding.eval "__method__"
@klass = binding.eval("self").method(@method).owner
end
def ruby_call?
"call" == @event
end
def event?(type)
type.to_s == @event
end
def context
@binding
end
def to_s
"#{@klass}##{@method}"
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/pry/print_stack.rb
|
<filename>lib/irwebmachine/pry/print_stack.rb
class IRWebmachine::Pry::PrintStack < Pry::ClassCommand
match 'print-stack'
description 'Prints the call stack for the previous webmachine request.'
group 'irwebmachine'
banner <<-BANNER
print-stack [OPTIONS]
Prints the stack of method calls(in order) made during the previous
webmachine request. The stack excludes calls that don't originate from
a subclass of Webmachine::Resource.
BANNER
def setup
@app = target.eval "app"
end
def options(opt)
opt.on :f, 'Filter the stack with a regular expression.', optional: true
end
def process
frames = stack.to_a.map do |frame|
if frame.ruby_call? && frame.to_s =~ filter
frame.to_s
end
end.compact.join "\n"
stagger_output text.with_line_numbers(frames, 0)
end
private
def stack
@app.last_request.stack
end
def filter
Regexp.new(opts[:f].to_s)
end
end
set = Pry::CommandSet.new
set.commands["print-stack"] = IRWebmachine::Pry::PrintStack
Pry.commands.import(set)
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/irb/bundle.rb
|
module IRWebmachine::IRB::Bundle
def app
IRWebmachine.app || raise(RuntimeError, "No app set. Use IRWebmachine.app= to set one.", [])
end
def show_stack(filter = //)
request = app.last_request
request.stack.each_with_index do |trace, int|
puts "#{int}> #{trace}" if trace.to_s =~ filter
end
nil
end
def enter_stack(num)
request = app.last_request
trace = request.stack[num]
puts "==> Entering #{trace.klass}##{trace.method}"
irb(trace.binding)
end
end
|
iamjoshbinder/irwebmachine
|
lib/irwebmachine/tracer.rb
|
<filename>lib/irwebmachine/tracer.rb
require 'thread'
class IRWebmachine::Tracer
def initialize
@thread = nil
@queue = SizedQueue.new(1)
@targets = [BasicObject]
@events = ["call", "c-call", "return", "c-return", "class", "end", "line",
"raise"]
end
#
# The [set\_trace\_func](http://apidock.com/ruby/Kernel/set_trace_func) API
# documentation has a list of possible events.
#
# @param [Array<String>] events
# An array of events.
#
# @return [void]
#
# @example
# #
# # Push a frame onto the queue when the "call" or "return" event is
# # emitted by set_trace_func. By default, all events push a frame
# # onto the queue.
# #
# tracer.events = ["call", "return"]
#
def events=(events)
@events = events
end
#
# @param [Array<Module>] targets
# An array of classes/modules.
#
# @return [void]
#
# @example
# #
# # Push a frame onto the queue when `binding.eval('self')` has
# # Webmachine::Resource::Callbacks somewhere in its ancestry tree.
# # By default, targets is equal to [BasicObject].
# #
# tracer.targets = [Webmachine::Resource::Callbacks]
#
def targets=(targets)
@targets = targets
end
#
# @return [Boolean]
# Returns true when the tracer has finished tracing.
#
def finished?
[false, nil].include? @thread.status
end
#
#
# @return [IRwebmachine::Frame]
# Returns an instance of {IRWebmachine::Frame}.
#
# @example
# #
# # Each call to continue resumes & then suspends the tracer.
# # If you want to trace until there is no more code to trace you
# # could wrap this method in a loop.
# #
# tracer.continue
# tracer.continue
#
def continue
while @queue.empty?
sleep 0.01
return if finished?
end
@queue.deq
end
#
# @overload def trace(&block)
#
# @param [Proc] block
# A block to execute inside the tracer.
#
# @return [void]
#
# @see Tracer#continue
#
# @example
# tracer.trace do
# …
# end
#
def trace
@thread ||=
Thread.new do
Thread.current.set_trace_func method(:tracer).to_proc
yield
Thread.current.set_trace_func(nil)
end
end
private
def tracer(event, file, lineno, id, binding, klass)
try do
has_ancestor = @targets.any? do |t|
# This says, "binding.eval('self') references a class or module,
# and the event(f. ex ':call') came from one of the iterated
# targets".
klass.is_a?(Module) && klass.ancestors.include?(t)
end
if has_ancestor && @events.include?(event)
frame = IRWebmachine::Frame.new(binding,event)
@queue.enq(frame)
end
end
end
def try
begin
yield
rescue SystemStackError => e
puts <<-CRASH
----------------------
CRASH (IRWebmachine)
----------------------
The tracer appears to be locked in infinite
recursion. This may be a bug in IRWebmachine,
but your own code may be the cause.
The tracer will stop execution now, but the
stack up to the point of infinite recursion
is retained for debugging.
CRASH
Thread.current.set_trace_func(nil)
rescue Exception => e
puts <<-CRASH
----------------------
CRASH (IRWebmachine)
----------------------
The tracer has crashed.
This is a bug in IRWebmachine.
EXCEPTION:
#{e.class}
MESSAGE:
#{e.message}
BACKTRACE:
#{e.backtrace.each { |line| puts(line) }}
CRASH
Thread.current.set_trace_func(nil)
end
end
end
|
bini-i/Tic-Tac-Toe
|
lib/board.rb
|
<reponame>bini-i/Tic-Tac-Toe
class Board
attr_accessor :board
def initialize
@board = Array.new(3) { Array.new(3, '_') }
end
def update(value, pos)
@board[pos[0]][pos[1]] = value
end
# Check if user input is legal
def legal_input?(pos)
arr = pos.split('')
x_axis = arr[1]
y_axis = arr[0].upcase
return true if (%w[A B C].include? y_axis) && (%w[1 2 3].include? x_axis)
false
end
# Check if cell that user wants to play is empty
def cell_empty?(pos)
return true if @board[pos[0]][pos[1]] == '_'
false
end
def status
return 1 if check_x_win || check_y_win || check_diag_win
# check for tie
# If board is full and no winner it means tie.
0 unless @board.flatten.any?('_')
end
# draws game layout
def draw
puts ' ___________'
puts "C |_#{@board[2][0]}_|_#{@board[2][1]}_|_#{@board[2][2]}_|"
puts "B |_#{@board[1][0]}_|_#{@board[1][1]}_|_#{@board[1][2]}_|"
puts "A |_#{@board[0][0]}_|_#{@board[0][1]}_|_#{@board[0][2]}_|"
puts " 1 2 3\t\t"
end
private
def check_y_win
rows = @board.transpose
rows.each do |y_axis|
return y_axis.all?('X') || y_axis.all?('O')
end
end
def check_x_win
@board.each do |x_axis|
return x_axis.all?('X') || x_axis.all?('O')
end
end
def check_diag_win
if @board[1][1] != '_'
diag1 = @board[0][0] == @board[1][1] && @board[1][1] == @board[2][2]
diag2 = @board[0][2] == @board[1][1] && @board[1][1] == @board[2][0]
return diag1 || diag2
end
false
end
end
|
bini-i/Tic-Tac-Toe
|
bin/main.rb
|
#!/usr/bin/env ruby
require_relative '../lib/game'
require_relative '../lib/player'
require_relative '../lib/board'
system('clear')
puts ' _____ _ _____ _____ '
puts '|_ _(_) |_ _| |_ _| '
puts ' | | _ ___ | | __ _ ___ | | ___ ___ '
puts ' | | | |/ __| | |/ _` |/ __| | |/ _ \\ / _ \\ '
puts ' | | | | (__ | | (_| | (__ | | (_) | __/ '
puts ' \\_/ |_|\\___| \\_/\\__,_|\\___| \\_/\\___/ \\___| '
puts "\n\nPress Enter to start playing"
gets
begin
system('clear')
puts 'Press s to start playing'
puts 'Press q to quit'
input_opt = gets.chomp
raise unless input_opt.include?('s') || input_opt.include?('q')
if input_opt == 's'
loop do
system('clear')
# player 1 initialize
puts 'Enter player 1 name'
player1_name = gets.chomp
# player 2 initialize
puts 'Enter player 2 name'
player2_name = gets.chomp
system('clear')
game = Game.new(player1_name, player2_name)
game.play
puts "\nEnter r to play again or q to quit"
input_opt = gets.chomp
break if input_opt == 'q'
next if input_opt == 'r'
end
end
rescue StandardError
retry
end
|
bini-i/Tic-Tac-Toe
|
lib/game.rb
|
<filename>lib/game.rb
class Game
def initialize(player1_name, player2_name)
@player1 = Player.new(player1_name)
@player1.type = 'X'
@player2 = Player.new(player2_name)
@player2.type = 'O'
@board = Board.new
end
def play
loop do
@board.draw
input(@player1)
system('clear')
break unless check_outcome(@player1) == -1
@board.draw
input(@player2)
system('clear')
break unless check_outcome(@player2) == -1
end
end
def input(player)
playing = false
until playing
puts "\n#{player.name}'s turn"
puts "\nEnter position (eg. A2)"
input_pos = gets.chomp
legal = @board.legal_input?(input_pos)
if legal
pos = clean_position(input_pos)
unless @board.cell_empty?(pos)
puts '*** This cell is not empty. Please try again. ***'
next
end
@board.update(player.type, pos)
playing = true
else
puts '*** This move is illegal. Please try again. ***'
end
end
end
def clean_position(input_pos)
arr = input_pos.split('')
x_axis = arr[1].to_i - 1
y_axis = arr[0].upcase
# convert string input to array indices
case y_axis
when 'A' then y_axis = 0
when 'B' then y_axis = 1
when 'C' then y_axis = 2
end
[y_axis, x_axis]
end
# Prints out game result
def check_outcome(player)
case @board.status
when 1
puts "*** #{player.name} Won Congratulations! ***"
1
when 0
puts "*** That's a tie ***"
0
else
-1
end
end
end
|
aaronsama/in_or_out
|
lib/in_or_out/geocode.rb
|
require 'pry'
require 'geocoder'
require 'in_or_out/template'
module InOrOut
class Geocode
def self.geocode records, address_template
template = InOrOut::Template.new(address_template, records.headers)
records.map do |r|
r["latitude"], r["longitude"] = Geocoder.coordinates(template.build_address_string_for r)
r
end
end
end
end
|
aaronsama/in_or_out
|
lib/in_or_out/template.rb
|
<filename>lib/in_or_out/template.rb
module InOrOut
class AddressTemplateError < StandardError
end
class Template
def initialize(template_string, headers)
@template_string = template_string
unless parse_column_names(headers)
raise AddressTemplateError.new, "Some keys in the address template do not match any column"
end
end
def build_address_string_for record
column_values = {}
@columns.each do |col_name|
column_values[col_name.to_sym] = record[col_name]
end
@template_string % column_values
end
private
def parse_column_names headers
@columns = @template_string.scan(/\%\{([^\}]+)\}/).flatten
(@columns & headers) == @columns
end
end
end
|
aaronsama/in_or_out
|
lib/in_or_out/group.rb
|
<gh_stars>0
require 'border_patrol'
module InOrOut
class Group
def self.label_records records, polygons, latitude_column, longitude_column
output = []
records.each do |record|
group_found = false
point = BorderPatrol::Point.new(record[longitude_column].to_f, record[latitude_column].to_f)
polygons.each_with_index do |p, idx|
if p.contains_point? point
group_found = true
if p.placemark_name
output << (record << p.placemark_name)
else
output << (record << "AREA #{(idx + 1)}")
end
break
end
end
unless group_found
output << (record << "NO GROUP")
end
end
output
end
end
end
|
aaronsama/in_or_out
|
lib/in_or_out.rb
|
require 'thor'
require 'border_patrol'
require 'csv'
require 'in_or_out/placemark_name'
require 'in_or_out/group'
require 'in_or_out/geocode'
# require 'in_or_out/placemark_name'
# require 'pry'
module InOrOut
class Main < Thor
desc "group CSV_FILE KML_FILE OUTPUT_FILE", "Assigns a group to each point in a CSV_FILE based on the areas defined as polygons in a KML_FILE"
long_desc <<-LONGDESC
Reads an input CSV_FILE of geocoded points (i.e. records that have a latitude and longitude columns) and a KML_FILE containing polygons.
The group command labels each point according to its belonging to one of the polygons in the KML_FILE. If a point does not belong to any polygon it is labeled as "NO GROUP".
The csv OUTPUT_FILE will have the same content of the input CSV with a new column at the end indicating the label.
LONGDESC
method_option :latitude_column, desc: "The name of the column containing the latitude", default: "latitude"
method_option :longitude_column, desc: "The name of the column containing the longitude", default: "longitude"
# method_option :csv_file, :desc => "Path to a CSV file with latitude and longitude columns"
# method_option :kml_file, :desc => "Path to a KML file containing the polygons to use for checking where the points belong"
def group(csv_file, kml_file, output_file)
in_data = CSV.read(csv_file, headers: true)
if (in_data.headers & [options[:latitude_column],options[:longitude_column]]).any?
polygons = BorderPatrol.parse_kml File.read(kml_file)
CSV.open(output_file, "wb", write_headers: true, headers: (in_data.headers + ["GROUP"])) do |output_csv|
grouped_data = InOrOut::Group.label_records in_data, polygons, options[:latitude_column], options[:longitude_column]
grouped_data.each do |line|
output_csv << line
end
end
else
puts "ERROR: The columns '#{options[:latitude_column]}' and '#{options[:longitude_column]}' could not be found in the headers of #{csv_file}"
end
end
desc "geocode CSV_FILE OUTPUT_FILE", "gecode all the entries in the input CSV_FILE"
method_option :address, desc: "The format of the address using the format %{...} to wrap column names. Example %{street} %{city}", required: true
method_option :api_key, desck: "Your Google Maps API key"
def geocode(csv_file, output_file)
if options[:api_key]
Geocoder.configure api_key: options[:api_key]
end
in_data = CSV.read(csv_file, headers: true)
puts "Geocoding #{in_data.size} entries. Please wait..."
begin
out_data = Geocode.geocode(in_data, options[:address])
CSV.open(output_file, "wb", write_headers: true, headers: in_data.headers) do |output_csv|
out_data.each do |line|
output_csv << line
end
end
rescue AddressTemplateError => error
puts error
end
end
end
end
# InOrOut::Main.start
|
aaronsama/in_or_out
|
spec/geocoder_spec.rb
|
require 'spec_helper'
describe InOrOut::Geocode do
describe 'build_address_string_for' do
let(:data) { { "street"=>"via Sommarive", "number"=>"18", "zip"=>"38123", "city"=>"Trento", "state"=>"TN" } }
describe "when a valid template is provided" do
let(:template) { InOrOut::Template.new "%{street} %{number}, %{zip} %{city} (%{state})", data.keys }
it "returns a valid address string" do
expect(template.build_address_string_for data).to eq("via Sommarive 18, 38123 Trento (TN)")
end
end
end
describe 'geocode' do
before do
allow(data).to receive(:headers).and_return(["street","number","zip","city","state"])
end
describe "when an invalid template is provided" do
let(:data) { [{ "street"=>"via Sommarive", "number"=>"18", "zip"=>"38123", "city"=>"Trento", "state"=>"TN" }] }
let(:template) { "%{flipsod}" }
it "throws an exception" do
expect{ InOrOut::Geocode.geocode data, template }.to raise_error(InOrOut::AddressTemplateError, "Some keys in the address template do not match any column")
end
end
describe "when a valid template is provided" do
let(:template) { "%{street} %{number}, %{zip} %{city} (%{state})" }
describe "when records can be geocoded" do
let(:data) { [{ "street"=>"via Sommarive", "number"=>"18", "zip"=>"38123", "city"=>"Trento", "state"=>"TN" }] }
it "returns the record with added latitude and longitude" do
expect(InOrOut::Geocode.geocode(data, template).first).to include("latitude" => 46.0659552, "longitude" => 11.1500445)
end
end
describe "when records cannot be geocoded" do
let(:data) { [{ "street"=>"zapfgharma", "number"=>"-99", "zip"=>"0678", "city"=>"Zmorrgamand", "state"=>"ZZ" }] }
it "returns the record with empty latitude and longitude" do
expect(InOrOut::Geocode.geocode(data, template).first).to include("latitude" => nil, "longitude" => nil)
end
end
end
end
end
|
aaronsama/in_or_out
|
in_or_out.gemspec
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require File.expand_path('../lib/in_or_out/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "in_or_out"
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.summary = %q{This is a very simple Ruby script to label a set of points according to their location inside given areas.}
# gem.description = %q{Longer description of your project.}
gem.homepage = "https://github.com/aaronsama/in_or_out"
gem.license = "MIT"
gem.files = %x{git ls-files}.split($\)
gem.executables = ['in_or_out']
# gem.test_files = ['tests/test_NAME.rb']
gem.require_paths = ["lib"]
gem.version = InOrOut::VERSION
gem.add_runtime_dependency 'border_patrol', ['>= 0.2.1']
gem.add_runtime_dependency 'geocoder', ['~> 1.2.11']
gem.add_development_dependency "rspec"
end
|
aaronsama/in_or_out
|
lib/in_or_out/placemark_name.rb
|
<filename>lib/in_or_out/placemark_name.rb
# This is partially copied from https://github.com/square/border_patrol/blob/master/lib/border_patrol.rb
# because the gem on rubygems is outdated!
module BorderPatrol
class Polygon
attr_reader :placemark_name
def with_placemark_name(placemark)
@placemark_name ||= placemark
self
end
end
def self.parse_kml(string)
doc = Nokogiri::XML(string)
polygons = doc.search('Polygon').map do |polygon_kml|
placemark_name = placemark_name_for_polygon(polygon_kml)
parse_kml_polygon_data(polygon_kml.to_s).with_placemark_name(placemark_name)
end
BorderPatrol::Region.new(polygons)
end
private
def self.placemark_name_for_polygon(p)
# A polygon can be contained by a MultiGeometry or Placemark
parent = p.parent
parent = parent.parent if parent.name == 'MultiGeometry'
return nil unless parent.name == 'Placemark'
parent.search('name').text
end
end
|
alexey-protopopov/ruber_dialog
|
lib/ruber_dialog/parser/description_parser.rb
|
<reponame>alexey-protopopov/ruber_dialog<gh_stars>0
# frozen_string_literal: true
require_relative "errors"
require_relative "tokens"
require_relative "parser"
module RuberDialog
module Parser
# Single Description parser from string
class DescriptionLineParser < TokenParser
include Parser::Tokens
# @param forbidden_expressions [String/RegExpr], expressions that are not supposed to be inside description
# @param reserved_names [String], reserved names such as "Description"
def initialize(forbidden_expressions: [], reserved_names: ["{Description}"])
super(forbidden_expressions, reserved_names)
end
def forbidden_expression_error(expression)
"Forbidden symbol '#{expression}'"
end
def reserved_name_error(name)
"Use of reserved name (#{name}) as a description name is forbidden"
end
protected :forbidden_expression_error, :reserved_name_error
#Input requirements for the description string:
# 1.Character name starts with an uppercase letter, includes only letters,
# mixing uppercase and lowercase is not allowed
# 2.Content inside parentheses'{}' starts with an uppercase letter,
# includes only letters, mixing uppercase and lowercase is not allowed
# 3.Only one character name is expected
# 4.Only one pair of braces '{}' is allowed
# 5.Only one description line('Description:...') is allowed
def validate_description_start(content)
start_regexp = /^{[A-Z][a-z]+}$/
unless content.match?(start_regexp)
raise ParsingError.new("Failed to parse start of description for\n'#{content}'")
end
end
def validate_character(content)
name_regexp = /^(?!Description)[A-Z][a-z]+:/
names_count = content.scan(name_regexp).length
unless content.match?(name_regexp)
raise ParsingError.new("Failed to parse character name for\n'#{content}'")
end
unless names_count == 1
raise ParsingError.new("Only one character name expected but found #{names_count} for\n'#{content}'")
end
end
def validate_description_line(content)
desc_line_regexp = /^{[A-Z][a-z]+}\n^Description: /
desc_line_count = content.scan(/^Description: /).length
unless content.match?(desc_line_regexp)
raise ParsingError.new("Failed to parse start of description line for\n'#{content}'")
end
unless desc_line_count == 1
raise ParsingError.new("Only one description line expected but found #{desc_line_count} for\n'#{content}'")
end
end
def validate_braces_count(content)
unless content.count("{") == 1 and content.count("}") == 1
raise ParsingError.new(msg = "Only one pair of '{}' is allowed for\n'#{content}'")
end
end
def validate(content)
validate_description_start(content)
validate_description_line(content)
validate_character(content)
validate_braces_count(content)
super(content)
end
# parses string into Line
def parse(content)
raise RuberArgumentError unless content.is_a?(String)
self.validate(content)
character_name=content.match(/^(?!Description)\w+:/).to_s[0...-1]
content = content.gsub(/\A\n+/,"") #removes newline characters before the start of the content
Line.new(character_name, content)
end
end
end
end
|
alexey-protopopov/ruber_dialog
|
lib/ruber_dialog/parser/description_block_parser.rb
|
# frozen_string_literal: true
require_relative "errors"
require_relative "tokens"
require_relative "description_parser"
require_relative "block_parser"
module RuberDialog
module Parser
# class for parsing block of Descriptions
class DescriptionBlockParser < BlockParser
attr_reader :block_start_regexp, :reserved_name, :forbidden_expressions
attr_accessor :separator
# @param starting_line Integer, line number where the blocks starts.
# @param block_start_regexp RegularExpression, that matches start of a Description block
# @param reserved_names [String], reserved names such as "Description"
# @param forbidden_expressions [String/RegExpr], expressions that are not supposed to be inside description name
# @param separator String/RegExpr, used to separate characters
def initialize(starting_line: 1, block_start_regexp: /^{[A-Z][a-z]+}$/, reserved_names: ["{Description}"],
forbidden_expressions: %w( [ ] ), separator: "\n")
@block_start_regexp = block_start_regexp
reserved_names = reserved_names.clone
description_parser = DescriptionLineParser.new(forbidden_expressions: forbidden_expressions,
reserved_names: reserved_names)
@separator = separator
super(forbidden_expressions, reserved_names,
starting_line: starting_line, token_parser: description_parser)
end
# for validation and parsing
def split_to_token_contents(descriptions_content)
contents = descriptions_content.split(@separator).reject { |c| c.empty? }
token_contents = []
new_desc = ""
contents.each do |content|
if content.match?(@block_start_regexp) and !new_desc.empty?
token_contents << TokenContent.new(new_desc, new_desc.count('\n'))
new_desc = ""
end
new_desc += content + "\n"
end
token_contents << TokenContent.new(new_desc, new_desc.count('\n'))
end
# validates descriptions block, returns hash<line number, ValidationError>
def validate(descriptions_string)
errors = Hash.new { |hash, key| hash[key] = [] }
unless descriptions_string.match?(@block_start_regexp)
errors[@starting_line] = [ValidationError.new("No description block definition", @starting_line)]
end
super_errors = super(descriptions_string)
errors.merge(super_errors) { |_key, old_val, new_val| old_val.push(*new_val) }
end
# parses descriptions block, returns list of Description
def parse(descriptions_string)
unless descriptions_string.match?(@block_start_regexp)
raise ParsingError.new(@starting_line, "No description block definition")
end
desc_lines = split_to_token_contents descriptions_string
desc_lines.map { |desc_content| @token_parser.parse(desc_content.content) }
end
end
end
end
|
alexey-protopopov/ruber_dialog
|
test/description_block_parser_test.rb
|
<gh_stars>0
# frozen_string_literal: true
require "test_helper"
class DescriptionBlockParserTest < Minitest::Test
include RuberDialog::Parser
include RuberDialog::Parser::Tokens
def val_err(err, line)
ValidationError.new(err, line)
end
def test_description_block_parser_returns_characters
description_parser = DescriptionBlockParser.new
res = description_parser.parse("{Test}\nDescription: test\nPerson: test\n{Goodbye}\nDescription: test\n
Person: test\n")
assert_instance_of Line, res[0]
end
def test_description_block_parser_returns_one_line
description_parser = DescriptionBlockParser.new
res = description_parser.parse("{Test}\nDescription: test\nPerson: test")
assert_equal 1, res.length
end
def test_description_block_parser_returns_multiple_lines
description_parser = DescriptionBlockParser.new
res = description_parser.parse("{Test}\nDescription: test\nPerson: test\n{Goodbye}\nDescription: test\n
Person: test\n")
assert_equal 2, res.length
end
def description_block_parser_parses
description_parser = DescriptionBlockParser.new
tokens = description_parser.parse("{Test}\nDescription: test\nPerson: test\n{Goodbye}\nDescription: test\n
Peter: test\n")
assert_equal [Line.new("Person","{Test}\nDescription: test\nPerson: test\n"),
Line.new("Peter","{Goodbye}\nDescription: test\nPeter: test\n")], tokens
end
def test_description_block_parser_validates_one_forbidden_expressions
description_parser = DescriptionBlockParser.new(forbidden_expressions: %w( [ ] ))
errors = description_parser.validate("{Test}\nDescription: ]test]\nPerson: test\n")
expected_errors = { 2 => [val_err("Forbidden symbol ']'", 2)] }
assert_equal expected_errors, errors
end
def test_description_block_parser_validate_multiple_forbidden_expressions
description_parser = DescriptionBlockParser.new(forbidden_expressions: %w( [ ] ? ))
errors = description_parser.validate("{Test}\nDescription: ]test]\nPerson: test???\n")
expected_errors = { 2 => [val_err("Forbidden symbol ']'", 2)],
3 => [val_err("Forbidden symbol '?'", 3)] }
assert_equal expected_errors, errors
end
def test_description_block_parser_validates_reserved_name
description_parser = DescriptionBlockParser.new(reserved_names: ["{Character}"])
errors = description_parser.validate("{Character}\nDescription: test\nPerson: test\n")
expected_errors = { 1 => [val_err("Use of reserved name ({Character}) as a description name is forbidden", 1)] }
assert_equal expected_errors, errors
end
def test_description_block_parser_throws_parsing_error
description_parser = DescriptionBlockParser.new
assert_raises(ParsingError) do |err|
description_parser.parse("\nGandalf\nDescription")
assert_equal "Failed to parse start of description for", err.to_s
end
end
end
|
alexey-protopopov/ruber_dialog
|
test/description_parser_test.rb
|
<filename>test/description_parser_test.rb<gh_stars>0
# frozen_string_literal: true
require "test_helper"
class DescriptionLineParserTest < Minitest::Test
include RuberDialog::Parser
include RuberDialog::Parser::Tokens
def val_err(err, line = 1)
ValidationError.new(err, line)
end
def test_description_parser_validation_reserved_names
description_parser = DescriptionLineParser.new(reserved_names: %w[{Forbidden} Reserved])
assert_equal [val_err("Use of reserved name ({Forbidden}) as a description name is forbidden")],
description_parser.validate("{Forbidden}\nDescription: test\nMe: test")
assert_equal [val_err("Use of reserved name (Reserved) as a description name is forbidden", 3)],
description_parser.validate("{Reserved}\nDescription: test\nReserved: test")
end
def test_description_parser_validates_one_forbidden_expression
description_parser = DescriptionLineParser.new(forbidden_expressions: %w( [ ] ! ))
assert_equal [val_err("Forbidden symbol '['",2)], description_parser.validate("{Test}\nDescription: t[est\nMe: test")
assert_equal [val_err("Forbidden symbol ']'", 2)], description_parser.validate("{Test}\nDescription: tes]t\nMe: test")
assert_equal [val_err("Forbidden symbol '!'", 3)], description_parser.validate("{Test}\nDescription: test\nMe: test!")
end
def test_description_parser_validates_multiple_forbidden_expressions
description_parser = DescriptionLineParser.new(forbidden_expressions: %w( [ ] !))
assert_equal [val_err("Forbidden symbol '!'",2), val_err("Forbidden symbol '['",2),
val_err("Forbidden symbol ']'",2)],
description_parser.validate("{Test}\nDescription: !t[est]\nMe: test")
end
def test_description_parser_validates_repetitive_error_once
description_parser = DescriptionLineParser.new(forbidden_expressions: %w([ ]))
assert_equal [val_err("Forbidden symbol '['",2)],
description_parser.validate("{Test}\nDescription: [t[e[s[t\nMe: test")
end
def test_description_parser_validates_many_lines
description_parser = DescriptionLineParser.new(forbidden_expressions: %w( [ ] ))
assert_equal [val_err("Forbidden symbol ']'", 3), val_err("Forbidden symbol '['", 2)],
description_parser.validate("{Test}\nDescription: [test\nMe: test]")
end
def test_description_parser_parses_line
description_parser = DescriptionLineParser.new
line = description_parser.parse("{Test}\nDescription: test\nMe: test")
assert_instance_of Line, line
end
def test_description_parser_parser_parses
description_parser = DescriptionLineParser.new
line = description_parser.parse("{Test}\nDescription: test\nMe: test")
assert_equal Line.new("Me","{Test}\nDescription: test\nMe: test"), line
end
def test_description_name_must_start_with_an_uppercase
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{test}\nDescription: test\nMe: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse start of description for"), true
end
def test_description_name_must_include_letters_only
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Act 1}\nDescription: test\nMe: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse start of description for"), true
end
def test_description_name_mixed_case_is_not_allowed
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{GreetinG}\nDescription: test\nMe: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse start of description for"), true
end
def test_character_name_must_start_with_an_uppercase
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Test}\nDescription: test\nme: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse character name for"), true
end
def test_character_name_must_include_letters_only
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Action}\nDescription: test\nRookie-1: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse character name for"), true
end
def test_character_name_mixed_case_is_not_allowed
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Greeting}\nDescription: test\nALeXeY: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse character name for"), true
end
def test_description_line_must_exist
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Test}\nMe: no description line!\nMe: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Failed to parse start of description line for"), true
end
def test_description_line_must_be_alone
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Test}\nDescription: one!\nDescription: two!\nMe: test")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Only one description line expected but found 2"), true
end
def test_character_name_must_be_alone
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Test}\nDescription: one!\nSergey: hi!\nMe: hello")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Only one character name expected but found 2"), true
end
def test_extra_braces_are_not_allowed
result = nil
begin
description_parser = DescriptionLineParser.new
description_parser.parse("{Test}\nDescription: one!\nSergey: {hi}!")
rescue ParsingError => ex
result = :exception_handled
end
assert_equal :exception_handled, result
assert_equal ex.message.match?("Only one pair of '{}' is allowed for"), true
end
end
|
alexey-protopopov/ruber_dialog
|
lib/ruber_dialog.rb
|
# frozen_string_literal: true
require_relative "ruber_dialog/version"
require_relative "ruber_dialog/parser/errors"
require_relative "ruber_dialog/parser/tokens"
require_relative "ruber_dialog/parser/character_block_parser"
require_relative "ruber_dialog/parser/block_parser"
require_relative "ruber_dialog/parser/description_block_parser"
require_relative "ruber_dialog/parser/description_parser"
module RuberDialog
class RuberArgumentError < ArgumentError; end
# Your code goes here...
end
|
ambethia/LuckyPrincessNitro
|
lib/screens/test_screen.rb
|
class TestScreen < BaseScreen
def setup
@systems = %w[
Input
Test
]
end
end
|
ambethia/LuckyPrincessNitro
|
lib/factories/particle_factory.rb
|
class ParticleFactory < EntitySystem::Factory::Base
build :particle
using :px, :py, :type, :attach_to
def construct
entity = manager.create(:particle)
manager.attach(entity, ParticleComponent.new({
effect: type, attach_to: attach_to
}))
manager.attach(entity, SpatialComponent.new({
px: px , py: py, bearing: 0, speed: 0
}))
entity
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/enemy_system.rb
|
class EnemySystem < EntitySystem::System
RATE_OF_FIRE = 0.33
MIN_FIRE_DISTANCE = 120
MAX_FIRE_DISTANCE = 180
def update(delta)
each(EnemyComponent) do |entity, component|
enemy = manager.component(SpatialComponent, entity)
camera = manager.component(SpatialComponent, manager.find(:camera))
player_id = manager.find(:player)
if player_id && !$game.did_we_win_yet?
player_s = manager.component(SpatialComponent, player_id)
player_c = manager.component(PlayerComponent, manager.find(:player))
distance_to_player = Vector2.new(player_s.px, player_s.py).dst(enemy.px, enemy.py)
# rotate around the player, but not if they are holding steady
if player_c.is_turning_left
increment = rand(5)
component.data[:t_angle] -= (increment * delta) % 360
elsif player_c.is_turning_right
increment = rand(5)
component.data[:t_angle] += (increment * delta) % 360
end
component.data[:c_angle] = weighted_average(component.data[:c_angle], component.data[:t_angle])
ellipse_w, ellipse_h = 50, 50
delta_x = player_s.px - enemy.px
delta_y = player_s.py - enemy.py
target_x = player_s.px - (delta_x * 0.25)
target_y = player_s.py - (delta_y * 0.25)
enemy_x = target_x + (Math.cos(component.data[:c_angle]) * ellipse_w)
enemy_y = target_y + (Math.sin(component.data[:c_angle]) * ellipse_h)
enemy.px = weighted_average(enemy.px, enemy_x, 20)
enemy.py = weighted_average(enemy.py, enemy_y, 20)
# face player
angle = (Math.atan2(delta_y , delta_x) * 180 / Math::PI) % 360
enemy.bearing = angle
if component.data[:elapsed_since_last_shot] > RATE_OF_FIRE &&
distance_to_player > MIN_FIRE_DISTANCE
component.data[:elapsed_since_last_shot] = 0
manager.factory.bullet do |bullet|
bullet.owner = entity
bullet.type = "enemy_#{component.type}".to_sym
bullet.px = enemy.px
bullet.py = enemy.py
bullet.bearing = enemy.bearing
end
$game.screen.sounds["enemy_#{component.type}_bullet".to_sym].play
else
component.data[:elapsed_since_last_shot] += delta
end
else
# Fly away if the player is dead
enemy.speed = 100
manager.attach(entity, MotionComponent.new)
end
end
end
def setup
atlas = $game.screen.atlas
$game.screen.sprites[:enemy_a] = {
0 => atlas.create_sprite("enemy_a", 1),
45 => atlas.create_sprite("enemy_a", 2),
90 => atlas.create_sprite("enemy_a", 3),
135 => atlas.create_sprite("enemy_a", 4),
180 => atlas.create_sprite("enemy_a", 5),
225 => atlas.create_sprite("enemy_a", 6),
270 => atlas.create_sprite("enemy_a", 7),
315 => atlas.create_sprite("enemy_a", 8)
}
$game.screen.sprites[:enemy_a_bullets] = {
0 => atlas.create_sprite("bullet_1", 1),
45 => atlas.create_sprite("bullet_1", 2),
90 => atlas.create_sprite("bullet_1", 3),
135 => atlas.create_sprite("bullet_1", 4),
180 => atlas.create_sprite("bullet_1", 5),
225 => atlas.create_sprite("bullet_1", 6),
270 => atlas.create_sprite("bullet_1", 7),
315 => atlas.create_sprite("bullet_1", 8)
}
[:enemy_a_spawn, :enemy_a_bullet, :enemy_a_death].each do |sound|
$game.screen.sounds[sound] = Gdx.audio.new_sound(load_asset("#{sound}.ogg"))
end
end
def reset
each(EnemyComponent) do |entity|
manager.destroy(entity)
end
end
end
|
ambethia/LuckyPrincessNitro
|
lib/factories/item_factory.rb
|
<filename>lib/factories/item_factory.rb
class ItemFactory < EntitySystem::Factory::Base
build :item
using :type, :x, :y
RADIUS = {
gem: 64
}
def construct
entity = manager.create(:item)
manager.attach(entity, ItemComponent.new({
type: type,
}))
manager.attach(entity, CollisionComponent.new({
owner: entity,
radius: RADIUS[type]
}))
manager.attach(entity, SpatialComponent.new({
px: x, py: y, bearing: rand(360), speed: 0
}))
manager.attach(entity, RenderableComponent.new)
manager.attach(entity, RotatedComponent.new({
mapping: $game.screen.sprites[type]
}))
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/input_system.rb
|
class InputSystem < EntitySystem::System
def update(delta)
if Gdx.input.is_key_pressed(Input::Keys::Q)
Gdx.app.exit
elsif Gdx.input.is_key_pressed(Input::Keys::F)
$game.toggle_fullscreen
end
case $game.screen
when SplashScreen
if Gdx.input.is_key_pressed(Input::Keys::SPACE)
$game.game_begin
end
when GameScreen
player_id = manager.find(:player)
if player_id
player = manager.component(PlayerComponent, player_id)
player.is_turning_right = Gdx.input.is_key_pressed(Input::Keys::RIGHT)
player.is_turning_left = Gdx.input.is_key_pressed(Input::Keys::LEFT)
player.is_firing = (Gdx.input.is_key_pressed(Input::Keys::SPACE) || Gdx.input.is_key_pressed(Input::Keys::UP))
end
when GameOverScreen, VictoryScreen
if Gdx.input.is_key_pressed(Input::Keys::SPACE)
$game.game_begin
end
if Gdx.input.is_key_pressed(Input::Keys::ESCAPE)
$game.game_menu
end
when TestScreen
end
end
end
|
ambethia/LuckyPrincessNitro
|
lib/factories/bullet_factory.rb
|
class BulletFactory < EntitySystem::Factory::Base
SPEED = {
player: 240,
enemy_a: 300
}
RADIUS = 8
CULL_RANGE = 400
build :bullet
using :px, :py, :bearing, :type, :owner
def construct
bullet = manager.create(:bullet)
manager.attach(bullet, SpatialComponent.new({
px: px, py: py,
bearing: bearing, speed: SPEED[type]
}))
manager.attach(bullet, CollisionComponent.new({
owner: owner,
radius: RADIUS
}))
manager.attach(bullet, MotionComponent.new)
manager.attach(bullet, RenderableComponent.new)
manager.attach(bullet, RangedCullComponent.new({
range: CULL_RANGE
}))
manager.attach(bullet, RotatedComponent.new({
mapping: bullet_sprites
}))
bullet
end
private
def bullet_sprites
$game.screen.sprites["#{type}_bullets".to_sym]
end
end
|
ambethia/LuckyPrincessNitro
|
lib/components/animated_component.rb
|
class AnimatedComponent < EntitySystem::Component
provides :animation, :is_looped
end
|
ambethia/LuckyPrincessNitro
|
lib/entity_system/factory.rb
|
class EntitySystem::Factory
def initialize(manager)
@manager = manager
end
def build_entity(type, &block)
factory = @@factories[type].new
factory.manager = @manager
yield factory if block_given?
factory.construct
end
def self.factories
@@factories ||= {}
end
class Base
attr_accessor :manager
def self.build(type)
EntitySystem::Factory.factories[type] = self
EntitySystem::Factory.class_eval do
define_method type do |&block|
build_entity(type, &block)
end
end
end
def self.using(*attribute_list)
attribute_list.each do |key|
attr_accessor key
end
end
# overriden in subclasses
def construct
end
end
end
|
ambethia/LuckyPrincessNitro
|
lib/components/player_component.rb
|
<reponame>ambethia/LuckyPrincessNitro<filename>lib/components/player_component.rb<gh_stars>1-10
class PlayerComponent < EntitySystem::Component
provides :shields, :is_turning_left, :is_turning_right, :is_firing
end
|
ambethia/LuckyPrincessNitro
|
lib/entity_system/component.rb
|
class EntitySystem::Component
attr_accessor :entity
def self.provides(*attribute_list)
attribute_list.each do |key|
attr_accessor key
end
end
def initialize(attributes = {})
attributes.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/test_system.rb
|
<reponame>ambethia/LuckyPrincessNitro
class TestSystem < EntitySystem::System
def setup
@effect = ParticleEffect.new
@effect.load(load_asset("explosion.particle"), load_asset(""))
end
def update(delta)
if !@has_run
@has_run = true
@effect.emitters.each(&:start)
end
if Gdx.input.is_key_pressed(Input::Keys::SPACE)
@has_run = false
end
@effect.set_position($game.width/2, $game.height/2)
end
def render(delta)
@effect.draw($game.screen.batch, delta)
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/background_system.rb
|
class BackgroundSystem < EntitySystem::System
STARFIELD_WIDTH = 320
STARFIELD_HEIGHT = 200
STARFIELD_DENSITY = 100
def setup
# dark grey fill
@pixmap = Pixmap.new($game.width, $game.height, Pixmap::Format::RGB888)
@pixmap.set_color(0.1,0.1,0.1,1)
@pixmap.fill
@background = Texture.new(@pixmap)
# stars
@star_sprites = []
3.times do |i|
@star_sprites << $game.screen.atlas.create_sprite("star", i)
end
@stars = []
STARFIELD_DENSITY.times do |i|
@stars << [rand(STARFIELD_WIDTH), rand(STARFIELD_HEIGHT), rand(20)+1, rand(3)]
end
end
def render(delta)
world = Vector3.new(0, 0, 0)
manager.component(CameraComponent, manager.find(:camera)).object.unproject(world)
@background.draw(@pixmap, 0, 0)
$game.screen.batch.draw(@background, world.x, world.y - $game.height)
# player_id = manager.find(:player)
# if player_id
# player = manager.component(SpatialComponent, player_id)
camera = manager.component(SpatialComponent,
manager.find(:camera))
@stars.each do |star|
# translate relative to the camera, parallax based on depth and wrap them around the screen
x = (camera.px + (((star[0] - STARFIELD_WIDTH) - (camera.px / (star[2] * 0.25))) % STARFIELD_WIDTH) - STARFIELD_WIDTH / 2)
y = (camera.py + (((star[1] - STARFIELD_HEIGHT) - (camera.py / (star[2] * 0.25))) % STARFIELD_HEIGHT) - STARFIELD_HEIGHT / 2)
# culll stars outside the viewport
if x > world.x && x < world.x + $game.width &&
y < world.y && y > world.y - $game.height
$game.screen.batch.draw(@star_sprites[star[3]], x, y)
end
end
# end
end
end
|
ambethia/LuckyPrincessNitro
|
test/entity_system_test.rb
|
require_relative 'test_helper'
require 'game_helpers'
require 'entity_system'
class Position < EntitySystem::Component
provides :x, :y
end
class Locator < EntitySystem::System
def process(delta)
each(Position) do |entity, component|
component.x += (1 * delta)
component.y += (1 * delta)
end
end
end
class WidgetFactory < EntitySystem::Factory::Base
build :widget
using :x, :y
def construct
entity = manager.create(:widget)
manager.attach(entity, Position.new(x: 0, y: 0))
entity
end
end
class EntitySystem::ManagerTest < Test::Unit::TestCase
def setup
@manager = EntitySystem::Manager.new
end
def test_create_entity_returns_a_uuid
entity = @manager.create
assert_match /^[0-9a-f\-]{36}$/, entity
end
def test_create_tagged_entity
entity = @manager.create(:player)
assert_equal entity, @manager.find(:player)
end
def test_create_entities_with_same_tag
entities = [@manager.create(:enemy), @manager.create(:enemy)]
assert @manager.all(:enemy).include?(entities[0])
assert @manager.all(:enemy).include?(entities[1])
end
end
class EntitySystem::ComponentTest < Test::Unit::TestCase
def setup
@component = Position.new(x: 1, y: 2)
end
def test_component_gains_attribute_readers
assert_equal 1, @component.x
end
def test_component_gains_attribute_setter
@component.y = 42
assert_equal 42, @component.y
end
end
class EntitySystem::ComponentTest < Test::Unit::TestCase
def setup
@component = Position.new(x: 1, y: 2)
end
def test_component_gains_attribute_readers
assert_equal 1, @component.x
end
def test_component_gains_attribute_setter
@component.y = 42
assert_equal 42, @component.y
end
end
class EntitySystem::SystemTest < Test::Unit::TestCase
def setup
@manager = EntitySystem::Manager.new
@component = Position.new(x: 1, y: 2)
entity = @manager.create
@manager.attach(entity, @component)
@system = Locator.new(@manager)
end
def test_system_changes_component
@system.process(1)
assert_equal 2, @component.x
end
end
class EntitySystem::FactoryTest < Test::Unit::TestCase
def setup
@manager = EntitySystem::Manager.new
end
def test_factory_attaches_component
@manager.factory.widget do |widget|
widget.x = 0
widget.y = 0
end
component = @manager.component(Position, @manager.find(:widget))
assert_equal 0, component.x
end
end
|
ambethia/LuckyPrincessNitro
|
lib/entity_system/system.rb
|
class EntitySystem::System
include GameHelpers
attr_reader :manager
def initialize(manager)
@manager = manager
setup
end
def each(component_class)
manager.entities(component_class).each do |entity|
yield(entity, manager.component(component_class, entity))
end
end
# Optionally overriden in subclasses
def setup
end
# Called in the update block, don't draw in here
def update(delta)
end
# Called in the render block, draw in here
def render(delta)
end
def reset
end
def dispose
end
end
|
ambethia/LuckyPrincessNitro
|
lib/factories/player_factory.rb
|
class PlayerFactory < EntitySystem::Factory::Base
INITIAL_SHIELDS = 6
build :player
using :px, :py, :animations
def construct
entity = manager.create(:player)
manager.attach(entity, PlayerComponent.new({
shields: INITIAL_SHIELDS
}))
manager.attach(entity, MotionComponent.new)
manager.attach(entity, SpatialComponent.new({
px: px, py: py, bearing: 0, speed: 0
}))
manager.attach(entity, AnimatedComponent.new({
is_looped: true
}))
manager.attach(entity, RenderableComponent.new)
manager.attach(entity, RotatedComponent.new({
mapping: $game.screen.sprites[:player],
is_animated: true
}))
entity
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/game_over_system.rb
|
class GameOverSystem < EntitySystem::System
def setup
@image = Texture.new(Gdx.files.internal(RELATIVE_ROOT + "assets/game_over.png"))
end
def render(delta)
if $game.screen.is_a? GameOverScreen
$game.screen.batch.draw(@image, 0, 0)
end
end
end
|
ambethia/LuckyPrincessNitro
|
lib/components/spatial_component.rb
|
class SpatialComponent < EntitySystem::Component
provides :px, :py, :bearing, :speed
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/rotation_system.rb
|
class RotationSystem < EntitySystem::System
def update(delta)
each(RotatedComponent) do |entity, component|
spatial = manager.component(SpatialComponent, entity)
render = manager.component(RenderableComponent, entity)
angle = nearest_increment(spatial.bearing)
if component.is_animated
animated_component = manager.component(AnimatedComponent, entity)
animated_component.animation = component.mapping[angle]
else
render.image = component.mapping[angle]
end
end
end
def nearest_increment(angle, inc = 45)
((angle.round + inc / 2) / inc * inc) % 360
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/music_system.rb
|
class MusicSystem < EntitySystem::System
def setup
@music = Gdx.audio.new_music(load_asset("theme_01.ogg"))
@music.looping = true
end
def update(delta)
@elapsed ||= 0
if @elapsed > 3 && !@music.is_playing
@music.play
end
@elapsed += delta
end
def dispose
@music.dispose
end
end
|
ambethia/LuckyPrincessNitro
|
lib/systems/motion_system.rb
|
class MotionSystem < EntitySystem::System
def update(delta)
each(MotionComponent) do |entity, component|
spatial = manager.component(SpatialComponent, entity)
x_vel = Math.cos(spatial.bearing * Math::PI/180) * spatial.speed
y_vel = Math.sin(spatial.bearing * Math::PI/180) * spatial.speed
spatial.px += x_vel * delta
spatial.py += y_vel * delta
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.