text stringlengths 10 2.61M |
|---|
class Chef
module Provisioning
module AzureDriver
# Represents available options when bootstrapping a host on Azure
# These are used to tell Azure some initial pieces of information
# for building a new VM.
class BootstrapOptions < Chef::Provisioning::BootstrapOptions
# @return [String] The name of the VM
attr_accessor :vm_name
# @return [String] The VM user
attr_accessor :vm_user
# @return [String] The identifier for the VM image to use
attr_accessor :image
# @return [String] the password to use
attr_accessor :password
# @return [String] The Azure location to store this in
attr_accessor :location
end
end
end
end
|
# frozen_string_literal: true
module API
# Global api error handlers. With rollbar notifications
module ErrorHandlers
extend ActiveSupport::Concern
included do
rescue_from ActiveRecord::RecordNotFound do |e|
# Rollbar.warning(e)
return_error!("Record not found", 404)
end
rescue_from PG::UniqueViolation do |e|
# Rollbar.warning(e)
return_error!("Duplicate key value violates unique constraint", 409)
end
rescue_from ActiveRecord::RecordInvalid do |e|
# Rollbar.error(e)
return_error!(e.message, 400)
end
rescue_from :all do |e|
# Rollbar.error(e)
status = e.try(:status) || 500
return_error!(e.message, status, e)
end
rescue_from ActiveRecord::InvalidForeignKey do |e|
# Rollbar.error(e)
return_error!("Invalid Foreign Key", 500)
end
rescue_from Grape::Exceptions::ValidationErrors do |e|
# Rollbar.error(e)
return_error!(e.message, 400)
end
rescue_from Pundit::NotAuthorizedError do |e|
# Rollbar.error(e)
return_error!("Action unathorized", 403)
end
end
end
end
|
module TicTacToe
class Player
CORNERS = ["1", "3", "7", "9"]
def initialize(board)
@board = board
end
protected
def win
check(@me)
end
def block
check(@opponent)
end
def check(side = @me)
[1,2,3].each do |i|
return true if check_row(i, side)
return true if check_column(i, side)
end
return true if check_diagonals(side)
nil
end
def mark_random_corner
index = rand(4)
(0..3).each do |i|
space = CORNERS[(index+i)%4]
if @board.spaces[space] == " "
@board.move(space, @me)
return true
end
end
false
end
def mark_random_edge
index = rand(4)
(0..4).each do |i|
space = (((index+i)*2)%8 + 2).to_s
if @board.spaces[space] == " "
@board.move(space, @me)
return true
end
end
false
end
def mark_kitty_corner
CORNERS.each do |c|
if @board.spaces[c] == @opponent
kitty_corner = (10 - c.to_i).to_s
@board.move(kitty_corner, @me)
return
end
end
end
def mark_bordered_corner(marker = @opponent)
if @board.spaces["1"] == " " && @board.spaces["2"] == marker && @board.spaces["4"] == marker
@board.move("1", @me)
return true
end
if @board.spaces["3"] == " " && @board.spaces["2"] == marker && @board.spaces["6"] == marker
@board.move("3", @me)
return true
end
if @board.spaces["7"] == " " && @board.spaces["8"] == marker && @board.spaces["4"] == marker
@board.move("7", @me)
return true
end
if @board.spaces["9"] == " " && @board.spaces["8"] == marker && @board.spaces["6"] == marker
@board.move("9", @me)
return true
end
return false
end
def mark_unbordered_corner
mark_bordered_corner(" ")
end
def check_row(i, side = @me)
left = ((i-1)*3)+1
row = left.upto(left+2).inject("") { |memo, index| memo + @board.spaces[index.to_s]}
if row.gsub(/\s/, "") == side*2
@board.move((left + row.index(" ")).to_s, @me)
return true
end
false
end
def check_column(i, side = @me)
column = (1..3).inject("") { |memo, index| memo + @board.spaces[(i + ((index-1)*3)).to_s]}
if column.gsub(/\s/, "") == side*2
@board.move((i + (column.index(" ")*3)).to_s, @me)
return true
end
false
end
def check_diagonals(side = @me)
diagonals = [["1", "5", "9"], ["3", "5", "7"]]
diagonals.each do |diagonal|
d = (0..2).inject("") { |memo, index| memo + @board.spaces[diagonal[index]]}
if d.gsub(/\s/, "") == side*2
@board.move(diagonal[d.index(" ")], @me)
return true
end
end
false
end
def edge_and_corner
corner && edge
end
def edge_and_edge
edges.count(@opponent) == 2
end
def corner(side = @opponent)
corners.include?(side)
end
def edge(side = @opponent)
edges.include?(side)
end
def edges
(1..4).map { |index| @board.spaces[(2*index).to_s]}
end
def corners
CORNERS.map { |index| @board.spaces[index]}
end
end
end
|
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
workspace 'App.xcworkspace'
project 'App.xcodeproj'
platform :ios, '10.0'
inhibit_all_warnings!
use_frameworks!
CCPod = Struct.new(:name, :version, :git, :branch)
snapkit = CCPod.new('SnapKit', '~> 4.0.0')
alamofire = CCPod.new('Alamofire', '~> 4.6')
skyFloatingLabelTextField = CCPod.new('SkyFloatingLabelTextField', '~> 3.0')
#Every pod that is used in the framework must be
#included in the main app as framework does not copy pods to target,
#so you would end up with dyld: library not loaded
["App", "AppTests"].each do |targetName|
target targetName do
inherit! :search_paths
pod snapkit.name, snapkit.version
pod skyFloatingLabelTextField.name, skyFloatingLabelTextField.version
pod alamofire.name, alamofire.version
end
end
def project_path(projectName)
return "../#{projectName}/#{projectName}"
end
target 'CCCore' do
project project_path("CCCore")
pod alamofire.name, alamofire.version
end
target 'CCComponents' do
project project_path("CCComponents")
pod snapkit.name, snapkit.version
end
target 'CCFeature0' do
project project_path("CCFeature0")
pod skyFloatingLabelTextField.name, skyFloatingLabelTextField.version
pod snapkit.name, snapkit.version
end
target 'CCFeature1' do
project project_path("CCFeature1")
pod skyFloatingLabelTextField.name, skyFloatingLabelTextField.version
pod snapkit.name, snapkit.version
end
target 'CCFeature2' do
project project_path("CCFeature2")
pod snapkit.name, snapkit.version
end
|
# By default, <code>chart</code> uses a line width of 3 for line charts.
#
# You can use the <code>:line_width</code> option to customize this value.
#
filename = File.basename(__FILE__).gsub('.rb', '.pdf')
Prawn::ManualBuilder::Example.generate(filename) do
data = {views: {2013 => 182, 2014 => 46, 2015 => 802000000000000000000}}
chart data, type: :line, line_width: 10
end
|
require 'test_helper'
class EppDomainTransferQueryTest < ApplicationIntegrationTest
def test_returns_domain_transfer_details
post '/epp/command/transfer', { frame: request_xml }, { 'HTTP_COOKIE' => 'session=api_bestnames' }
xml_doc = Nokogiri::XML(response.body)
assert_equal '1000', xml_doc.at_css('result')[:code]
assert_equal 1, xml_doc.css('result').size
assert_equal 'shop.test', xml_doc.xpath('//domain:name', 'domain' => 'https://epp.tld.ee/schema/domain-eis-1.0.xsd').text
assert_equal 'serverApproved', xml_doc.xpath('//domain:trStatus', 'domain' => 'https://epp.tld.ee/schema/domain-eis-1.0.xsd').text
assert_equal 'goodnames', xml_doc.xpath('//domain:reID', 'domain' => 'https://epp.tld.ee/schema/domain-eis-1.0.xsd').text
assert_equal 'bestnames', xml_doc.xpath('//domain:acID', 'domain' => 'https://epp.tld.ee/schema/domain-eis-1.0.xsd').text
end
def test_wrong_transfer_code
request_xml = <<-XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="https://epp.tld.ee/schema/epp-ee-1.0.xsd">
<command>
<transfer op="query">
<domain:transfer xmlns:domain="https://epp.tld.ee/schema/domain-eis-1.0.xsd">
<domain:name>shop.test</domain:name>
<domain:authInfo>
<domain:pw>wrong</domain:pw>
</domain:authInfo>
</domain:transfer>
</transfer>
</command>
</epp>
XML
post '/epp/command/transfer', { frame: request_xml }, { 'HTTP_COOKIE' => 'session=api_bestnames' }
assert_equal '2201', Nokogiri::XML(response.body).at_css('result')[:code]
end
def test_no_domain_transfer
domains(:shop).transfers.delete_all
post '/epp/command/transfer', { frame: request_xml }, { 'HTTP_COOKIE' => 'session=api_bestnames' }
assert_equal '2303', Nokogiri::XML(response.body).at_css('result')[:code]
end
private
def request_xml
<<-XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="https://epp.tld.ee/schema/epp-ee-1.0.xsd">
<command>
<transfer op="query">
<domain:transfer xmlns:domain="https://epp.tld.ee/schema/domain-eis-1.0.xsd">
<domain:name>shop.test</domain:name>
<domain:authInfo>
<domain:pw>65078d5</domain:pw>
</domain:authInfo>
</domain:transfer>
</transfer>
</command>
</epp>
XML
end
end
|
require 'bundler/setup'
require 'rack/rewrite'
require 'sinatra/base'
# The project root directory
$root = ::File.dirname(__FILE__)
use Rack::Rewrite do
app_host = ENV['APP_HOST'] || 'stevenharman.net'
old_posts = { 'a-first-step-to-better-user-experience-thinking-like-a' => 'a-first-step-to-better-user-experience-thinking-like-a-human',
'make-money-by-making-getting-paid-easy' => 'want-to-make-money-make-getting-paid-the-easy-part',
'yagni-ainrsquot-what-you-think-it-is' => 'yagni-aint-what-you-think-it-is',
'omg-better-rake-for-.net' => 'omg-better-rake-for-dot-net' }
if ENV['RACK_ENV'] == 'production'
r301 %r{.*}, %{https://#{app_host}$&}, scheme: 'http'
r301 %r{.*}, %{https://#{app_host}$&}, if: Proc.new { |rack_env|
rack_env['SERVER_NAME'] != app_host
}
end
r301 %r{^/blog/default\.aspx$}i, '/'
r301 %r{^/blog/archives\.aspx$}i, '/archives'
r301 %r{^/blog/archive/\d{4}/\d{2}/\d{2}/(.+)\.aspx$}i, '/$1'
old_posts.each { |old, new|
r301 %r{^/#{old}$}i, "/#{new}"
}
r301 %r{^(.+)/$}, '$1' # strip tailing slashes
r301 %r{^/atom$}i, '/atom.xml'
end
class SinatraStaticServer < Sinatra::Base
set :public_folder, 'public'
get(/.+/) do
send_sinatra_file(request.path) {404}
end
not_found do
send_file(File.join(File.dirname(__FILE__), 'public', '404.html'), {status: 404})
end
def send_sinatra_file(path, &missing_file_block)
file_path = File.join(File.dirname(__FILE__), 'public', path)
file_path = File.join(file_path, 'index.html') unless file_path =~ /\.[a-z]+$/i
File.exist?(file_path) ? send_file(file_path) : missing_file_block.call
end
end
run SinatraStaticServer
|
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :first_name, :last_name, :gender, :mugshot, :link, :remote_id
attr_accessor :password
before_save :encrypt_password
validates_presence_of :name
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates :email, :presence => true,
:length => {:minimum => 3, :maximum => 254},
:uniqueness => true,
:format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}
has_one :admin
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.crypted_password == BCrypt::Engine.hash_secret(password, user.salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.salt = BCrypt::Engine.generate_salt
self.crypted_password = BCrypt::Engine.hash_secret(password, salt)
end
end
def guest?
id.blank?
end
def admin?
return true if Rails.env == 'development'
not admin.nil?
end
def name
return first_name if last_name.blank?
[first_name, last_name].join(" ")
end
def gender
super || 'unknown'
end
def make_admin!
return if admin?
Admin.create(:user => self, :level => 0)
end
def to_s
name
end
end
|
# 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)
owner = User.first
500.times do |i|
Event.create!(
name: "Event#{sprintf('%03d', i)}",
place: 'Tokyo',
content: 'This is a sample event.',
start_at: Time.zone.now.since(1.day),
end_at: Time.zone.now.since(1.day).since(3.hours),
owner: owner
)
end
|
class IngredientsController < ApplicationController
def index
ingredients = Ingredient.all
options = {
include: [:recipe, :inventory_item]
}
render json: IngredientSerializer.new(ingredients, options)
end
def show
ingredient = Ingredient.find_by(id: params[:id])
options = {
include: [:recipe, :inventory_item]
}
render json: IngredientSerializer.new(ingredient, options)
end
def create
ingredient = Ingredient.new(ingredient_params)
if ingredient.save
render json: ingredient.to_json(:include => {
:recipe => {:only => [:recipe_id, :name, :ingredients]}
})
else
render json: {error: "Could not create ingredient"}
end
end
def destroy
ingredient = Ingredient.find(params[:id])
ingredient.destroy
render json: {message: "Succesfully deleted ingredient"}
end
def update
ingredient = Ingredient.find(params[:id])
ingredient.update(ingredient_params)
render json: {message: "Updated ingredient"}
end
private
def ingredient_params
params.require(:ingredient).permit(:recipe_id, :measurement, :name, :amount)
end
end
|
class CategorySerializer < ActiveModel::Serializer
attributes :id, :title, :todos
has_many :todos
end
|
module FFI
class StructLayout # [
# def initialize ;end # in ffi.rb for fixed instvars
def __get(fieldname, cbytearray)
idx = @members_dict[fieldname]
if idx._equal?(nil)
raise ArgumentError, 'invalid field name'
end
ofs = @offsets[idx]
elem_siz = @elem_sizes[idx]
if elem_siz._not_equal?(0)
if elem_siz._isFixnum # a nested array
siz = @sizes[idx]
mp = Pointer.__fromRegionOf(cbytearray, ofs, siz)
mp.__initialize(elem_siz)
mp
else # a nested Struct , elem_siz._kind_of?(Struct.class) == true
unless elem_siz._kind_of?(Struct.class)
raise TypeError, 'logic error, expected a Struct class'
end
nested_struct_cls = elem_siz
struct = nested_struct_cls.__fromRegionOf(cbytearray, ofs, elem_siz.size)
struct.__set_layout( nested_struct_cls.__cl_layout )
struct.__initialize
end
else
sel = @accessors[idx]
cbytearray.__perform_se(ofs, sel, 1) # assumes envId 1
end
end
def __put(fieldname, cbytearray, value)
idx = @members_dict[fieldname]
if idx._equal?(nil)
raise ArgumentError, 'invalid field name'
end
ofs = @offsets[idx]
elem_siz = @elem_sizes[idx]
if elem_siz._not_equal?(0)
raise ArgumentError, 'store to nested Array/Struct by value not supported'
nil
else
sel = @setters[idx]
cbytearray.__perform__se(ofs, value, sel, 1) # assumes envId 1
end
end
def size
if @closed
@totalsize
else
raise 'StructLayout build in progress'
end
end
def __offsets
@offsets
end
def offsets
# Returns an array of name, offset pairs in layout order
ofss = @offsets
syms = @members
lim = ofss.size
arr = Array.new(lim)
n = 0
while n < lim
arr[n] = [ syms[n], ofss[n] ]
n += 1
end
arr
end
def offset_of(field_name)
idx = @members_dict[field_name]
@offsets[idx]
end
def members
@members # in layout order
end
def __add_member_name(name)
if @members_dict[name]._equal?(nil)
@members_dict[name] = @members.size
else
raise 'duplicate field name #{name}'
end
end
def __check_offset(offset)
if offset._equal?(nil)
offset = @totalsize
else
unless offset._isFixnum && offset >= 0
raise TypeError, 'field offset must be a Fixnum >= 0'
end
unless offset == @totalsize
raise "specified offset #{offset} inconsistent with size+padding #{@totalsize} of previous fields"
end
end
offset
end
def __add_accessors( ctype )
rubysel = StructAccessors[ctype]
if rubysel._equal?(nil)
raise 'internal error, inconsistent StructAccessors'
end
@accessors << rubysel
rubysel = StructSetters[ctype]
if rubysel._equal?(nil)
raise 'internal error, inconsistent StructSetters'
end
@setters << rubysel
end
def __alignment
@alignment
end
def add_field(name, type, offset)
# Returns size in bytes of the added field
if @closed
raise 'cannot add more fields to a closed FFI::Struct'
end
unless name._isSymbol
raise TypeError, 'field name must be a Symbol'
end
ctype = PrimTypeDefs[type]
nstruct = nil
if ctype._equal?(nil)
if type._kind_of?(Struct.class)
nstruct = type # a nested Struct
csize = type.size
s_alignment = type.align
unless (align = @totalsize % s_alignment) == 0
@totalsize += s_alignment - align # add pad
end
if s_alignment > @alignment
@alignment = s_alignment
end
else
raise 'unrecognized field type ' , type.to_s
end
else
csize = PrimTypeSizes[ctype]
unless (align = @totalsize % csize) == 0
@totalsize += csize - align # add pad
end
if csize > @alignment
@alignment = csize
end
end
offset = self.__check_offset(offset)
self.__add_member_name(name)
@members << name
ofs = @totalsize
@offsets << ofs
if nstruct._equal?(nil)
@elem_sizes << 0
@sizes << csize
self.__add_accessors( ctype )
else
@elem_sizes << nstruct # a nested Struct
@sizes << csize
@accessors << nil
@setters << nil
end
@totalsize += csize
csize
end
def add_array(name, type, num_elements, offset)
# Returns size in bytes of the added array
if type._isSymbol
ctype = PrimTypeDefs[type]
if ctype._equal?(nil)
raise 'unrecognized array element type ' , type.to_s
end
elemsiz = PrimTypeSizes[ctype]
elsif is_a_struct?(type)
elemsiz = type.size
else
raise "invalid Type of array elements , #{type}"
end
unless num_elements._isFixnum && num_elements > 0
raise "num_elements must be a Fixnum > 0"
end
csize = elemsiz * num_elements
if csize > 100000000000
raise "total Array size must be <= 100.0e9 bytes"
end
unless (align = @totalsize % elemsiz) == 0
@totalsize += elemsiz - align # add pad
end
offset = self.__check_offset(offset)
self.__add_member_name(name)
@members << name
@offsets << @totalsize
@elem_sizes << elemsiz
@sizes << csize
@totalsize += csize
@accessors << nil # array access handled in __get ...
@setters << nil
csize
end
def close
@closed = true
end
end # ]
class UnionLayout # [
def add_field(name, type, offset)
save_size = @totalsize
@totalsize = 0
elem_siz = 0
begin
elem_siz = super(name, type, offset)
ensure
@totalsize = save_size
end
if elem_siz > save_size
@totalsize = elem_siz
end
elem_siz
end
def add_array(name, type, num_elements, offset)
save_size = @totalsize
@totalsize = 0
arr_size = 0
begin
arr_size = super(name, type, num_elements, offset)
ensure
@totalsize = save_size
end
if arr_size > save_size
@totalsize = arr_size
end
arr_size
end
end # ]
class Struct # [
def self.new(*args)
if args.size._equal?(1)
ly = @cl_layout
if ly._not_equal?(nil)
arg = args[0]
if arg._kind_of?(CByteArray)
ly_siz = ly.size
ba_siz = arg.total
if ba_siz < ly_siz
raise ArgumentError, "argument CByteArray is too small for a Struct #{self.name}"
end
inst = self.__fromRegionOf( arg, 0, ly_siz )
elsif arg._kind_of?(CPointer)
inst = self.__fromCPointer( arg , ly.size )
else
raise TypeError, "cannot construct a Struct from a #{arg.class.name}"
inst = nil
end
inst.__set_layout(ly)
inst.initialize
return inst
end
end
ly = self.layout(*args)
inst = self.__gc_malloc(ly.size)
inst.__set_layout(ly)
inst.initialize
inst
end
def self.__layout_class
StructLayout
end
def self.in
:buffer_in
end
def self.out
:buffer_out
end
def self.size
@cl_layout.size
end
def self.members
@cl_layout.members
end
def self.align
@cl_layout.__alignment
end
def self.offsets
@cl_layout.offsets
end
def self.offset_of(field_name)
@cl_layout.offset_of(field_name)
end
def size
@layout.size
end
def align
@layout.__alignment
end
def members
@layout.members
end
def values
@layout.members.map { |m| self[m] }
end
def offsets
@layout.offsets
end
def offset_of(field_name)
@layout.offset_of(field_name)
end
# def clear ; end # inherited
# def self.in # Maglev TODO
# :buffer_in
# end
# def self.out # Maglev TODO
# :buffer_out
# end
def [](field_name)
@layout.__get(field_name, self)
end
def []=(field_name, value)
@layout.__put(field_name, self, value)
end
def pointer
# result is usable as arguments to an FFI function call
self
end
def __initialize
self.initialize
self
end
protected # --------------------------------
# def self.callback(params, ret)
# mod = enclosing_module
# FFI::CallbackInfo.new(find_type(ret, mod), params.map { |e| find_type(e, mod) })
# end
private # --------------------------------
def self.enclosing_module
begin
mod = self.name.split("::")[0..-2].inject(Object) { |obj, c| obj.const_get(c) }
mod.respond_to?(:find_type) ? mod : nil
rescue Exception => ex
nil
end
end
def self.is_a_struct?(type)
type._is_a?(Class) and type < Struct
end
def self.find_type(type, mod = nil)
return type if is_a_struct?(type) or type._is_a?(::Array)
mod ? mod.find_type(type) : FFI.find_type(type)
end
def self.hash_layout(*spec)
raise "FFI::Struct hash_layout not supported by Maglev, must use array_layout"
end
def self.array_layout(*spec)
builder = self.__layout_class.new
mod = enclosing_module
i = 0
while i < spec.size
name = spec[i]
type = spec[i + 1]
if type._equal?(nil)
raise ArgumentError, "odd sized layout spec, type nil for #{name}"
end
i += 2
# If the next param is a Fixnum, it specifies the offset
offset = spec[i]
if offset._isFixnum
i += 1
else
offset = nil
end
if type._kind_of?(Class) && type < Struct
builder.add_field(name, type, offset)
elsif type._kind_of?(::Array)
builder.add_array(name, find_type(type[0], mod), type[1], offset)
else
builder.add_field(name, find_type(type, mod), offset)
end
end
builder.close
builder
end
def self.layout(*spec)
sp_size = spec.size
if sp_size._equal?(0)
return @cl_layout
end
if sp_size._equal?(1)
if spec[0]._isHash
raise "FFI::Struct hash_layout not supported by Maglev, must use array_layout"
end
raise ArgumentError , 'minimum argument size is 2'
end
cspec = spec[0]._isHash ? hash_layout(*spec) : array_layout(*spec)
unless self._equal?(Struct)
@cl_layout = cspec
end
return cspec
end
def self.__cl_layout
@cl_layout
end
def self.alloc_in
self.new
end
def self.alloc_out
self.new
end
# def initialize ; end # in ffi.rb to get fixed instvars
end # ]
class Union # [
def self.__layout_class
UnionLayout
end
end # ]
end
|
class Leave < ActiveRecord::Base
belongs_to :member
belongs_to :last_updated_by, class_name: 'Member'
validates :member, presence: true
validates :date, presence: true
default_scope -> { order(date: :desc) }
end
|
class PostsController < ApplicationController
require 'digest/md5'
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.where(state: 'published').order('created_at DESC').all
@props = @posts.map do |post|
{
created_at: post.created_at.strftime('%d %B %Y'),
title: post.title,
body: post.body,
comments: comments_for(post),
comments_url: comments_url,
id: post.id,
signed_in: current_user.present?,
gravathar: current_user.present? ? gravathar(current_user.email) : '',
post_url: post_path(post)
}
end
end
def show
@props = {
created_at: @post.created_at.strftime('%d %B %Y'),
title: @post.title,
body: @post.body,
comments: comments_for(@post),
comments_url: comments_url,
post_id: @post.id,
signed_in: current_user.present?,
login: current_user.try(:login),
gravathar: current_user.present? ? gravathar(current_user.email) : '',
post_url: post_path(@post)
}
end
private
def gravathar(email)
"https://secure.gravatar.com/avatar/#{Digest::MD5.hexdigest(email)}"
end
def set_post
@post = Post.where(permalink: params[:id]).first
end
def comments_for(post)
post.comments.map{ |comment|
{
id: comment.id,
created_at: comment.created_at.strftime('%d %B %Y'),
text: comment.text,
gravathar: gravathar(comment.user.email),
email: comment.user.email,
login: comment.user.login
}
}
end
end
|
#==============================================================================
# +++ MOG - Anti Animation Lag (v1.1) +++
#==============================================================================
# By Moghunter
# https://atelierrgss.wordpress.com/
#==============================================================================
# Este script remove as travadas (Lag) relacionadas ao dispose de uma animação.
#==============================================================================
#==============================================================================
# Durante a execução do jogo o Rpg Maker VX ACE leva um tempo considerável para
# ler ou apagar (Dispose) um arquivo. (Imagem, som ou video)
# O que acaba acarretando pequenas travadas durante o jogo, efeito perceptível
# ao usar arquivos relativamente pesados. (Arquivos de animações.)
#==============================================================================
# NOTA - Este script não elimina as travadas relacionadas ao tempo de leitura
# de uma animação, apenas ao tempo relacionado para apagar uma animação.
#==============================================================================
$imported = {} if $imported.nil?
$imported[:mog_anti_animation_lag] = true
#===============================================================================
# ■ Game_Temp
#===============================================================================
class Game_Temp
attr_accessor :animation_garbage
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
alias mog_anti_lag_animation_initialize initialize
def initialize
@animation_garbage = []
mog_anti_lag_animation_initialize
end
end
#===============================================================================
# ■ Game System
#===============================================================================
class Game_System
attr_accessor :anti_lag_animation
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
alias mog_antilag_animation_initialize initialize
def initialize
@anti_lag_animation = true
mog_antilag_animation_initialize
end
end
#===============================================================================
# ■ SceneManager
#===============================================================================
class << SceneManager
#--------------------------------------------------------------------------
# ● Call
#--------------------------------------------------------------------------
alias mog_anti_lag_animation_call call
def call(scene_class)
mog_anti_lag_animation_call(scene_class)
dispose_animation_garbage
end
#--------------------------------------------------------------------------
# ● Goto
#--------------------------------------------------------------------------
alias mog_anti_lag_animation_goto goto
def goto(scene_class)
mog_anti_lag_animation_goto(scene_class)
dispose_animation_garbage
end
#--------------------------------------------------------------------------
# ● Dispose Animation Garbage
#--------------------------------------------------------------------------
def dispose_animation_garbage
return if $game_temp.animation_garbage == nil
for animation in $game_temp.animation_garbage
animation.dispose
end
$game_temp.animation_garbage = nil
end
end
#==============================================================================
# ■ Game Map
#==============================================================================
class Game_Map
#--------------------------------------------------------------------------
# ● Setup
#--------------------------------------------------------------------------
alias mog_anti_lag_animation_setup setup
def setup(map_id)
SceneManager.dispose_animation_garbage
mog_anti_lag_animation_setup(map_id)
end
end
#==============================================================================
# ■ Scene Base
#==============================================================================
class Scene_Base
#--------------------------------------------------------------------------
# ● Terminate
#--------------------------------------------------------------------------
alias mog_anti_lag_animation_terminate terminate
def terminate
mog_anti_lag_animation_terminate
SceneManager.dispose_animation_garbage
end
end
#==============================================================================
# ■ Sprite Base
#==============================================================================
class Sprite_Base < Sprite
#--------------------------------------------------------------------------
# ● Dispose Animation
#--------------------------------------------------------------------------
alias mog_anti_lag_animation_dispose_animation dispose_animation
def dispose_animation
if $game_system.anti_lag_animation
execute_animation_garbage
return
end
mog_anti_lag_animation_dispose_animation
end
#--------------------------------------------------------------------------
# ● Execute Animation Garbage
#--------------------------------------------------------------------------
def execute_animation_garbage
$game_temp.animation_garbage = [] if $game_temp.animation_garbage == nil
if @ani_bitmap1
@@_reference_count[@ani_bitmap1] -= 1
if @@_reference_count[@ani_bitmap1] == 0
$game_temp.animation_garbage.push(@ani_bitmap1)
end
end
if @ani_bitmap2
@@_reference_count[@ani_bitmap2] -= 1
if @@_reference_count[@ani_bitmap2] == 0
$game_temp.animation_garbage.push(@ani_bitmap2)
end
end
if @ani_sprites
@ani_sprites.each {|sprite| sprite.dispose }
@ani_sprites = nil ; @animation = nil
end
@ani_bitmap1 = nil ; @ani_bitmap2 = nil
end
end |
# encoding: utf-8
$: << File.expand_path("../lib", File.dirname(__FILE__))
require "rubygems" unless defined?(Gem)
require "bundler/setup"
require "minitest/autorun"
require "minitest/hell"
require "colors"
class ColorsTest < MiniTest::Unit::TestCase
def test_should_define_colors_mames_as_methods
%w[black red green yellow blue magenta pink cyan white].each do |color_name|
assert Colors.respond_to?(color_name), "`%s' color is not defined" % color_name
end
end
end
|
class Api::V1::BooksController < Api::V1::ApiController
wrap_parameters format: [:json, :xml, :url_encoded_form, :multipart_form]
def index
@books = Book.all
render json: @books
end
def create
@book = Book.new(book_params)
if @book.save
render json: @book
else
render json: @book.errors
end
end
private
def book_params
params.require(:book).permit(:title, :description)
end
end
|
require_relative './encounter.rb'
# Factory that creates a random monster encounter based on the level of the dungeon.
class DistressedHumanoidEncounter < Encounter
def initialize(level, variation)
@variation = variation # variation can be ally or trap
@type = "distressed humanoid, #{variation}"
super(level)
end
private
def fill_description
@description = if @variation == 'ally'
'Someone requires your help! They appear to be friendly and want to join!'
else
"Someone looks to need your help! But it's a trap!"
end
end
end
|
class AddOptionToAnswer < ActiveRecord::Migration
def change
add_reference :answers, :option, index: true, foreign_key: true
add_reference :answers, :result, index: true, foreign_key: true
end
end
|
module Requests
module Balancing
extend ActiveSupport::Concern
included do
has_one :balance, class_name: 'Requests::Balance', foreign_key: :user_id
has_many :refunds, class_name: 'Requests::Refund'#, foreign_key: :issued_by
after_create :init_balance!
end
def init_balance!
return balance if balance
build_balance
save
balance
end
def has_balance?
balance.present?
end
end
end |
require 'spec_helper'
require 'libraries/example'
describe_inspec_resource 'example' do
context 'on windows' do
# This helper method here is the equivalent to the first line within the environment
# that defines an os that returns a true when the names align.
# let(:platform) { 'windows' }
environment do
os.returns(windows?: true, linux?: false)
command('C:\example\bin\example.bat --version').returns(stdout: '0.1.0 (windows-build)')
end
its(:version) { should eq('0.1.0') }
end
context 'on linux' do
let(:platform) { 'linux' }
environment do
command('/usr/bin/example --version').returns(stdout: '0.1.0 (GNULinux-build)')
end
its(:version) { should eq('0.1.0') }
end
end |
class MergeAndReassociateTypos < ActiveRecord::Migration[6.1]
def change
# NB: irreversible!
# Create temporary columns to keep track of associations
add_column :typos, :context_id, :integer
add_column :samples, :typo_id, :integer
# Join typos and contexts (formerly periods and site_phases)
execute %(
INSERT INTO typos
(name, approx_start_time, approx_end_time, created_at, updated_at, parent_id, context_id)
SELECT
name, approx_start_time, approx_end_time, created_at, updated_at, parent_id,
site_phase_id AS context_id
FROM typos
INNER JOIN periods_site_phases
ON typos.id = periods_site_phases.period_id
)
# Repeat for typochronological_units (merging into typos)
execute %(
INSERT INTO typos
(name, approx_start_time, approx_end_time, created_at, updated_at, parent_id, context_id)
SELECT
name, approx_start_time, approx_end_time, created_at, updated_at, parent_id,
site_phase_id AS context_id
FROM typochronological_units
INNER JOIN site_phases_typochronological_units
ON typochronological_units.id = site_phases_typochronological_units.typochronological_unit_id
)
# Remove unjoined data from typos
execute "DELETE FROM typos WHERE context_id IS NULL"
# Create associations path typo->xron->sample->context using temporary columns
add_reference :xrons, :typo
execute %(
INSERT INTO xrons
(typo_id, created_at, updated_at, measurement_state_id)
SELECT
id AS typo_id,
created_at, updated_at,
1 AS measurement_state_id
FROM typos
)
execute %(
INSERT INTO samples
(created_at, updated_at, context_id, typo_id)
SELECT
created_at, updated_at, context_id,
id AS typo_id
FROM typos
)
execute "UPDATE xrons SET sample_id = samples.id FROM samples WHERE xrons.typo_id = samples.typo_id"
# Drop temporary columns
remove_column :samples, :typo_id
remove_column :typos, :context_id
# Drop typochronological_units
drop_table :typochronological_units
end
end
|
require 'socket'
module ArtNetServer
class Server
include UdpSocket
def initialize
@counter = 0
end
def run
@counter += 1
send_message("hello #{@counter}")
end
def send_quit_message
send_message('quit')
end
end
end
|
class Users::RegistrationsController < Devise::RegistrationsController
def if_user_exist?
respond_to do |format|
@user = User.find_by(username: params[:username])
if @user.nil?
format.json { head :no_content}
else
format.json { head :not_acceptable}
end
end
end
end |
class PostCategory < ActiveRecord::Base
has_and_belongs_to_many :posts
validates_uniqueness_of :title
# open up everything for mass assignment
attr_protected
end
|
# frozen_string_literal: true
class Hand < Cardset
# Can accept cards from the deck
def receive(cards)
@cards += cards
end
# Human readable list of cards
def to_s
@cards.join ', '
end
def points
result = @cards.inject(0) { |sum, c| sum + c.points }
# Ace can be 1 and can be 11 (11 by default).
# Lets correct points number as it was 1
# if actor has too many points.
if result > 21
# supposed that actor can't have more then 3 cards
# and more then 3 Aces.
case @cards.select {|c| c.name == 'Ace'}.size
when 1, 2
result -= 10
when 3
result -= 20
else
# do nothing if there's no Aces
end
end
result
end
# Player looses if he has to many of points
def overheat?
points > 21
end
end
|
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2023, by Samuel Williams.
require_relative 'format/safe'
module Console
module Format
def self.default
Safe.new(format: ::JSON)
end
def self.default_json
self.default
end
end
end
|
require "test_helper"
class CollectionSearchingTest < MiniTest::Unit::TestCase
def setup
@app, @stubs = make_application({parallel:true})
@items = @app[:items]
@query = "foo"
@limit = 100
@total = 110
@make_listing = lambda{|i| make_kv_listing(:items, key: "item-#{i}", reftime: nil, score: @total-i/@total*5.0) }
@handle_offset = lambda do |offset|
case offset
when nil
{ "results" => 100.times.map{|i| @make_listing.call(i)}, "count" => 100, "total_count" => @total,
"next" => "/v0/items?query=foo&offset=100&limit=100"}
when "100"
{ "results" => 10.times.map{|i| @make_listing.call(i+100)}, "count" => 10, "total_count" => @total }
else
raise ArgumentError.new("unexpected offset: #{env.params['offset']}")
end
end
@called = false
@stubs.get("/v0/items") do |env|
@called = true
assert_equal @query, env.params['query']
assert_equal @limit, env.params['limit'].to_i
body = @handle_offset.call(env.params['offset'])
[ 200, response_headers, body.to_json ]
end
end
def test_basic_search
results = @items.search("foo").map{|i| i }
assert_equal 110, results.length
results.each_with_index do |item, idx|
assert_in_delta (@total-idx/@total * 5.0), item[0], 0.005
assert_equal "item-#{idx}", item[1].key
assert_nil item[1].reftime
end
end
def test_basic_as_needed
@limit = 50
offset = 10
@handle_offset = lambda do |o|
case o
when "10"
{ "results" => 50.times.map{|i| @make_listing.call(i+offset) }, "count" => @limit, "total_count" => @total,
"next" => "/v0/items?query=foo&offset=#{offset+@limit}&limit=#{@limit}"}
else
raise ArgumentError.new("unexpected offset: #{o}")
end
end
results = @items.search("foo").offset(offset).take(@limit)
assert_equal 50, results.length
results.each_with_index do |item, idx|
assert_in_delta (@total-(idx+10)/@total * 5.0), item[0], 0.005
assert_equal "item-#{idx+10}", item[1].key
assert_nil item[1].reftime
end
end
def test_in_parallel_prefetches_enums
items = nil
@app.in_parallel { items = @app[:items].search("foo").each }
assert @called, "enum wasn't prefetched inside in_parallel"
assert_equal @total, items.to_a.size
end
def test_in_parallel_prefetches_lazy_enums
return unless [].respond_to?(:lazy)
items = nil
@app.in_parallel { items = @app[:items].search("foo").lazy.map{|d| d } }
assert @called, "lazy wasn't prefetched from in_parallel"
assert_equal @total, items.force.size
end
def test_in_parallel_raises_if_forced
assert_raises Orchestrate::ResultsNotReady do
@app.in_parallel { @app[:items].search("foo").to_a }
end
end
def test_enums_prefetch
items = nil
@app.in_parallel { items = @app[:items].search("foo").each }
assert @called, "enum wasn't prefetched"
assert_equal @total, items.to_a.size
end
def test_lazy_enums_dont_prefetch
return unless [].respond_to?(:lazy)
items = @app[:items].search("foo").lazy.map{|d| d }
refute @called, "lazy was prefetched outside in_parallel"
assert_equal @total, items.force.size
end
end
|
require 'rails_helper'
RSpec.describe ShortVisitsController, type: :controller do
before(:each) do
@user = FactoryGirl.create(:user)
@short_url = FactoryGirl.create(:short_url, {user: @user})
@short_visit = FactoryGirl.create(:short_visit, {short_url: @short_url})
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials(@user.api_token)
end
it "can get a short visit entry geolocated" do
get :geolocate, {id: @short_visit.id, short_url_id: @short_url.id, email: @user.email, api_token: @user.api_token}
@short_visit.reload
expect(@short_visit.visitor_ip).to eq('68.180.194.243')
expect(@short_visit.visitor_city).to eq('Sunnyvale')
expect(@short_visit.visitor_state).to eq ('California')
expect(@short_visit.visitor_country_iso2).to eq ('US')
end
it "index" do
FactoryGirl.create(:short_visit, {short_url: @short_url})
get :index, {short_url_id: @short_url.id, email: @user.email, api_token: @user.api_token}
expect(JSON.parse(response.body)['data'].count).to eq(2)
end
it "show" do
get :show, {id: 1, short_url_id: @short_url.id, email: @user.email, api_token: @user.api_token}
expect(JSON.parse(response.body)['data']['attributes']['visitor-ip']).to eq('68.180.194.243')
end
end |
class RanameFriendsColumn < ActiveRecord::Migration
def up
rename_column :user_preferences, :friend_on_sidekick, :friends_on_sidekick
end
def down
end
end
|
class EmployeesController < ApplicationController
before_action :logged_in_user
def index
@employees = Employee.all
@employers = Employer.all
end
def show
@employee = Employee.find(params[:id])
@employer = @employee.employer
@timesheets = @employee.timesheets
@budgets = @employee.budgets.distinct.order(:id)
end
def new
@employee = Employee.new
@employer = Employer.new
end
def create
@employee = Employee.new(employee_params)
if @employee.save
flash[:success] = "Employee created"
redirect_to employees_path
else
flash.now[:danger] = "Employee was not created"
render 'new'
end
end
def edit
@employee = Employee.find(params[:id])
@employer = @employee.employer
end
def update
@employee = Employee.find(params[:id])
@employer = @employee.employer
if @employee.update(employee_update_params)
flash[:success] = "Employee updated"
redirect_to employees_path
else
flash.now[:danger] = "Employee was not updated"
render 'edit'
end
end
def destroy
@employee = Employee.find(params[:id]).destroy
flash[:success] = "Employee and any associated timesheets were deleted"
redirect_to employees_path
end
private
def employee_params
params.require(:employee).permit(:employer_id, :first_name, :last_name)
end
def employee_update_params
params.require(:employee).permit(:first_name, :last_name)
end
end |
class StructureLinkService < BaseServicer
attr_accessor :physical_structure,
:audit_structure
def execute!
audit_structure.physical_structure.update(physical_structure.cloneable_attributes)
end
end
|
describe StatusController do
describe 'should return Status for every env for WEBv1 application' do
it 'should return proper status for UAT' do
get '/status/WEBv1/uat'
expect(last_response).to be_ok
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:version]).to eq '2.0.0'
expect(result[:status]).to eq 'failure'
expect(result[:deployment_date]).to be_truthy
expect(result[:log_url]).to match 'localhost:9292/status/WEBv1/uat/5/logs'
end
it 'should return proper status for dev' do
get '/status/WEBv1/dev'
expect(last_response).to be_ok
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:version]).to eq '2.0.0'
expect(result[:status]).to eq 'success'
expect(result[:deployment_date]).to be_truthy
expect(result[:log_url]).to be_truthy
end
it 'should return proper status for prod' do
get '/status/WEBv1/prod'
expect(last_response).to be_ok
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:version]).to eq '1.0.0'
expect(result[:status]).to eq 'success'
expect(result[:deployment_date]).to be_truthy
expect(result[:log_url]).to be_truthy
end
end
it 'should return 404 when there were no deployments' do
get '/status/TEST%20APPLICATION/prod'
expect(last_response.status).to eq 404
end
end
|
require File.expand_path('rm_vx_data') if false
#===============================================================================
# Vibrazione in battaglia di Holy87
# Difficoltà utente: ★
# Versione 1.1
# Licenza: CC. Chiunque può scaricare, modificare, distribuire e utilizzare
# lo script nei propri progetti, sia amatoriali che commerciali. Vietata
# l'attribuzione impropria.
#===============================================================================
# Questo script farà vibrare automaticamente il controller con attacchi critici
# in battaglia o attraverso animazioni con un determinato timing.
#===============================================================================
# Istruzioni: inserire lo script sotto Materials prima del Main.
#
# Se si vuole assegnare un effetto speciale all'animazione, aggiungere una
# nuova voce in Tempismo SE e Flash dell'animazione, selezionare il frame
# desiderato, impostare flash su bersaglio e COLORE ROSSO A 1.
# Quindi, modificare Forza (del colore) per modificare la forza della vibrazione
# e durata per la durata.
# Novità della versione 1.1:
# Puoi impostare separatamente la forza della vibrazione destra o sinistra!
# Regola il colore verde nell'FX per la vibrazione sinistra e il colore blu
# per la vibrazione destra!
#
# Sotto è possibile configurare i testi per le voci e i comandi personalizzabili.
#===============================================================================
#===============================================================================
# ** IMPOSTAZIONI SCRIPT
#===============================================================================
module VibrationConfig
# Vibrazione con critico su nemico | Forza SX | Forza DX | Durata
CRITICAL_ENEMY = [ 100, 100, 30 ]
# Vibrazione con critico su alleato
CRITICAL_ALLY = [ 75, 75, 30 ]
#--------------------------------------------------------------------------
# * Valore di rosso che determinerà il timing della vibrazione nella
# sequenza di animazione
#--------------------------------------------------------------------------
VIBRATION_ACTIVATE = 1
end
#===============================================================================
# ** ATTENZIONE: NON MODIFICARE SOTTO QUESTO SCRIPT SE NON SAI COSA TOCCARE! **
#===============================================================================
$imported = {} if $imported == nil
$imported['H87-Vibration'] = 1.1
#===============================================================================
# ** RPG::Animation
#-------------------------------------------------------------------------------
# Vibration info
#===============================================================================
module RPG
class Animation
#===============================================================================
# ** RPG::Animation::Vibration_Info
#-------------------------------------------------------------------------------
# Vibration info
#===============================================================================
class Vibration_Info
attr_accessor :left_force
attr_accessor :right_force
attr_accessor :neutral_force
#---------------------------------------------------------------------
# * Object initialization
# @param [Color] color
#---------------------------------------------------------------------
def initialize(color = nil)
@left_force = 0
@right_force = 0
@neutral_force = 0
set_vibration(color) if color
end
#---------------------------------------------------------------------
# * Set vibration info
# @param [Color] color
#---------------------------------------------------------------------
def set_vibration(color)
self.left_force = color.green * 100 / 255
self.right_force = color.blue * 100 / 255
self.neutral_force = color.alpha * 100 / 255
end
#---------------------------------------------------------------------
# * Returns the total amount of vibration
#---------------------------------------------------------------------
def total_vibration; @right_force + @left_force + @neutral_force; end
end
#===============================================================================
# ** RPG::Animation::Timing
#-------------------------------------------------------------------------------
# adding vibration method
#===============================================================================
class Timing
#---------------------------------------------------------------------
# * Returns vibration strenght and cancels the flash target
# @return [Vibration_Info]
#---------------------------------------------------------------------
def vibration
if @vibration.nil?
@vibration = Vibration_Info.new
if @flash_scope == 1 && @flash_color.red == VibrationConfig::VIBRATION_ACTIVATE
@vibration.set_vibration(@flash_color)
@flash_scope = 0
end
end
@vibration
end
end
end
end
#===============================================================================
# ** Game_Battler
#-------------------------------------------------------------------------------
# Vibration on critical damage
#===============================================================================
class Game_Battler < Game_BattlerBase
alias h87vib_apply_critical apply_critical unless $@
#--------------------------------------------------------------------------
# * Apply critical
#--------------------------------------------------------------------------
def apply_critical(damage)
apply_vibration
h87vib_apply_critical(damage)
end
#--------------------------------------------------------------------------
# * Apply vibration on critical damage
#--------------------------------------------------------------------------
def apply_vibration
str = actor? ? VibrationConfig::CRITICAL_ALLY : VibrationConfig::CRITICAL_ENEMY
Input.vibrate(str[0], str[1], str[2])
end
end
#===============================================================================
# ** Sprite_Base
#-------------------------------------------------------------------------------
# Vibration on animation timing
#===============================================================================
class Sprite_Base < Sprite
alias h87vibr_apt animation_process_timing unless $@
#--------------------------------------------------------------------------
# * Adds vibration check to the animation
# @param [RPG::Animation::Timing] timing
#--------------------------------------------------------------------------
def animation_process_timing(timing)
if timing && timing.vibration.total_vibration > 0
left_v = timing.vibration.left_force + timing.vibration.neutral_force
right_v = timing.vibration.right_force + timing.vibration.neutral_force
left_v, right_v = right_v, left_v if @ani_mirror
Input.vibrate(left_v, right_v, timing.flash_duration * @ani_rate)
end
h87vibr_apt(timing)
end
end |
Given /^an empty (\w+) document collection$/ do |doc|
klass = doc.constantize
step "an empty #{klass.collection_name} collection"
end
Given /^an? (\w+) document named '(.*)' :$/ do |doc, name, table|
@all = []
klass = doc.constantize
table.hashes.each do |hash|
@last = klass.new
hash.each do |attr, value|
@last.send("#{attr.underscore.gsub(' ', '_')}=", value)
end
@all << @last
end
instance_variable_set("@#{name}", @last)
end
Given /^'(.*)' has one (.*?) as (.*) :$/ do |doc_name, class_name, assoc_name, table|
doc = instance_variable_get("@#{doc_name}")
obj = class_name.constantize.new
table.hashes.each do |hash|
hash.each do |key, value|
obj.send("#{key.underscore.gsub(' ', '_')}=", value)
end
end
doc.send("#{assoc_name.underscore.gsub(' ', '_')}=", obj)
@last = obj
end
Given /^'(.*)' has (?:a|an|many) (.*) :$/ do |doc_name, assoc_name, table|
doc = instance_variable_get("@#{doc_name}")
table.hashes.each do |hash|
doc.send(assoc_name).build(hash.inject({}) do |attrs, (attr, value)|
attrs["#{attr.underscore.gsub(' ', '_')}"] = value
attrs
end)
end
@all = doc.send(assoc_name)
@last = @all.last
end
Given /^I set the id on the document '(.*)' to (.*)$/ do |doc_name, value|
doc = instance_variable_get("@#{doc_name}")
doc._id = BSON::ObjectId.from_string("%024x" % value.to_i(16))
end
Given /^'(.+)' has one (.+?) as (.+?) \(identified by '(.+)'\):$/ do |doc_name, class_name, assoc_name, var_name, table|
doc = instance_variable_get("@#{doc_name}")
obj = class_name.constantize.new
table.hashes.each do |hash|
hash.each do |key, value|
obj.send("#{key.underscore.gsub(' ', '_')}=", value)
end
end
instance_variable_set("@#{var_name}", obj)
doc.send("#{assoc_name.underscore.gsub(' ', '_')}=", obj)
@last = obj
end
When /^I save the document '(.*)'$/ do |name|
object = instance_variable_get("@#{name}")
@last_return = object.save
end
When /^I save the last document$/ do
@last_return = @last.save
end
When /^I create an (.*) '(.*)' from the hash '(.*)'$/ do |doc, name, hash|
klass = doc.constantize
attrs = instance_variable_get("@#{hash}")
instance_variable_set("@#{name}", klass.create(attrs))
end
When /^I update the document '(.*)' with the hash named '(.*)'$/ do |doc_name, hash_name|
doc = instance_variable_get("@#{doc_name}")
attrs = instance_variable_get("@#{hash_name}")
@last_return = doc.update_attributes(attrs)
end
When /^I query (.*) with criteria (.*)$/ do |doc, criteria_text|
klass = doc.singularize.camelize
@query = @last_return = eval("#{klass}.criteria.#{criteria_text}")
end
When /^I query (.*) with the '(.*)' id$/ do |doc, name|
klass = doc.singularize.camelize.constantize
doc = instance_variable_get("@#{name}")
@query = @last_return = klass.criteria.id(doc.id).entries
end
When /^I find a (.*) using the id of '(.*)'$/ do |type, doc_name|
klass = type.camelize.constantize
doc = instance_variable_get("@#{doc_name}")
@last_return = klass.find(doc.id)
end
When /^'(.+)' is the first (.+?) of '(.+)'$/ do |var_name, single_assoc, doc_name|
doc = instance_variable_get("@#{doc_name}")
instance_variable_set("@#{var_name}", doc.send(single_assoc.pluralize).first)
end
Then /^'(.*)' is not a new record$/ do |name|
instance_variable_get("@#{name}").new_record?.should be_false
end
Then /the (.*) collection should have (\d+) documents?/ do |doc, count|
klass = doc.constantize
klass.count.should == count.to_i
end
Then /^the document '(.*)' roundtrips$/ do |name|
object = instance_variable_get("@#{name}")
from_db = object.class.find_one(object._id)
from_db.should == object
instance_variable_set("@#{name}", from_db)
end
Then /^the document '(.+)' does not roundtrip$/ do |name|
object = instance_variable_get("@#{name}")
from_db = object.class.find_one(object._id)
from_db.should_not == object
end
Then /^the document '(\w+)' is reloaded$/ do |name|
object = instance_variable_get("@#{name}")
from_db = object.class.find_one(object._id)
instance_variable_set("@#{name}", from_db)
end
Then /^the last return value is (.+)$/ do |bool_val|
@last_return.should send("be_#{bool_val}")
end
Then /^the first (.*) of '(.*)' is not a new record$/ do |assoc, name|
object = instance_variable_get("@#{name}")
plural = assoc.pluralize
object.send(plural).first.should_not be_new_record
end
Then /^the (\w*) of '(.*)' is not a new record$/ do |assoc, name|
object = instance_variable_get("@#{name}")
object.send(assoc).should_not be_new_record
end
Then /^the (\w*) of '(.*)' roundtrips$/ do |assoc, name|
object = instance_variable_get("@#{name}")
from_db = object.class.find_one(object._id)
object.send(assoc).id.should == from_db.send(assoc).id
end
Then /^the size of the last return value is (.*)$/ do |count|
@last_return.size.should == count.to_i
end
|
puts "Hello welcome to Caesar's Cypher"
puts "The old chap used a cryptographic method to encode his messages and letters"
puts "How? Shift each letter in the alphabet by a certain number. "
puts "What sentence do you want to encode?"
def cypher(string, shift=5)
code = string.split(//)
code_table =* ("a".."z")
alphabet =* ("a".."z")
shift.times do
code_table.push(code_table.first)
code_table.shift
end
code.each do |x|
if /[[:upper:]]/.match(x)
x.downcase!
flag = true
end
if /[a-z]/.match(x)
x.replace(code_table[alphabet.index(x)])
x.upcase! if flag == true
end
end
puts code.join
end
cypher(gets.chomp) |
class Task < ApplicationRecord
belongs_to :user
has_many :taggings
has_many :tags, through: :taggings, dependent: :destroy
validates :title, :subject, :start_time, :end_time, :priority, presence: true
validates :title, uniqueness: {scope: :user_id}
validate :end_time_after_start_time
scope :search_task, -> (keyword) { where("title LIKE ? OR subject LIKE ?", "%#{keyword}%", "%#{keyword}%") if keyword }
scope :search_by_tag, -> (tag) { joins(:tags).where("tags.name LIKE ?", "%#{tag}%") if tag }
scope :search_by_state, -> (state) { where(state: state) if state }
enum priority: { low: 0, medium: 1, high: 2 }
def self.sort_tasks(params)
if params[:order_by_created_time]
Task.order(created_at: params[:order_by_created_time])
elsif params[:order_by_end_time]
Task.order(end_time: params[:order_by_end_time])
elsif params[:order_by_priority]
Task.order(priority: params[:order_by_priority])
else
Task.order(created_at: :DESC)
end
end
def end_time_after_start_time
return if end_time.blank? || start_time.blank?
if end_time < start_time
errors.add(:end_time, I18n.t('activerecord.errors.models.task.attributes.end_time_after_start_time'))
# TODO 這裡的錯誤訊息用英文寫死,翻譯的話到 view 再翻譯
end
end
# Getter
def tag_list
tags.map{ |t| t.name }.join(',')
end
# Setter
def tag_list=(names)
self.tags = names.split(',').map do |name|
Tag.where(name: name.strip).first_or_create # first_or_create:如果沒有的話就建立並存入資料庫
end
end
end
|
module Api
class CustomersController < ApplicationController
skip_before_action :verify_authenticity_token
def index; end
def show
customer = find_customer
render_response(customer)
end
def create
customer = CreateCustomerServices.new(customer_params).create
render json: customer
end
def update
customer = find_customer
customer.update(customer_params) if customer.present?
render_response(customer)
end
private
def customer_params
params.require(:customer).permit(:name, :email)
end
def find_customer
customer = Customer.find_by(account_number: params[:id])
raise404 if customer.nil?
customer
end
def render_response(customer)
return render json: { body: "No se encontro el número de cuenta #{params[:id]}", status: :not_found } if customer.nil?
return render json: { errors: customer.errors.messages } if customer.present? && customer.errors.present?
render json: customer
end
end
end
|
class AddSorteotToJugadalots < ActiveRecord::Migration[5.0]
def change
add_reference :jugadalots, :sorteot, foreign_key: true
end
end
|
class CreateKptBoards < ActiveRecord::Migration
def change
create_table :kpt_boards do |t|
t.integer :project_id, :null => false
t.string :title, :null => false, :limit => 80
t.integer :keeps_count, :null => false, :default => 0
t.integer :problems_count, :null => false, :default => 0
t.integer :tries_count, :null => false, :default => 0
t.boolean :locked, :null => false, :default => false
t.datetime :created_at
end
add_index :kpt_boards, :project_id
add_index :kpt_boards, :created_at
end
end
|
class SendMessageMutation < Types::BaseMutation
description "Sends a message to the specified number"
argument :to, Types::PhoneNumberType, required: true
argument :body, String, required: false
argument :media, [Types::ActiveStorageSignedIdType], required: false, default_value: []
field :conversation, Outputs::ConversationType, null: true
field :message, Outputs::MessageType, null: true
field :errors, resolver: Resolvers::Error
policy ApplicationPolicy, :logged_in?
def authorized_resolve
result = SendMessage.new(send_message_args).call
if result.success?
{conversation: result.conversation, message: result.message, errors: []}
else
{conversation: nil, message: nil, errors: result.errors}
end
end
private
def send_message_args
{
to: input.to,
from: current_user,
body: input.body,
media: input.media,
}
end
end
|
# Copyright 2013 Claude Mamo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'java'
require 'jruby/core_ext'
require 'web_service_definition'
require 'jruby_service_configuration'
require 'jruby_cxf_non_spring_servlet'
java_import javax.xml.namespace.QName
module CXF
module WebServiceServlet
include CXF::WebServiceDefinition
def self.included(base)
base.extend(self)
end
# required to avoid inheritance
def method_missing(m, *args, &block)
@proxy_servlet.send(m, *args, &block)
end
def initialize(path = '/')
web_service_definition = get_web_service_definition(self)
service_factory = create_service_factory({service_name: web_service_definition[:service_name],
service_namespace: web_service_definition[:service_namespace],
endpoint_name: web_service_definition[:endpoint_name],
declared_methods: web_service_definition[:methods]})
data_binder = create_data_binder(web_service_definition[:complex_types])
server_factory = create_server_factory({service_factory: service_factory,
data_binder: data_binder,
path: path,
service_bean: self.class.become_java!.newInstance})
@proxy_servlet = JRubyCXFNonSpringServlet.new
@proxy_servlet.server_factory = server_factory
end
private
def get_web_service_definition(web_service)
declared_methods = {}
found_complex_types = {}
web_service_definition = web_service.class.web_service_definition
web_service_definition['exposed_methods'] = {} if not web_service_definition.has_key? 'exposed_methods'
web_service.methods.each{ |method|
if web_service_definition['exposed_methods'].has_key? method
in_parameter_names = []
web_service_definition['exposed_methods'][method].each{|config_key, config_value|
if config_key == :expects
config_value.each { |expect|
found_complex_types = find_complex_types(expect.values.first, found_complex_types)
in_parameter_names << expect.keys.first.to_s
}
end
}
unless web_service_definition['exposed_methods'][method][:label].nil?
method_label = web_service_definition['exposed_methods'][method][:label].to_s
end
unless web_service_definition['exposed_methods'][method][:response_wrapper_name].nil?
response_wrapper_name = web_service_definition['exposed_methods'][method][:response_wrapper_name].to_s
end
unless web_service_definition['exposed_methods'][method][:out_parameter_name].nil?
out_parameter_name = web_service_definition['exposed_methods'][method][:out_parameter_name].to_s
end
declared_methods[method.to_s] = { in_parameter_names: in_parameter_names,
label: method_label,
response_wrapper_name: response_wrapper_name,
out_parameter_name: out_parameter_name }
end
}
return { methods: declared_methods,
complex_types: found_complex_types,
service_name: web_service_definition['service_name'],
service_namespace: web_service_definition['service_namespace'],
endpoint_name: web_service_definition['endpoint_name'] }
end
def create_data_binder(complex_types)
data_binder = org.jrubycxf.aegis.databinding.AegisDatabinding.new
aegis_context = org.jrubycxf.aegis.AegisContext.new
opts = org.jrubycxf.aegis.type.TypeCreationOptions.new
opts.set_default_min_occurs(1);
opts.set_default_nillable(false)
opts.set_complex_types(complex_types.to_java)
aegis_context.set_type_creation_options(opts)
data_binder.set_aegis_context(aegis_context)
return data_binder
end
def create_service_factory(config)
service_factory = org.apache.cxf.service.factory.ReflectionServiceFactoryBean.new;
service_configuration = JRubyServiceConfiguration.new
service_configuration.service_namespace = config[:service_namespace]
service_configuration.service_name = config[:service_name]
service_configuration.declared_methods = config[:declared_methods]
service_factory.get_service_configurations.add(0, service_configuration)
unless config[:endpoint_name].nil?
service_factory.set_endpoint_name(QName.new(config[:endpoint_name].to_s))
end
return service_factory
end
def create_server_factory(config)
server_factory = org.apache.cxf.frontend.ServerFactoryBean.new;
server_factory.set_service_factory(config[:service_factory])
server_factory.set_data_binding(config[:data_binder])
server_factory.set_service_bean(config[:service_bean])
server_factory.set_address(config[:path])
return server_factory
end
def find_complex_types(complex_type, found_complex_types)
if is_complex_type? complex_type
complex_type_class = Kernel.const_get(complex_type)
complex_type_java_class = get_java_type(complex_type).to_s
found_complex_types[complex_type_java_class] ||= {}
if complex_type_class.complex_type_definition.has_key? 'namespace'
found_complex_types[complex_type_java_class]['namespace'] = complex_type_class.complex_type_definition['namespace'].to_s
end
complex_type_class.complex_type_definition['members'].each{ |member_name, definition|
found_complex_types[complex_type_java_class] ||= {}
found_complex_types[complex_type_java_class][definition[:label]] ||= {}
found_complex_types[complex_type_java_class][definition[:label]]['required'] = definition[:required]
# avoid infinite recursion
if is_complex_type?(definition[:type]) and Kernel.const_get(definition[:type].to_s) != complex_type_class
find_complex_types(definition[:type], found_complex_types)
end
}
end
return found_complex_types
end
def is_complex_type?(type)
Kernel.const_get(type.to_s).included_modules.include? CXF::ComplexType
rescue
return false
end
end
end |
Rails.application.routes.draw do
resources :hospitals, only: [] do
resources :surgeries, controller: "hospital_surgeries", only: [:index]
end
resources :surgeries, only: [:index, :show] do
resources :doctor_surgeries
end
end
|
class CatRentalRequestsController < ApplicationController
def new
@cat_request = CatRentalRequest.new
render :new
end
def create
request = CatRentalRequest.new(cat_rental_params)
if request.save
redirect_to cat_url(request.cat_id)
else
render json: request.errors.full_messages, status: 422
end
end
private
def cat_rental_params
params.require(:cat_rental_request).permit(:cat_id, :start_date, :end_date, :status)
end
end
# == Schema Information
#
# Table name: cat_rental_requests
#
# id :integer not null, primary key
# cat_id :integer not null
# start_date :date not null
# end_date :date not null
# status :string default("PENDING"), not null
# created_at :datetime not null
# updated_at :datetime not null
#
|
class AddColumnShipperidToOrders < ActiveRecord::Migration[5.1]
def change
add_column :orders, :shipper_id, :integer
end
end
|
class ModifyInvoiceItemTotalAmount < ActiveRecord::Migration
def change
rename_column :invoice_items, :total_amount, :total
change_column_default :invoice_items, :total, 0
change_column_default :invoice_items, :price, 0
change_column_default :invoice_items, :quantity, 0
end
end |
require 'rails_helper'
RSpec.describe Admin::PlansController, :type => :controller do
# This should return the minimal set of attributes required to create a valid
# Admin::Plan. As you add validations to Admin::Plan, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# 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
# Admin::PlansController. Be sure to keep this updated too.
let(:valid_session) {
{"warden.user.user.key" => session["warden.user.user.key"]}
}
xdescribe "GET index" do
it "assigns all admin_plans as @admin_plans" do
plan = Plan.create! valid_attributes
get :index, {}, valid_session
expect(assigns(:admin_plans)).to eq([plan])
end
end
xdescribe "GET show" do
it "assigns the requested admin_plan as @admin_plan" do
plan = Plan.create! valid_attributes
get :show, {:id => plan.to_param}, valid_session
expect(assigns(:admin_plan)).to eq(plan)
end
end
xdescribe "GET new" do
it "assigns a new admin_plan as @admin_plan" do
plan = Plan.create! valid_attributes
get :new, {}, valid_session
expect(assigns(:admin_plan)).to be_a_new(plan)
end
end
xdescribe "GET edit" do
it "assigns the requested admin_plan as @admin_plan" do
plan = Plan.create! valid_attributes
get :edit, {:id => plan.to_param}, valid_session
expect(assigns(:admin_plan)).to eq(plan)
end
end
xdescribe "POST create" do
describe "with valid params" do
it "creates a new Admin::Plan" do
expect {
post :create, {:admin_plan => valid_attributes}, valid_session
}.to change(Plan, :count).by(1)
end
it "assigns a newly created admin_plan as @admin_plan" do
post :create, {:admin_plan => valid_attributes}, valid_session
expect(assigns(:admin_plan)).to be_a(Plan)
expect(assigns(:admin_plan)).to be_persisted
end
it "redirects to the created admin_plan" do
post :create, {:admin_plan => valid_attributes}, valid_session
expect(response).to redirect_to(Plan.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved admin_plan as @admin_plan" do
post :create, {:admin_plan => invalid_attributes}, valid_session
expect(assigns(:admin_plan)).to be_a_new(Plan)
end
it "re-renders the 'new' template" do
post :create, {:admin_plan => invalid_attributes}, valid_session
expect(response).to render_template("new")
end
end
end
xdescribe "PUT update" do
describe "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested admin_plan" do
plan = Plan.create! valid_attributes
put :update, {:id => plan.to_param, :admin_plan => new_attributes}, valid_session
plan.reload
skip("Add assertions for updated state")
end
it "assigns the requested admin_plan as @admin_plan" do
plan = Plan.create! valid_attributes
put :update, {:id => plan.to_param, :admin_plan => valid_attributes}, valid_session
expect(assigns(:admin_plan)).to eq(plan)
end
it "redirects to the admin_plan" do
plan = Plan.create! valid_attributes
put :update, {:id => plan.to_param, :admin_plan => valid_attributes}, valid_session
expect(response).to redirect_to(plan)
end
end
describe "with invalid params" do
it "assigns the admin_plan as @admin_plan" do
plan = Plan.create! valid_attributes
put :update, {:id => plan.to_param, :admin_plan => invalid_attributes}, valid_session
expect(assigns(:admin_plan)).to eq(plan)
end
it "re-renders the 'edit' template" do
plan = Plan.create! valid_attributes
put :update, {:id => plan.to_param, :admin_plan => invalid_attributes}, valid_session
expect(response).to render_template("edit")
end
end
end
xdescribe "DELETE destroy" do
it "destroys the requested admin_plan" do
plan = Plan.create! valid_attributes
expect {
delete :destroy, {:id => plan.to_param}, valid_session
}.to change(Plan, :count).by(-1)
end
it "redirects to the admin_plans list" do
plan = Plan.create! valid_attributes
delete :destroy, {:id => plan.to_param}, valid_session
expect(response).to redirect_to(admin_plans_url)
end
end
end
|
module SmsEnum
CONFIRM = 1
DECLINE = 2
BALANCE = 3
OTHER = 4
end |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string
# last_sign_in_ip :string
# created_at :datetime not null
# updated_at :datetime not null
# is_admin :boolean default(FALSE)
# username :string
# nickname :string
# address :string
# phone :string
# birthday :date
# gender :string
# avater :string
#
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
validates :nickname, presence: { message: "请输入用戶名" }
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# 关联 #
has_many :orders
has_many :wish_lists
has_many :wish_list_items, :through => :wish_lists, :source => :product
# 将该商品加入收藏
def add_to_wish_list!(product)
wish_list_items << product
end
# 從收藏清单中删除
def remove_from_wish_list!(product)
wish_list_items.delete(product)
end
# 商品是否在使用者的收藏清单中
def is_wish_list_owner_of?(product)
wish_list_items.include?(product)
end
# 檢查 is_admin 的 boolean 值 #
def admin?
is_admin
end
end
|
class User
include MongoMapper::Document
safe
key :name, String
key :location, String
key :email, String
key :website, String
key :description, String
key :image, String
key :unit_system, String, :default => "IMPERIAL"
timestamps!
many :authorizations
many :trips
many :days, :through => :trips
def self.create_with_omniauth(auth)
user = User.new(:name => auth["info"]["name"],
:location => auth["info"]["location"],
:email => auth["info"]["email"],
:description => auth["info"]["description"],
:image => auth["info"]["image"]
)
#:website => auth["info"]["urls"].first.last,
user.authorizations.push(Authorization.new(:provider => auth["provider"], :uid => auth["uid"]))
user.save
return user
end
def self.find_by_authorization(provider, uid)
u = where('authorizations.provider' => provider, 'authorizations.uid' => uid).first
u.save if u
return u
end
def user_tags
user_tags = {}
trips.each do |t|
user_tags.merge!(t.trip_day_tags) {|k, old, new| old.to_i+new.to_i}
end
return user_tags
end
def completed(bool)
#trips.count { |t| t.complete == bool}
trips.map {|t| t.complete}.count(bool)
end
end
|
Fabricator(:review) do
rating { ["1", "2", "3", "4", "5"].sample }
comment { Faker::Lorem.paragraph }
end |
# frozen_string_literal: true
require 'test_helper'
class Employee < ::PlainModel::Model
attribute :id, :integer
attribute :name
attribute :hired_at, :time, default: -> { Time.now }
attr_accessor :_query
define_association :boss
define_association :colleagues
define_association :pets
def self._records(options)
records = %w[1 2].map do |id|
new(id: id, name: 'John', _query: options)
end
load_associations records, options[:includes]
records
end
def self._records_for_boss(records, options)
boss = new(id: '3', name: 'Jake', _query: options)
records.each { |record| record.boss = boss }
end
def self._records_for_colleagues(records, options)
colleagues = [
new(id: '4', name: 'Jane', _query: options),
new(id: '5', name: 'James', _query: options)
]
records.each { |record| record.colleagues = colleagues }
end
end
class PlainModelTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::PlainModel::VERSION
end
def test_my_model
records = Employee.where(name: 'John', hired: true).includes(:boss, colleagues: :boss).to_a
assert_equal 2, records.size
record = records.first
assert_kind_of Employee, record
assert_equal 1, record.id
assert_equal 'John', record.name
expected_query = {
where: [name: 'John', hired: true],
includes: { boss: {}, colleagues: { boss: {} } }
}
assert_equal expected_query, record._query
boss = record.boss
assert_kind_of Employee, boss
assert_equal 3, boss.id
assert_equal 'Jake', boss.name
expected_boss_query = { context: nil, includes: {}, association: :boss }
assert_equal expected_boss_query, boss._query
colleagues = record.colleagues
assert_equal 2, colleagues.size
colleague = colleagues.first
assert_kind_of Employee, colleague
assert_equal 4, colleague.id
assert_equal 'Jane', colleague.name
expected_colleague_query = { context: nil, includes: { boss: {} }, association: :colleagues }
assert_equal expected_colleague_query, colleague._query
end
def test_merge_includes
old_includes = {}
new_includes = [:foo, :baz, bar: :baz, qwe: [:asd, :zxc], foo: { baz: { asd: [:qwe] } }]
result = ::PlainModel::MergeIncludes.new(old_includes).merge(new_includes)
expected_result = {
foo: {
baz: {
asd: {
qwe: {}
}
}
},
bar: { baz: {} },
baz: {},
qwe: {
asd: {},
zxc: {}
}
}
assert_equal expected_result, result
end
end
|
# == Schema Information
# Schema version: 20110504160931
#
# Table name: cars
#
# id :integer not null, primary key
# grade :string(255)
# rate :float
# nic :float
# created_at :datetime
# updated_at :datetime
#
class Car < ActiveRecord::Base
attr_accessible :grade, :rate, :nic
has_many :employees
validates :grade, :presence => true,
:length => { :maximum => 10 },
:uniqueness => true
validates :rate, :presence => true,
:numericality => { :greater_than => -1 }
validates :nic, :presence => true,
:numericality => { :greater_than => -1 }
end
|
class Board < ApplicationRecord
# acts_as_list scope: :board
extend FriendlyId
friendly_id :name, use: :slugged
belongs_to :workspace
has_many :groups, dependent: :destroy
# create instance前給slug值,做unique網址
before_create { self.slug = SecureRandom.uuid }
validates :name, presence: true
default_scope { order(id: :desc) }
end
|
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
Rails.application.routes.draw do
# Start page
get '/pages/start_page'
root to: 'pages#start_page'
# Auth/OAuth controller/pages
get '/oauth_authentications/start'
get '/auth/:provider/callback', to: 'oauth_authentications#callback'
match '/auth/failure', to: redirect('/'), via: [:get, :post]
end
|
require 'yaml'
namespace :harmonious_dictionary do
desc "generate harmonious dictionary for use"
task(:generate => :environment) do
chinese_dictionary_path = File.join(GGA.root, 'config','harmonious_dictionary','chinese_dictionary.txt')
english_dictionary_path = File.join(GGA.root, 'config','harmonious_dictionary','english_dictionary.txt')
puts "Processing chinese words..."
tree = {}
process(chinese_dictionary_path, tree)
File.open(hash_path, "wb") {|io| Marshal.dump(tree, io)}
puts 'Done'
puts 'Processing english words...'
english_dictionary = []
process_english_words(english_dictionary_path,english_dictionary)
File.open(yaml_path, "wb") {|io| YAML::dump(english_dictionary, io)}
puts 'Done'
end
end
def process_english_words(path,list)
File.open(path, 'r') do |file|
file.each_line{|line| list << line.gsub!("\n",'') }
end
end
def process(path, tree)
File.open(path, 'r') do |file|
file.each_line do |line|
node = nil
line.chars.each do |c|
next if c == "\n" || c == "\r"
if node
node[c] ||= {}
node = node[c]
else
tree[c] ||= Hash.new
node = tree[c]
end
end
node[:end] = true
end
end
end
def hash_path
File.join(GGA.root, 'config','harmonious_dictionary','harmonious.hash')
end
def yaml_path
File.join(GGA.root, 'config','harmonious_dictionary','harmonious_english.yml')
end
|
class GarageCommand
def self.command(direction)
new.command(direction)
end
def command(dir_str)
direction = :toggle if dir_str.match?(/(toggle|garage)/i)
direction = :open if dir_str.match?(/(open)/i)
direction = :close if dir_str.match?(/(clos)/i)
direction ||= :toggle
ActionCable.server.broadcast(:garage_channel, { msg: "#{direction}Garage" })
case direction
when :open then "Opening the garage"
when :close then "Closing the garage"
when :toggle then "Toggling the garage"
end
end
end
|
require_relative '../spec_helper.rb'
require 'repository'
require 'redis'
require 'json'
describe Repository do
let(:repository) { Repository.new }
before(:each) do
@redis = Redis.new
keys = @redis.keys('*')
keys.each{ |key| @redis.del(key)}
end
context 'no data' do
it 'gets an empty list of sheets' do
expect(repository.all).to eq([])
end
end
context 'some data' do
it 'gets all stored data' do
sheet = Sheet.new('Cal')
@redis.setnx "Cal", sheet.state.to_json
sheets = repository.all
expect(sheets.size).to eq(1)
end
it 'returns data as sheets objects' do
sheet = Sheet.new('Cal')
@redis.setnx "Cal", sheet.state.to_json
sheets = repository.all
expect(sheets[0] == sheet).to be true
end
it 'retrieves skills' do
sheet = Sheet.new('Cal')
skill = Skill.new('skillz')
skill.hours = 23
sheet.add_skill skill
@redis.setnx "Cal", sheet.state.to_json
stored_skills = repository.all[0].skills
expect(stored_skills.size).to eq(1)
expect(stored_skills[0] == skill).to be true
end
it 'returns data as sheets objects' do
sheet = Sheet.new('Cal')
@redis.setnx "Cal", sheet.state.to_json
sheets = repository.all
expect(sheets[0] == sheet).to be true
end
end
context 'retrieve by name' do
it 'returns nil if name does not exist' do
expect(repository.get('nada')).to eq(nil)
end
it 'returns sheet if name is found' do
sheet = Sheet.new('Cal')
@redis.setnx "Cal", sheet.state.to_json
expect(repository.get('Cal') == sheet).to be true
end
it 'retrieves skills' do
sheet = Sheet.new('Cal')
skill = Skill.new('skillz')
skill.hours = 23
sheet.add_skill skill
@redis.setnx "Cal", sheet.state.to_json
stored_skills = repository.get('Cal').skills
expect(stored_skills.size).to eq(1)
expect(stored_skills[0] == skill).to be true
end
end
context 'adding sheet' do
it 'adds given sheet to database by name' do
sheet = Sheet.new('New Sheet')
repository.add(sheet)
expect(@redis.keys('*')[0]).to eq('New Sheet')
stored_sheet = @redis.get('New Sheet')
expect(stored_sheet == sheet.state.to_json).to be true
end
end
end
|
require 'test_helper'
# TODO: Split this file as it takes too long.
class Admin::Api::BuyerUsersTest < ActionDispatch::IntegrationTest
include FieldsDefinitionsHelpers
def setup
@provider = FactoryBot.create :provider_account, :domain => 'provider.example.com'
@provider.default_account_plan = @provider.account_plans.first
@buyer = FactoryBot.create(:buyer_account, :provider_account => @provider)
@buyer.buy! @provider.default_account_plan
@member = FactoryBot.create :user, :account => @buyer, :role => "member"
FactoryBot.create :user
host! @provider.admin_domain
end
class AccessTokenWithCallbacks < ActionDispatch::IntegrationTest
def setup
@provider = FactoryBot.create(:simple_provider)
@buyer = FactoryBot.create(:simple_buyer, provider_account: @provider)
host! @provider.admin_domain
end
test 'create action should not logout a current user' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:admin, account: @provider)
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
User.any_instance.expects(:forget_me).never
post(admin_api_account_users_path(@buyer, format: :xml),
username: 'alex', email: 'alex@alaska.hu', access_token: token.value)
assert_response :success
end
end
# Access token
test 'index (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider)
token = FactoryBot.create(:access_token, owner: user)
get(admin_api_account_users_path(@buyer, format: :xml), access_token: token.value)
assert_response :forbidden
user.admin_sections = ['partners']
user.save!
get(admin_api_account_users_path(@buyer, format: :xml), access_token: token.value)
assert_response :forbidden
token.scopes = ['account_management']
token.save!
get(admin_api_account_users_path(@buyer, format: :xml), access_token: token.value)
assert_response :success
end
test 'show (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
get(admin_api_account_user_path(@buyer, id: @member.id, format: :xml), access_token: token.value)
assert_response :success
user.role = 'admin'
user.save!
get(admin_api_account_user_path(@buyer, id: @member.id, format: :xml), access_token: token.value)
assert_response :success
end
test 'update (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
put(admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'Alex', access_token: token.value)
assert_response :success
user.role = 'admin'
user.save!
put(admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'Alex', access_token: token.value)
assert_response :success
end
test 'create (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
post(admin_api_account_users_path(@buyer, format: :xml),
username: 'alex', email: 'alex@alaska.hu', access_token: token.value)
assert_response :forbidden
user.role = 'admin'
user.save!
post(admin_api_account_users_path(@buyer, format: :xml),
username: 'alex', email: 'alex@alaska.hu', access_token: token.value)
assert_response :success
end
test 'update/activate (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
put(admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
put(activate_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
user.role = 'admin'
user.save!
put(admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
put(activate_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
end
test 'admin/member (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
put(admin_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
put(member_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
user.role = 'admin'
user.save!
put(admin_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
put(member_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
end
test 'destroy (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
User.any_instance.expects(:destroy).returns(true)
delete(admin_api_account_user_path(@buyer, format: :xml, id: @member.id), access_token: token.value)
assert_response :success
user.role = 'admin'
user.save!
User.any_instance.expects(:destroy).returns(true)
delete(admin_api_account_user_path(@buyer, format: :xml, id: @member.id), access_token: token.value)
assert_response :success
end
test 'suspend/unsuspend (access_token)' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners'])
token = FactoryBot.create(:access_token, owner: user, scopes: ['account_management'])
User.any_instance.expects(:suspend!).returns(true)
put(suspend_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
User.any_instance.expects(:unsuspend).returns(true)
put(unsuspend_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
user.role = 'admin'
user.save!
User.any_instance.expects(:suspend!).returns(true)
put(suspend_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
User.any_instance.expects(:unsuspend).returns(true)
put(unsuspend_admin_api_account_user_path(@buyer.id, id: @member.id, format: :xml),
username: 'alex', access_token: token.value)
assert_response :success
end
# Provider key
test 'buyer account not found' do
other_provider = FactoryBot.create :provider_account, :domain => 'other.example.com'
other_buyer = FactoryBot.create(:buyer_account, :provider_account => other_provider)
other_buyer.buy! other_provider.account_plans.first
get(admin_api_account_users_path(:account_id => other_buyer.id,
:format => :xml),
:provider_key => @provider.api_key)
assert_xml_404
end
test 'index' do
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key)
assert_response :success
assert_users @response.body, { :account_id => @buyer.id }
end
#TODO: dry these roles tests
test 'admins' do
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key, :role => 'admin')
assert_response :success
assert_users @response.body, { :account_id => @buyer.id, :role => "admin" }
end
test 'members' do
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key, :role => 'member')
assert_response :success
assert_users @response.body, { :account_id => @buyer.id, :role => "member" }
end
#TODO: dry these states tests
test 'actives' do
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key, :state => 'active')
assert_response :success
assert_users @response.body, { :account_id => @buyer.id, :state => "active" }
end
test 'pendings' do
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key, :state => 'pending')
assert_response :success
assert_users @response.body, { :account_id => @buyer.id, :state => "pending" }
end
test 'suspendeds' do
chuck = FactoryBot.create :user, :account => @buyer
chuck.activate!
chuck.suspend!
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key, :state => 'suspended')
assert_response :success
assert_users @response.body, {:account_id => @buyer.id, :state => "suspended"}
end
test 'invalid role' do
get(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:provider_key => @provider.api_key, :role => 'invalid')
assert_response :success
assert_empty_users @response.body
end
pending_test 'index returns fields defined'
test 'create defaults is pending member' do
post(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:username => 'chuck',
:email => 'chuck@norris.us',
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body,
{ :account_id => @buyer.id,
:role => "member", :state => "pending" })
assert User.last.pending?
assert User.last.member?
end
test "create sends no email" do
assert_no_change :of => -> { ActionMailer::Base.deliveries.count } do
post(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:username => 'chuck',
:email => 'chuck@norris.us',
:provider_key => @provider.api_key)
end
assert_response :success
end
test 'create does not creates admins nor active users' do
post(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:username => 'chuck', :role => "admin",
:email => 'chuck@norris.us', :state => "active",
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body,
{ :account_id => @buyer.id,
:role => "member",
:state => "pending" })
assert User.last.pending?
assert User.last.member?
end
test 'create also sets user password' do
post(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:username => 'chuck', :email => 'chuck@norris.us',
:password => "posted-password",
:password_confirmation => "posted-password",
:provider_key => @provider.api_key)
chuck = User.last
assert chuck.authenticate("posted-password")
assert_not_empty chuck.password_digest
end
test 'create with extra fields' do
field_defined(@provider,
{ :target => "User", "name" => "some_extra_field" })
post(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:username => 'chuck',
:email => 'chuck@norris.us',
:some_extra_field => "extra value",
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body,
{ :account_id => @buyer.id,
:extra_fields => { :some_extra_field => "extra value" }})
assert User.find_by_username("chuck")
.extra_fields["some_extra_field"] == "extra value"
end
test 'create errors' do
post(admin_api_account_users_path(:account_id => @buyer.id,
:format => :xml),
:username => 'chuck', :role => "admin",
:provider_key => @provider.api_key)
assert_response :unprocessable_entity
assert_xml_error @response.body, "Email should look like an email address"
end
test 'show' do
get(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
assert_user @response.body, { :account_id => @buyer.id, :role => "member" }
end
test 'show user not found' do
get(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => 0),
:provider_key => @provider.api_key)
assert_xml_404
end
test 'show returns fields defined' do
FactoryBot.create(:fields_definition, :account => @provider, :target => "User",
:name => "first_name")
FactoryBot.create(:fields_definition, :account => @provider, :target => "User",
:name => "last_name")
@member.update_attributes(:first_name => "name non < > &",
:last_name => "last non < > &")
get(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body,
{ :first_name => "name non < > &",
:last_name => "last non < > &" })
end
test 'show does not return fields not defined' do
@member.update_attribute :title, "title-not-returned"
assert @member.defined_fields.map(&:name).exclude?(:title)
get(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
xml = Nokogiri::XML::Document.parse(@response.body)
assert xml.xpath('.//user/title').empty?
end
test 'update does not updates state nor role' do
chuck = FactoryBot.create :user, :account => @buyer, :role => "member"
assert chuck.pending?
assert chuck.member?
put(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => chuck.id),
:username => 'chuck', :role => "admin", :state => "active",
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body,
{ :account_id => @buyer.id,
:role => "member",
:state => "pending" })
chuck.reload
assert chuck.pending?
assert chuck.member?
end
test 'update also updates password' do
chuck = FactoryBot.create :user, :account => @buyer, :role => "member"
assert_not_empty chuck.password_digest
assert chuck.authenticate('supersecret')
put(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => chuck.id,
:password => "updated-password",
:password_confirmation => "updated-password"),
:provider_key => @provider.api_key)
chuck.reload
assert_response :success
assert chuck.authenticate('updated-password')
end
test 'update also updates extra fields' do
field_defined(@provider,
{ :target => "User", "name" => "some_extra_field" })
chuck = FactoryBot.create :user, :account => @buyer, :role => "member"
put(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => chuck.id,
:some_extra_field => "extra value" ),
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body, { :account_id => @buyer.id,
:extra_fields => { :some_extra_field => "extra value" }})
chuck.reload
assert chuck.extra_fields["some_extra_field"] == "extra value"
end
test 'update not found' do
put(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => 0),
:provider_key => @provider.api_key)
assert_xml_404
end
test 'destroy' do
delete(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
assert_empty_xml @response.body
delete(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => @buyer.users.first.id),
:provider_key => @provider.api_key)
assert_response :forbidden, "last buyer's user should not be deleteable"
assert_xml_error @response.body, 'last admin'
end
test 'destroy not found' do
delete(admin_api_account_user_path(:account_id => @buyer.id,
:format => :xml, :id => 0),
:provider_key => @provider.api_key)
assert_xml_404
end
test 'member' do
chuck = FactoryBot.create :user, :account => @buyer
chuck.make_admin
put "/admin/api/accounts/#{@buyer.id}/users/#{chuck.id}/member.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, { :account_id => @buyer.id, :role => "member" }
chuck.reload
assert chuck.member?
end
test 'admin' do
chuck = FactoryBot.create :user, :account => @buyer
chuck.make_member
put "/admin/api/accounts/#{@buyer.id}/users/#{chuck.id}/admin.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, { :account_id => @buyer.id, :role => "admin" }
chuck.reload
assert chuck.admin?
end
test 'suspend an active user' do
chuck = FactoryBot.create :user, :account => @buyer
chuck.activate!
put "/admin/api/accounts/#{@buyer.id}/users/#{chuck.id}/suspend.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, {:account_id => @buyer.id, :state => "suspended"}
chuck.reload
assert chuck.suspended?
end
test 'activate a pending user' do
chuck = FactoryBot.create :user, :account => @buyer
put "/admin/api/accounts/#{@buyer.id}/users/#{chuck.id}/activate.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, {:account_id => @buyer.id, :state => "active"}
chuck.reload
assert chuck.active?
end
test 'shows error on failed user activation XML' do
user = suspended_user
put "/admin/api/accounts/#{@buyer.id}/users/#{user.id}/activate.xml?provider_key=#{@provider.api_key}"
assert_response :unprocessable_entity
assert_xml('/error') do |xml|
assert_xml xml, './from', 'suspended'
assert_xml xml, './event', 'activate'
assert_xml xml, './user', Nokogiri::XML::Document.parse(user.to_xml)
end
assert user.reload.suspended?, 'user should be suspended'
end
test 'shows error on failed user activation JSON' do
user = suspended_user
put "/admin/api/accounts/#{@buyer.id}/users/#{user.id}/activate.json?provider_key=#{@provider.api_key}"
assert_response :unprocessable_entity
res = JSON.parse(@response.body)
error = res.fetch('error')
assert_equal({ 'from' => 'suspended', 'event' => 'activate',
'error' => 'State cannot transition via "activate"'
}, error.except('object'))
assert_equal({'id' => user.id, 'state' => user.state },
error.fetch('object').fetch('user').slice('id', 'state'))
assert user.reload.suspended?, 'user should be suspended'
end
test 'activate sends no email' do
chuck = FactoryBot.create :user, :account => @buyer
assert_no_change :of => -> { ActionMailer::Base.deliveries.count } do
put "/admin/api/accounts/#{@buyer.id}/users/#{chuck.id}/activate.xml?provider_key=#{@provider.api_key}"
end
assert_response :success
chuck.reload
assert chuck.active?
end
test 'unsuspend a suspended user' do
chuck = suspended_user
put "/admin/api/accounts/#{@buyer.id}/users/#{chuck.id}/unsuspend.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, {:account_id => @buyer.id, :state => "active"}
chuck.reload
assert chuck.active?
end
protected
def active_user
user = FactoryBot.create(:user, :account => @buyer)
user.activate!
user
end
def suspended_user
user = active_user
user.suspend!
user
end
end
|
class Peep
include DataMapper::Resource
property :id, Serial
property :message, Text
belongs_to :user
end
|
# coding: utf-8
class AgreementsController < ApplicationController
before_filter :auth_required
respond_to :html, :xml, :json
def index
end
def search
@items = Agreement.order(:name).includes(:participants)
if !params[:q].blank?
@items = @items.where("(name LIKE :q) OR (details LIKE :q)", {:q => "%#{params[:q]}%"})
end
if params[:filter].to_i > 0
@items = @items.where("(status = :s AND year(start_date) = :y)", {:s => Agreement::ACTIVE, :y => params[:filter]})
end
respond_with do |format|
format.html do
render :layout => false
end
end
end
def new
@agreement = Agreement.new
render :layout => false
end
def create
raise "User watching must be equal to user logged in" if current_user.id != current_user_watching.id
params[:agreement][:user_id] = current_user.id
@agreement= Agreement.new(params[:agreement])
flash = {}
if @agreement.save
flash[:notice] = "Convenio creado satisfactoriamente."
# LOG
@agreement.activity_log.create(user_id: current_user.id,
message: "Creó el convenio \"#{@agreement.name}\" (ID: #{@agreement.id}).")
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:id] = @agreement.id
json[:title] = @agreement.name
json[:flash] = flash
render :json => json
else
render :inline => "Esta accion debe ser accesada via XHR"
end
end
end
else
flash[:error] = "No se pudo crear el convenio."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @agreement.errors
render :json => json, :status => :unprocessable_entity
else
redirect_to @agreement
end
end
end
end
end
def show
@agreement = Agreement.find(params[:id])
render :layout => false
end
def update
@agreement = Agreement.find(params[:id])
previous_status_class = @agreement.status_class
flash = {}
if @agreement.update_attributes(params[:agreement])
flash[:notice] = "Convenio actualizado satisfactoriamente."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:id] = @agreement.id
json[:title] = @agreement.name
json[:status_text] = @agreement.status_text
json[:status_class] = @agreement.status_class
json[:previous_status_class] = previous_status_class
json[:flash] = flash
render :json => json
else
render :inline => "Esta accion debe ser accesada via XHR"
end
end
end
else
flash[:error] = "No se pudo actualizar el convenio."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @agreement.errors
render :json => json, :status => :unprocessable_entity
else
redirect_to @agreement
end
end
end
end
end
end
|
require 'minitest/autorun'
require 'minitest/pride'
require './lib/Card_Generator.rb'
class TestCard_Generator <Minitest::Test
def setup
@generate = Card_Generator.new("./lib/cards.txt")
@card = []
end
def test_generator_exists
assert_instance_of Card_Generator, @generate
end
def test_create_a_card
@generate = Card_Generator.new("./test/cards_test.txt").cards
card0= @generate[0]
rank = card0.rank
suit = card0.suit
name = card0.value
assert_equal 12, rank
assert_equal :club, suit
assert_equal "Queen", name
end
def test_vaidate_cards
card = ["Jack", :heart, 11]
assert_equal false, @generate.validate_card(card)
card = ["Freddy Mercury", :ear_drum_slayer, 999]
assert_equal true, @generate.validate_card(card)
end
def test_create_deck
assert_equal 52 , @generate.cards.length
end
end
|
# 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)
require 'faker'
User.destroy_all
20.times do |index|
User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, description: Faker::Lorem.sentence(word_count: 23), email: "nom#{index}@yopmail.com")
end
20.times do
Event.create(start_date: "2019-12-25", duration: 30, title: Faker::Lorem.sentence(word_count: 5), description: Faker::Lorem.sentence(word_count: 25), price: Faker::Number.between(from: 2, to: 100), location: Faker::Nation.capital_city)
end |
class MemberStatus < ActiveRecord::Base
belongs_to :member
has_and_belongs_to_many :member_references, :class_name => 'Member'
has_many :notifications, :as => :notifiable, :dependent => :destroy
acts_as_taggable
validates_presence_of :body, :member_id
validate :empty_message
before_create :set_member_references
after_create :notify!
default_scope order('created_at desc')
def reply_to_members
(["@#{member.nickname}"] + member_references.collect {|m| "@#{m.nickname}"}).join(', ')
end
protected
def empty_message
if body.blank? or body == "What's new, #{member.nickname}?"
errors.add :body, "can't be blank"
end
end
def set_member_references
body.scan(/@\w+/) do |nickname|
if (member_referenced = Member.where('nickname ilike ?', nickname[1..-1]).first) and member_referenced.id != member_id
member_references << member_referenced
end
end
end
def notify!
member_references.each {|m| m.delay.notify!(self, "#{member.nickname} referred to you in his/her status update")}
member.member_followers.each do |m|
if not member_reference_ids.include? m.id
m.delay.notify!(self, "#{member.nickname}'s status was updated")
end
end
end
end
|
class SharedMix < ApplicationRecord
belongs_to :mix
belongs_to :user
belongs_to :dj
end
|
module Codegrade
class Commit
attr_reader :sha, :working_directory
def initialize(working_directory = '.', sha = nil)
@working_directory = File.expand_path(working_directory)
@sha = sha
end
def author
commit.author
end
def message
commit.message
end
def files
parse_git_tree(commit.tree, working_directory)
end
private
def repo
@repo ||= Rugged::Repository.new(working_directory)
end
def commit
@commit ||= sha.nil? ? repo.last_commit : repo.lookup(sha)
end
def parse_git_tree(tree, path)
files = []
return [] if commit.parents.size > 1
diff = commit.parents[0].diff(commit)
diff.deltas.each do |delta|
next if delta.status == :deleted
files.push(delta.new_file[:path])
end
files
end
end
end |
# frozen_string_literal: true
class DraScore < ApplicationRecord
has_many :dra_score_students, dependent: :destroy
has_many :students, through: :dra_score_students
validates \
:dra_level,
:rank,
presence: true,
uniqueness: true
validates \
:rank,
numericality: true
end
|
Gem::Specification.new do |s|
s.name = 'maths-units'
s.version = '0.1.0'
s.date = '2016-08-31'
s.summary = %(Maths Units)
s.description = <<EOS
== Maths Units
Conveniently convert degrees and gradians to radians, for use in
the trig functions in the `Math` module.
See the documentation at <https://github.com/phluid61/maths-units>.
EOS
s.authors = ['Matthew Kerwin'.freeze]
s.email = ['matthew@kerwin.net.au'.freeze]
s.files = Dir['lib/**/*.rb']
s.test_files=Dir['test/*.rb']
s.homepage = 'https://phluid61.github.com/maths-units'.freeze
s.license = 'ISC'.freeze
s.has_rdoc = true
end
|
#!/Users/moomindani/.rbenv/shims/ruby
# -*- coding: utf-8 -*-
# Ruby template for Google Code Jam
require 'benchmark'
class Solution
def solve(dataset)
File.open(dataset, 'r') do |input|
File.open(dataset.sub(/\.in/, '.out'), 'w') do |output|
test_cases = input.readline.to_i
1.upto(test_cases) do |test_case|
# input
tbl = []
5.times{
row = input.readline.split(//)
tbl.push(row)
}
# check row
next if put_result(output,test_case,check_row(tbl))
# check column
next if put_result(output,test_case,check_column(tbl))
# check diagonal
next if put_result(output,test_case,check_diagonal(tbl))
# check continue
next if put_result(output,test_case,check_continue(tbl))
# draw
put_result(output,test_case,4)
end
end
end
end
def put_result(output, test_case, num)
case num
when 0 # not determined
return false
when 1 # X won
puts "Case ##{test_case}: X won"
output << %Q{Case ##{test_case}: X won\n}
when 2 # O won
puts "Case ##{test_case}: O won"
output << %Q{Case ##{test_case}: O won\n}
when 3 # continue
puts "Case ##{test_case}: Game has not completed"
output << %Q{Case ##{test_case}: Game has not completed\n}
when 4 # draw
puts "Case ##{test_case}: Draw"
output << %Q{Case ##{test_case}: Draw\n}
end
return true
end
def check_row(table)
table.each{|row|
if row.join().scan(/X|T/).size == 4
return 1
elsif row.join().scan(/O|T/).size == 4
return 2
end
}
return 0
end
def check_column(table)
for i in 0..4
column = []
table.each{|row|
column.push(row[i])
}
if column.join().scan(/X|T/).size == 4
return 1
elsif column.join().scan(/O|T/).size == 4
return 2
end
end
return 0
end
def check_diagonal(table)
diagonal_1 = []
diagonal_2 = []
diagonal_index = 0
table.each{|row|
diagonal_1.push(row[diagonal_index])
diagonal_2.push(row[3-diagonal_index])
diagonal_index += 1
}
if diagonal_1.join().scan(/X|T/).size == 4
return 1
elsif diagonal_1.join().scan(/O|T/).size == 4
return 2
end
if diagonal_2.join().scan(/X|T/).size == 4
return 1
elsif diagonal_2.join().scan(/O|T/).size == 4
return 2
end
return 0
end
def check_continue(table)
table.each{|row|
if row.include?(".")
return 3
end
}
return 0
end
end
problem = Solution.new
#problem.solve('test.in')
Benchmark.bm do |x|
# x.report('small') { problem.solve('A-small-attempt0.in') }
x.report('large') { problem.solve('A-large.in') }
end
|
require 'rspec'
require 'rest_client'
require 'json'
require_relative '../../lib/config/configuration_reader'
require_relative '../../lib/config/configuration'
require_relative '../../lib/authentication/authenticator'
describe 'Authenticates' do
it 'returns the bearer token for the given username/password' do
config_reader = ConfigurationReader.new('./spec/bosh_lite_config.json')
config = config_reader.parse
authenticator = Authenticator.new config
token_response = authenticator.login "admin", "admin"
expect(token_response.access_token).not_to be_nil
expect(token_response.refresh_token).not_to be_nil
end
end |
# Object to find user linked to email from session variable
class GetTeacherInSessionVar
def initialize(token)
@token = token
end
def call
return nil unless @token
decoded_token = JWT.decode @token, ENV['MSG_KEY'], true
payload = decoded_token.first
Teacher.find_by_email(payload['email'])
end
end
|
class AddProjectReferenceToDefects < ActiveRecord::Migration
def change
add_reference :defects, :project, index: true, foreign_key: true
change_column :defects, :fixed, :boolean, default: :false
end
end
|
require 'crypto'
require 'spec_helper'
describe Solver do
let(:test_solver) { Solver.new }
# let(:test_feed) { Document.new(test_solver.get_feed('http://threadbender.com/rss.xml')) }
let(:test_feed) { REXML::Document.new(File.open('./data/test.xml')) }
let(:test_root) { test_feed.root }
subject {test_solver}
it { should respond_to(:puzzle_list, :calculations, :let_list, :dicts, :name_dict, :pop_dict, :dict_1k)}
it "should read the XML stream items" do
test_root.each_element('//item') { |item|
desc = item.delete_element('description').to_s
}
end
it "should break up the Puzzles" do
test_solver.puzzle_list.clear
x = test_solver.puzzle_list.length
test_solver.puzzle_list = test_solver.conform_puzzles(test_root)
y = test_solver.puzzle_list.length
x.should < y
end
it "should have a 4 dictionaries" do
test_solver.pop_dict[6].values.length.should be > 1100
test_solver.dicts[6].values.length.should be > 1100
test_solver.name_dict[6].values.length.should be > 100
test_solver.dict_1k[6].values.length.should be > 20
end
it "should create A list of puzzle objects" do
test_solver.puzzle_list = test_solver.conform_puzzles(test_root)
test_solver.puzzle_list[0].should be_an_instance_of(Puzzle)
end
it "should create puzzle objects with Crypto/Author/Date attribs" do
test_solver.puzzle_list = test_solver.conform_puzzles(test_root)
test_solver.puzzle_list[0].publ_date.should be_true
test_solver.puzzle_list[0].author.should be_true
test_solver.puzzle_list[0].crypto.should be_true
end
it 'should split the string at the /[.?!]"* - / point' do
a, b = test_solver.seperate_author("UWDC W FXWYFC! WII IREC RA W FXWYFC. UXC QWY LXB MBCA EVZUXCAU RA MCYCZWIIH UXC BYC LXB RA LRIIRYM UB TB WYT TWZC. - TWIC FWZYCMRC")
a.should eq("UWDC W FXWYFC WII IREC RA W FXWYFC UXC QWY LXB MBCA EVZUXCAU RA MCYCZWIIH UXC BYC LXB RA LRIIRYM UB TB WYT TWZC".downcase)
b.should eq("TWIC FWZYCMRC".downcase)
#also converts to downcase for puzzle... UPCASE reserved for solved letters
end
it "should start a puzzle by splitting and sorting words" do
test_solver.puzzle_list = test_solver.get_puzzles()
puzz = test_solver.puzzle_list[1]
puzz.crypto_broken.length.should be > 0
puzz.crypto_broken[0].length.should < puzz.crypto_broken[-1].length
puzz.crypto_broken[1].length.should < puzz.crypto_broken[-2].length
puzz.crypto_broken[2].length.should <= puzz.crypto_broken[3].length
puzz.crypto_broken[3].length.should <= puzz.crypto_broken[4].length
end
it "should return letter objects from the let_list hash" do
test_solver.set_letters([*('a'..'z')].join)
test_solver.let_list['g'].should be_kind_of(Letter)
test_solver.let_list['g'].should respond_to(:name, :possible)
end
it "should be able to switch a dictionary for a word" do
subject.set_letters(subject.puzzle_list[5].full_uniques)
solver_test_word = subject.puzzle_list[5].crypto_broken[-1]
solver_test_word = Word.new(solver_test_word, subject.dicts)
stw_pos_len = solver_test_word.possibles.length
solver_test_word.possibles = subject.try_dictionary(solver_test_word, subject.name_dict)
stw_pos_len.should_not eq(solver_test_word.possibles.length)
solver_test_word.possibles = subject.try_dictionary(solver_test_word, subject.pop_dict)
stw_pos_len.should_not eq(solver_test_word.possibles.length)
end
end
|
class Question < ActiveRecord::Base
# Relationships
has_many :indicator_questions, :dependent => :destroy
has_many :indicators, through: :indicator_questions
# Validations
validates_presence_of :question
# Scopes
scope :active, -> { where("questions.active = ?", true) }
scope :inactive, -> { where("questions.active = ?",false) }
scope :alphabetical, -> { order("question") }
scope :for_indicator, -> (indicator_id) {joins(:indicators).where("indicators.id = ?",indicator_id).group("question")}
scope :for_competency, -> (competency_id) {
joins(:indicators).where("indicators.competency_id = ?", competency_id).group("question")
}
# Methods
def self.parse(spreadsheet)
questions_sheet = spreadsheet.sheet("Questions")
questions_hash =
questions_sheet.parse(question: "Question")
questions = []
questions_hash.each_with_index do |q, index|
question = Question.new
question.attributes = q.to_hash
questions << question
end
return questions
end
end
|
require 'spec_helper'
describe_recipe 'consul::default' do
cached(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }
context 'with default attributes' do
it { expect(chef_run).to include_recipe('selinux::permissive') }
it { expect(chef_run).to create_poise_service_user('consul').with(group: 'consul') }
it { expect(chef_run).to create_consul_config('consul').with(path: '/etc/consul.json') }
it { expect(chef_run).to create_consul_service('consul').with(config_file: '/etc/consul.json') }
it { expect(chef_run).to enable_consul_service('consul').with(config_file: '/etc/consul.json') }
it 'converges successfully' do
chef_run
end
end
end
|
require 'spec_helper'
describe 'Querying Locations endpoint' do
before do
@client = Locations.new
end
context 'when given integer' do
it 'locations should return data' do
expect(@client.locations 1).not_to eq nil
end
it 'locationAreas should return data' do
expect(@client.locationAreas 1).not_to eq nil
end
it 'palParkAreas should return data' do
expect(@client.palParkAreas 1).not_to eq nil
end
it 'regions should return data' do
expect(@client.regions 1).not_to eq nil
end
end
context 'when given string' do
it 'locations should return nil' do
expect(@client.locations 'starmie').to eq nil
end
it 'locationAreas should return nil' do
expect(@client.locationAreas 'starmie').to eq nil
end
it 'palParkAreas should return data' do
expect(@client.palParkAreas 'forest').not_to eq nil
end
it 'regions should return data' do
expect(@client.regions 'kanto').not_to eq nil
end
end
context 'when given float' do
it 'locations should return nil' do
expect(@client.locations 1.1).to eq nil
end
it 'locationAreas should return nil' do
expect(@client.locationAreas 1.1).to eq nil
end
it 'palParkAreas should return nil' do
expect(@client.palParkAreas 1.1).to eq nil
end
it 'regions should return nil' do
expect(@client.regions 1.1).to eq nil
end
end
end |
require 'paypal-sdk-permissions'
class PermissionsController < ApplicationController
def show
api = PayPal::SDK::Permissions::API.new
# Build request object
permissions_request = api.build_request_permissions
permissions_request.scope = ["EXPRESS_CHECKOUT"]
permissions_request.callback = "http://localhost:3055/samples/permissions/get_access_token"
# Make API call & get response
permissions_response = api.request_permissions(permissions_request)
# Access Response
permissions_response.response_envelope
@token = permissions_response.token
end
def get_access_token
api = PayPal::SDK::Permissions::API.new
# Build request object
token_request = api.build_get_access_token
token_request.token = params["request_token"] if params["request_token"]
token_request.verifier = params["verification_code"] if params["verification_code"]
# Make API call & get response
token_response = api.get_access_token(token_request)
# Access Response
token_response.response_envelope
token_response.error
logger.info("Token is : #{token_response.token}")
logger.info("Token secret is : #{token_response.token_secret}")
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { FactoryGirl.build(:user) }
it 'should be valid' do
expect(user).to be_valid
end
it 'should have a name' do
user.name = ' '
expect(user).to_not be_valid
end
it 'should have an email' do
user.email = ' '
expect(user).to_not be_valid
end
it 'should not have a name longer than 50 characters' do
user.name = 'a' * 51
expect(user).to_not be_valid
end
it 'should not have an email longer than 255 characters' do
user.email = 'a' * 244 + '@example.com'
expect(user).to_not be_valid
end
it 'should only accept valid email addresses' do
valid_addresses = %w[user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com foo@bar..com]
valid_addresses.each do |valid_address|
user.email = valid_address
expect(user).to_not be_valid
end
end
it 'should save email address as lowercase' do
mixed_case_email = 'User@ExAMPle.CoM'
user.email = mixed_case_email
user.save
expect(user.reload.email).to eql(mixed_case_email.downcase)
end
it 'should only accept unique email addresses' do
duplicate_user = user.dup
duplicate_user.email = user.email.upcase
user.save
expect(duplicate_user).to_not be_valid
end
it 'should only accept passwords with 6 or more characters' do
user.password = user.password_confirmation = 'a' * 5
expect(user).to_not be_valid
end
it 'authenticated? should return false for a user with nil digest' do
expect(user.authenticated?(:remember, '')).to be false
end
end
|
class PostsController < ApplicationController
before_action :set_post, only: %i[ show edit update destroy]
def index
# posts = "COALESCE(title, '') LIKE '%'"
# unless params[:q].nil?
# posts = "COALESCE(title, '') LIKE '%" + params[:q] +
# "%' OR COALESCE(content, '') LIKE '%" + params[:q] + "%'"
# end
# @posts = Post.where(posts)
if params[:search]
@search_results_posts = Post.search_by_title_and_content(params[:search])
respond_to do |format|
format.js { render partial: 'search-results'}
end
else
@posts = Post.all
end
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.js { render nothing: true, notice: 'Lo creaste' }
end
end
end
def show
end
def edit
end
def update
respond_to do |format|
if @post.update!(post_params)
format.js { render nothing: true, notice: 'Lo actualizaste' }
end
end
end
def destroy
respond_to do |format|
if @post.destroy
format.js { render nothing: true, notice: 'borrado' }
end
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
def set_post
@post = Post.find(params[:id])
end
end
|
class AddNameAndAdminAndHighestLevelAndRoomsExploredAndEnemiesKilledAndEmblemAndTitleToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_column :users, :admin, :boolean
add_column :users, :highest_level, :integer
add_column :users, :rooms_explored, :float
add_column :users, :enemies_killed, :float
add_column :users, :emblem, :text
add_column :users, :title, :string
end
end
|
class Tweeet < ApplicationRecord
belongs_to :user, :optional => true
validates_length_of :tweeet, :within =>1...140
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'バリデーションテスト' do
context '作成時' do
subject(:user) { create(:user) }
it { is_expected.to be_valid }
it { is_expected.to validate_presence_of(:user_id) }
it { is_expected.to validate_presence_of(:user_name) }
# it { is_expected.to validate_presence_of(:password) }
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_length_of(:user_id) }
it { is_expected.to validate_length_of(:user_name) }
# it { is_expected.to validate_length_of(:password) }
it { is_expected.to validate_length_of(:email) }
it 'user_id, user_name, emailの値が設定済みだと成功' do
user = build(:user)
expect(user).to be_valid
end
it 'user_id, user_name, emailの値が未設定だと失敗' do
user = build(:user)
user.user_id = ''
user.user_name = ''
user.email = ''
expect(user).to_not be_valid
end
# it 'user_id, emailの値がユニークだと成功' do
# user_1 = create(:user)
# user_2 = build(:user)
# expect(user_2).to be_valid
# end
# it 'user_id, emailの値がユニークでないと失敗' do
# user_1 = create(:user)
# user_2 = build(:user)
# user_2.user_id = user_1.user_id
# user_2.email = user_1.email
# expect(user_2).to_not be_valid
# end
end
# context '更新時' do
# it 'profileの文字数が255以下だと成功' do
# user = build(:user)
# user.profile = "255以下"
# expect(user).to be_valid
# end
# it 'profileの文字数が255以上だと失敗' do
# user = build(:user)
# profile = "255以上" * 255
# user.profile = profile
# expect(user).to_not be_valid
# end
# end
end
describe "アソシエーションテスト" do
subject(:user) { create(:user)}
it { is_expected.to have_many(:posts) }
it { is_expected.to have_many(:likes) }
end
end
|
require 'test_helper'
class Api::V1::RequestControllerTest < ActionDispatch::IntegrationTest
setup do
@request = requests(:one)
end
# index
test "should get index as json" do
get :index
assert_equal "application/json", response.content_type include()
end
test "should return success" do
assert_response :success
get :index
end
# show
test "should return request" do
get request_url(@request)
assert_response :success
end
test "should show request that includes current user" do
get :show
assert_equal current_user.id, request.helpr_id || request.requester_id
end
# create
test "should create request" do
assert_difference('Request.count') do
post '/api/v1/requests', params: { request: { user_id: requests(:one).user_id, title: requests(:one).title, description: requests(:one).description, latitude: requests(:one).latitude, longitude: requests(:one).longitude, request_type: requests(:one).request_type}}, as: :json
end
assert_response :success
end
end
|
# == Schema Information
#
# Table name: visits
#
# id :integer not null, primary key
# submitter_id :integer not null
# url_id :integer not null
#
class Visit < ActiveRecord::Base
def self.record_visit!(user, shortened_url)
Visit.create!(submitter_id: user.id, url_id: shortened_url.id)
end
belongs_to :user,
foreign_key: :submitter_id,
primary_key: :id,
class_name: 'User'
belongs_to :shortened_url,
foreign_key: :url_id,
primary_key: :id,
class_name: 'ShortenedUrl'
end
|
require 'nokogiri'
require 'open-uri'
namespace :cf_affiliates do
desc "Connect to .com and import the affiliate data"
task :scrape => :environment do
ScrapeLogger = Logger.new("#{Rails.root}/log/scrape.log")
url = "http://www.crossfit.com/cf-info/main_affil.htm"
doc = Nokogiri::HTML(open(url))
@timestamp_regex = /<!-- ([0-9\-\s:]+) -->/
@raw_doc = doc
@raw_doc_timestamp = @raw_doc.inner_html.match(@timestamp_regex)[1]
unless Scrape.count.eql?(0)
ScrapeLogger.info(DateTime.now.strftime + ": Comparing " + @raw_doc_timestamp + " to " + Scrape.last.hq_timestamp)
@run_import = !@raw_doc_timestamp.eql?(Scrape.last.hq_timestamp)
else
@run_import = true
end
# Check to see if it's more up to date than our current version
if @run_import.eql?(true)
ScrapeLogger.info(DateTime.now.strftime + ": Running update") # Log that this ran
puts "Running update"
@scrape = Scrape.new # Save the scrape!
@scrape.raw_html = @raw_doc.inner_html
@scrape.hq_timestamp = @raw_doc_timestamp
@scrape.save
# Create array for each affiliate that we added
@new_affiliate_array = []
@affiliates_div = @raw_doc.inner_html
@regex_for_each_line = /(<a.*?br\s?\/?>)/
@affiliates_array = @affiliates_div.scan(@regex_for_each_line)
ScrapeLogger.info(DateTime.now.strftime + ": Affiliates Count = " + @affiliates_array.count.to_s) # Log that this ran
puts "Affiliate count: " + @affiliates_array.count.to_s
unless @affiliates_array.blank?
@affiliates_array.each do |scrape_line|
# Regex Pattern
# Epic Regex Winnings!
# /(<a href="(http:\/\/[A-Za-z0-9\/\.]+)" target="_blank">([\w\s]+)<\/a>([\w\s\-,&;]+)?<br>)/
# a[0] = the whole string
# a[1] = website url
# a[2] = affiliate title
# a[3] = location data TODO:This needs parsing and saving
# @regex = /(<a href="(http:\/\/[A-Za-z0-9\/\.\-]+)" target="_blank">([\w\s]+)<\/a>([\w\s\-,&;]+)?<br>)/
# Updated Regex. Hope this is a bit more thorough because it looks EPIC!
# @regex = /([<a-z\s=]+["']+([:\/A-Za-z\-\.0-9_\?#=!]+)["']+[a-z=\s'"_]+>([A-Za-z0-9\-\s\.\(\)&;]+)[<\/A-Za-z>]+([\w\s\-,&;\.]+)[br\/<\s]+>)/
# [<a href=][']([http://www.crossfit-sheffield.co.uk/])['][target='_blank']>([CrossFit Sheffield])[</a>]([ - Sheffield, United Kingdom])[<br />]
# Another regex. Identifies the elements we want with lazy *'s to make sure it gets all content regardless of if it's valid
@regex = /(<.+??="(.+?)(?="|').*?>(.+?)<.+?>(.+?)?<.+?>)/
# 0 - Full Match
# 1 - Website
# 2 - Name
# 3 - Location
@line = scrape_line[0]
@affiliate_line = @regex.match(@line)
# @affiliates_array.each do |a|
# puts a[3]
# More Epic Regex Winnings!
# - Denver, CO
# - Freiburg, BW, Germany
# New Regex
@location_regex = /( - ([0-9A-Za-z\s\-\.&;\(\)]+), ([A-Z]{2})?([A-Za-z\s]+)?)/
# 1 - Full Match
# 2 - City
# 3 - State
# 4 - Country
# Old Regex
#@location_regex = /( - ([A-Za-z\s]+),(\s| )([a-zA-Z\s]+)(, ([A-Za-z\s]+))?)/
# 1 = Whole thing
# 2 = City
# 4 = State
# 5 = Country (optional)
@match = @location_regex.match(@affiliate_line[4])
puts @affiliate_line[4]
unless @match.blank?
@title = @affiliate_line[3]
@website = @affiliate_line[2]
@city = @match[2]
unless @match[3].blank?
@state = @match[3]
@country = "United States"
else
@state = nil
end
if @match[4].blank?
unless @country.present?
@country = nil
end
else
@country = @match[4]
end
@original_scrape_data = @affiliate_line[0]
# puts @match.inspect
# Don't want to overwrite data anymore
if @affiliate = Affiliate.find_by_title(@title)
# @affiliate.city = @city unless @city.blank?
# @affiliate.state = @state unless @state.blank?
# @affiliate.country = @country unless @country.blank?
# @affiliate.original_scrape_data = @original_scrape_data
# @affiliate.save
else
# Can't find this affiliate
# Create a new one and notify Admin to confirm
@affiliate = Affiliate.new
@affiliate.title = @title unless @title.blank?
@affiliate.website = @website unless @website.blank?
@affiliate.city = @city unless @city.blank?
@affiliate.state = @state unless @state.blank?
@affiliate.country = @country unless @country.blank?
@affiliate.original_scrape_data = @original_scrape_data
@affiliate.save!
ScrapeLogger.info(DateTime.now.strftime + ": New Affiliate found and added - " + @affiliate.title)
@new_affiliate_array.push(@affiliate)
end
end
end
end
ScraperMailer.new_affiliates_added(@new_affilliate_array).deliver
puts "New affiliates:" + @new_affiliate_array.count.to_s
else
ScrapeLogger.info(DateTime.now.strftime + ": No update required")
end
end
desc "See which affiliates are missing from our import"
task :compare_imported_to_data => :environment do
# Grab the whole line
@regex = /(<a.*?br\s?\/?>)/
@complete_array = Scrape.last.raw_html.scan(@regex)
total_count = @complete_array.count
missing_count = 0
unless @complete_array.blank?
@complete_array.each do |aff|
unless Affiliate.exists?(:original_scrape_data => aff[0])
missing_count += 1
puts aff.inspect
end
end
end
puts "Total count = " + total_count.to_s
puts "Missing count = " + missing_count.to_s
end
desc "Get geolocation from postcode"
task :get_geolocations_from_postcode => :environment do
@root_url = "http://uk-postcodes.com/postcode/"
@extention = ".xml"
@affiliates = Affiliate.uk
unless @affiliates.blank?
@affiliates.each do |a|
unless a.has_geolocation_data?
if a.has_postcode?
@postcode = a.postcode.gsub(/\s+/, "")
@url = @root_url + @postcode + @extention
puts "URL = " + @url
begin
doc = Nokogiri::HTML(open(@url))
@lat = doc.css('lat').text
@long = doc.css('lng').text
puts "Lat: " + @lat
puts "Long: " + @long
a.coords_lat = @lat
a.coords_long = @long
a.save!
rescue OpenURI::HTTPError => ex
puts ex.to_s
end
else
puts a.title + " has no postcode"
end
end
end
end
end
desc "Compare data to alternative site"
task :compare_data => :environment do
@url = "http://www.colinmcnulty.com/blog/2010/03/13/list-and-map-of-crossfit-affiliates-in-the-uk/"
doc = Nokogiri::HTML(open(@url))
@affiliates = doc.css(".post_content h3 a")
@affiliates.each do |a|
@affiliate_name = a.text
unless Affiliate.find_by_title(@affiliate_name)
puts @affiliate_name
end
end
end
desc "Get a list of affiliates that use Wordpress"
task :get_wordpress_users => :environment do
@affiliates = Affiliate.uk
unless @affiliates.blank?
@affiliates.each do |a|
begin
@url = a.website + "/wp-login.php"
puts @url
@response = open(@url, :redirect => false)
unless @response.blank?
puts @response.status.inspect
end
rescue OpenURI::HTTPError => the_error
puts the_error.inspect
end
end
end
end
desc "Set all unprocessed data"
task :assign_unprocessed => :environment do
@affiliates = Affiliate.uk
unless @affiliates.blank?
@affiliates.each do |a|
unless a.coords_lat.present?
a.unprocessed = true
a.save
end
end
end
end
end
|
# frozen_string_literal: true
# user_intros.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that provides custom intros for users for yossarian-bot.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "yaml"
require "fileutils"
require_relative "../yossarian_plugin"
class UserIntros < YossarianPlugin
include Cinch::Plugin
use_blacklist
def initialize(*args)
super
@intros_file = File.expand_path(File.join(File.dirname(__FILE__), @bot.server_id, "user_intros.yml"))
if File.file?(@intros_file)
@intros = YAML.load_file(@intros_file)
else
FileUtils.mkdir_p File.dirname(@intros_file)
@intros = {}
end
end
def sync_intros_file
File.open(@intros_file, "w+") do |file|
file.write @intros.to_yaml
end
end
def usage
"!intro <set TEXT|clear|show> - Manage the intro message for your nick."
end
def match?(cmd)
cmd =~ /^(!)?intro$/
end
match /intro (?:add|set) (.+)/, method: :set_intro
def set_intro(m, intro)
intro = Cinch::Formatting.unformat intro
nick = m.user.nick.downcase
if @intros.key?(m.channel.to_s)
@intros[m.channel.to_s][nick] = intro
else
@intros[m.channel.to_s] = { nick => intro }
end
m.reply "Your intro for #{m.channel.to_s} has been set to: \'#{intro}\'.", true
sync_intros_file
end
match /intro (clear|rm|remove|delete|del)$/, method: :remove_intro
def remove_intro(m)
nick = m.user.nick.downcase
if @intros.key?(m.channel.to_s) && @intros[m.channel.to_s].key?(nick)
@intros[m.channel.to_s].delete(nick)
m.reply "Your intro for #{m.channel.to_s} has been removed.", true
sync_intros_file
else
m.reply "You don't currently have an intro.", true
end
end
match /intro show$/, method: :show_intro
def show_intro(m)
nick = m.user.nick.downcase
if @intros.key?(m.channel.to_s) && @intros[m.channel.to_s].key?(nick)
m.reply "Your intro is currently \'#{@intros[m.channel.to_s][nick]}\'.", true
else
m.reply "You don't currently have an intro.", true
end
end
listen_to :join, method: :intro_user
def intro_user(m)
nick = m.user.nick.downcase
return unless @intros.key?(m.channel.to_s) && @intros[m.channel.to_s].key?(nick)
m.reply "\u200B#{@intros[m.channel.to_s][nick]}"
end
end
|
# Author: Jim Noble
# jimnoble@xjjz.co.uk
#
# Tournament.rb
#
# A Rock/Paper/Scissors tournament.
#
# Takes an array of ["Player", "Strategy"] arrays. The Array can be
# nested to an arbitrary depth. Array must contain all valid
# strategies, and contain n^2 players or a validation error will be
# thrown.
#
# a1 = [[[["Robin", "R"], ["Jim", "P"]], [["Jacqui", "S"], ["Pierre", "r"]]], [[["Zebedee", "p"], ["Sylvan", "s"]], [["Elly", "R"], ["Wilf", "P"]]]]
# t = Tournament.new(a1)
#
# puts t
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
class Tournament
attr_accessor :round, :tournament_data, :rounds, :longest_player_name
def initialize(tournament_data)
@round = 1
@tournament_data = tournament_data.flatten
@rounds = Array.new
@players = Array.new
validate_data
create_players
play_tournament
end
def to_s
t_str = ""
@rounds.each_with_index do |round, index|
r_str = "\nROUND #{index + 1}\n"
r_str.length.times {|t| r_str << "="}
r_str << "\n\n"
round.games.each {|g| r_str << g.to_s}
r_str << "\n"
t_str << r_str
end
return t_str
end
def play_tournament
until(@players.length == 1)
build_round
rounds[-1].games.each {|g| g}
@players = @rounds[@round - 1].winners.select {|w| w}
@round += 1
end
end
def create_players
until (@tournament_data.empty?)
player = Player.new(@tournament_data.shift, @tournament_data.shift)
@players << player
end
end
def build_round
@rounds << Round.new(@players)
@players.clear
end
def validate_data
raise WrongNumberOfPlayersError unless well_formed_tournament?
raise NoSuchStrategyError unless valid_strategies?
end
def well_formed_tournament?
num_players = @tournament_data.length / 2
Math.log(num_players)/Math.log(2) % 1 == 0.0
end
def valid_strategies?
strategies = @tournament_data.values_at(* @tournament_data.each_index.select { |i| i.odd? })
is_valid = true
strategies.each do |s|
unless (s.length == 1 && s =~ /[RPS]/i) then
is_valid = false
end
end
return is_valid
end
end
|
module Leaderboards
class Standout
include Enumerable
# l = Leaderboards::Standout.new(year: 2015, stage: 'regional', fictional: true)
# l.reject {|r| r[:event_num] == 3 && r[:division].in?(%w[men women]) }.first(10)
def initialize(tags)
@tags = tags
end
attr_reader :tags
def each
Result.includes(:competitor, :competition).tagged(tags).finished.order('est_standout desc').each_with_index do |result, index|
attrs = {
rank: index + 1,
competitor: result.competitor.name,
division: result.tags['division'],
event: result.event.name,
event_num: result.event_num,
raw: result.raw,
normalized: result.normalized,
mean: result.mean,
std_dev: result.std_dev,
standout: result.standout,
result_id: result.id,
est_raw: result.est_raw,
est_normalized: result.est_normalized,
est_mean: result.est_mean,
est_std_dev: result.est_std_dev,
est_standout: result.est_standout
}
yield attrs
end
end
end
end |
# == Schema Information
#
# Table name: home_slides
#
# id :integer not null, primary key
# image_uid :string(255)
# image_name :string(255)
# order :integer
# url :string(255)
# page_id :integer
# site_setting_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class HomeSlide < ActiveRecord::Base
image_accessor :image
belongs_to :page
belongs_to :site_setting
attr_accessible :image, :image, :order, :url, :image_url
validates_size_of :image, maximum: 10.megabytes,
message: " is too large. Please, no larger than 10MB"
class << self
def make_image_thumbnails
HomeSlide.all.each do |slide|
slide.update_attributes(image_url: slide.image.remote_url)
end
end
end
end
|
require 'xcpretty'
require 'base64'
class BuildkiteFormatter < XCPretty::Simple
KSDIFF_MATCHER = /^ksdiff \"(.*)\"\s\"(.*)\"/
def pretty_format(text)
if KSDIFF_MATCHER.match(text)
if buildkite?
upload_artifacts($1, $2)
inline_artifacts($1, $2)
else
STDOUT.puts("\e[33mNot on Buildkite, would have uploaded: \n #{$1}\n #{$2}\e[0m")
end
end
parser.parse(text)
end
def inline_artifacts(*artifacts)
artifacts.each do |artifact|
image_contents = Base64.encode64(File.read(artifact)).gsub("\n", '')
image_name = Base64.encode64(File.basename(artifact)).gsub("\n", '')
STDOUT.puts("\e]1337;File=name=#{image_name};inline=1:#{image_contents}\a")
end
end
def upload_artifacts(*artifacts)
artifacts.each do |artifact|
Kernel.system('buildkite-agent', 'artifact', 'upload', artifact)
end
end
def buildkite?
!!ENV['BUILDKITE']
end
end
BuildkiteFormatter
|
require_relative 'product'
require_relative 'county'
require_relative 'store'
# Instantiate the three counties so that we can later utilize them for their tax rates and their ids
miami_dade_county = County.new(1, "Miami-Dade", 0.06)
palm_beach_county = County.new(2, "Palm Beach", 0.08)
broward_county = County.new(3, "Broward", 0.07)
# Instantiate our product so that we can later use the cost price
clorox_wipes = Product.new(1, "Clorox", "Disinfectant Wipes", 30)
inventory_hash = { 1 => clorox_wipes }
county_hash = {
miami_dade_county.id => miami_dade_county,
palm_beach_county.id => palm_beach_county,
broward_county.id => broward_county
}
unit_sold_for_product_id_for_county_id = {
1 => { 1 => 100 },
2 => { 1 => 100 },
3 => { 1 => 100 },
}
markup_per_county_id = {
1 => 0.25,
2 => 0.30,
3 => 0.30,
}
st_bernard_corner_store = Store.new(county_hash, unit_sold_for_product_id_for_county_id, inventory_hash, markup_per_county_id)
puts "total profit: "
puts "--------------"
puts st_bernard_corner_store.total_profit |
class Contact < ApplicationRecord
belongs_to :user
has_many :connections, dependent: :destroy
accepts_nested_attributes_for :connections
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
def created_time
self.created_at.strftime("%b %e -- %l:%M %p")
end
end
|
require 'rails_helper'
RSpec.describe Category, type: :model do
describe 'Validations' do
it { should validate_presence_of(:title) }
it { should validate_uniqueness_of(:title) }
end
describe 'Associations' do
it { should have_and_belong_to_many(:books) }
end
describe '.home_page_category' do
let(:params) { Hash.new }
before do
@category = create(:category)
@default_category = create(:category, title: Category::MAIN_GATEGORY)
end
it 'return category from params' do
params[:category_id] = @category.id
expect(Category.home_page_category(params).id).to eq(@category.id)
end
it 'return home category if no category in params' do
expect(Category.home_page_category(params).title).to eq(Category::MAIN_GATEGORY)
end
end
end
|
module SchemaToScaffold
RSpec.describe CLI do
let(:empty_schema_file) { File.expand_path(File.dirname(__FILE__)) + '/support/empty_schema.rb' }
let(:schema_file) { File.expand_path(File.dirname(__FILE__)) + '/support/schema.rb' }
describe ".start" do
it "prints help message" do
expect {
begin
SchemaToScaffold::CLI.start("-h")
rescue SystemExit
end
}.to output(/Usage:/).to_stdout
end
it "prints file not found message" do
expect {
begin
SchemaToScaffold::CLI.start("-p", "/support/schema.rb")
rescue SystemExit
end
}.to output(/Unable to open file /).to_stdout
end
it "prints could not find tables message" do
expect {
begin
SchemaToScaffold::CLI.start("-p", empty_schema_file)
rescue SystemExit
end
}.to output(/Could not find tables /).to_stdout
end
context "choose table" do
before do
allow(STDIN).to receive(:gets) { "" }
end
it "prints Not a valid input message" do
expect {
begin
SchemaToScaffold::CLI.start("-p", schema_file)
rescue SystemExit
end
}.to output(/Not a valid input/).to_stdout
end
end
context "choose all tables" do
before do
allow(STDIN).to receive(:gets).once { "*" }
end
it "prints scaffold lines message" do
expect {
begin
SchemaToScaffold::CLI.start("-p", schema_file)
rescue SystemExit
end
}.to output(/Script for/).to_stdout
end
end
context "copies first table to clipboard" do
before do
allow(STDIN).to receive(:gets).once { "0" }
expect_any_instance_of(Kernel).to receive(:exec).with("echo 'rails generate scaffold User email:string encrypted_password:string reset_password_token:string reset_password_sent_at:datetime remember_created_at:datetime sign_in_count:integer current_sign_in_at:datetime last_sign_in_at:datetime current_sign_in_ip:string last_sign_in_ip:string name:string role:integer --no-migration\n\n' | tr -d '\n' | pbcopy")
expect_any_instance_of(Clipboard).to receive(:platform).and_return("/darwin/i")
end
it "prints copied to your clipboard message" do
expect {
begin
SchemaToScaffold::CLI.start("-c", "-p", schema_file)
rescue SystemExit
end
}.to output(/copied to your clipboard/).to_stdout
end
end
end
describe ".parse_arguments" do
it "handles wrong arguments" do
expect {
begin
SchemaToScaffold::CLI.parse_arguments(["--help"])
rescue SystemExit
end
}.to output(/Wrong set of arguments/).to_stdout
end
context "handles arguments" do
it "help argument" do
expect(CLI.parse_arguments(["-h"])).to eq({clipboard: nil, factory_bot: nil, migration: nil, help: "-h", path: nil})
end
it "path argument" do
expect(CLI.parse_arguments(["-p", "/some/path"])).to eq({clipboard: nil, factory_bot: nil, migration: nil, help: nil, path: "/some/path"})
end
it "clipboard argument" do
expect(CLI.parse_arguments(["-c"])).to eq({clipboard: "-c", factory_bot: nil, migration: nil, help: nil, path: nil})
end
it "factory girl argument" do
expect(CLI.parse_arguments(["-f"])).to eq({clipboard: nil, factory_bot: "-f", migration: nil, help: nil, path: nil})
end
it "migration argument" do
expect(CLI.parse_arguments(["-m"])).to eq({clipboard: nil, factory_bot: nil, migration: "-m", help: nil, path: nil})
end
end
end
end
end
|
# frozen_string_literal: true
RSpec.describe SC::Billing::Stripe::Webhooks::Plans::UpdateOperation, :stripe do
subject(:call) do
described_class.new.call(event)
end
let(:event) { StripeMock.mock_webhook_event('plan.updated') }
let(:plan_data) { event.data.object }
let!(:plan) { create(:stripe_plan, stripe_id: plan_data.id, interval: 'day', interval_count: 7) }
it 'updates plan' do
expect { call }.to(
change { plan.reload.name }.to(plan_data.nickname)
.and(change { plan.reload.amount }.to(2700))
.and(change { plan.reload.currency }.to('cad'))
.and(change { plan.reload.interval }.to('month'))
.and(change { plan.reload.interval_count }.to(1))
.and(change { plan.reload.trial_period_days }.to(7))
)
end
end
|
module GapIntelligence
class Download < Record
attributes :start_at, :end_at, class: Date
attribute :created_at, class: Time
attributes :categories, :countries, :category_versions, class: Array
attributes :report_types, :report_type_names, class: Array
attributes :brands, :printer_brands, :channels, :merchants, class: Array
attributes :pricing_date
attributes :advertisements_display_currency, :pricings_display_currency, :promotions_display_currency
attributes :advertisements_headers, :pricings_headers, :promotions_headers, :average_contract_pricings_headers, :dealer_costs_headers, class: Array
attributes :included_core_spec_headers, :included_spec_headers, class: Array
attributes :standalone_core_spec_headers, :standalone_spec_headers, class: Array
attributes :file_type, :custom_file_name, :status
end
end
|
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(article_params)
@contact.request = request
if @contact.save
if @contact.deliver
flash.now[:notice] = 'Thank you for your message. I will contact you soon!'
else
flash.now[:error] = 'There was a problem sending your message. Please try again!'
render :new
end
else
flash.now[:error] = 'There was a problem sending your message. Please try again!'
render :new
end
end
private
def article_params
params.require(:contact).permit(:first_name, :last_name, :email, :phone_number, :message)
end
end
|
# -*- coding: utf-8 -*-
require "gettext"
module S7n
class S7nCli
# コマンドを表現する。
class Command
include GetText
# オプションの配列。
attr_reader :options
# 設定。
attr_reader :config
# World オブジェクト。
attr_reader :world
@@command_classes = {}
class << self
# s で指定した文字列をコマンド名とオプションに分割する。
def split_name_and_argv(s)
s = s.strip
name = s.slice!(/\A\w+/)
argv = s.split
return name, argv
end
def create_instance(name, world)
klass = @@command_classes[name]
if klass
return klass.new(world)
else
return nil
end
end
private
def command(name, aliases, description, usage)
@@command_classes[name] = self
self.const_set("NAME", name)
aliases.each do |s|
@@command_classes[s] = self
end
self.const_set("ALIASES", aliases)
self.const_set("DESCRIPTION", description)
self.const_set("USAGE", usage)
end
end
def initialize(world)
@world = world
@config = {}
@options = []
end
# コマンド名を取得する。
def name
return self.class.const_get("NAME")
end
# 別名の配列を取得する。
def aliases
return self.class.const_get("ALIASES")
end
# 概要を取得する。
def description
return self.class.const_get("DESCRIPTION")
end
# 使用例を取得する。
def usage
return self.class.const_get("USAGE")
end
# コマンドラインオプションを解析するための OptionParser オブジェ
# クトを取得する。
def option_parser
return OptionParser.new { |opts|
opts.banner = [
"#{name} (#{aliases.join(",")}): #{description}",
usage,
].join("\n")
if options && options.length > 0
opts.separator("")
opts.separator("Valid options:")
for option in options
option.define(opts, config)
end
end
}
end
# 使用方法を示す文字列を返す。
def help
puts(option_parser)
return
end
private
# キャンセルした旨を出力し、true を返す。
# Command オブジェクトの run メソッドで return canceled という使
# い方を想定している。
def canceled
puts("\n" + Canceled::MESSAGE)
return true
end
end
# プログラムを終了するコマンドを表現する。
class HelpCommand < Command
command("help",
["usage", "h"],
_("Describe the commands."),
_("usage: help [COMMAND]"))
def run(argv)
if argv.length > 0
command_name = argv.shift
command = Command.create_instance(command_name, world)
if command
command.help
else
puts(_("Unknown command: %s") % command_name)
end
else
puts(_("Type 'help <command>' for help on a specific command."))
puts("")
puts(_("Available commands:"))
command_classes = @@command_classes.values.uniq.sort_by { |klass|
klass.const_get("NAME")
}
command_classes.each do |klass|
s = " #{klass.const_get("NAME")}"
aliases = klass.const_get("ALIASES")
if aliases.length > 0
s << " (#{aliases.sort_by { |s| s.length}.first})"
end
puts(s)
end
end
return true
end
end
# 現在の状態を保存するコマンドを表現する。
class SaveCommand < Command
command("save", [], _("Save."), _("usage: save"))
def initialize(*args)
super
@options.push(BoolOption.new("f", "force", _("Force.")))
end
def run(argv)
option_parser.parse!(argv)
world.save(config["force"])
puts(_("Saved."))
return true
end
end
# スクリーンロックし、マスターキーを入力するまでは操作できないよう
# にするコマンドを表現する。
class LockCommand < Command
command("lock", [], _("Lock screen after saved."), _("usage: lock"))
def run(argv)
system("clear")
puts(_("Locked screen."))
world.save
prompt = _("Enter the master key for s7n: ")
begin
input = S7nCli.input_string_without_echo(prompt)
if input != world.master_key
raise InvalidPassphrase
end
puts(_("Unlocked."))
return true
rescue Interrupt
rescue ApplicationError => e
puts($!.message + _("Try again."))
retry
rescue Exception => e
puts(e.message)
if world.debug
puts(_("----- back trace -----"))
e.backtrace.each do |line|
puts(" #{line}")
end
end
end
puts(_("Quit."))
return false
end
end
# プログラムを終了するコマンドを表現する。
class QuitCommand < Command
command("quit",
["exit", "q"],
_("Quit."),
_("usage: quit"))
def run(argv)
return false
end
end
end
end
|
class Store < ActiveRecord::Base
belongs_to :seller
has_many :products
end |
class Tree
attr_reader :root_node, :leaf
def initialize(root_node)
@root_node = root_node
end
def add_node(value)
node = @root_node
new_node = Node.new(value)
loop do
if check_value(node, new_node) && node.right
node = node.right
elsif ! check_value(node, new_node) && node.left
node = node.left
else
if check_value(node, new_node)
node.right = new_node
break
else
node.left = new_node
break
end
end
end
end
def check_value(node, new_node)
return new_node.value >= node.value
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.