repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
michenriksen/nmunch
|
spec/spec_helper.rb
|
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts 'Run `bundle install` to install missing gems'
exit e.status_code
end
require 'pcap'
require 'ipaddr'
require 'paint'
require 'nmunch'
RSpec.configure do |config|
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
def capture_stdout
original_stdout = $stdout
$stdout = fake = StringIO.new
begin
yield
ensure
$stdout = original_stdout
end
fake.string
end
ARP_PACKET_DATA = "\xff\xff\xff\xff\xff\xff\xde\xad\xbe\xef\xde\xad\x08\x06\x00\x01" +
"\x08\x00\x06\x04\x00\x01\xde\xad\xbe\xef\xde\xad\xc0\xa8\x00\x7d" +
"\x00\x00\x00\x00\x00\x00\xc0\xa8\x00\x42"
IP_PACKET_DATA = "\x7b\x22\x68\x6f\x73\x74\xde\xad\xbe\xef\xde\xad\x20\x32\x36\x37" +
"\x35\x37\x32\x31\x31\x30\x2c\x20\x22\x76\x65\x72\x73\x69\x6f\x6e" +
"\x22\x3a\x20\x5b\x31\x2c\x20\x38\x5d\x2c\x20\x22\x64\x69\x73\x70" +
"\x6c\x61\x79\x6e\x61\x6d\x65\x22\x3a\x20\x22\x32\x36\x37\x35\x37" +
"\x32\x31\x31\x30\x22\x2c\x20\x22\x70\x6f\x72\x74\x22\x3a\x20\x31" +
"\x37\x35\x30\x30\x2c\x20\x22\x6e\x61\x6d\x65\x73\x70\x61\x63\x65" +
"\x73\x22\x3a\x20\x5b\x31\x34\x33\x30\x30\x33\x33\x37\x36\x2c\x20" +
"\x31\x31\x35\x36\x33\x34\x38\x35\x38\x2c\x20\x31\x31\x38\x39\x30" +
"\x36\x37\x30\x31\x5d\x7d"
|
michenriksen/nmunch
|
lib/nmunch/dissectors/ip.rb
|
<reponame>michenriksen/nmunch
module Nmunch
module Dissectors
# Public: Internet Protocol dissector
#
# Extracts IP and MAC address from IP packet
#
# See http://en.wikipedia.org/wiki/Internet_Protocol for protocol details
class Ip < Nmunch::Dissectors::Base
# Public: Get sender IP address from IP packet
#
# Returns IP address
def ip_address
@ip_address ||= pcap_packet.ip_src.to_s
end
# Public: Get sender MAC address from IP packet
#
# Returns MAC address
def mac_address
@mac_address ||= raw_data[6..11].join(':')
end
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/dissectors/arp_spec.rb
|
require 'spec_helper'
describe Nmunch::Dissectors::Arp do
let(:arp_pcap_packet) do
packet = stub(Pcap::Packet)
packet.stub(:raw_data).and_return(ARP_PACKET_DATA)
packet.stub(:ip?).and_return(false)
packet
end
subject { Nmunch::Dissectors::Arp.new(arp_pcap_packet) }
describe '#ip_address' do
it 'returns correct IP address' do
subject.ip_address.should == '192.168.0.125'
end
end
describe '#mac_address' do
it 'returns correct MAC address' do
subject.mac_address.should == 'de:ad:be:ef:de:ad'
end
end
end
|
michenriksen/nmunch
|
lib/nmunch/node.rb
|
module Nmunch
# Public: A class to represent a network node
#
# For now it is a simple wrapper around IP and MAC address information but might
# contain more information in the future.
class Node
attr_reader :ip_address, :mac_address
# Public: Initialize a new node
#
# options - A hash that must contain the keys :ip_address and :mac_address
#
# Returns nothing
def initialize(options)
@ip_address = options[:ip_address]
@mac_address = options[:mac_address]
end
# Public: Determine if node has a meta address
#
# A node will have a meta address (0.0.0.0) if it has not yet been given a
# DHCP lease
#
# Returns TRUE if meta address and FALSE if not
def meta_address?
ip_address == '0.0.0.0'
end
# Public: Convert node to string
#
# Returns IP address
def to_s
ip_address
end
# Public: Compare string version of node
#
# Returns TRUE if same and FALSE if not
def ==(obj)
self.to_s == obj.to_s
end
# Public: Convenience method to create a node from an Nmunch::Dissector instance
#
# dissector - An instance of Nmunch::Dissector
#
# Returns instance of Nmunch::Node with details from dissector
def self.create_from_dissector(dissector)
self.new(ip_address: dissector.ip_address, mac_address: dissector.mac_address)
end
end
end
|
michenriksen/nmunch
|
lib/nmunch/version.rb
|
module Nmunch
# Public: Current version of Nmunch
VERSION = "0.1.0"
end
|
theresamorelli/refood-with-js
|
app/models/request.rb
|
<reponame>theresamorelli/refood-with-js
class Request < ApplicationRecord
belongs_to :requestor
belongs_to :offer
has_one :user, through: :requestor
has_one :giver, through: :offer
validates :message, presence: true
validate :email_or_phone
# def self.recently_completed
# Request.where("completed_requestor = ?", true).or(Request.where("completed_giver = ?", true)).order(updated_at: :desc).limit(10)
# end
scope :recently_completed, -> { order(updated_at: :desc).where(completed_requestor: true).where(completed_giver: true) }
def requestor_name
self.user.name
end
def created_date
self.created_at.strftime('%A, %B %e, %Y @ %l:%M %P')
end
def formatted_phone
if self.requestor_phone.present?
phone = self.requestor_phone
phone.insert(3, "-")
phone.insert(7, "-")
else
"Ask for phone"
end
end
private
def email_or_phone
if requestor_phone.blank? && requestor_email.blank?
errors.add(:base, "Please provide an email address or password")
end
end
end
|
theresamorelli/refood-with-js
|
app/models/requestor.rb
|
<gh_stars>0
class Requestor < ApplicationRecord
belongs_to :user
has_many :requests
has_many :offers, through: :requests
has_many :givers, through: :offers
end
|
theresamorelli/refood-with-js
|
app/controllers/users_controller.rb
|
<gh_stars>0
class UsersController < ApplicationController
layout "application_no_login_link", only: [:new, :create]
before_action :require_login, except: [:new, :create, :user]
before_action only: [:update, :destroy] do
redirect_to_index_if_not_authorized('id', 'profile')
end
before_action :redirect_to_index_if_logged_in, only: [:new]
# before_destroy
def index
end
def show
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.valid?
@user.build_giver
@user.build_requestor
@user.save
flash.now[:message] = "Hi #{@user.name}! Welcome to Refood!"
session[:user_id] = @user.id
render :'add_info'
else
flash.now[:error] = @user.errors.full_messages.uniq
@user = User.new
render :new
end
end
def edit
@user = current_user
end
def add_info
@user = current_user
end
def update
@user = current_user
if @user.update(user_params)
flash[:message] = "Profile successfully updated"
redirect_to '/index'
else
flash.now[:error] = @user.errors.full_messages
render :edit
end
end
def show
@user = User.find(params[:id])
end
def user
@user = current_user
render json: @user.to_json(only: :id)
end
# def destroy
# current_user.delete
# session.delete :user_id
# flash[:message] = "Account successfully removed. Come back anytime!"
# redirect_to root_path
# end
private
def user_params
params.require(:user).permit(:email, :name, :username, :address, :address2, :city, :state, :zip_code, :phone, :password, :password_confirmation)
end
end
|
theresamorelli/refood-with-js
|
db/seeds.rb
|
<reponame>theresamorelli/refood-with-js<filename>db/seeds.rb<gh_stars>0
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
users = [
{
name: 'John',
email: '<EMAIL>',
address: '95 Bannock St',
city: 'Denver', state: 'CO',
zip_code: '80223',
phone: '1234567890',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
},
{
name: 'Paul',
email: '<EMAIL>',
address: '241 W 113th St',
city: 'New York',
state: 'NY',
zip_code: '10026',
phone: '1234567899',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
},
{
name: 'George',
email: '<EMAIL>',
address: '3267 W Wrightwood Ave',
city: 'Chicago',
state: 'IL',
zip_code: '60647',
phone: '9876543210',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
},
{
name: 'Ringo',
email: '<EMAIL>',
address: '1270 Marion St',
city: 'Denver',
state: 'CO',
zip_code: '80218',
phone: '1236543210',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
]
offers = [
{
giver_id: 1,
headline: 'Box of apples',
description: 'Around 20 fuji apples from a happy little tree',
city: 'Denver',
state: 'CO',
availability: 'Anytime this weekend'
},
{
giver_id: 3,
headline: 'Pan of veg lasagna from catered lunch',
description: 'One large pan of spinach lasagna, hot n ready',
city: 'Chicago',
state: 'IL'
},
{
giver_id: 2,
headline: 'Five boxes mac n cheese, blue box',
description: 'Gluten free now, cheesy mac needs new home',
city: 'New York',
state: 'NY',
availability: 'evenings after 7'
}
]
requests = [
{
offer_id: 2,
requestor_id: 2,
message: 'I can pick up around 4:30! Please text your address',
requestor_phone: '9175555555',
requestor_email: '<EMAIL>'
},
{
offer_id: 1,
requestor_id: 3,
message: 'Would it be possible to grab just half of these? I could stop by tomorrow early afternoon. I have a bag.',
requestor_email: '<EMAIL>'
},
{
offer_id: 2,
requestor_id: 1,
message: 'I can pickup ASAP',
requestor_email: '<EMAIL>'
},
{
offer_id: 3,
requestor_id: 3,
message: 'Would it be possible to grab just half of these? I could stop by tomorrow early afternoon. I have a bag.',
requestor_email: '<EMAIL>'
},
{
offer_id: 3,
requestor_id: 4,
message: 'Are these regular or extra cheezy?',
requestor_email: '<EMAIL>',
requestor_phone: '1236543210'
},
{
offer_id: 1,
requestor_id: 4,
message: 'I like apples a lot',
requestor_email: '<EMAIL>',
requestor_phone: '1236543210'
}
]
users.each do |user|
new_user = User.new(user)
new_user.build_giver
new_user.build_requestor
new_user.save
end
offers.each do |offer|
Offer.create(offer)
end
requests.each do |request|
Request.create(request)
end
|
theresamorelli/refood-with-js
|
app/models/user.rb
|
require 'uri'
class User < ApplicationRecord
has_one :giver
has_one :requestor
has_many :offers, through: :giver
has_many :requests, through: :requestor
has_secure_password
# accepts_nested_attributes_for :requests
validates :name, presence: true
validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
validates :phone, allow_blank: true, length: { is: 10 }, format: { with: /\A[0-9]*\z/,
message: "only allows numbers" }
validates :city, presence: true, on: :update
validates :state, presence: true, on: :update
validates :password, presence: true, allow_nil: true
validates :password_confirmation, presence: true, allow_nil: true
def city_state
"#{city}, #{state}"
end
def karma
# number of requests marked completed by other users' givers and requestors
giver.requests.select { |r| r.completed_giver }.count + requestor.requests.select { |r| r.completed_requestor }.count
end
end
|
theresamorelli/refood-with-js
|
app/controllers/sessions_controller.rb
|
<reponame>theresamorelli/refood-with-js
class SessionsController < ApplicationController
layout "application_no_login_link"
before_action :require_login, only: [:destroy]
before_action :redirect_to_index_if_logged_in, only: [:new, :create]
def new
end
def create
user = User.find_by(email: params[:email])
if !user
flash.now[:error] = ["Email not found. Please try again."]
render :new
elsif user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to index_path
else
flash.now[:error] = ["Invalid password. Please try again."]
render :new
end
end
def create_with_google
@user = User.find_by(email: auth[:email])
if @user
session[:user_id] = @user.try(:id)
redirect_to index_path
else
@user = User.new(email: auth[:email], name: auth[:first_name], password: <PASSWORD>Random.urlsafe_base64(n=6))
if @user.save
@user.build_giver.save
@user.build_requestor.save
session[:user_id] = @user.id
flash.now[:message] = "Welcome to Refood!"
render :'users/add_info'
else
flash.now[:error] = ["There was a problem with your Google login"]
render :signup
end
end
end
def destroy
session.delete :user_id
redirect_to root_path
end
private
def auth
request.env['omniauth.auth'][:info]
end
end
|
theresamorelli/refood-with-js
|
app/controllers/application_controller.rb
|
<gh_stars>0
class ApplicationController < ActionController::Base
private
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in
!!current_user
end
def require_login
if !logged_in
flash[:error] = ["Please sign up or log in"]
redirect_to signup_path if !logged_in
end
end
def auth_redirect(resource)
flash[:error] = ["Hey, that's not your #{resource}"]
redirect_to index_path
end
def redirect_to_index_if_not_authorized(params_id, resource)
if params[params_id].to_i != current_user.id
auth_redirect(resource)
end
end
def redirect_to_index_if_not_authorized_to_edit_offer
# if single offer route
if !params[:offer_id]
offer = Offer.find(params[:id])
# if offer requests route
elsif params[:offer_id] && !params[:id]
offer = Offer.find(params[:offer_id])
end
if offer && offer.user != current_user
auth_redirect('offer')
end
end
def redirect_to_index_if_not_authorized_to_edit_request
request = Request.find_by(id: params[:id])
if !request || request.user != current_user
auth_redirect('request')
end
end
def redirect_to_index_if_logged_in
if logged_in
redirect_to index_path
end
end
def redirect_to_existing_request
offer = Offer.find(params[:offer_id])
request = Request.where("requestor_id = ? AND offer_id = ?", current_user.id, offer.id).first
if request
flash[:error] = ["You already have a request for this offer"]
redirect_to offer_request_path(offer, request)
end
end
def redirect_if_user_owns_offer
offer = Offer.find(params[:offer_id])
if current_user == offer.user
flash[:error] =["Oops, that's your offer"]
redirect_to offer_path(offer)
end
end
def redirect_if_offer_and_request_not_associated
offer = Offer.find_by(id: params[:offer_id])
request = Request.find_by(id: params[:id])
if !offer || !request || !offer.requests.include?(request)
flash[:error] = ["Hmm, something's not quite right"]
redirect_to offer_path(offer)
end
end
def convert_string_to_date(string)
Time.strptime(string, '%m/%d/%Y %H:%M %p')
end
def format_date(date)
date.strftime('%A, %B %e, %Y @ %l:%M %P')
end
def format_date_no_time(date)
date.strftime('%B %e, %Y')
end
helper_method :current_user, :logged_in, :require_login, :format_date, :format_date_no_time, :convert_string_to_date
end
|
theresamorelli/refood-with-js
|
config/routes.rb
|
<reponame>theresamorelli/refood-with-js
Rails.application.routes.draw do
root 'welcome#home'
resources :users, only: [:update, :show, :destroy]
get '/add-info' => 'users#add_info'
get '/edit-profile' => 'users#edit'
get '/signup' => 'users#new'
post '/signup' => 'users#create'
get '/user' => 'users#user'
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
delete '/logout' => 'sessions#destroy'
get '/auth/google_oauth2/callback' => 'sessions#create_with_google'
get '/index' => 'welcome#index'
# get '/offers/expired' => 'offers#expired'
get '/offers/closed' => 'offers#closed'
get '/current-offers' => 'offers#current_offers'
resources :offers do
resources :requests
get '/completed' => 'requests#offer_completed'
end
get '/requests/completed' => 'requests#completed'
patch '/request/:id' => 'requests#complete'
post '/comments' => 'comments#create'
get '/requests/recently-completed' => 'requests#recently_completed'
get '/offers-by-location' => 'offers#by_location'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
theresamorelli/refood-with-js
|
app/serializers/request_serializer.rb
|
class RequestSerializer < ActiveModel::Serializer
attributes :id, :offer_id, :requestor_id, :requestor_name, :message, :requestor_email, :requestor_phone, :completed_giver, :completed_requestor, :formatted_phone, :created_date
end
|
theresamorelli/refood-with-js
|
db/migrate/20180915142832_create_offers.rb
|
<gh_stars>0
class CreateOffers < ActiveRecord::Migration[5.2]
def change
create_table :offers do |t|
t.integer :giver_id
t.string :headline
t.string :city
t.string :state
t.text :description
t.string :availability
t.boolean :closed, :default => false
t.boolean :deleted, :default => false
t.timestamps
end
end
end
|
theresamorelli/refood-with-js
|
app/helpers/offers_helper.rb
|
<reponame>theresamorelli/refood-with-js
module OffersHelper
def has_request(user, offer)
# loop through user's requests to see if matches offer
user.requests.any? do |request|
offer.requests.include?(request)
end
end
def number_of_items(collection, thing_string)
if collection.count == 0
"No #{thing_string}s"
elsif collection.count == 1
"1 #{thing_string}"
else
"#{collection.count} #{thing_string}s"
end
end
end
|
theresamorelli/refood-with-js
|
app/models/comment.rb
|
class Comment < ApplicationRecord
belongs_to :request
has_one :requestor, through: :request
has_one :offer, through: :request
has_one :giver, through: :offer
end
|
theresamorelli/refood-with-js
|
app/controllers/welcome_controller.rb
|
class WelcomeController < ApplicationController
layout "application_login_link", only: [:home]
before_action :require_login, only: [:index]
before_action :redirect_to_index_if_logged_in, only: [:home]
def home
end
def index
@offers = current_user.offers.select { |o| !o.closed && !o.deleted }
@requests = current_user.requests.select { |r| !r.completed_giver }
end
end
|
theresamorelli/refood-with-js
|
app/controllers/comments_controller.rb
|
class CommentsController < ApplicationController
# def new
# @comment = Comment.new
# end
def create
end
end
|
theresamorelli/refood-with-js
|
app/serializers/offer_serializer.rb
|
<filename>app/serializers/offer_serializer.rb
class OfferSerializer < ActiveModel::Serializer
attributes :id, :giver_id, :giver_name, :headline, :description, :city, :state, :city_state, :availability, :closed, :deleted, :created_ago, :created_date
has_many :requests, serializer: RequestSerializer
end
|
theresamorelli/refood-with-js
|
app/models/giver.rb
|
<reponame>theresamorelli/refood-with-js
class Giver < ApplicationRecord
belongs_to :user
has_many :offers
has_many :requests, through: :offers
has_many :requestors, through: :requests
end
|
theresamorelli/refood-with-js
|
test/decorators/welcome_decorator_test.rb
|
<filename>test/decorators/welcome_decorator_test.rb<gh_stars>0
require 'test_helper'
class WelcomeDecoratorTest < Draper::TestCase
end
|
theresamorelli/refood-with-js
|
app/helpers/application_helper.rb
|
<filename>app/helpers/application_helper.rb
module ApplicationHelper
def format_phone(string)
phone = string.insert 3, "-"
phone.insert 7, "-"
end
def time_units_string(time_ago, unit)
# convert number to string and pluralize unit if multiple
if time_ago == 1
time_ago.to_s + " #{unit} "
else
time_ago.to_s + " #{unit}s "
end
end
def time_ago(resource)
seconds_ago = Time.now - resource.created_at.localtime
minutes_ago = (seconds_ago/60).floor
hours_ago = (minutes_ago/60).floor
days_ago = (hours_ago/24).floor
# get time estimate in days, hours, or minutes
if days_ago > 0
time_units_string(days_ago, "day")
elsif hours_ago > 0
time_units_string(hours_ago, "hour")
elsif minutes_ago > 0
time_units_string(minutes_ago, "minute")
else
time_units_string(seconds_ago.floor, "second")
end
end
def time_from_expiration(offer)
expiration = Time.strptime(offer.expiration, '%m/%d/%Y %H:%M %p')
seconds_away = expiration - Time.now
minutes_away = ((seconds_away / 60) % 60).floor
hours_away = ((seconds_away / 60 / 60) % 24).floor
days_away = ((seconds_away / 60 / 60 / 24)).floor
if days_away > 0
time_units_string(days_away, 'day') + time_units_string(hours_away, 'hour') + time_units_string(minutes_away, 'minutes')
elsif hours_away > 0
time_units_string(hours_away, 'hour') + time_units_string(minutes_away, 'minute')
elsif minutes_away > 0
time_units_string(minutes_away, 'minute')
else
time_units_string(seconds_away, 'second')
end
end
def city_state
"#{city}, #{state}"
end
end
|
theresamorelli/refood-with-js
|
app/models/offer.rb
|
class Offer < ApplicationRecord
belongs_to :giver
has_one :user, through: :giver
has_many :requests
has_many :requestors, through: :requests
validates :headline, presence: true
scope :group_by_location, -> { where(closed: false).order(state: :asc).order(city: :asc) }
def giver_name
self.user.name
end
def city_state
if city && state
"#{city}, #{state}"
else
"Ask for location"
end
end
def self.open_offers
Offer.where(closed: false).where(deleted: false)
end
def created_ago
seconds_ago = Time.now - self.created_at.localtime
minutes_ago = (seconds_ago/60).floor
hours_ago = (minutes_ago/60).floor
days_ago = (hours_ago/24).floor
# get time estimate in days, hours, or minutes
if days_ago > 0
time_units_string(days_ago, "day")
elsif hours_ago > 0
time_units_string(hours_ago, "hour")
elsif minutes_ago > 0
time_units_string(minutes_ago, "minute")
else
time_units_string(seconds_ago.floor, "second")
end
end
def time_units_string(time_ago, unit)
# convert number to string and pluralize unit if multiple
if time_ago == 1
time_ago.to_s + " #{unit} "
else
time_ago.to_s + " #{unit}s "
end
end
def created_date
self.created_at.localtime.strftime('%A, %B %e, %Y @ %l:%M %P')
end
end
|
theresamorelli/refood-with-js
|
db/migrate/20180915151021_create_requests.rb
|
<reponame>theresamorelli/refood-with-js<filename>db/migrate/20180915151021_create_requests.rb
class CreateRequests < ActiveRecord::Migration[5.2]
def change
create_table :requests do |t|
t.integer :offer_id
t.integer :requestor_id
t.text :message
t.string :requestor_email
t.string :requestor_phone
t.boolean :completed_giver, :default => false
t.boolean :completed_requestor, :default => false
t.timestamps
end
end
end
|
theresamorelli/refood-with-js
|
app/controllers/offers_controller.rb
|
class OffersController < ApplicationController
layout 'application_no_login_link', only: [:current_offers]
before_action :require_login, except: [:current_offers]
before_action :redirect_to_index_if_not_authorized_to_edit_offer, only: [:edit, :update, :destroy]
def new
@offer = current_user.giver.offers.build
end
def create
offer = current_user.giver.offers.build(offer_params)
if offer.save
flash[:message] = "Offer successfully created"
redirect_to offer_path(offer)
else
flash.now[:error] = user.errors.full_messages
render :new
end
end
def index
@offers = Offer.open_offers.select { |o| o.giver_id != current_user.id }.reverse
respond_to do |format|
format.html { render :index }
format.json { render json: @offers }
end
end
def by_location
@offers = Offer.group_by_location
end
def closed
@offers = Offer.select { |o| o.giver_id == current_user.id && o.closed }
end
def current_offers
@offers = Offer.select { |o| !o.deleted && !o.closed }.reverse
end
def show
@offer = Offer.find(params[:id])
@request = Request.select { |r| r.offer == @offer && r.requestor == current_user.requestor }.first
@requests = @offer.requests.select { |r| r.completed_requestor == false }
@completed_requests = @offer.requests.select { |r| r.completed_requestor }
respond_to do |format|
format.html { render :show }
format.json { render json: @offer }
end
end
def edit
@offer = Offer.find(params[:id])
end
def update
@offer = Offer.find(params[:id])
# if params are coming from the offer edit form
if params[:offer]
if @offer.update(offer_params)
flash[:message] = "Offer successfully updated"
redirect_to offer_path(@offer)
else
flash.now[:error] = offer.errors.full_messages
render :edit
end
# if params are coming from offer requests (close offer)
else
@offer.closed = true
@offer.save
flash[:message] = "Offer successfully closed"
redirect_to '/index'
end
end
def destroy
offer = Offer.find(params[:id])
if offer.requests.present?
offer.deleted = true
offer.save
flash[:message] = "Offer successfully deleted"
redirect_to index_path
else
offer.delete
flash[:message] = "Offer successfully deleted"
redirect_to index_path
end
end
private
def offer_params
params.require(:offer).permit(:headline, :description, :availability, :expiration, :closed, :city, :state)
end
end
|
theresamorelli/refood-with-js
|
config/environment.rb
|
# Load the Rails application.
require_relative 'application'
require 'active_support/core_ext/string/conversions'
require 'time'
# Initialize the Rails application.
Rails.application.initialize!
|
theresamorelli/refood-with-js
|
app/decorators/offer_decorator.rb
|
class OfferDecorator < ApplicationDecorator
delegate_all
# decorates :offer, :welcome
def expired
Time.strptime(f.expiration, '%m/%d/%Y %H:%M %p').past?
end
end
|
theresamorelli/refood-with-js
|
app/controllers/requests_controller.rb
|
<filename>app/controllers/requests_controller.rb<gh_stars>0
class RequestsController < ApplicationController
before_action :require_login
before_action :redirect_to_index_if_not_authorized_to_edit_request, only: [:show, :edit, :update, :destroy]
before_action :redirect_to_index_if_not_authorized_to_edit_offer, only: [:index]
before_action :redirect_to_existing_request, only: [:new, :create]
before_action :redirect_if_user_owns_offer, only: [:new, :create]
before_action :redirect_if_offer_and_request_not_associated, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token
def new
@offer = Offer.find(params[:offer_id])
@request = @offer.requests.build
end
def create
request = Request.new(request_params)
request.offer_id = params[:offer_id]
request.requestor = current_user.requestor
if request.save
@offer = Offer.find(params[:offer_id])
flash.now[:message] = "Request successfully created"
render :show
# redirect_to offer_request_path(offer, request)
else
flash.now[:error] = request.errors.full_messages
@offer = Offer.find(params[:offer_id])
@request = @offer.requests.build
render :new
end
end
def show
@offer = Offer.find(params[:offer_id])
@request = Request.find(params[:id])
end
def index
@offer = Offer.find(params[:offer_id])
@requests = @offer.requests.select { |r| r.completed_requestor == false }
end
def offer_completed
@offer = Offer.find(params[:offer_id])
@requests = @offer.requests.select { |r| r.completed_requestor == true }
end
def completed
@requests = current_user.requests.select { |r| r.completed_giver == true}
end
def recently_completed
@requests = Request.recently_completed.take(10)
end
def edit
@offer = Offer.find(params[:offer_id])
@request = Request.find(params[:id])
end
def update
@offer = Offer.find(params[:offer_id])
@request = Request.find(params[:id])
if @request.update(request_params)
flash[:message] = 'Request successfully updated'
redirect_to offer_request_path(@offer, @request)
else
flash.now[:error] = @request.errors.full_messages.uniq
render :edit
end
end
def complete
request = Request.find(params[:id])
request.update(request_params)
flash[:message] = "Thanks for being an awesome human!"
redirect_to '/index'
end
def destroy
request = Request.find(params[:id])
request.delete
flash[:message] = "Request successfully deleted"
redirect_to '/index'
end
private
def request_params
params.require(:request).permit(:message, :requestor_email, :requestor_phone, :offer_id, :completed_requestor, :completed_giver)
end
end
|
paulradzkov-heaven/paulradzkov.com-nanoc
|
lib/file_changes.rb
|
<reponame>paulradzkov-heaven/paulradzkov.com-nanoc<filename>lib/file_changes.rb<gh_stars>1-10
require 'yaml'
require 'digest/sha1'
module MGutz
# Tracks a file's last content change using SHA1 digest algorithm.
#
# File.mtime is not sufficient to detect if content has been updated. This
# class will set `updated_at` if it detects a change in the content
# irregardless of the file's mtime.
#
# Values are stored in `file_changes.yaml` by default.
#
class FileChanges
def initialize(store_filename = "file_changes.yaml")
@store_filename = store_filename
if File.exists?(@store_filename)
@changes = YAML.load_file(@store_filename)
else
@changes = {}
end
end
# Gets a file's status change.
#
# filename - Name of the file
# created_at - Optional. Use this date if change status not yet recorded.
# content - Optional. Content of the file (if it has already been read).
#
# returns { :created_at => '', :updated_at => '', :digest = ''}
#
def status(filename, created_at = nil, content = nil)
content ||= File.readlines(filename)
digest = Digest::SHA1.hexdigest(content)
item = @changes[filename.to_sym]
if !item
item = {}
item[:created_at] = created_at || File.ctime(filename)
item[:updated_at] = File.mtime(filename)
item[:digest] = digest
@changes[filename.to_sym] = item
write_changes
elsif item[:digest] != digest
item[:updated_at] = File.mtime(filename)
item[:digest] = digest
write_changes
end
item
end
private
def write_changes
File.open(@store_filename, 'w') do |f|
YAML.dump @changes, f
end
end
end
end
|
paulradzkov-heaven/paulradzkov.com-nanoc
|
lib/default.rb
|
<filename>lib/default.rb
# All files in the 'lib' directory will be loaded
# before nanoc starts compiling.
def keywords
if is_front_page?
tag_set.join(', ')
else
tags = @item[:tags].nil? ? '' : @item[:tags].join(', ')
keywords = @item[:keywords] || ''
[keywords, tags].join(', ')
end
end
def link_unless_current(name, s)
if @item.identifier != "/#{s}/"
"<li><a href='/#{s}/'>#{name}</a></li>"
else
"<li><span class=\"active\">#{name}</span></li>"
end
end
def nav_link_to_unless_current(text, path)
if @item_rep and @item_rep.path == path
"<span class=\"active\" title=\"Вы здесь\"><span>#{text}</span></span>"
else
"<a href=\"#{path}/\"><span>#{text}</span></a>"
end
end
def logo
if is_front_page?
site_name
else
"<a href='/'>#{site_name}</a>"
end
end
# Переопределяем имена месяцев
RUSMONTHS = {
1 => "Января", 2 => "Февраля", 3 => "Марта",
4 => "Апреля", 5 => "Мая", 6 => "Июня",
7 => "Июля", 8 => "Августа", 9 => "Сентября",
10 => "Октября", 11 => "Ноября", 12 => "Декабря"
}
RUSMON = {
1 => "Январь", 2 => "Февраль", 3 => "Март",
4 => "Апрель", 5 => "Май", 6 => "Июнь",
7 => "Июль", 8 => "Август", 9 => "Сентябрь",
10 => "Октябрь", 11 => "Ноябрь", 12 => "Декабрь"
}
# Метод для форматирования даты
def blogpost_date(blog_date)
blog_date = blog_date.is_a?(String) ? Date.parse(blog_date) : blog_date
"#{blog_date.mday} #{RUSMONTHS[blog_date.mon]} #{blog_date.year}"
end
# Год написания поста, иначе — текущий год
def blogpost_year(blog_date)
if blog_date
blog_date = blog_date.is_a?(String) ? Date.parse(blog_date) : blog_date
"#{blog_date.year}"
else
time = Time.new
"#{time.year}"
end
end
|
paulradzkov-heaven/paulradzkov.com-nanoc
|
lib/extensions.rb
|
<gh_stars>1-10
class Array
def to_hash_keys(&block)
Hash[*self.collect { |v|
[v, block.call(v)]
}.flatten]
end
def to_hash_values(&block)
Hash[*self.collect { |v|
[block.call(v), v]
}.flatten]
end
end
|
paulradzkov-heaven/paulradzkov.com-nanoc
|
lib/helpers.rb
|
<gh_stars>0
include Nanoc::Helpers::Rendering
include Nanoc::Helpers::Blogging
include Nanoc::Helpers::XMLSitemap
include Nanoc::Helpers::Filtering
require 'builder'
require 'fileutils'
require 'time'
# Hyphens are converted to sub-directories in the output folder.
#
# If a file has two extensions like Rails naming conventions, then the first extension
# is used as part of the output file.
#
# sitemap.xml.erb # => sitemap.xml
#
# If the output file does not end with an .html extension, item[:layout] is set to 'none'
# bypassing the use of layouts.
#
def route_path(item)
# in-memory items have not file
return item.identifier + "index.html" if item[:content_filename].nil?
url = item[:content_filename].gsub(/^content/, '')
# determine output extension
extname = '.' + item[:extension].split('.').last
outext = '.haml'
if url.match(/(\.[a-zA-Z0-9]+){2}$/) # => *.html.erb, *.html.md ...
outext = '' # remove 2nd extension
elsif extname == ".sass"
outext = '.css'
else
outext = '.html'
end
url.gsub!(extname, outext)
if url.include?('--')
url = url.split('--').join('/') # /2010/01/01--some_title.html -> /2010/01/01/some_title.html
end
url
end
# Creates in-memory tag pages from partial: layouts/_tag_page.haml
def create_tag_pages
tag_set(items).each do |tag|
items << Nanoc::Item.new(
"= render('_tag_page', :tag => '#{tag}')", # use locals to pass data
{ :title => "Category: #{tag}", :is_hidden => true}, # do not include in sitemap.xml
"/tags/#{tag}/", # identifier
:binary => false
)
end
end
def add_update_item_attributes
changes = MGutz::FileChanges.new
items.each do |item|
# do not include assets or xml files in sitemap
if item[:content_filename]
ext = File.extname(route_path(item))
item[:is_hidden] = true if item[:content_filename] =~ /assets\// || ext == '.xml' || ext == '.txt' || ext == '.png' || ext == '.jpg' || ext == '.jpeg'
end
if item[:kind] == "article"
# filename might contain the created_at date
item[:created_at] ||= derive_created_at(item)
# sometimes Nanoc stores created_at as Date instead of String causing a bunch of issues
item[:created_at] = item[:created_at].to_s if item[:created_at].is_a?(Date)
# sets updated_at based on content change date not file time
change = changes.status(item[:content_filename], item[:created_at], item.raw_content)
item[:updated_at] = change[:updated_at].to_s
end
end
end
# Copy static assets outside of content instead of having Nanoc process them.
def copy_static
FileUtils.cp_r 'static/.', 'output/'
end
def partial(identifier_or_item)
item = !item.is_a?(Nanoc::Item) ? identifier_or_item : item_by_identifier(identifier_or_item)
item.compiled_content(:snapshot => :pre)
end
def item_by_identifier(identifier)
items ||= @items
items.find { |item| item.identifier == identifier }
end
#=> { 2010 => { 12 => [item0, item1], 3 => [item0, item2]}, 2009 => {12 => [...]}}
def articles_by_year_month
result = {}
current_year = current_month = year_h = month_a = nil
sorted_articles.each do |item|
d = Date.parse(item[:created_at])
if current_year != d.year
current_month = nil
current_year = d.year
year_h = result[current_year] = {}
end
if current_month != d.month
current_month = d.month
month_a = year_h[current_month] = []
end
month_a << item
end
result
end
def is_front_page?
@item.identifier == '/'
end
def n_newer_articles(n, reference_item)
@sorted_articles ||= sorted_articles
index = @sorted_articles.index(reference_item)
# n = 3, index = 4
if index >= n
@sorted_articles[index - n, n]
elsif index == 0
[]
else # index < n
@sorted_articles[0, index]
end
end
def n_older_articles(n, reference_item)
@sorted_articles ||= sorted_articles
index = @sorted_articles.index(reference_item)
# n = 3, index = 4, length = 6
length = @sorted_articles.length
if index < length
@sorted_articles[index + 1, n]
else
[]
end
end
def site_name
@config[:site_name]
end
def pretty_time(time)
Time.parse(time).strftime("%b %d, %Y") if !time.nil?
end
def featured_count
@config[:featured_count].to_i
end
def excerpt_count
@config[:excerpt_count].to_i
end
def disqus_shortname
@config[:disqus_shortname]
end
def to_month_s(month)
Date.new(2010, month).strftime("%B")
end
private
def derive_created_at(item)
parts = item.identifier.gsub('-', '/').split('/')[1,3]
date = '1980/1/1'
begin
Date.strptime(parts.join('/'), "%Y/%m/%d")
date = parts.join('/')
rescue
end
date
end
|
geezify/Geezify-rb
|
lib/geezify-rb/geezify.rb
|
<filename>lib/geezify-rb/geezify.rb
#!/usr/bin/ruby
# coding: utf-8
# frozen_string_literal:true
module GeezifyRb
# This class contains the processing tools to convert arabic numbers to Geeze.
class Geezify
ERROR_MSG_CONSTRUCTOR = 'invalid input the input is not a number'
ERROR_MSG1 = 'invalid input to method geezify_2digit'
ERROR_MSG2 = 'invalid input to geezify_4digit'
# constructor
def initialize(num)
raise ArgumentError, ERROR_MSG_CONSTRUCTOR unless num.integer?
@num = num
end
def self.geezify(num)
new(num).geezify
end
def geezify
clean_up_uncessary_1s geezify_with_1s(@num)
end
private
def geezify_2digit(num)
oneth_array = Array['', '፩', '፪', '፫', '፬', '፭', '፮', '፯', '፰', '፱']
tenth_array = Array['', '፲', '፳', '፴', '፵', '፶', '፷', '፸', '፹', '፺']
raise ArgumentError, ERROR_MSG1 unless num.integer? &&
num >= 0 &&
num < 100
tenth_array[(num / 10)] + oneth_array[num % 10]
end
def geezify_4digit(num)
raise ArgumentError, ERROR_MSG unless num.integer? && num < 10_000
num.digits(100).reverse.map { |x| geezify_2digit(x) }.join('፻')
end
def geezify_with_1s(num)
num.digits(10_000).reverse.map { |x| geezify_4digit(x) }.join('፼')
end
def clean_up_uncessary_1s(num)
num.gsub('፼፩፻', '፼፻').gsub(/^፩፼/, '፼').gsub(/^(፩፻)/, '፻') || num
end
end
end
|
geezify/Geezify-rb
|
lib/geezify-rb/arabify.rb
|
<reponame>geezify/Geezify-rb
#!/usr/bin/ruby
# coding: utf-8
# frozen_string_literal:true
module GeezifyRb
# processing tools to convert Geeze numbers to arabic.
class Arabify
ERROR_MSG_CONSTRUCTOR = 'invalid input the string is not a geez number'
ERROR_MSG1 = 'invalid input to method convert_2digit'
NUMHASH = Hash['፩' => 1, '፪' => 2, '፫' => 3, '፬' => 4,
'፭' => 5, '፮' => 6, '፯' => 7, '፰' => 8,
'፱' => 9, '፲' => 10, '፳' => 20, '፴' => 30,
'፵' => 40, '፶' => 50, '፷' => 60, '፸' => 70,
'፹' => 80, '፺' => 90, ' ' => 0]
def initialize(str)
raise ArgumentError, ERROR_MSG_CONSTRUCTOR unless validinput?(str)
@geezstr = str
end
def self.arabify(str)
new(str).arabify
end
def arabify
preprocessed = rollback(@geezstr.gsub('፼', '፼ ')).split('፼')
preprocessed
.each_with_index
.reduce(0) do |sum, (v, i)|
sum + convert_upto10000(v.strip) *
(10_000**(preprocessed.length - 1 - i))
end
end
private
def rollback(str)
raise ArgumentError, ERROR_MSG3 unless validinput?(str)
str.gsub('፼፻', '፼፩፻').gsub(/^፻/, '፩፻').gsub(/^፼/, '፩፼')
end
def convert_2digit(string)
str = string || ''
raise ArgumentError, ERROR_MSG1 unless valid_for_2digit?(str)
str.split('').sum { |x| x == '' ? 0 : NUMHASH[x] }
end
def convert_upto10000(str)
return unless valid_for_convupto10000?(str)
pos100 = str.index('፻')
return convert_2digit(str) if pos100.nil?
return 100 + convert_2digit(str[1..-1]) if pos100.zero?
convert_2digit(str[0..(pos100 - 1)]) * 100 +
convert_2digit(str[(pos100 + 1)..-1])
end
def validinput?(str)
str.split('')
.map { |x| NUMHASH.key?(x) || x == '፼' || x == '፻' }
.reduce(true) { |result, n| result && n }
end
def valid_for_2digit?(str)
str.length <= 2 && str.split('')
.map { |x| NUMHASH.key?(x) }
.reduce(true) { |res, n| res && n }
end
def valid_for_convupto10000?(str)
str.is_a?(String) && str.length <= 5 && str.match('፼').nil?
end
end
end
|
geezify/Geezify-rb
|
test/geezify_test.rb
|
<filename>test/geezify_test.rb
# coding: utf-8
require 'minitest/autorun'
require_relative '../lib/geezify-rb.rb'
require_relative 'test_case'
class GeezifyTest < Minitest::Test
include GeezifyRb
def test_geezify_for_all_test_cases
TESTDATA
.map { |x| assert_equal x[1], GeezifyRb::Geezify.geezify(x[0]) }
end
end
|
geezify/Geezify-rb
|
test/test_case.rb
|
<filename>test/test_case.rb<gh_stars>1-10
#!/usr/bin/ruby
# coding: utf-8
TESTDATA = [
[1, '፩'],
[10, '፲'],
[100, '፻'],
[1000, '፲፻'],
[10000, '፼'], # (እልፍ)
[100000, '፲፼'], # (አእላፍ)
[1000000, '፻፼'], # (አእላፋት)
[10000000, '፲፻፼'], # (ትእልፊት)
[100000000, '፼፼'], # (ትእልፊታት)
[1000000000, '፲፼፼'],
[10000000000, '፻፼፼'],
[100000000000, '፲፻፼፼'], # (ምእልፊት)
[1000000000000, '፼፼፼'], # (ምእልፊታት)
[100010000, '፼፩፼'],
[100100000, '፼፲፼'],
[100200000, '፼፳፼'],
[100110000, '፼፲፩፼'],
[1, '፩'],
[11, '፲፩'],
[111, '፻፲፩'],
[1111, '፲፩፻፲፩'],
[11111, '፼፲፩፻፲፩'],
[111111, '፲፩፼፲፩፻፲፩'],
[1111111, '፻፲፩፼፲፩፻፲፩'],
[11111111, '፲፩፻፲፩፼፲፩፻፲፩'],
[111111111, '፼፲፩፻፲፩፼፲፩፻፲፩'],
[1111111111, '፲፩፼፲፩፻፲፩፼፲፩፻፲፩'],
[11111111111, '፻፲፩፼፲፩፻፲፩፼፲፩፻፲፩'],
[111111111111, '፲፩፻፲፩፼፲፩፻፲፩፼፲፩፻፲፩'],
[1111111111111, '፼፲፩፻፲፩፼፲፩፻፲፩፼፲፩፻፲፩'],
[1, '፩'],
[12, '፲፪'],
[123, '፻፳፫'],
[1234, '፲፪፻፴፬'],
[12345, '፼፳፫፻፵፭'],
[7654321, '፯፻፷፭፼፵፫፻፳፩'],
[17654321, '፲፯፻፷፭፼፵፫፻፳፩'],
[51615131, '፶፩፻፷፩፼፶፩፻፴፩'],
[15161513, '፲፭፻፲፮፼፲፭፻፲፫'],
[10101011, '፲፻፲፼፲፻፲፩'],
[101, '፻፩'],
[1001, '፲፻፩'],
[1010, '፲፻፲'],
[1011, '፲፻፲፩'],
[1100, '፲፩፻'],
[1101, '፲፩፻፩'],
[1111, '፲፩፻፲፩'],
[10001, '፼፩'],
[10010, '፼፲'],
[10100, '፼፻'],
[10101, '፼፻፩'],
[10110, '፼፻፲'],
[10111, '፼፻፲፩'],
[100001, '፲፼፩'],
[100010, '፲፼፲'],
[100011, '፲፼፲፩'],
[100100, '፲፼፻'],
[101010, '፲፼፲፻፲'],
[1000001, '፻፼፩'],
[1000101, '፻፼፻፩'],
[1000100, '፻፼፻'],
[1010000, '፻፩፼'],
[1010001, '፻፩፼፩'],
[1100001, '፻፲፼፩'],
[1010101, '፻፩፼፻፩'],
[101010101, '፼፻፩፼፻፩'],
[100010000, '፼፩፼'],
[100010100, '፼፩፼፻'],
[101010100, '፼፻፩፼፻'],
[3, '፫'],
[30, '፴'],
[33, '፴፫'],
[303, '፫፻፫'],
[3003, '፴፻፫'],
[3030, '፴፻፴'],
[3033, '፴፻፴፫'],
[3300, '፴፫፻'],
[3303, '፴፫፻፫'],
[3333, '፴፫፻፴፫'],
[30003, '፫፼፫'],
[30303, '፫፼፫፻፫'],
[300003, '፴፼፫'],
[303030, '፴፼፴፻፴'],
[3000003, '፫፻፼፫'],
[3000303, '፫፻፼፫፻፫'],
[3030003, '፫፻፫፼፫'],
[3300003, '፫፻፴፼፫'],
[3030303, '፫፻፫፼፫፻፫'],
[303030303, '፫፼፫፻፫፼፫፻፫'],
[333333333, '፫፼፴፫፻፴፫፼፴፫፻፴፫']
]
|
geezify/Geezify-rb
|
test/arabify_test.rb
|
<reponame>geezify/Geezify-rb<filename>test/arabify_test.rb<gh_stars>1-10
# coding: utf-8
require 'minitest/autorun'
require_relative '../lib/geezify-rb'
require_relative 'test_case'
class ArabifyTest < Minitest::Test
include GeezifyRb
def test_geezify_for_all_test_cases
TESTDATA
.map { |x| assert_equal x[0], GeezifyRb::Arabify.arabify(x[1]) }
end
end
|
geezify/Geezify-rb
|
lib/geezify-rb.rb
|
require_relative './geezify-rb/geezify.rb'
require_relative './geezify-rb/arabify.rb'
require_relative './geezify-rb/version.rb'
module GeezifyRb
end
|
marcocarvalho/ffi-talib
|
spec/ffi/talib/methods/stddev_spec.rb
|
<filename>spec/ffi/talib/methods/stddev_spec.rb
require 'spec_helper'
describe Talib do
subject { Talib }
it 'should call simple moving average' do
expect(subject.ta_stddev([0,0,14,14])).to eq [7.0]
end
it 'should be possible to pass optional value for deviation' do
expect(subject.ta_stddev([0,0,14,14], optInNbDev: 2)).to eq [14.0]
end
it 'should return empty array if an empty one is given' do
expect(subject.ta_stddev([])).to eq []
end
it 'should raise error if no array is given' do
expect { subject.ta_stddev(nil) }.to raise_error('prices must be an array')
end
end
|
marcocarvalho/ffi-talib
|
spec/ffi/talib/methods/sar_parabolic_spec.rb
|
<reponame>marcocarvalho/ffi-talib<gh_stars>1-10
require 'spec_helper'
describe Talib do
subject { Talib }
let(:high) { [18.88, 18.82, 18.71, 18.86, 19.16, 19.35, 19.35, 19.55, 19.38, 19.20, 19.14, 18.97, 19.32, 19.58, 18.27, 16.76, 17.10, 17.02, 16.85] }
let(:low) { [18.48, 18.42, 18.46, 18.49, 18.68, 18.83, 18.84, 19.01, 18.60, 18.73, 18.63, 17.92, 18.16, 18.31, 17.22, 16.47, 16.48, 16.40, 16.55] }
it 'should call simple moving average' do
expect(subject.ta_sar(high, low)).to eq [18.88, 18.8708, 18.861784, 18.42, 18.434800000000003, 18.471408000000004, 18.506551680000005, 18.569158579200003, 18.6, 18.6, 19.55, 19.517400000000002, 17.92, 19.58, 19.58, 19.455599999999997, 19.336176, 19.16000544]
end
it 'should return empty array if an empty one is given' do
expect(subject.ta_sar([], [])).to eq []
end
it 'should raise error if no array is given' do
expect { subject.ta_sar(nil, nil) }.to raise_error('high and low prices must be an array')
end
end
|
marcocarvalho/ffi-talib
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb
require 'talib'
|
marcocarvalho/ffi-talib
|
spec/ffi/talib/methods/var_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
describe Talib do
subject { Talib }
it 'should call simple moving average' do
expect(subject.ta_var([0,0,14,14])).to eq [49.0]
end
it 'should be possible to pass optional value for deviation' do
expect(subject.ta_var([1,2,3,4])).to eq [1.25]
end
it 'should return empty array if an empty one is given' do
expect(subject.ta_var([])).to eq []
end
it 'should raise error if no array is given' do
expect { subject.ta_var(nil) }.to raise_error('prices must be an array')
end
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods/var.rb
|
<reponame>marcocarvalho/ffi-talib
module Talib::Methods
# TA_RetCode TA_VAR( int startIdx,
# int endIdx,
# const double inReal[],
# int optInTimePeriod, /* From 1 to 100000 */
# double optInNbDev, /* From TA_REAL_MIN to TA_REAL_MAX */
# int *outBegIdx,
# int *outNBElement,
# double outReal[] );
def ta_var(prices, opts = {})
raise ArgumentError.new('prices must be an array') unless prices.is_a?(Array)
return [] if prices.empty?
optInTimePeriod = opts[:optInTimePeriod] || prices.size
optInNbDev = opts[:optInNbDev] || 1
inReal = Talib::LibC.malloc(DoubleSize * prices.size)
outReal = Talib::LibC.malloc(DoubleSize * Talib::TA_VAR_Lookback(optInTimePeriod, optInNbDev))
outBegIdx = FFI::MemoryPointer.new(1.size)
outNBElement = FFI::MemoryPointer.new(1.size)
inReal.write_array_of_double(prices)
ret = Talib::TA_VAR(0,prices.size - 1, inReal, optInTimePeriod, optInNbDev, outBegIdx, outNBElement, outReal)
if ret == 0
ret = outReal.read_array_of_double(outNBElement.read_int)
else
ret = false
end
Talib::LibC.free(inReal)
Talib::LibC.free(outReal)
outBegIdx.free
outNBElement.free
ret
end
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods/atr.rb
|
<filename>lib/talib/methods/atr.rb
# TA_RetCode TA_ATR( int startIdx,
# int endIdx,
# const double inHigh[],
# const double inLow[],
# const double inClose[],
# int optInTimePeriod, /* From 1 to 100000 */
# int *outBegIdx,
# int *outNBElement,
# double outReal[] );
module Talib::Methods
def ta_atr(high, low, close, opts = {})
raise ArgumentError.new('prices must be an array') unless high.is_a?(Array) and low.is_a?(Array) and close.is_a?(Array)
return [] if high.empty? or low.empty? or close.empty?
inHigh = Talib::LibC.malloc(DoubleSize * high.size)
inLow = Talib::LibC.malloc(DoubleSize * low.size)
inClose = Talib::LibC.malloc(DoubleSize * close.size)
outReal = Talib::LibC.malloc(DoubleSize * Talib::TA_ATR_Lookback(close.size))
outBegIdx = FFI::MemoryPointer.new(1.size)
outNBElement = FFI::MemoryPointer.new(1.size)
inHigh.write_array_of_double(high)
inLow.write_array_of_double(low)
inClose.write_array_of_double(close)
ret = Talib::TA_ATR(0,close.size - 1, inHigh, inLow, inClose, close.size, outBegIdx, outNBElement, outReal)
if ret == 0
ret = outReal.read_array_of_double(outNBElement.read_int)
else
ret = false
end
Talib::LibC.free(inHigh)
Talib::LibC.free(inLow)
Talib::LibC.free(inClose)
Talib::LibC.free(outReal)
outBegIdx.free
outNBElement.free
ret
end
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods/floor.rb
|
<gh_stars>1-10
module Talib::Methods
def ta_floor(prices, opts = {})
raise ArgumentError.new('prices must be an array') unless prices.is_a?(Array)
return [] if prices.empty?
# 8 is size of double in GCC linux, other SO got other sizes. For now it will be like this
inReal = Talib::LibC.malloc(8 * prices.size)
outReal = Talib::LibC.malloc(8 * prices.size) #Talib::TA_FLOOR_Lookback())
outBegIdx = FFI::MemoryPointer.new(1.size)
outNBElement = FFI::MemoryPointer.new(1.size)
inReal.write_array_of_double(prices)
ret = Talib::TA_FLOOR(0,prices.size - 1, inReal, outBegIdx, outNBElement, outReal)
if ret == 0
ret = outReal.read_array_of_double(outNBElement.read_int)
else
ret = false
end
Talib::LibC.free(inReal)
Talib::LibC.free(outReal)
outBegIdx.free
outNBElement.free
ret
end
end
|
marcocarvalho/ffi-talib
|
lib/talib.rb
|
<reponame>marcocarvalho/ffi-talib<filename>lib/talib.rb<gh_stars>1-10
require 'ffi'
module Talib
module LibC
extend FFI::Library
ffi_lib FFI::Library::LIBC
# memory allocators
attach_function :malloc, [:size_t], :pointer
attach_function :calloc, [:size_t], :pointer
attach_function :valloc, [:size_t], :pointer
attach_function :realloc, [:pointer, :size_t], :pointer
attach_function :free, [:pointer], :void
# memory movers
attach_function :memcpy, [:pointer, :pointer, :size_t], :pointer
attach_function :bcopy, [:pointer, :pointer, :size_t], :void
end # module LibC
extend FFI::Library
ffi_lib 'ta_lib'
startIdx = :int
endIdx = :int
inReal = :pointer
optInTimePeriod = :int
optInNbDev = :double
outBegIdx = :pointer # to int
outNBElement = :pointer # to int
outReal = :pointer # array of double
TA_RetCode = :uint
optInFastPeriod = :int
optInSlowPeriod = :int
optInSignalPeriod = :int
outMACD = :pointer
outMACDSignal = :pointer
outMACDHist = :pointer
optInAcceleration = :double
optInMaximum = :double
inHigh = :pointer
inLow = :pointer
inClose = :pointer
# TA_RetCode TA_ATR( int startIdx,
# int endIdx,
# const double inHigh[],
# const double inLow[],
# const double inClose[],
# int optInTimePeriod, /* From 1 to 100000 */
# int *outBegIdx,
# int *outNBElement,
# double outReal[] );
attach_function :TA_ATR, [startIdx, endIdx, inHigh, inLow, inClose, optInTimePeriod, outBegIdx, outNBElement, outReal], :uint
attach_function :TA_ATR_Lookback, [optInTimePeriod], :int
attach_function :TA_SAR, [startIdx, endIdx, inHigh, inLow, optInAcceleration, optInMaximum, outBegIdx, outNBElement, outReal], :uint
attach_function :TA_SAR_Lookback, [optInAcceleration, optInMaximum], :int
attach_function :TA_SMA, [ :int, :int, :pointer, :int, :pointer, :pointer, :pointer], :uint
attach_function :TA_SMA_Lookback, [:int], :int
attach_function :TA_FLOOR, [startIdx, endIdx, inReal, outBegIdx, outNBElement, outReal], TA_RetCode
attach_function :TA_FLOOR_Lookback, [], :int
attach_function :TA_TRIMA, [:int, :int, :pointer, :int, :pointer, :pointer, :pointer], :uint
attach_function :TA_TRIMA_Lookback, [:int], :int
attach_function :TA_STDDEV, [startIdx, endIdx, inReal, optInTimePeriod, optInNbDev, outBegIdx, outNBElement, outReal], :uint
attach_function :TA_STDDEV_Lookback, [optInTimePeriod, optInNbDev], :int
attach_function :TA_VAR, [startIdx, endIdx, inReal, optInTimePeriod, optInNbDev, outBegIdx, outNBElement, outReal], :uint
attach_function :TA_VAR_Lookback, [optInTimePeriod, optInNbDev], :int
attach_function :TA_MACD, [startIdx, endIdx, inReal, optInFastPeriod, optInSlowPeriod, optInSignalPeriod, outBegIdx, outNBElement, outMACD, outMACDSignal, outMACDHist], TA_RetCode
attach_function :TA_MACD_Lookback, [optInFastPeriod, optInSlowPeriod, optInSignalPeriod], :int
module Methods
DoubleSize = 8
def implemented_talib_methods
@implemented_talib_methods ||= methods.map { |n| v = n.to_s; v[0..2] == 'ta_' ? v[3, v.size].to_sym : nil }.compact
end
require 'talib/methods'
end
def self.included(klass)
klass.extend(Methods)
klass.send(:include, Methods)
end
extend Methods
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods/sma.rb
|
module Talib::Methods
def ta_sma(prices, period, opts = {})
raise ArgumentError.new('prices must be an array') unless prices.is_a?(Array)
raise ArgumentError.new('period must be a Fixnum and greater than 1') if !period.is_a?(Fixnum) or period < 2
return [] if prices.empty?
inReal = Talib::LibC.malloc(DoubleSize * prices.size)
outReal = Talib::LibC.malloc(DoubleSize * Talib::TA_SMA_Lookback(prices.size))
outBegIdx = FFI::MemoryPointer.new(1.size)
outNBElement = FFI::MemoryPointer.new(1.size)
inReal.write_array_of_double(prices)
ret = Talib::TA_SMA(0,prices.size - 1, inReal, period, outBegIdx, outNBElement, outReal)
if ret == 0
ret = outReal.read_array_of_double(outNBElement.read_int)
else
ret = false
end
Talib::LibC.free(inReal)
Talib::LibC.free(outReal)
outBegIdx.free
outNBElement.free
ret
end
end
|
marcocarvalho/ffi-talib
|
spec/ffi/talib/methods/floor_spec.rb
|
require 'spec_helper'
describe Talib do
subject { Talib }
it 'should call floor' do
expect(subject.ta_floor([1.2,2.3,3.6,4.4,5.5,6.8,7.2,8.1,9.1234,10.40])).to eq [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
end
it 'should return empty array if an empty one is given' do
expect(subject.ta_floor([])).to eq []
end
it 'should raise error if no array is given' do
expect { subject.ta_floor(nil) }.to raise_error('prices must be an array')
end
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods/macd.rb
|
<gh_stars>1-10
# TA_RetCode TA_MACD( int startIdx,
# int endIdx,
# const double inReal[],
# int optInFastPeriod, /* From 2 to 100000 */
# int optInSlowPeriod, /* From 2 to 100000 */
# int optInSignalPeriod, /* From 1 to 100000 */
# int *outBegIdx,
# int *outNBElement,
# double outMACD[],
# double outMACDSignal[],
# double outMACDHist[] );
module Talib::Methods
def ta_macd(prices, opts = {})
raise ArgumentError.new('prices must be an array') unless prices.is_a?(Array)
return [] if prices.empty?
options = {
optInFastPeriod: 12,
optInSlowPeriod: 26,
optInSignalPeriod: 9
}.merge(opts)
inReal = Talib::LibC.malloc(DoubleSize * prices.size)
lookback = Talib::TA_MACD_Lookback(options[:optInFastPeriod], options[:optInSlowPeriod], options[:optInSignalPeriod])
outMACD = Talib::LibC.malloc(DoubleSize * prices.size)
outMACDSignal = Talib::LibC.malloc(DoubleSize * prices.size)
outMACDHist = Talib::LibC.malloc(DoubleSize * prices.size)
outBegIdx = FFI::MemoryPointer.new(1.size)
outNBElement = FFI::MemoryPointer.new(1.size)
inReal.write_array_of_double(prices)
ret = Talib::TA_MACD(0,prices.size - 1, inReal, options[:optInFastPeriod], options[:optInSlowPeriod], options[:optInSignalPeriod], outBegIdx, outNBElement, outMACD, outMACDSignal, outMACDHist)
if ret == 0
ret = {}
el = outNBElement.read_int
ret[:macd] = outMACD.read_array_of_double(el)
ret[:hist] = outMACDHist.read_array_of_double(el)
ret[:signal] = outMACDSignal.read_array_of_double(el)
else
ret = false
end
Talib::LibC.free(inReal)
Talib::LibC.free(outMACD)
Talib::LibC.free(outMACDHist)
Talib::LibC.free(outMACDSignal)
outBegIdx.free
outNBElement.free
ret
end
end
|
marcocarvalho/ffi-talib
|
talib-ffi-wrapper.gemspec
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'talib/version'
Gem::Specification.new do |spec|
spec.name = "ffi-talib"
spec.version = Talib::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.description = %q{talib wrapper}
spec.summary = %q{talib wrapper}
spec.homepage = ""
spec.license = "BSD"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.add_dependency 'ffi'
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
|
marcocarvalho/ffi-talib
|
spec/ffi/talib/talib_spec.rb
|
<filename>spec/ffi/talib/talib_spec.rb
require 'spec_helper'
describe Talib do
subject { Talib }
it 'should now all TALib methods implemented' do
expect(subject.respond_to?(:implemented_talib_methods)).to eq(true)
expect(subject.implemented_talib_methods.is_a?(Array)).to eq(true)
end
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods/sar_parabolic.rb
|
<reponame>marcocarvalho/ffi-talib<filename>lib/talib/methods/sar_parabolic.rb<gh_stars>1-10
# TA_RetCode TA_SAR( int startIdx,
# int endIdx,
# const double inHigh[],
# const double inLow[],
# double optInAcceleration, /* From 0 to TA_REAL_MAX */
# double optInMaximum, /* From 0 to TA_REAL_MAX */
# int *outBegIdx,
# int *outNBElement,
# double outReal[] );
module Talib::Methods
def ta_sar(high, low, opts = {})
raise ArgumentError.new('high and low prices must be an array') unless high.is_a?(Array) and low.is_a?(Array)
return [] if high.empty? or low.empty?
options = {
optInAcceleration: 0.02,
optInMaximum: 0.2
}.merge(opts)
inHigh = Talib::LibC.malloc(DoubleSize * high.size)
inLow = Talib::LibC.malloc(DoubleSize * low.size)
outReal = Talib::LibC.malloc(DoubleSize * high.size)
outBegIdx = FFI::MemoryPointer.new(1.size)
outNBElement = FFI::MemoryPointer.new(1.size)
inHigh.write_array_of_double(high)
inLow.write_array_of_double(low)
ret = Talib::TA_SAR(0, high.size - 1, inHigh, inLow, options[:optInAcceleration], options[:optInMaximum], outBegIdx, outNBElement, outReal)
if ret == 0
ret = {}
el = outNBElement.read_int
ret = outReal.read_array_of_double(el)
else
ret = false
end
Talib::LibC.free(inHigh)
Talib::LibC.free(inLow)
Talib::LibC.free(outReal)
outBegIdx.free
outNBElement.free
ret
end
end
|
marcocarvalho/ffi-talib
|
spec/ffi/talib/methods/sma_spec.rb
|
require 'spec_helper'
describe Talib do
subject { Talib }
it 'should call simple moving average' do
expect(subject.ta_sma([1,2,3,4,5,6,7,8,9,10], 3)).to eq [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
end
it 'should return empty array if an empty one is given' do
expect(subject.ta_sma([], 2)).to eq []
end
it 'should raise error if no array is given' do
expect { subject.ta_sma(nil, 2) }.to raise_error('prices must be an array')
end
it 'should raise error if period not a fixnum or not greater than 1' do
expect { subject.ta_sma([], nil) }.to raise_error('period must be a Fixnum and greater than 1')
expect { subject.ta_sma([], 1)}.to raise_error('period must be a Fixnum and greater than 1')
end
end
|
marcocarvalho/ffi-talib
|
lib/talib/methods.rb
|
Dir[ File.join(File.dirname(__FILE__), 'methods/*.rb' )].each { |file| require file }
|
lbriais/dir_glob_ignore
|
spec/spec_helper.rb
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'dir_glob_ignore'
|
lbriais/dir_glob_ignore
|
spec/dir_glob_ignore_spec.rb
|
<filename>spec/dir_glob_ignore_spec.rb
require 'spec_helper'
describe DirGlobIgnore do
it 'has a version number' do
expect(DirGlobIgnore::VERSION).not_to be nil
end
end
|
lbriais/dir_glob_ignore
|
spec/ignore_file_lists_spec.rb
|
<reponame>lbriais/dir_glob_ignore
require 'spec_helper'
describe DirGlobIgnore::IgnoreFileLists do
let(:test_root) { File.expand_path File.join('..', '..', 'test'), __FILE__ }
let(:an_ignored_file) { File.join test_root, 'file1.txt'}
let(:a_non_ignored_file) { File.join test_root, 'file2.rb'}
subject { described_class.new test_root }
it 'should start the search of ignore files from a base dir' do
expect(subject.base_dir).to eq test_root
end
it 'should search for all specified ".ignore" files' do
expect(subject.send(:ignore_files).size).to eq 3
end
context 'when loading ignore files' do
it 'should build lists of files to be ignored into a cache' do
expect {subject.load_ignore_files}.not_to raise_error
cache = subject.send :cache
# There are 3 .ignore files in tests
expect(cache.size).to eq 3
# each path leads to an ignore list
cache.values.each do |info|
expect(info[:ignored_files]).to be_an Array
expect(info[:ignored_files]).not_to be_empty
end
end
it 'should tell if a file should be ignored or not' do
subject.load_ignore_files
expect(subject.ignore_file? an_ignored_file).to be_truthy
expect(subject.ignore_file? a_non_ignored_file).to be_falsey
end
end
end
|
lbriais/dir_glob_ignore
|
lib/dir_glob_ignore/ignore_file_lists.rb
|
module DirGlobIgnore
class IgnoreFileLists
DEFAULT_FILE_NAME = '.ignore'.freeze
attr_writer :ignore_file_name, :base_dir
def initialize(base_dir = nil)
self.base_dir = base_dir
end
def ignore_file_name
@ignore_file_name ||= DEFAULT_FILE_NAME
end
def base_dir
@base_dir ||= Dir.pwd
end
def load_ignore_files
@cache = {}
ignore_files.each do |ignore_file|
cache[File.expand_path File.dirname ignore_file] = {
ignore_file: ignore_file,
patterns: load_ignore_file(ignore_file),
ignored_files: []
}
end
build_cached_ignore_lists
end
def ignore_file?(file)
cache.values.each do |info|
return true if info[:ignored_files].include? File.expand_path(file)
end
false
end
private
attr_reader :cache
def build_cached_ignore_lists
cache.each do |dir, info|
info[:patterns].each do |pattern|
info[:ignored_files].concat Dir.glob(File.join(dir, pattern), File::FNM_DOTMATCH)
end
end
end
def load_ignore_file(ignore_file)
File.readlines(ignore_file).map(&:chomp).reject do |entry|
if entry =~ /^\s*#/
# Ignore commented lines
true
elsif entry =~ /^\s*$/
# Ignore empty lines
true
else
false
end
end
end
def ignore_files
file_pattern = File.join base_dir, '**', ignore_file_name
Dir.glob file_pattern, File::FNM_DOTMATCH
end
end
end
|
lbriais/dir_glob_ignore
|
lib/dir_glob_ignore.rb
|
require 'dir_glob_ignore/version'
require 'dir_glob_ignore/ignore_file_lists'
require 'dir_glob_ignore/dir_patch'
|
lbriais/dir_glob_ignore
|
lib/dir_glob_ignore/dir_patch.rb
|
class Dir
def self.glob_with_ignore_file(ignore_file, base_dir, *glob_args, &block)
filter = DirGlobIgnore::IgnoreFileLists.new base_dir
filter.ignore_file_name = ignore_file
filter.load_ignore_files
Dir.glob(*glob_args).reject do |file|
if filter.ignore_file? file
true
else
yield file if block_given?
false
end
end
end
end
|
lbriais/dir_glob_ignore
|
spec/dir_patch_spec.rb
|
<reponame>lbriais/dir_glob_ignore
require 'spec_helper'
describe Dir do
let(:base_dir) { File.expand_path File.join('..', '..', 'test'), __FILE__ }
let(:ignore_file) { DirGlobIgnore::IgnoreFileLists::DEFAULT_FILE_NAME }
subject { described_class }
it 'should provide a list of files without the ignored ones' do
expect(subject.glob_with_ignore_file(ignore_file, base_dir, "#{base_dir}/**/*").size).to eq 11
end
context 'when the glob path is relative' do
it 'should provide a list of files without the ignored ones' do
expect(subject.glob_with_ignore_file(ignore_file, base_dir, 'test/**/*').size).to eq 11
end
end
end
|
djberg96/notation
|
lib/notation.rb
|
# encoding: utf-8
# Run with -Ku if using Ruby 1.8.
module Kernel
# Version of the notation library
NOTATION_VERSION = '0.2.1'.freeze
# Make lambda a true lambda
#
# Example:
# λ { puts 'Hello' }.call => 'Hello'
#
alias λ proc
# Sigma, i.e. the sum of all elements.
#
# Example:
# ∑ [1,2,3] => 6
#
def ∑(*args)
args.inject(0){ |e,m| m += e }
end
# Pi product, i.e. the product of all elements.
#
# Example:
# ∏ [2,3,4] => 24
#
def ∏(*args)
args.inject(1){ |e,m| m *= e }
end
# Square root
#
# Example:
# √ 49 => 7.0
#
def √(root)
Math.sqrt(root)
end
end
|
djberg96/notation
|
spec/notation_spec.rb
|
<filename>spec/notation_spec.rb
# encoding: utf-8
################################################################
# notation_spec.rb
#
# Specs for the notation library. This should be run via the
# 'rake spec' (or just 'rake') task.
################################################################
require 'rspec'
require 'notation'
RSpec.describe "Notation" do
example "version" do
expect(Kernel::NOTATION_VERSION).to eq('0.2.1')
expect(Kernel::NOTATION_VERSION).to be_frozen
end
example "sigma" do
expect(Kernel).to respond_to(:∑)
expect(∑(1,2,3)).to eq(6)
end
example "pi" do
expect(Kernel).to respond_to(:∏)
expect(∏(2,3,4)).to eq(24)
end
example "square_root" do
expect(Kernel).to respond_to(:√)
expect(√(49)).to eq(7.0)
end
example "lambda" do
expect(λ{ 'hello' }.call).to eq('hello')
end
end
|
chukitow/blogo
|
db/migrate/20140218134620_create_blogo_taggings.rb
|
<reponame>chukitow/blogo
class CreateBlogoTaggings < ActiveRecord::Migration
def change
taggings_table = "#{Blogo.table_name_prefix}taggings"
create_table(taggings_table) do |t|
t.integer :post_id, null: false
t.integer :tag_id , null: false
end
add_index taggings_table, [:tag_id, :post_id], unique: true
if defined?(Foreigner)
tags_table = "#{Blogo.table_name_prefix}tags"
posts_table = "#{Blogo.table_name_prefix}posts"
add_foreign_key taggings_table, tags_table , column: :tag_id
add_foreign_key taggings_table, posts_table, column: :post_id
end
end
end
|
NoUseFreak/lig-test
|
Formula/.rb
|
# This file was generated by LetItGo.
class < Formula
desc ""
homepage "https://github.com/NoUseFreak/lig-test"
version "0.1.17"
url "https://github.com/NoUseFreak/lig-test/releases/download/0.1.17/lig-test"
sha256 "aaddca1e81609f71ca199022020f65d65feae33a12e5599b08e49dbfa58e56a5"
def install
bin.install ""
end
test do
system "#{bin}/ -h"
end
end
|
NoUseFreak/lig-test
|
Formula/lig-test.rb
|
<reponame>NoUseFreak/lig-test<filename>Formula/lig-test.rb
# This file was generated by LetItGo.
class Lig-test < Formula
desc "lig-test testing."
homepage "https://github.com/NoUseFreak/lig-test"
version "0.1.18"
url "https://github.com/NoUseFreak/lig-test/releases/download/0.1.18/lig-test"
sha256 "aaddca1e81609f71ca199022020f65d65feae33a12e5599b08e49dbfa58e56a5"
def install
bin.install "lig-test"
end
test do
system "#{bin}/lig-test -h"
end
end
|
fsateler/webpacker
|
lib/webpacker/configuration.rb
|
# Loads webpacker configuration from config/webpack/paths.yml
require "webpacker/file_loader"
class Webpacker::Configuration < Webpacker::FileLoader
class << self
def config_path
Rails.root.join(paths.fetch(:config, "config/webpack"))
end
def entry_path
Rails.root.join(source_path, paths.fetch(:entry, "packs"))
end
def file_path
Rails.root.join("config", "webpack", "paths.yml")
end
def manifest_path
Rails.root.join(output_path, paths.fetch(:manifest, "manifest.json"))
end
def output_path
Rails.root.join(paths.fetch(:output, "public"), paths.fetch(:entry, "packs"))
end
def paths
load if Rails.env.development?
raise Webpacker::FileLoader::FileLoaderError.new("Webpacker::Configuration.load must be called first") unless instance
instance.data
end
def source_path
Rails.root.join(paths.fetch(:source, "app/javascript"))
end
end
private
def load
return super unless File.exist?(@path)
HashWithIndifferentAccess.new(YAML.load(File.read(@path))[Rails.env])
end
end
|
fsateler/webpacker
|
lib/install/template.rb
|
# Install webpacker
puts "Creating javascript app source directory"
directory "#{__dir__}/javascript", "app/javascript"
puts "Copying binstubs"
directory "#{__dir__}/bin", "bin"
chmod "bin", 0755 & ~File.umask, verbose: false
puts "Copying webpack core config and loaders"
directory "#{__dir__}/config/webpack", "config/webpack"
directory "#{__dir__}/config/loaders/core", "config/webpack/loaders"
copy_file "#{__dir__}/config/.postcssrc.yml", ".postcssrc.yml"
append_to_file ".gitignore", <<-EOS
/public/packs
/node_modules
EOS
puts "Installing all JavaScript dependencies"
run "./bin/yarn add webpack webpack-merge js-yaml path-complete-extname " \
"webpack-manifest-plugin babel-loader coffee-loader coffee-script " \
"babel-core babel-preset-env compression-webpack-plugin rails-erb-loader glob " \
"extract-text-webpack-plugin node-sass file-loader sass-loader css-loader style-loader " \
"postcss-loader autoprefixer postcss-smart-import precss"
puts "Installing dev server for live reloading"
run "./bin/yarn add --dev webpack-dev-server"
puts "Webpacker successfully installed 🎉 🍰"
|
fsateler/webpacker
|
lib/install/vue.rb
|
require "webpacker/configuration"
puts "Copying vue loader to #{Webpacker::Configuration.config_path}/loaders"
copy_file "#{__dir__}/config/loaders/installers/vue.js", "config/webpack/loaders/vue.js"
puts "Copying the example entry file to #{Webpacker::Configuration.entry_path}"
copy_file "#{__dir__}/examples/vue/hello_vue.js", "#{Webpacker::Configuration.entry_path}/hello_vue.js"
puts "Copying vue app file to #{Webpacker::Configuration.entry_path}"
copy_file "#{__dir__}/examples/vue/app.vue", "#{Webpacker::Configuration.entry_path}/app.vue"
puts "Installing all vue dependencies"
run "./bin/yarn add vue vue-loader vue-template-compiler sass-loader node-sass css-loader"
puts "Webpacker now supports vue.js 🎉"
|
fsateler/webpacker
|
lib/tasks/webpacker/yarn_install.rake
|
namespace :webpacker do
desc "Support for older Rails versions.Install all JavaScript dependencies as specified via Yarn"
task :yarn_install do
system("./bin/yarn")
end
end
|
fsateler/webpacker
|
lib/webpacker/manifest.rb
|
# Singleton registry for accessing the packs path using generated manifest.
# This allows javascript_pack_tag, stylesheet_pack_tag, asset_pack_path to take a reference to,
# say, "calendar.js" or "calendar.css" and turn it into "/packs/calendar.js" or
# "/packs/calendar.css" in development. In production mode, it returns compiles
# files, # "/packs/calendar-1016838bab065ae1e314.js" and
# "/packs/calendar-1016838bab065ae1e314.css" for long-term caching
require "webpacker/file_loader"
require "webpacker/configuration"
class Webpacker::Manifest < Webpacker::FileLoader
class << self
def file_path
Webpacker::Configuration.manifest_path
end
def lookup(name)
load if Rails.env.development?
raise Webpacker::FileLoader::FileLoaderError.new("Webpacker::Manifest.load must be called first") unless instance
instance.data[name.to_s] || raise(Webpacker::FileLoader::NotFoundError.new("Can't find #{name} in #{file_path}. Is webpack still compiling?"))
end
end
private
def load
return super unless File.exist?(@path)
JSON.parse(File.read(@path))
end
end
|
fsateler/webpacker
|
lib/install/angular.rb
|
require "webpacker/configuration"
puts "Copying angular loader to #{Webpacker::Configuration.config_path}/loaders"
copy_file "#{__dir__}/config/loaders/installers/angular.js", "config/webpack/loaders/angular.js"
puts "Copying angular example entry file to #{Webpacker::Configuration.entry_path}"
copy_file "#{__dir__}/examples/angular/hello_angular.js", "#{Webpacker::Configuration.entry_path}/hello_angular.js"
puts "Copying hello_angular app to #{Webpacker::Configuration.source_path}"
directory "#{__dir__}/examples/angular/hello_angular", "#{Webpacker::Configuration.source_path}/hello_angular"
puts "Copying tsconfig.json to the Rails root directory for typescript"
copy_file "#{__dir__}/examples/angular/tsconfig.json", "tsconfig.json"
puts "Installing all angular dependencies"
run "./bin/yarn add typescript ts-loader core-js zone.js rxjs @angular/core @angular/common @angular/compiler @angular/platform-browser @angular/platform-browser-dynamic"
puts "Webpacker now supports angular.js and typescript 🎉"
|
fsateler/webpacker
|
lib/install/react.rb
|
require "webpacker/configuration"
puts "Copying react loader to #{Webpacker::Configuration.config_path}/loaders"
copy_file "#{__dir__}/config/loaders/installers/react.js", "config/webpack/loaders/react.js"
puts "Copying .babelrc to app root directory"
copy_file "#{__dir__}/examples/react/.babelrc", ".babelrc"
puts "Copying react example entry file to #{Webpacker::Configuration.entry_path}"
copy_file "#{__dir__}/examples/react/hello_react.jsx", "#{Webpacker::Configuration.entry_path}/hello_react.jsx"
puts "Installing all react dependencies"
run "./bin/yarn add react react-dom babel-preset-react"
puts "Webpacker now supports react.js 🎉"
|
fsateler/webpacker
|
lib/tasks/webpacker/compile.rake
|
<filename>lib/tasks/webpacker/compile.rake<gh_stars>0
require "webpacker/configuration"
REGEX_MAP = /\A.*\.map\z/
namespace :webpacker do
desc "Compile javascript packs using webpack for production with digests"
task compile: ["webpacker:verify_install", :environment] do
puts "Compiling webpacker assets 🎉"
result = `NODE_ENV=production ./bin/webpack`
unless $?.success?
puts JSON.parse(result)["errors"]
exit! $?.exitstatus
end
puts "Compiled digests for all packs in #{Webpacker::Configuration.output_path}: "
puts JSON.parse(File.read(Webpacker::Configuration.manifest_path))
end
end
# Compile packs after we've compiled all other assets during precompilation
if Rake::Task.task_defined?("assets:precompile")
Rake::Task["assets:precompile"].enhance do
unless Rake::Task.task_defined?("yarn:install")
# For Rails < 5.1
Rake::Task["webpacker:yarn_install"].invoke
end
Rake::Task["webpacker:compile"].invoke
end
end
|
fsateler/webpacker
|
lib/webpacker/railtie.rb
|
require "rails/railtie"
require "webpacker/helper"
class Webpacker::Engine < ::Rails::Engine
initializer :webpacker do |app|
ActiveSupport.on_load :action_controller do
ActionController::Base.helper Webpacker::Helper
end
# Loads webpacker config data from config/webpack/paths.yml
Webpacker::Configuration.load
# Loads manifest data from public/packs/manifest.json
Webpacker::Manifest.load
end
end
|
fsateler/webpacker
|
lib/tasks/webpacker/install.rake
|
<gh_stars>0
WEBPACKER_APP_TEMPLATE_PATH = File.expand_path("../../install/template.rb", __dir__)
namespace :webpacker do
desc "Install webpacker in this application"
task :install do
if Rails::VERSION::MAJOR >= 5
exec "./bin/rails app:template LOCATION=#{WEBPACKER_APP_TEMPLATE_PATH}"
else
exec "./bin/rake rails:template LOCATION=#{WEBPACKER_APP_TEMPLATE_PATH}"
end
end
end
|
fsateler/webpacker
|
lib/webpacker/helper.rb
|
<reponame>fsateler/webpacker
require "webpacker/manifest"
module Webpacker::Helper
# Computes the full path for a given webpacker asset.
# Return relative path using manifest.json and passes it to asset_url helper
# This will use asset_path internally, so most of their behaviors will be the same.
# Examples:
#
# In development mode:
# <%= asset_pack_path 'calendar.js' %> # => "/packs/calendar.js"
# In production mode:
# <%= asset_pack_path 'calendar.css' %> # => "/packs/calendar-1016838bab065ae1e122.css"
def asset_pack_path(name, **options)
asset_path(Webpacker::Manifest.lookup(name), **options)
end
# Creates a script tag that references the named pack file, as compiled by Webpack per the entries list
# in config/webpack/shared.js. By default, this list is auto-generated to match everything in
# app/javascript/packs/*.js. In production mode, the digested reference is automatically looked up.
#
# Examples:
#
# # In development mode:
# <%= javascript_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # =>
# <script src="/packs/calendar.js" data-turbolinks-track="reload"></script>
#
# # In production mode:
# <%= javascript_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # =>
# <script src="/packs/calendar-1016838bab065ae1e314.js" data-turbolinks-track="reload"></script>
def javascript_pack_tag(name, **options)
javascript_include_tag(Webpacker::Manifest.lookup("#{name}#{compute_asset_extname(name, type: :javascript)}"), **options)
end
# Creates a link tag that references the named pack file, as compiled by Webpack per the entries list
# in config/webpack/shared.js. By default, this list is auto-generated to match everything in
# app/javascript/packs/*.js. In production mode, the digested reference is automatically looked up.
#
# Examples:
#
# # In development mode:
# <%= stylesheet_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # =>
# <link rel="stylesheet" media="screen" href="/packs/calendar.css" data-turbolinks-track="reload" />
#
# # In production mode:
# <%= stylesheet_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # =>
# <link rel="stylesheet" media="screen" href="/packs/calendar-1016838bab065ae1e122.css" data-turbolinks-track="reload" />
def stylesheet_pack_tag(name, **options)
stylesheet_link_tag(Webpacker::Manifest.lookup("#{name}#{compute_asset_extname(name, type: :stylesheet)}"), **options)
end
end
|
fsateler/webpacker
|
lib/webpacker/version.rb
|
module Webpacker
VERSION = "1.1".freeze
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/event_handler.rb
|
# frozen_string_literal: true
module Geoserver
module Worker
class EventHandler
include Sneakers::Worker
from_queue :geoserver
def work(msg)
msg = JSON.parse(msg)
result = Worker::EventProcessor.new(msg).process
if result
ack!
else
reject!
end
end
end
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require "erb"
require "geoserver/publish"
require "json"
require "sneakers"
require "yaml"
module Geoserver
module Worker
require "geoserver/worker/config"
require "geoserver/worker/event_handler"
require "geoserver/worker/event_processor"
require "geoserver/worker/event_processor/processor"
require "geoserver/worker/event_processor/create_processor"
require "geoserver/worker/event_processor/delete_processor"
require "geoserver/worker/event_processor/update_processor"
require "geoserver/worker/event_processor/unknown_event"
def self.root
Pathname.new(File.expand_path("../../../", __FILE__))
end
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/event_processor/update_processor.rb
|
# frozen_string_literal: true
module Geoserver
module Worker
class EventProcessor
class UpdateProcessor < Processor
def create_method
return :geotiff if layer_type == "geotiff"
return :shapefile if layer_type == "shapefile"
end
def create_params
{
workspace_name: workspace,
file_path: path,
id: id,
title: title
}
end
def delete_method
return :delete_geotiff if layer_type == "geotiff"
return :delete_shapefile if layer_type == "shapefile"
end
def delete_params
{
workspace_name: workspace,
id: id
}
end
def process
return false unless create_method
Geoserver::Publish.send(delete_method, delete_params)
Geoserver::Publish.send(create_method, create_params)
true
rescue StandardError
false
end
end
end
end
end
|
eliotjordan/geoserver-worker
|
spec/spec_helper.rb
|
# frozen_string_literal: true
require "simplecov"
require "coveralls"
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(
[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
)
SimpleCov.start do
add_filter "spec"
add_filter "vendor"
end
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "bundler/setup"
require "geoserver/worker"
Dir[Pathname.new("./").join("spec", "support", "**", "*.rb")].sort.each { |file| require_relative file.gsub(/^spec\//, "") }
ROOT_PATH = Pathname.new(Dir.pwd)
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
config.example_status_persistence_file_path = ".rspec_status"
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/config.rb
|
# frozen_string_literal: true
module Geoserver
module Worker
def config
@config ||= config_yaml
end
private
def config_yaml
file_path = File.join(Geoserver::Worker.root, "config", "config.yml")
YAML.safe_load(ERB.new(File.read(file_path)).result, [], [], true)
end
module_function :config, :config_yaml
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/version.rb
|
<gh_stars>1-10
# frozen_string_literal: true
module Geoserver
module Worker
VERSION = "0.1.0"
end
end
|
eliotjordan/geoserver-worker
|
spec/geoserver/worker/config_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Geoserver::Worker do
subject(:config) { described_class.config }
it "loads a config object" do
expect(config["events"]["server"]).not_to be_empty
expect(config["events"]["exchange"]).not_to be_empty
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/event_processor/create_processor.rb
|
# frozen_string_literal: true
module Geoserver
module Worker
class EventProcessor
class CreateProcessor < Processor
def params
{
workspace_name: workspace,
file_path: path,
id: id,
title: title
}
end
def publish_method
return :geotiff if layer_type == "geotiff"
return :shapefile if layer_type == "shapefile"
end
def process
return false unless publish_method
Geoserver::Publish.send(publish_method, params)
true
rescue StandardError
false
end
end
end
end
end
|
eliotjordan/geoserver-worker
|
spec/geoserver/worker/event_processor_spec.rb
|
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Geoserver::Worker::EventProcessor do
subject(:processor) { described_class.new(event) }
let(:id) { "c2d14b8-0563c4a18b8a-2d0ae0d91-8b66" }
let(:layer_type) { "geotiff" }
let(:title) { "Title" }
let(:workspace) { "Public" }
let(:path) { "file:///dataset" }
let(:event) do
{
"event" => event_type,
"id" => id,
"layer_type" => layer_type,
"workspace" => workspace,
"path" => path,
"title" => title
}
end
context "when given an unknown event" do
let(:event_type) { "UNKNOWNEVENT" }
it "returns false" do
expect(processor.process).to eq false
end
end
context "when given a shapefile creation event" do
let(:event_type) { "CREATED" }
let(:layer_type) { "shapefile" }
before do
allow(Geoserver::Publish).to receive(:shapefile)
end
it "creates a GeoServer layer" do
expect(processor.process).to eq true
expect(Geoserver::Publish).to have_received(:shapefile)
end
end
context "when given a geotiff creation event that causes an error" do
let(:event_type) { "CREATED" }
let(:path) { nil }
before do
allow(Geoserver::Publish).to receive(:geotiff).and_raise(Geoserver::Publish::Error)
end
it "returns false" do
expect(processor.process).to eq false
end
end
context "when given an update event" do
let(:event_type) { "UPDATED" }
let(:layer_type) { "shapefile" }
before do
allow(Geoserver::Publish).to receive(:delete_shapefile)
allow(Geoserver::Publish).to receive(:shapefile)
end
it "recreates the shapefile layer in GeoServer" do
expect(processor.process).to eq true
expect(Geoserver::Publish).to have_received(:delete_shapefile)
expect(Geoserver::Publish).to have_received(:shapefile)
end
end
context "when given an update event that causes an error" do
let(:event_type) { "UPDATED" }
let(:path) { nil }
before do
allow(Geoserver::Publish).to receive(:geotiff).and_raise(Geoserver::Publish::Error)
end
it "returns false" do
expect(processor.process).to eq false
end
end
context "when given a shapefile delete event" do
let(:event_type) { "DELETED" }
let(:layer_type) { "shapefile" }
before do
allow(Geoserver::Publish).to receive(:delete_shapefile)
end
it "deletes the shapefile layer in GeoServer" do
expect(processor.process).to eq true
expect(Geoserver::Publish).to have_received(:delete_shapefile)
end
end
context "when given a geotiff delete event that causes an error" do
let(:event_type) { "DELETED" }
before do
allow(Geoserver::Publish).to receive(:delete_geotiff).and_raise(Geoserver::Publish::Error)
end
it "returns false" do
expect(processor.process).to eq false
end
end
end
|
eliotjordan/geoserver-worker
|
geoserver-worker.gemspec
|
# frozen_string_literal: true
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "geoserver/worker/version"
Gem::Specification.new do |spec|
spec.name = "geoserver-worker"
spec.version = Geoserver::Worker::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.summary = "Sneakers worker for syncing with GeoServer using RabbitMQ"
spec.description = "Sneakers worker for syncing with GeoServer using RabbitMQ"
spec.homepage = "https://github.com/pulibrary/geoserver-worker"
spec.license = "Apache-2.0"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "bin"
spec.executables = ["geoserver-worker"]
spec.require_paths = ["lib"]
spec.add_dependency "bundler", ">= 1.16"
spec.add_dependency "geoserver-publish"
spec.add_dependency "sneakers"
spec.add_development_dependency "bixby"
spec.add_development_dependency "coveralls"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "simplecov"
end
|
eliotjordan/geoserver-worker
|
spec/geoserver/worker_spec.rb
|
# frozen_string_literal: true
RSpec.describe Geoserver::Worker do
it "has a version number" do
expect(Geoserver::Worker::VERSION).not_to be nil
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/event_processor/processor.rb
|
# frozen_string_literal: true
module Geoserver
module Worker
class EventProcessor
class Processor
attr_reader :event
def initialize(event)
@event = event
end
private
def id
event["id"]
end
def layer_type
event["layer_type"]
end
def path
event["path"]
end
def title
event["title"]
end
def workspace
event["workspace"]
end
end
end
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/event_processor/unknown_event.rb
|
# frozen_string_literal: true
module Geoserver
module Worker
class EventProcessor
class UnknownEvent < Processor
attr_reader :event
def initialize(event)
@event = event
end
def process
false
end
end
end
end
end
|
eliotjordan/geoserver-worker
|
lib/geoserver/worker/event_processor/delete_processor.rb
|
<gh_stars>1-10
# frozen_string_literal: true
module Geoserver
module Worker
class EventProcessor
class DeleteProcessor < Processor
def params
{
workspace_name: workspace,
id: id
}
end
def publish_method
return :delete_geotiff if layer_type == "geotiff"
return :delete_shapefile if layer_type == "shapefile"
end
def process
return false unless publish_method
Geoserver::Publish.send(publish_method, params)
true
rescue StandardError
false
end
end
end
end
end
|
krzyzak/rpg
|
lib/rpg.rb
|
require "rpg/version"
require "rpg/pesel"
module Rpg
end
|
krzyzak/rpg
|
test/pesel_test.rb
|
<reponame>krzyzak/rpg
require "test_helper"
require "date"
class PeselTest < MiniTest::Unit::TestCase
def test_should_generate_valid_pesel_for_19th_century
date = Date.parse("1803-10-20")
pesel = Rpg::Pesel.new(date: date).generate
@pesel = Yapv::Pesel.new(pesel)
assert @pesel.valid?
assert_equal date, @pesel.birth_date
end
def test_should_generate_valid_pesel_for_20th_century
date = Date.parse("1920-04-11")
pesel = Rpg::Pesel.new(date: date).generate
@pesel = Yapv::Pesel.new(pesel)
assert @pesel.valid?
assert_equal date, @pesel.birth_date
end
def test_should_generate_valid_pesel_for_21st_century
date = Date.parse("2012-06-02")
pesel = Rpg::Pesel.new(date: date).generate
@pesel = Yapv::Pesel.new(pesel)
assert @pesel.valid?
assert_equal date, @pesel.birth_date
end
def test_should_generate_valid_pesel_for_22nd_century
date = Date.parse("2165-11-06")
pesel = Rpg::Pesel.new(date: date).generate
@pesel = Yapv::Pesel.new(pesel)
assert @pesel.valid?
assert_equal date, @pesel.birth_date
end
def test_should_generate_valid_pesel_for_23rd_century
date = Date.parse("2289-11-12")
pesel = Rpg::Pesel.new(date: date).generate
@pesel = Yapv::Pesel.new(pesel)
assert @pesel.valid?
assert_equal date, @pesel.birth_date
end
def test_should_raise_argument_error_for_date_below_18th_century
assert_raises ArgumentError do
Rpg::Pesel.new(date: "1799-04-11").generate
end
end
def test_should_raise_argument_error_for_date_over_23rd_century
assert_raises ArgumentError do
Rpg::Pesel.new(date: "2300-04-11").generate
end
end
def test_should_generate_pesel_for_female
@pesel = Rpg::Pesel.new(gender: :female, date: "2020-04-11").generate
assert Yapv::Pesel.new(@pesel).valid?
assert_equal :female, Yapv::Pesel.new(@pesel).gender
end
def test_should_generate_pesel_for_male
@pesel = Rpg::Pesel.new(gender: :male, date: "2020-04-11").generate
assert Yapv::Pesel.new(@pesel).valid?
assert_equal :male, Yapv::Pesel.new(@pesel).gender
end
def test_should_accept_date_as_string
@pesel = Rpg::Pesel.new(date: "2020-04-11").generate
assert Yapv::Pesel.new(@pesel).valid?
end
def test_should_accept_date_as_date_object
@pesel = Rpg::Pesel.new(date:Date.today).generate
assert Yapv::Pesel.new(@pesel).valid?
end
def test_generated_pesel_should_be_unique
numbers = [].tap do |content|
10.times{ content << Rpg::Pesel.new(date: Date.today).generate }
end
assert numbers.uniq.size != 1
end
end
|
krzyzak/rpg
|
lib/rpg/pesel.rb
|
module Rpg
class Pesel
def initialize(options = {})
@date = options[:date].is_a?(Date) ? options[:date] : Date.parse(options[:date])
if [:male, :female].include?(options[:gender])
@gender = options[:gender]
else
@gender = [:male, :female].sample
end
end
def generate
@pesel = [date, serie, gender_num].join
@pesel += calculate_control_sum.to_s
end
private
def serie
"%03d" % rand(0..999)
end
def calculate_control_sum
mask = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]
val = @pesel.split("").map(&:to_i)
modulo = (mask.inject(0){|sum, num| sum + (num * val.shift)} % 10)
modulo == 0 ? 0 : 10 - modulo
end
def gender_num
if @gender == :male
(0..9).to_a.select(&:odd?).sample
else
(0..9).to_a.select(&:even?).sample
end
end
def date
[@date.strftime("%y"), month_with_century_offset, @date.strftime("%d")]
end
def month_with_century_offset
offset = if (1800..1899).include?(@date.year)
80
elsif (1900..1999).include?(@date.year)
0
elsif (2000..2099).include?(@date.year)
20
elsif (2100..2199).include?(@date.year)
40
elsif (2200..2299).include?(@date.year)
60
else
raise ArgumentError.new("Year should be between 1800 and 2299")
end
"%02d" % (@date.month + offset)
end
end
end
|
krzyzak/rpg
|
test/test_helper.rb
|
<gh_stars>1-10
require "minitest/unit"
require "minitest/autorun"
require "active_model"
require "active_model/validations"
require "yapv/pesel"
require "rpg"
require "rpg/pesel"
|
dcuadraq/tic_tac_doh
|
lib/tic_tac_doh.rb
|
require 'tic_tac_doh/version'
module TicTacDoh
class Game
attr_reader :players, :grid
def initialize(args={})
@players = []
@turn = 0
args.fetch(:board_size, 3).times do
@grid = Array.new(3) {}
end
end
def reset
prepare_grid
@turn = rand(0..players.count)
end
def next_turn(cell_position)
insert_player_move_in_grid(calculate_cell(cell_position))
end
def who_is_next
{ nickname: players[player_turn].nickname, mark: players[player_turn].mark }
end
def player_turn
@turn % players.count
end
def set_board_size(size)
prepare_grid(size)
end
def scoreboard
scoreboard = []
players.each do |player|
scoreboard << { nickname: player.nickname, score: player.score }
end
scoreboard
end
def add_player(args)
if valid_mark(args[:mark])
players << Player.new(args)
true
else
false
end
end
def game_over?
# Winner
if symbol_winner?
return true
end
return false unless free_cells?
true
end
def free_cells?
@grid.each do |row|
row.each do |cell|
return false if cell.is_a? Numeric
end
end
true
end
def winner
return find_player_by(mark: symbol_winner?) if symbol_winner?
false
end
private
def valid_mark(mark)
players.each do |player|
if player.mark == mark[0]
return false
end
end
true
end
def prepare_grid(size=grid.length)
@grid = []
array = []
for cell in 0...size
for cell2 in cell * size...(cell * size + size)
array << cell2
end
@grid << array
array = []
end
end
def symbol_winner?
winner_mark = nil
grid.length.times do |n|
grid.length.times do |m|
winner_mark ||= secuential_mark(grid[n][m], n,0,0,1) # horizontal search
winner_mark ||= secuential_mark(grid[m][n], 0,n,1,0) # vertical search
winner_mark ||= secuential_mark(grid[m][n], m,n,1,1) # diagonal +
winner_mark ||= secuential_mark(grid[m][n], m,n,-1,1) # diagonal -
end
end
return winner_mark
end
def find_player_by(args={})
players.each { |player| return { nickname: player.nickname, mark: player.mark } if player.mark == args[:mark] }
false
end
def secuential_mark(mark, row, col, row_step, col_step, counter=1)
return nil unless within_grid_range?(row, col)
if grid[row][col] == mark
return grid[row][col] if counter == 3
return secuential_mark(mark, row + row_step, col + col_step, row_step, col_step, counter+1)
else
return nil
end
end
def within_grid_range? (arg, col)
if arg.is_a? Hash
return true if arg[:row] < grid.length && arg[:col] < grid.length if arg[:row] >= 0 && arg[:col] >= 0
else
return true if arg < grid.length && col < grid.length if arg >= 0 && col >= 0
end
false
end
def calculate_cell(cell_number)
row = 0
for n in 0..cell_number
row += 1 if (n % grid.size) == 0 unless n == 0
end
column = cell_number - (row * grid.size)
{row: row, column: column}
end
def insert_player_move_in_grid(position)
return false unless valid_move? position
@grid[position[:row]][position[:column]] = who_is_next[:mark]
@turn += 1
true
end
def valid_move?(position)
return false if position[:row] < 0 || position[:row] > (@grid.length) - 1
return false if position[:column] < 0 || position[:column] > (@grid.length) - 1
return false unless @grid[position[:row]][position[:column]].is_a? Numeric
true
end
end
class Player
attr_reader :nickname, :score
def initialize(args={})
@nickname = args.fetch(:nickname, "Anonymous#{rand(100)}")
@score = 0
@mark = args[:mark]
end
def add_to_score(score)
@score += score
end
def mark
@mark[0]
end
end
end
|
delba/SwiftyOAuth
|
SwiftyOAuth.podspec
|
Pod::Spec.new do |s|
s.name = 'SwiftyOAuth'
s.version = '2.0'
s.license = { :type => 'MIT' }
s.homepage = 'https://github.com/delba/SwiftyOAuth'
s.author = { 'Damien' => '<EMAIL>' }
s.summary = "A small OAuth library with a built-in set of providers"
s.source = { :git => 'https://github.com/delba/SwiftyOAuth.git', :tag => s.version }
s.swift_version = '5.0'
s.ios.deployment_target = '8.0'
s.source_files = 'Source/**/*.{swift,h}'
s.requires_arc = true
end
|
Youshu31415926/igetui-ruby
|
lib/igetui/client.rb
|
<reponame>Youshu31415926/igetui-ruby
module IGeTui
class Client
attr_accessor :client_id, :alias_name
def initialize(client_id=nil, alias_name=nil)
@client_id = client_id
@alias_name = alias_name
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.