text stringlengths 10 2.61M |
|---|
# Tree Level Order Print
# Given a binary tree of integers, print it in level order. The output will contain space between the numbers in the same level, and new line between different levels.
def level_order_print(tree)
unless tree
return
end
nodes = [tree]
current_line_count = 1
next_line_count = 0
while nodes.length != 0
current_node = nodes.shift
current_line_count -= 1
print current_node.key.to_s + ' '
if current_node.left_child
nodes.push(current_node.left_child)
next_line_count += 1
end
if current_node.right_child
nodes.push(current_node.right_child)
next_line_count += 1
end
if current_line_count == 0
# finished printing current level
puts ''
current_line_count = next_line_count
next_line_count = current_line_count
end
end
end
|
class Person
@@population = []
# attr_reader :name, :age #accomplishes the getter methods
# attr_writer :name, :age #accomplishes the setter methods
attr_accessor :name, :age #accomplishes both!
# sometimes reader and writer are good to keep information separate.
# Perhaps it shouldnt be changed (reader), or it shouldnt be read, like a SSN (writer)
def initialize(age=nil, name)
# these are available to us on setup when the Object is instantiated
# but they are not necessary and the initialize block could be empty
# AND! without these initialize values, we can't pass ANY values in
# when we create this instance.
@age = age
@name = name
# self refers to this instance of the
# person class
@@population << self
end
def self.population
@@population
end
#getter method or reader method for @age
# # def age
# @age
# end
# #getter for name
# def name
# @name
# end
#setter method for @age
# def age=(other)
# @age = other
# end
# #setter method for @name
# def name=(other)
# @name=other
# end
# the equals here is some syntactic sugar and adds some functionality
# per.instance_variables will yield the instance variables as symbols
# per.method(:age)
# in the terminal, _ yields the last returned value
end |
json.array!(@agendas) do |agenda|
json.extract! agenda, :id, :title, :when, :place, :description
json.url agenda_url(agenda, format: :json)
end
|
class NspirefilesController < ApplicationController
before_filter :login_required
# GET /nspirefiles
# GET /nspirefiles.xml
def index
@nspirefiles = Nspirefile.all(:order => "updated_at DESC")
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @nspirefiles }
end
end
# GET /nspirefiles/1
# GET /nspirefiles/1.xml
def show
@nspirefile = Nspirefile.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @nspirefile }
end
end
# GET /nspirefiles/new
# GET /nspirefiles/new.xml
def new
@nspirefile = Nspirefile.new
@categories = get_categories
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @nspirefile }
end
end
# GET /nspirefiles/1/edit
def edit
@nspirefile = Nspirefile.find(params[:id])
@categories = get_categories
end
# POST /nspirefiles
# POST /nspirefiles.xml
def create
@nspirefile = Nspirefile.new(params[:nspirefile])
respond_to do |format|
if @nspirefile.save
flash[:notice] = 'TI-Nspire file "' + @nspirefile.title + '" was successfully created.'
format.html { redirect_to(@nspirefile) }
format.xml { render :xml => @nspirefile, :status => :created, :location => @nspirefile }
else
format.html { render :action => "new" }
format.xml { render :xml => @nspirefile.errors, :status => :unprocessable_entity }
end
end
end
# PUT /nspirefiles/1
# PUT /nspirefiles/1.xml
def update
@nspirefile = Nspirefile.find(params[:id])
@categories = get_categories
respond_to do |format|
if @nspirefile.update_attributes(params[:nspirefile])
flash[:notice] = 'TI-Nspire file "' + @nspirefile.title + '" was successfully updated.'
format.html { redirect_to(@nspirefile) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @nspirefile.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /nspirefiles/1
# DELETE /nspirefiles/1.xml
def destroy
@nspirefile = Nspirefile.find(params[:id])
@nspirefile.destroy
respond_to do |format|
format.html { redirect_to(nspirefiles_url) }
format.xml { head :ok }
end
end
private
def get_categories
["Activities", "Algebra", "Assembly" ,"Calculus" ,"Games", "Geometry" ,"Libraries", "Middle School ", "Misc.", "Science", "Statistics"]
end
end
|
require_relative '../atomic_send_rewriter'
require_relative '../local_vars_in_ast'
class AtomicSendOnRbxRewriter < AtomicSendRewriter
def initialize(a_binding=nil)
super
@local_vars_in_privately_node = LocalVarsInAST.new
@currently_inside_rbx_asm_block = false
end
def on_block(node)
send_node, _, body_node = *node
receiver_node, method_name, *_ = *send_node
# Rubinius implements a special compiler macro called Rubinius.privately which executes code inside a block
# in a special way. Variables inside that macro should be treated as if they were defined _outside_ that block.
# So we add local variables found inside block to them to be excluded during on_send calls.
if is_rbx_privately_node?(receiver_node, method_name)
@local_vars_in_privately_node.add_from_tree(body_node)
end
# If this is a Rubinius.asm block node, we should register that fact before processing, so any send nodes
# processed afterwards are not transformed during future on_send calls for the current subtree.
if is_rbx_asm_node?(receiver_node, method_name)
@currently_inside_rbx_asm_block = true
processed_node = super
@currently_inside_rbx_asm_block = false
return processed_node
end
# continue processing...
super
end
private
def should_transform_to_atomic?(send_node)
_, method_name, *_ = *send_node
unless super
return false
end
# Rubinius implements a special compiler macro called Rubinius.privately which executes code inside a block
# in a special way. Variables inside that macro should be treated as if they were defined _outside_ that block.
# We should check if this send node corresponds to a local variable gathered from parsing a Rubinius.privately
# block node before.
if @local_vars_in_privately_node.include?(method_name)
return false
end
# Some Rubinius' send nodes are NOT defined as methods. Instead they are transformed using defined AST
# transformations found in the kernel which emit a special bytecode instead of a normal message send. We should
# not transform this nodes to atomic because if they are transformed, the transformations will not be applied
# due to unmatching method method_name so the interpreter will raise an unhandlable method_missing.
if is_a_rbx_undefined_method_node?(send_node)
return false
end
# Rubinius.asm special macro will execute bytecode passed as a block parameter. We do not want to perform any
# transformation when we are inside those special blocks.
if currently_inside_rbx_asm_block?
return false
end
true
end
def is_rbx_privately_node?(receiver_node, method_name)
!receiver_node.nil? && receiver_node.children[1] == :Rubinius &&
method_name == :privately
end
def is_rbx_asm_node?(receiver_node, method_name)
!receiver_node.nil? && receiver_node.children[1] == :Rubinius &&
method_name == :asm
end
def currently_inside_rbx_asm_block?
@currently_inside_rbx_asm_block
end
def is_a_rbx_undefined_method_node?(node)
receiver_node, method_name, *_ = *node
# based on the analysis of lib/rubinius/code/ast/transforms.rb in the rubinius-ast-3.8 gem
if not receiver_node.nil?
primitives = [:primitive, :invoke_primitive, :check_frozen,
:call_custom, :single_block_arg, :asm,
:privately]
is_rbx_primitive = receiver_node.children[1] == :Rubinius &&
primitives.include?(method_name)
undef_equal_send = receiver_node.children[1] == :undefined &&
method_name == :equal?
is_rbx_primitive || undef_equal_send
else
[:undefined, :block_given?, :iterator?].include?(method_name)
end
end
end |
require_relative "base"
class User < ModelBase
attr_accessor :fname, :lname
def save
options_hash = {"fname" => @fname, "lname" => @lname}
super(options_hash)
end
def self.find_by_name(fname, lname)
sql = "SELECT * FROM #{self.table_name} WHERE fname = #{fname} AND lname = #{lname}"
self.find_by_query(sql)
end
def authored_questions
Question.find_by_author_id(self.id)
end
def authored_replies
Reply.find_by_user_id(self.id)
end
def followed_questions
QuestionFollow.followed_questions_for_user_id(self.id)
end
def liked_questions
QuestionLike.liked_questions_for_user_id(self.id)
end
def average_karma
sql = "SELECT COUNT(DISTINCT q.id) as num_questions, COUNT(ql.id) as num_likes"\
" FROM questions q LEFT OUTER JOIN question_likes ql ON q.id = ql.question_id"\
" WHERE q.user_id = #{self.id} GROUP BY q.user_id"
query_result = QuestionsDatabase.instance.execute(sql).first
num_questions, num_likes = query_result["num_questions"], query_result["num_likes"]
num_likes / num_questions.to_f
end
end |
require 'test_helper'
class PropertyTest < ActiveSupport::TestCase
test "should find a match on address" do
test_property = Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_equal test_property, Property.searchAddress("117").first
end
test "should not find a match on address" do
test_property = Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_not_equal test_property, Property.searchAddress("118").first
end
test "should find a match on city" do
test_property = Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_equal test_property, Property.searchCity("Augusta").first
end
test "should not find a match on city" do
test_property = Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_not_equal test_property, Property.searchCity("tajiristan").first
end
test "should find a match on zip" do
test_property = Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_equal test_property, Property.searchZip("54722").first
end
test "should not find a match on zip" do
test_property = Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_not_equal test_property, Property.searchCity("99999").first
end
test "should find a match on 2 properties" do
Property.create(address: "117 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
Property.create(address: "120 west lincoln",
apt: "1",
city: "Augusta",
state: "Wisconsin",
zip: "54722",
rooms: "2",
rent: "500",
utilities: "200",
petsAllowed: "Yes")
assert_equal 2, Property.searchAddress("lincoln").count
end
end
|
module AuditsHelper
def link_to_audit(audit)
link_text = lock_icon(audit)
link_text << audit.audit_structure.name
link_to link_text, audit, class: 'row-block-link'
end
def lock_icon(audit)
if audit.is_locked?
'<i class="icon-locked"></i> '.html_safe
else
''
end
end
def expires_in(audit)
distance_of_time_in_words_to_now(audit.destroy_on_date)
end
def audit_type_options
audit_types = AuditType.where(active: true)
.order(:name)
.pluck(:name, :id)
options_for_select audit_types
end
end
|
class RenameColumnOfTablePost < ActiveRecord::Migration
def change
rename_column :posts, :type, :post_type
end
end
|
# == Schema Information
#
# Table name: zips
#
# id :integer not null, primary key
# code :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# city_id :integer
#
require 'rails_helper'
Rspec.describe City, :type => :model do
let(:member) { build(:member) }
let(:member_create) { create(:member, birthday: '1980-02-01') }
describe "正常系チェック" do
example "正常なオブジェクト" do
expect(member).to be_valid
end
end
describe "事前処理チェック" do
describe "索引用メールアドレスの変換代入処理" do
example "メールアドレスの大文字が小文字に変換されて索引用メールアドレスに格納される" do
mail_downcase = member["mail_address"].downcase
expect(member["mail_address_for_index"]).to eq(mail_downcase)
end
end
end
describe "必須項目チェック" do
# チェック対象カラム名の配列を作成
presence_chk = %w(mail_address family_name family_name_kana given_name given_name_kana sex_division birthday point_member_code member_maximum_amount_id billing_scheme_id member_sign_up_status member_registration_datetime verification_status)
# 必須チェック
presence_chk.each do |column_name|
example "#{column_name} は空であってはならない" do
member[column_name] = ''
expect(member).not_to be_valid
if column_name =~ /\A.*_id\z/
column_name_excepting_id = column_name.gsub(/_id\z/, '')
expect(member.errors[column_name_excepting_id]).to be_present
else
expect(member.errors[column_name]).to be_present
end
end
end
end
describe "桁数チェック" do
# チェック対象カラム名をkey,最大桁数をvalueとしてハッシュを作成
limit_chk = {"mail_address" => 255,
# "mail_address_for_index" => 255,
"member_code" => 9,
"point_member_code" => 9,
"family_name" => 50,
"family_name_kana" => 64,
"given_name" => 50,
"given_name_kana" => 64,
"sex_division" => 1,
"member_sign_up_status" => 1,
"verification_status" => 1
}
limit_chk.each do |column_name, column_limit|
example "#{column_name} は#{column_limit}文字以内" do
if (column_name == "mail_address" )
# メールアドレス
member[column_name] = ("a" * column_limit.to_i) + "@npay.jp"
elsif (column_name == "family_name" || column_name == "given_name")
# 全角
member[column_name] = "漢" * (column_limit.to_i + 1)
elsif (column_name == "family_name_kana" || column_name == "given_name_kana")
# 全角かな
member[column_name] = "あ" * (column_limit.to_i + 1)
elsif (column_name == "sex_division" || column_name == "member_sign_up_status" || column_name == "verification_status" || column_name == "member_code" || column_name == "point_member_code")
# 半角のみ、数値(区分値)
member[column_name] = "1" * (column_limit.to_i + 1)
else
# その他
member[column_name] = "a" * (column_limit.to_i + 1)
end
expect(member).not_to be_valid
expect(member.errors[column_name]).to be_present
end
end
end
describe "一意性チェック" do
# 一意性チェックを行いたい項目を「配列」として配列に格納(組み合わせも検証可能)
uniqueness_chk =[["mail_address_for_index", "member_code", "point_member_code"]]
uniqueness_chk.each do |columns|
describe "#{columns.join(', ')}の一意性検証" do
example "#{columns.join(', ')}は一意である" do
# 一度保存し、保存された項目と同じ値を設定することで一意性を検証
member.save
member_uniq_chk = build(:member)
columns.each do |column_name|
member_uniq_chk[column_name] = member[column_name]
member_uniq_chk["mail_address"] = member["mail_address"] if column_name == "mail_address_for_index"
end
expect(member_uniq_chk).not_to be_valid
end
end
end
end
describe "入力値チェック" do
describe "メールアドレス" do
# ポイント会員側のバリデーションロジックに沿う
column_name = "mail_address"
example "半角を含む" do
member[column_name] = "yaizawa@netprotections.co.jp"
expect(member).to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "全角を含まない" do
member[column_name] = "yaizawa@netprotections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "メールアドレス形式である" do
member[column_name] = "yaizawa@netprotections.co.jp"
expect(member[column_name]).to match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
expect(member).to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "メールアドレス形式でない場合はエラーとなる" do
member[column_name] = "yaizawa#netprotections.co.jp"
expect(member[column_name]).not_to match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
### ポイント会員側チェック仕様
example "ローカル部が半角英数字、記号(._!#$%&'*+-/=?^_`{|}~)で構成されている" do
member[column_name] = "yaizawaYAIZAWA0123456789._!#$%&'*+-/=?^_`{|}~@netprotections.co.jp"
expect(member).to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "ドメイン部が半角英数と記号(-.)で構成されている" do
member[column_name] = "yaizawaYAIZAWA0123456789._!#$%&'*+-/=?^_`{|}~@netprotections-123.co.jp"
expect(member).to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "@が二つ以上含まれている(ローカル(ユーザ)部、ドメイン部に分離できない)" do
member[column_name] = "yaizawa@netpr@otections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "@が含まれていない(ローカル(ユーザ)部、ドメイン部に分離できない)" do
member[column_name] = "yaizawanetprotections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "ドメイン部の先頭文字列が-(ハイフン)" do
member[column_name] = "yaizawa@-netprotections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "ドメイン部の先頭文字列が.(ピリオド)" do
member[column_name] = "yaizawa@.netprotections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "ドメイン部の最後の文字列が.(ピリオド)" do
member[column_name] = "yaizawa@netprotections.co.jp."
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "ドメイン部に.(ピリオド)が含まれていない" do
member[column_name] = "yaizawa@netprotections"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "ドメイン部に..(ピリオドの連続)が含まれている" do
member[column_name] = "yaizawa@netprotection..s.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "登録対象外:*@で始まるメールアドレス" do
member[column_name] = "*@netprotections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "登録対象外:xxx@netprotections.co.jp" do
member[column_name] = "xxx@netprotections.co.jp"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
example "登録対象外:xxx@xxx.xxx" do
member[column_name] = "xxx@xxx.xxx"
expect(member).not_to be_valid
puts "#{column_name} error:#{member.errors[column_name]}"
end
end
describe "関連チェック" do
example "1つ請求スキームに属する" do
expect(member).to belong_to(:billing_scheme)
end
example "1つ会員上限金額に属する" do
expect(member).to belong_to(:member_maximum_amount)
end
example "1つの会員利用状況を持つ" do
expect(member).to have_one(:member_usage)
end
end
end
end
|
module Acfs
# @api private
#
# Describes a URL with placeholders.
#
class Location
attr_reader :arguments, :raw, :struct, :args
REGEXP = /^:([A-z][A-z0-9_]*)$/
def initialize(uri, args = {})
@raw = URI.parse uri
@args = args
@struct = raw.path.split('/').reject(&:empty?).map {|s| s =~ REGEXP ? Regexp.last_match[1].to_sym : s }
@arguments = struct.select {|s| s.is_a?(Symbol) }
end
def build(args = {})
unless args.is_a?(Hash)
raise ArgumentError.new "URI path arguments must be a hash, `#{args.inspect}' given."
end
self.class.new raw.to_s, args.merge(self.args)
end
def extract_from(*args)
args = {}.tap do |collect|
arguments.each {|key| collect[key] = extract_arg key, args }
end
build args
end
def str
uri = raw.dup
uri.path = URI.escape '/' + struct.map {|s| lookup_arg(s, args) }.join('/')
uri.to_s
end
def raw_uri
raw.to_s
end
alias_method :to_s, :raw_uri
private
def extract_arg(key, hashes)
hashes.each_with_index do |hash, index|
return (index == 0 ? hash.delete(key) : hash.fetch(key)) if hash.key?(key)
end
nil
end
def lookup_arg(arg, args)
arg.is_a?(Symbol) ? lookup_replacement(arg, args) : arg
end
def lookup_replacement(sym, args)
value = get_replacement(sym, args).to_s
return value unless value.empty?
raise ArgumentError.new "Cannot replace path argument `#{sym}' with empty string."
end
def get_replacement(sym, args)
args.fetch(sym.to_s) do
args.fetch(sym) do
if args[:raise].nil? || args[:raise]
raise ArgumentError.new "URI path argument `#{sym}' missing on `#{self}'. Given: `#{args}.inspect'"
else
":#{sym}"
end
end
end
end
end
end
|
class District < ActiveRecord::Base
belongs_to :state
belongs_to :hearing
has_many :court_complexes
has_many :client_cases
validates_presence_of :name, :state_id
end
|
# -*- coding: utf-8 -*-
module Mushikago
module Mitsubachi
# mitsubachiサービスを利用する
#
# @example
# require 'mushikago'
# client = Mushikago::Mitsubachi::Client.new(:api_key => '<api_key>', :secret_key => '<secret_key>')
#
# client.project_create('project01')
# client.script_deploy('project01', 'sample.rb', 'sample.rb')
# client.http_fetch('project01', 'http://www.mushikago.org/', 'sample.rb')
#
# @example APIキーをファイルから読み込む場合
# Mushikago.config.load(YAML.load(File.read('config.yml')))
# client = Mushikago::Mitsubachi::Client.new
class Client < Mushikago::Http::Client
def projects
Mitsubachi::Projects.new(self)
end
# project/createを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @option options [Boolean] :dedicated
# @option options [Integer] :max_lead_time
# @option options [Boolean] :stdout
# @option options [Boolean] :stderr
# @option options [Boolean] :system_log
# @option options [String] :log_prefix
# @example
# client.project_create('project01', :stdout => true)
# @return [Mushikago::Http::Response] リクエストの結果
def project_create project_name, options={}
request = ProjectCreateRequest.new(project_name, options)
send_request(request)
end
# project/listを発行します
#
# @param [Hash] options リクエストのオプション
# @option options [Integer] :limit
# @option options [Integer] :offset
# @option options [String] :filter
# @example
# result = client.project_list
# result['projects'].each do |project|
# puts project['name']
# end
# @return [Mushikago::Http::Response] リクエストの結果
def project_list options={}
request = ProjectListRequest.new(options)
send_request(request)
end
# project/infoを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @example
# result = client.project_info('project01')
# puts result['dedicated']
# puts result['max_lead_time']
# puts result['stdout']
# puts result['stderr']
# puts result['system_log']
# puts result['log_prefix']
# puts result['storage_prefix']
# result['hourly_counts'].each do |hourly_count|
# puts hourly_count['name']
# hourly_count['call_counts'].each_with_index do |call_count,time|
# puts "#{time} : call_count"
# end
# end
# result['daily_counts'].each do |daily_count|
# puts daily_count['name']
# puts daily_count['call_count']
# end
# result['monthly_counts'].each do |monthly_count|
# puts monthly_count['name']
# puts monthly_count['call_count']
# end
# @return [Mushikago::Http::Response] リクエストの結果
def project_info project_name, options={}
request = ProjectInfoRequest.new(project_name, options)
send_request(request)
end
# project/queuesを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @example
# result = client.project_queues('project01')
# puts result['count']
# @return [Mushikago::Http::Response] リクエストの結果
def project_queues project_name, options={}
request = ProjectQueuesRequest.new(project_name, options)
send_request(request)
end
# project/deleteを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @option options [Boolean] :forcedelete
# @example
# client.project_delete('project01')
# @return [Mushikago::Http::Response] リクエストの結果
def project_delete project_name, options={}
request = ProjectDeleteRequest.new(project_name, options)
send_request(request)
end
# project/updateを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @option options [Integer] :max_lead_time
# @option options [Boolean] :stdout
# @option options [Boolean] :stderr
# @option options [Boolean] :system_log
# @option options [String] :log_prefix
# @example
# client.project_update('project01', :stdout => false)
# @return [Mushikago::Http::Response] リクエストの結果
def project_update project_name, options={}
request = ProjectUpdateRequest.new(project_name, options)
send_request(request)
end
# project/discontinueを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @example
# client.project_discontinue('project01')
# @return [Mushikago::Http::Response] リクエストの結果
def project_discontinue project_name, options={}
request = ProjectDiscontinueRequest.new(project_name, options)
send_request(request)
end
# http/fetchを発行します
#
# @param [String] project_name プロジェクト名
# @param [String] url クロール対象のURL
# @param [String] script_name スクレイピングスクリプトのパス
# @param [Hash] options リクエストのオプション
# @option options [String] :method
# @option options [String] :entity_parameter
# @option options [Boolean] :follow_redirect
# @option options [String] :parameters
# @option options [String] :header_overwrite
# @option options [String] :cookiejar
# @option options [String] :parent_request_id
# @option options [String] :group_id
# @option options [String] :unique_key
# @option options [Integer] :unique_key_expires
# @option options [String] :encode
# @example
# client.http_fetch('project01', 'http://www.tombo.ne.jp/', 'sample.rb', :follow_redirect => true)
# @return [Mushikago::Http::Response] リクエストの結果
def http_fetch project_name, url, script_name, options={}
request = HttpFetchRequest.new(project_name, url, script_name, options)
send_request(request)
end
# http/pushを発行します
#
# @param [String] project_name プロジェクト名
# @param [String] url クロール対象のURL
# @param [String] script_name スクレイピングスクリプトのパス
# @param [String] file_name
# @param [String] file_input_key
# @param [Hash] options リクエストのオプション
# @option options [String] :entity_parameter
# @option options [String] :parameters
# @option options [String] :header_overwrite
# @option options [String] :mime_type
# @option options [String] :cookiejar
# @option options [String] :parent_request_id
# @option options [String] :group_id
# @option options [String] :unique_key
# @option options [Integer] :unique_key_expires
# @option options [String] :encode
# @example
# client.http_push('project01', 'http://www.tombo.ne.jp/', 'sample.rb')
# @return [Mushikago::Http::Response] リクエストの結果
def http_push project_name, url, script_name, file_name, file_input_key, options={}
request = HttpPushRequest.new(project_name, url, script_name, file_name, file_input_key, options)
send_request(request)
end
# script/deployを発行します
#
# @param [String] project_name プロジェクト名
# @param [String or File] file_or_file_name デプロイするファイルオブジェクトもしくはファイルパス
# @param [Hash] options リクエストのオプション
# @option options [String] script_name デプロイ先のファイル名
# @example
# client.script_deploy('project01', 'sample.rb', :script_name => 'hoge.rb')
# @return [Mushikago::Http::Response] リクエストの結果
def script_deploy project_name, file_or_file_name, options={}
request = ScriptDeployRequest.new(project_name, file_or_file_name, options)
send_request(request)
end
# script/listを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @option options [Integer] :limit
# @option options [Integer] :offset
# @option options [String] :filter
# @example
# limit = 10
# offset = 0
# has_more_files = 1
# until has_more_files == 0
# result = client.script_list('project01', :limit => limit, :offset => offset)
# result['scripts'].each do |script|
# puts script['name']
# puts script['size']
# puts script['timestamp']
# end
# offset += limit
# has_more_files = result['has_more_files']
# end
# @return [Mushikago::Http::Response] リクエストの結果
def script_list project_name, options={}
request = ScriptListRequest.new(project_name, options)
send_request(request)
end
# script/getを発行します
#
# @param [String] project_name プロジェクト名
# @param [String] script_name デプロイ先のファイル名
# @param [Hash] options リクエストのオプション
# @option options [Boolean] :with_body trueを指定すると、response['body']でファイルの内容にアクセスすることができるようになります。
# @example
# result = client.script_get('project01', 'sample.rb')
# puts result['url']
# @return [Mushikago::Http::Response] リクエストの結果
def script_get project_name, script_name, options={}
request = ScriptGetRequest.new(project_name, script_name, options)
result = send_request(request)
if options[:with_body]
begin
uri = URI.parse(result['url'])
result['body'] = Net::HTTP.get(uri.host, uri.request_uri)
rescue
end
end
return result
end
# script/deleteを発行します
#
# @param [String] project_name プロジェクト名
# @param [String] script_name デプロイ先のファイル名
# @param [Hash] options リクエストのオプション
# @example
# client.script_delete('project01', 'sample.rb')
# @return [Mushikago::Http::Response] リクエストの結果
def script_delete project_name, script_name, options={}
request = ScriptDeleteRequest.new(project_name, script_name, options)
send_request(request)
end
# resource/storeを発行します
#
# @param [String] project_name プロジェクト名
# @param [String or File] file_or_file_name デプロイするファイルオブジェクトもしくはファイルパス
# @param [Hash] options リクエストのオプション
# @option options [String] :file_name デプロイ先のファイル名
# @option options [String] :content_type
# @option options [public] :public
# @example
# client.resource_store('project01', 'sample.csv', :public => true)
# @return [Mushikago::Http::Response] リクエストの結果
def resource_store project_name, file_or_file_name, options={}
request = ResourceStoreRequest.new(project_name, file_or_file_name, options)
send_request(request)
end
# resource/listを発行します
#
# @param [String] project_name プロジェクト名
# @param [Hash] options リクエストのオプション
# @option options [Integer] :limit
# @option options [Integer] :offset
# @option options [String] :filter
# @example
# limit = 10
# offset = 0
# has_more_files = 1
# until has_more_files == 0
# result = client.resource_list('project01', :limit => limit, :offset => offset)
# result['files'].each do |file|
# puts script['name']
# puts script['size']
# puts script['timestamp']
# end
# offset += limit
# has_more_files = result['has_more_files']
# end
# @return [Mushikago::Http::Response] リクエストの結果
def resource_list project_name, options={}
request = ResourceListRequest.new(project_name, options)
send_request(request)
end
# resource/getを発行します
#
# @param [String] project_name プロジェクト名
# @param [String] file_name 保存先のファイル名
# @param [Hash] options リクエストのオプション
# @option options [Boolean] :with_body trueを指定すると、response['body']でファイルの内容にアクセスすることができるようになります。
# @example
# result = client.resource_get('project01', 'sample.rb')
# puts result['url']
# @return [Mushikago::Http::Response] リクエストの結果
def resource_get project_name, file_name, options={}
request = ResourceGetRequest.new(project_name, file_name, options)
result = send_request(request)
if options[:with_body]
begin
uri = URI.parse(result['url'])
result['body'] = Net::HTTP.get(uri.host, uri.request_uri)
rescue
end
end
return result
end
# resource/deleteを発行します
#
# @param [String] project_name プロジェクト名
# @param [String] file_name 保存先のファイル名
# @param [Hash] options リクエストのオプション
# @example
# client.resource_delete('project01', 'sample.rb')
# @return [Mushikago::Http::Response] リクエストの結果
def resource_delete project_name, file_name, options={}
request = ResourceDeleteRequest.new(project_name, file_name, options)
send_request(request)
end
end
end
end
|
require "cuba"
require "mote"
require "mote/render"
require "byebug"
require "securerandom"
require "pg"
require_relative "db_utils.rb"
require_relative "http_utils.rb"
require_relative "scraper.rb"
Cuba.plugin(Mote::Render)
Cuba.define do
on root do
if req.cookies["CubaTutorialApp"]
cta_cookie = req.cookies["CubaTutorialApp"]
else
cta_cookie = SecureRandom::urlsafe_base64
res.set_cookie("CubaTutorialApp", cta_cookie)
end
res.write partial("home", cookie: cta_cookie)
end
on get do
on "about" do
res.write("This is a sandbox application for trying things out with the
Cuba gem. In development it runs on a puma server.\n\n
Your SecureRandom-generated CubaTutorialApp cookie is
#{req.cookies["CubaTutorialApp"]}.")
end
on "randnum" do
sleep 2
res.write(rand(100))
end
on "deleteCookie" do
res.delete_cookie("CubaTutorialApp")
res.write(nil)
end
on "database" do
on "get" do
nums = get_user_numbers
res.write(nums)
end
on "set" do
set_user_numbers(params.values)
res.write(nil)
end
end
end
end
|
module Api
module V1
class OpinionSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :cliente, :descripcion, :calificacion, :foto
def foto
rails_blob_path(object.foto, only_path: true) if object.foto.attached?
end
end
end
end
|
require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator::ObjectValidator do
before do
@validator = OpenAPIParser::SchemaValidator::ObjectValidator.new(nil, nil)
@root = OpenAPIParser.parse(
'openapi' => '3.0.0',
'components' => {
'schemas' => {
'object_with_required_but_no_properties' => {
'type' => 'object',
'required' => ['id'],
},
},
},
)
end
it 'shows error when required key is absent' do
schema = @root.components.schemas['object_with_required_but_no_properties']
_value, e = *@validator.coerce_and_validate({}, schema)
expect(e&.message).to match('.* missing required parameters: id')
end
end
RSpec.describe OpenAPIParser::Schemas::RequestBody do
describe 'object properties' do
context 'discriminator check' do
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/save_the_pets' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
let(:root) { OpenAPIParser.parse(petstore_with_discriminator_schema, {}) }
it 'throws error when sending unknown property key with no additionalProperties defined' do
body = {
"baskets" => [
{
"name" => "cats",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10,
"unknown_key" => "value"
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: unknown_key")
end
end
it 'throws error when sending multiple unknown property keys with no additionalProperties defined' do
body = {
"baskets" => [
{
"name" => "cats",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10,
"unknown_key" => "value",
"another_unknown_key" => "another_value"
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: unknown_key, another_unknown_key")
end
end
it 'ignores unknown property key if additionalProperties is defined' do
# TODO: we have to use additional properties to do the validation
body = {
"baskets" => [
{
"name" => "squirrels",
"content" => [
{
"name" => "Mrs. Squirrel",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Squirrel superhero",
"nut_stock" => 10,
"unknown_key" => "value"
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'throws error when sending nil disallowed in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"required_combat_style" => nil,
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotNullError)
expect(e.message).to end_with("does not allow null values")
end
end
it 'passing when sending nil nested to anyOf that is allowed' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"optional_combat_style" => nil,
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'throws error when unknown attribute nested in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"required_combat_style" => {
"bo_color" => "brown",
"grappling_hook_length" => 10.2
},
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotAnyOf)).to eq true
expect(e.message).to match("^.*?(isn't any of).*?$")
end
end
it 'passes error with correct attributes nested in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"required_combat_style" => {
"bo_color" => "brown",
"shuriken_count" => 10
},
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'throws error when unknown attribute nested in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"optional_combat_style" => {
"bo_color" => "brown",
"grappling_hook_length" => 10.2
},
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotAnyOf)).to eq true
expect(e.message).to match("^.*?(isn't any of).*?$")
end
end
it 'passes error with correct attributes nested in anyOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"optional_combat_style" => {
"bo_color" => "brown",
"shuriken_count" => 10
},
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
end
context 'additional_properties check' do
subject { request_operation.validate_request_body(content_type, JSON.load(params.to_json)) }
let(:root) { OpenAPIParser.parse(schema, {}) }
let(:schema) { build_validate_test_schema(replace_schema) }
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/validate_test' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
context 'no additional_properties' do
let(:replace_schema) do
{
query_string: {
type: 'string',
},
}
end
let(:params) { { 'query_string' => 'query' } }
it { expect(subject).to eq({ 'query_string' => 'query'}) }
end
context 'additional_properties = default' do
let(:replace_schema) do
{
query_string: {
type: 'string',
},
}
end
let(:params) { { 'query_string' => 'query', 'unknown' => 1 } }
it { expect(subject).to eq({ 'query_string' => 'query', 'unknown' => 1 }) }
end
context 'additional_properties = false' do
let(:schema) do
s = build_validate_test_schema(replace_schema)
obj = s['paths']['/validate_test']['post']['requestBody']['content']['application/json']['schema']
obj['additionalProperties'] = { 'type' => 'string' }
s
end
let(:replace_schema) do
{
query_string: {
type: 'string',
},
}
end
let(:params) { { 'query_string' => 'query', 'unknown' => 1 } }
# TODO: we need to perform a validation based on schema.additional_properties here, if
it { expect(params).to eq({ 'query_string' => 'query', 'unknown' => 1 }) }
end
end
end
end
|
class Tile < ActiveRecord::Base
attr_accessible :x_location, :y_location
#attr_protected :board_id, :advertisement_id, :cost
before_update :calculate_cost
belongs_to :advertisement
has_one :board, through: :advertisement
validates :x_location, presence: true, :numericality => { :greater_than_or_equal_to => 0}
validates :y_location, presence: true, :numericality => { :greater_than_or_equal_to => 0}
validates :cost, presence: true, :numericality => { :greater_than_or_equal_to => 0}
validate :check_tile_bounds
def age
if (cost/2) < 0.01
cost = 0
else
cost = (cost / 2).truncate(2)
end
end
def calculate_cost
if cost <= 1
cost = 0
else
if cost > 1.0
cost = cost * 2.0
else
cost = 1.0
end
end
end
private
def check_tile_bounds
unless x_location.nil?
if x_location >= board.width
errors.add(:x_location, "x location outside board width")
end
if (x_location < advertisement.x_location)
errors.add(:x_location, "x smaller than ad location")
end
if (x_location > advertisement.width + advertisement.x_location - 1)
errors.add(:x_location, "x larger than ad width")
end
end
unless y_location.nil?
if (y_location >= board.height)
errors.add(:y_location, "y location outside board")
end
if (y_location > advertisement.height + advertisement.y_location - 1)
errors.add(:y_location, "y larger than ad height")
end
if (y_location < advertisement.y_location)
errors.add(:y_location, "y smaller than ad location")
end
end
end
end
|
require 'test_helper'
class Admin::Api::UsersTest < ActionDispatch::IntegrationTest
include FieldsDefinitionsHelpers
def setup
@provider = FactoryBot.create :provider_account, :domain => 'provider.example.com'
@master = @provider.provider_account
field_defined(@master, :name => 'username')
field_defined(@master, :name => 'email')
@member = FactoryBot.create :user, account: @provider, role: 'member', admin_sections: ['partners']
host! @provider.admin_domain
end
# ACCESS TOKEN
test 'index with access token as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
get(admin_api_users_path(format: :xml), access_token: token.value)
assert_response :forbidden
end
test 'index with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
Settings::Switch.any_instance.stubs(:allowed?).returns(false)
get(admin_api_users_path(format: :xml), access_token: token.value)
assert_response :forbidden
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
get(admin_api_users_path(format: :xml), access_token: token.value)
assert_response :success
end
test 'index do not return the impersonation admin user' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
impersonation_admin = Signup::ImpersonationAdminBuilder.build(account: @provider)
impersonation_admin.save!
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
get(admin_api_users_path(format: :xml), access_token: token.value)
assert_response :success
refute_xpath ".//username", /impersonation_admin/
end
test 'show with access token as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
# member's opening his page
get(admin_api_user_path(format: :xml, id: @member.id), access_token: token.value)
assert_response :success
# member's opening admin's page
get(admin_api_user_path(format: :xml, id: admin.id), access_token: token.value)
assert_response :forbidden
end
test 'show with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
get(admin_api_user_path(format: :xml, id: @member.id), access_token: token.value)
assert_response :success
end
test 'create with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
Settings::Switch.any_instance.stubs(:allowed?).returns(false)
post(admin_api_users_path(format: :xml), username: 'aaa', email: 'aaa@aaa.hu', access_token: token.value)
assert_response :forbidden
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
post(admin_api_users_path(format: :xml), username: 'aaa', email: 'aaa@aaa.hu', access_token: token.value)
assert_response :success
end
test 'update with access token as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
put(admin_api_user_path(format: :xml, id: @member.id, access_token: token.value))
assert_response :success
put(admin_api_user_path(format: :xml, id: admin.id, access_token: token.value))
assert_response :forbidden
end
test 'update with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
put(admin_api_user_path(format: :xml, id: @member.id, access_token: token.value))
assert_response :success
end
test 'destroy with access token as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
delete(admin_api_user_path(format: :xml, id: admin.id, access_token: token.value))
assert_response :forbidden
end
test 'destroy with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
delete(admin_api_user_path(format: :xml, id: @member.id, access_token: token.value))
assert_response :success
end
test 'admin/update_role with access token as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
put "/admin/api/users/#{admin.id}/admin.xml?access_token=#{token.value}"
assert_response :forbidden
end
test 'admin/update_role with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
put "/admin/api/users/#{@member.id}/admin.xml?access_token=#{token.value}"
assert_response :success
end
test 'set group permissions as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
service = @provider.services.default
put admin_api_user_path(format: :xml, id: @member.id, access_token: token.value),
{ member_permission_service_ids: [ service.id ], member_permission_ids: %w[monitoring services] }
assert_response :success
assert @member.reload
assert_equal [ service.id ], @member.member_permission_service_ids
assert_equal Set[ :services, :monitoring ], @member.admin_sections
end
test 'set group permissions as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
service = @provider.services.default
admin_sections = @member.admin_sections
put admin_api_user_path(format: :xml, id: @member.id, access_token: token.value),
{ member_permission_service_ids: [ service.id], member_permission_ids: %w[monitoring] }
assert_response :success
# the permissions have not changed - the same as original
assert @member.reload
assert_nil @member.member_permission_service_ids
assert_equal admin_sections, @member.admin_sections
end
test 'suspend/unsuspend with access token as a member' do
token = FactoryBot.create(:access_token, owner: @member, scopes: ['account_management'])
admin.activate!
put "/admin/api/users/#{admin.id}/suspend.xml?access_token=#{token.value}"
assert_response :forbidden
put "/admin/api/users/#{admin.id}/unsuspend.xml?access_token=#{token.value}"
assert_response :forbidden
end
test 'suspend/unsuspend with access token as an admin' do
token = FactoryBot.create(:access_token, owner: admin, scopes: ['account_management'])
@member.activate!
put "/admin/api/users/#{@member.id}/suspend.xml?access_token=#{token.value}"
assert_response :success
put "/admin/api/users/#{@member.id}/unsuspend.xml?access_token=#{token.value}"
assert_response :success
end
# PROVIDER ID
#TODO: explicitly test the extra fields
test 'index' do
get(admin_api_users_path(:format => :xml),
:provider_key => @provider.api_key)
assert_response :success
assert_users @response.body, { :account_id => @provider.id }
end
#TODO: dry these roles tests
test 'admins' do
get(admin_api_users_path(:format => :xml),
:provider_key => @provider.api_key, :role => 'admin')
assert_response :success
assert_users @response.body, { :account_id => @provider.id, :role => "admin" }
end
test 'members' do
get(admin_api_users_path(:format => :xml),
:provider_key => @provider.api_key, :role => 'member')
assert_response :success
assert_users @response.body, { :account_id => @provider.id, :role => "member" }
end
#TODO: dry these states tests
test 'actives' do
get(admin_api_users_path(:format => :xml),
:provider_key => @provider.api_key, :state => 'active')
assert_response :success
assert_users @response.body, { :account_id => @provider.id, :state => "active" }
end
test 'pendings' do
get(admin_api_users_path(:format => :xml),
:provider_key => @provider.api_key, :state => 'pending')
assert_response :success
assert_users @response.body, { :account_id => @provider.id, :state => "pending" }
end
test 'suspendeds' do
chuck = FactoryBot.create :user, :account => @provider
chuck.activate!
chuck.suspend!
get(admin_api_users_path(:format => :xml),
:provider_key => @provider.api_key, :state => 'suspended')
assert_response :success
assert_users @response.body, {:account_id => @provider.id, :state => "suspended"}
end
test 'invalid role' do
get(admin_api_users_path(: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
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
post(admin_api_users_path(:format => :xml),
:username => 'chuck',
:email => 'chuck@norris.us',
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body,
{ :account_id => @provider.id,
:role => "member", :state => "pending" })
assert User.last.pending?
assert User.last.member?
end
test 'create with extra fields' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
field_defined(@master,
{ :target => "User", "name" => "some_extra_field" })
post(admin_api_users_path(: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 => @provider.id,
:extra_fields => { :some_extra_field => "extra value" }})
assert User.last.extra_fields["some_extra_field"] == "extra value"
end
test "create sends no email" do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
assert_no_change :of => -> { ActionMailer::Base.deliveries.count } do
post(admin_api_users_path(:format => :xml),
:username => 'chuck',
:email => 'chuck@norris.us',
:provider_key => @provider.api_key)
end
assert_response :success
end
test "create with cas_identifier" do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
post(admin_api_users_path(:format => :xml),
:username => 'luis',
:email => 'luis@norris.us',
:cas_identifier => 'luis',
:provider_key => @provider.api_key)
assert_response :success
assert_user body, {:cas_identifier => 'luis'}
end
test 'create does not creates admins nor active users' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
post(admin_api_users_path(: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 => @provider.id,
:role => "member",
:state => "pending" })
assert User.last.pending?
assert User.last.member?
end
test 'create also sets user password' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
post(admin_api_users_path(: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.authenticated?('posted-password')
end
test 'create errors' do
Settings::Switch.any_instance.stubs(:allowed?).returns(true)
post(admin_api_users_path(: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 "create forbidden if multiple_users is not allowed" do
assert_no_change :of => -> { ActionMailer::Base.deliveries.count } do
post(admin_api_users_path(:format => :xml),
:username => 'chuck',
:email => 'chuck@norris.us',
:provider_key => @provider.api_key)
end
assert_response :forbidden
end
test 'show' do
get(admin_api_user_path(:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body, {
:account_id => @provider.id, :role => "member",
:created_at => @member.created_at.xmlschema,
:updated_at => @member.updated_at.xmlschema })
end
test '3scale not found' do
impersonation_admin = Signup::ImpersonationAdminBuilder.build(account: @provider)
impersonation_admin.save!
get(admin_api_user_path(:format => :xml, :id => impersonation_admin.id),
:provider_key => @provider.api_key)
assert_response :not_found
assert_empty_xml @response.body
end
test 'show with cas identifier' do
cas_user = FactoryBot.create :user, :account => @provider, :role => 'member', :cas_identifier => 'xxx-enterprise'
get(admin_api_user_path(:format => :xml, :id => cas_user.id),
:provider_key => @provider.api_key)
assert_response :success
assert_user body, :cas_identifier => 'xxx-enterprise'
end
test 'show returns extra fields escaped' do
field_defined(@master,
{ :target => "User", "name" => "some_extra_field" })
@member.reload
@member.extra_fields = { :some_extra_field => "< > &" }
@member.save
get(admin_api_user_path(:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body, :extra_fields => {
:some_extra_field => '< > &' })
end
test 'show user not found' do
get(admin_api_user_path(:format => :xml, :id => 0),
:provider_key => @provider.api_key)
assert_response :not_found
assert_empty_xml @response.body
end
test 'update also updates extra fields' do
field_defined(@master,
{ :target => "User", "name" => "some_extra_field" })
chuck = FactoryBot.create :user, :account => @provider, :role => "member"
put(admin_api_user_path(:format => :xml, :id => chuck.id,
:some_extra_field => "extra value" ),
:provider_key => @provider.api_key)
assert_response :success
assert_user(@response.body, { :account_id => @provider.id,
:extra_fields => { :some_extra_field => "extra value" }})
chuck.reload
assert chuck.extra_fields["some_extra_field"] == "extra value"
end
test 'update also updates password' do
chuck = FactoryBot.create :user, :account => @provider, :role => "member"
assert chuck.authenticated?('supersecret')
put(admin_api_user_path(:format => :xml, :id => chuck.id,
:password => "updated-password",
:password_confirmation => "updated-password"),
:provider_key => @provider.api_key)
chuck.reload
assert_response :success
assert chuck.authenticated?('updated-password')
end
test 'update does not updates state nor role' do
chuck = FactoryBot.create :user, :account => @provider, :role => "member"
assert chuck.pending?
assert chuck.member?
put(admin_api_user_path(: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 => @provider.id,
:role => "member",
:state => "pending" })
chuck.reload
assert chuck.pending?
assert chuck.member?
end
test 'update not found' do
put(admin_api_user_path(:format => :xml, :id => 0),
:provider_key => @provider.api_key)
assert_response :not_found
assert_empty_xml @response.body
end
test 'destroy' do
delete(admin_api_user_path(:format => :xml, :id => @member.id),
:provider_key => @provider.api_key)
assert_response :success
assert_empty_xml @response.body
end
test 'destroy not found' do
delete(admin_api_user_path(:format => :xml, :id => 0),
:provider_key => @provider.api_key)
assert_response :not_found
assert_empty_xml @response.body
end
test 'member' do
chuck = FactoryBot.create :user, :account => @provider
chuck.make_admin
put "/admin/api/users/#{chuck.id}/member.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, { :account_id => @provider.id, :role => "member" }
chuck.reload
assert chuck.member?
end
test 'admin' do
chuck = FactoryBot.create :user, :account => @provider
chuck.make_member
put "/admin/api/users/#{chuck.id}/admin.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, { :account_id => @provider.id, :role => "admin" }
chuck.reload
assert chuck.admin?
end
test 'suspend an active user' do
chuck = FactoryBot.create :user, :account => @provider
chuck.activate!
put "/admin/api/users/#{chuck.id}/suspend.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, {:account_id => @provider.id, :state => "suspended"}
chuck.reload
assert chuck.suspended?
end
test 'activate a pending user' do
chuck = FactoryBot.create :user, :account => @provider
put "/admin/api/users/#{chuck.id}/activate.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, {:account_id => @provider.id, :state => "active"}
chuck.reload
assert chuck.active?
end
test 'activate sends no email' do
chuck = FactoryBot.create :user, :account => @provider
assert_no_change :of => -> { ActionMailer::Base.deliveries.count } do
put "/admin/api/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 = FactoryBot.create :user, :account => @provider
chuck.activate!
chuck.suspend!
put "/admin/api/users/#{chuck.id}/unsuspend.xml?provider_key=#{@provider.api_key}"
assert_response :success
assert_user @response.body, {:account_id => @provider.id, :state => "active"}
chuck.reload
assert chuck.active?
end
private
def admin
@admin ||= FactoryBot.create :simple_user, account: @provider, role: 'admin'
end
end
|
class CreateGames < ActiveRecord::Migration[6.0]
def change
create_table :games do |t|
t.datetime :date
t.integer :home_team_score
t.integer :visitor_team_score
t.integer :season
t.references :home_team
t.references :visitor_team
t.timestamps
end
end
end
|
require('rspec')
require('triangle')
require('pry')
describe(Triangle) do
describe('#triangle?') do
it("returns false if any side is equal to 0") do
test_triangle = Triangle.new(0, 7, 6)
expect(test_triangle.triangle?()).to(eq(false))
end
it("returns false if it is not a triangle") do
test_triangle = Triangle.new(2, 2, 6)
expect(test_triangle.triangle?()).to(eq(false))
end
it("returns true if it is a triangle") do
test_triangle = Triangle.new( 3, 5, 7)
expect(test_triangle.triangle?()).to(eq(true))
end
it("returns 'equilateral' if all sides are equal") do
test_triangle = Triangle.new(4, 4, 4)
expect(test_triangle.type?()).to(eq("equilateral"))
end
it("returns 'isosceles' if two of three sides are equal") do
test_triangle = Triangle.new(4, 4, 6)
expect(test_triangle.type?()).to(eq("isosceles"))
end
it("returns 'scalene' if no sides are equal") do
test_triangle = Triangle.new(4, 5, 6)
expect(test_triangle.type?()).to(eq("scalene"))
end
end
end
|
module FastGettext
# Responsibility:
# - store data threadsave
# - provide error messages when repositories are unconfigured
# - accept/reject locales that are set by the user
module Storage
class NoTextDomainConfigured < Exception;end
[:available_locales,:text_domain,:_locale,:current_cache].each do |method|
eval <<EOF
def #{method}
Thread.current[:fast_gettext_#{method}]
end
def #{method}=(value)
Thread.current[:fast_gettext_#{method}]=value
end
EOF
end
private :_locale, :_locale=
#so initial translations does not crash
Thread.current[:fast_gettext_current_cache]={}
def text_domain=(new_domain)
Thread.current[:fast_gettext_text_domain]=new_domain
update_current_cache
end
#global, since re-parsing whole folders takes too much time...
@@translation_repositories={}
def translation_repositories
@@translation_repositories
end
# used to speedup simple translations, does not work for pluralisation
# caches[text_domain][locale][key]=translation
@@caches={}
def caches
@@caches
end
def current_repository
translation_repositories[text_domain] || NoTextDomainConfigured
end
def locale
_locale || (available_locales||[]).first || 'en'
end
def locale=(new_locale)
new_locale = best_locale_in(new_locale)
if new_locale
self._locale = new_locale
update_current_cache
end
end
# for chaining: puts set_locale('xx') == 'xx' ? 'applied' : 'rejected'
# returns the current locale, not the one that was supplied
# like locale=(), whoes behavior cannot be changed
def set_locale(new_locale)
self.locale = new_locale
locale
end
#Opera: de-DE,de;q=0.9,en;q=0.8
#Firefox de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
#IE6/7 de
#nil if nothing matches
def best_locale_in(locales)
locales = locales.to_s.gsub(/\s/,'')
#split the locale and seperate it into different languages
#[['de-de','de','0.5'], ['en','0.8'], ...]
parts = locales.split(',')
locales = [[]]
parts.each do |part|
locales.last << part.split(/;q=/)#add another language or language and weight
locales += [] if part.length == 2 #if it could be split we are now in a new locale
end
locales.sort!(&:last) #sort them by weight which is the last entry
locales.flatten.each do |candidate|
candidate = candidate.sub(/^([a-zA-Z]{2})[-_]([a-zA-Z]{2})$/){$1.downcase+'_'+$2.upcase}#de-de -> de_DE
return candidate if not available_locales or available_locales.include?(candidate)
end
return nil#nothing found im sorry :P
end
#turn off translation if none was defined to disable all resulting errors
def silence_errors
if not self.current_repository or self.current_repository == NoTextDomainConfigured
require 'fast_gettext/translation_repository/base'
translation_repositories[text_domain] = TranslationRepository::Base.new('x')
end
end
private
def update_current_cache
caches[text_domain]||={}
caches[text_domain][locale]||={}
self.current_cache = caches[text_domain][locale]
end
end
end |
class Panel::HistoriesController < Panel::TabledController
def model
History
end
def table_headers
%w(created_date patient_fullname weight_str size_str)
end
def init_form
@histories = History.accessible_by(current_ability).order([:patient_id, id: :desc])
end
private
def item_params
params.require(:history).permit(:clinic_id, :patient_id, :pathological, :nonpathological, :family, :surgical, :allergies, :medicines, :weight, :size)
end
end
|
require 'xml_patch/diff_builder'
require 'xml_patch/target_document'
module XmlPatch
class Applicator
attr_reader :diff_xml
def initialize(diff_xml)
@diff_xml = diff_xml.dup.freeze
end
def to(target_xml)
diff = XmlPatch::DiffBuilder.new.parse(diff_xml).diff_document
target = XmlPatch::TargetDocument.new(target_xml)
diff.apply_to(target)
target.to_xml
end
end
end
|
require 'plist'
module Encrust
class Converter
class << self
def iterm_to_df(path)
header << colors(path) << footer(path)
end
private
# ANSI Color 3 ("yellow") is called "BROWN" in Dwarf Fortress,
# while ANSI Color 11 ("bright yellow") is simply called "YELLOW".
# ANSI Color 7 ("white") is called "LGRAY" in Dwarf Fortress,
# ANSI Color 8 ("bright black") is called "DGRAY", and
# ANSI Color 15 ("bright white") is called "WHITE".
def df_color_names
%i[BLACK RED GREEN BROWN BLUE MAGENTA CYAN LGRAY
DGRAY LRED LGREEN YELLOW LBLUE LMAGENTA LCYAN WHITE]
end
def parse(path)
begin
Plist.parse_xml(path)
rescue RuntimeError => e
msg = "Failed to parse file at path: #{path}"
raise ArgumentError.new(msg)
end
end
def colors(path)
iterm_colors = parse(path)
df_color_names.each_with_index.reduce("") do |df_colors, (color, i)|
iterm_rgb = iterm_colors["Ansi #{i} Color"]
if iterm_rgb.nil?
msg = "Missing color definition for #{color} (DF) / #{i} (ANSI)"
raise ArgumentError.new(msg)
end
df_colors << generate_df_color(color, iterm_rgb)
end
end
def generate_df_color(color, iterm_rgb)
red = (iterm_rgb['Red Component'] * 255).to_i
green = (iterm_rgb['Green Component'] * 255).to_i
blue = (iterm_rgb['Blue Component'] * 255).to_i
if [red, green, blue].any? { |x| x > 255 || 0 > x }
msg = "RGB value for #{color} (DF) out of valid range."
raise ArgumentError.new(msg)
end
<<~DWARF
[#{color}_R:#{red}]
[#{color}_G:#{green}]
[#{color}_B:#{blue}]
DWARF
end
def header
<<~DWARF
These are the display colors in RGB. \
The game is actually displaying extended \
ASCII characters in OpenGL, so you can modify the colors.
DWARF
end
def footer(path)
<<~DWARF
Converted from `#{File.basename(path)}` using encrust:
https://github.com/molly-cactus/encrust
DWARF
end
end
end
end
|
class HomeController < ApplicationController
def new
@guest = Guest.new
@communities = Community.all
end
def create
@guest = Guest.new(guest_params)
respond_to do |format|
if @guest.save
format.html { redirect_to :action => "thank_you", notice: 'Thank you your response has been recorded.' }
format.json { render :show, status: :created, location: @guest }
else
format.html { render :new }
format.json { render json: @guest.errors, status: :unprocessable_entity }
end
end
end
def thank_you
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def guest_params
params.require(:guest).permit(:name, :email, :community_ids => [], :welcomer_ids => [])
end
end
|
class Definition
attr_accessor :inputdef, :word_id, :id
@@definitions = {}
@@total_ids = 0
def initialize(inputdef, word_id, id)
@inputdef = inputdef
@word_id = word_id
@id = id || @@total_ids += 1
end
def self.all
@@definitions.values
end
def save
@@definitions[self.id] = Definition.new(self.inputdef, self.word_id, self.id)
end
def self.clear
@@definitions = {}
@@total_ids = 0
end
def ==(definition_to_compare)
(self.inputdef() == definition_to_compare.inputdef()) && (self.word_id() == definition_to_compare.word_id())
end
def self.find(id)
@@definitions[id]
end
def update(inputdef)
@inputdef = inputdef
end
def delete
@@definitions.delete(self.id)
end
def edit(inputdef, word_id)
self.inputdef = inputdef
self.word_id = word_id
@@definitions[self.id] = Definition.new(self.inputdef, self.word_id, self.id)
end
def self.find_by_word(word_id)
definitions_arr = []
@@definitions.values.each do |definition|
if definition.word_id == word_id
definitions_arr.push(definition)
end
end
definitions_arr
end
def word
Word.find(self.word_id)
end
end
|
require './lib/board'
require './lib/user'
class Player < User
def setup
@ships.values.each do |ship|
print "Enter the cells for the #{ship.name} (#{ship.length} spaces):\n> "
coordinates_prompt(ship)
end
end
def coordinates_prompt(ship)
input = gets.chomp
cells = input.upcase.split(' ')
if @board.valid_placement?(ship, cells)
@board.place(ship, cells)
puts @board.render(true)
else
print "Those are invalid coordinates. Please try again:\n> "
coordinates_prompt(ship)
end
end
def shoot(board)
shot = gets.chomp.upcase
while !board.valid_coordinate?(shot) || board.cells[shot].fired_upon?
coordinate_feedback(board, shot)
shot = gets.chomp.upcase
end
board.cells[shot].fire_upon
shot
end
def coordinate_feedback(board, shot)
if !board.valid_coordinate?(shot)
print "Please enter a valid coordinate:\n> "
else
print "You have already fired on that cell. Please enter a new one:\n> "
end
end
def shot_feedback(shot, letter)
puts "My shot on #{shot} #{meanings[letter]}."
end
end
|
class CreateVlans < ActiveRecord::Migration
def self.up
create_table :vlans do |t|
t.integer :numero
t.references :practica
t.references :puerto
t.references :endpoint
t.timestamps
end
end
def self.down
drop_table :vlans
end
end
|
class MealsController
def initialize(meal_repo)
@repo = meal_repo
@view = MealView.new
end
def add_meal
info = @view.ask_for_info
meal = Meal.new(info)
@repo.add_meal(meal)
end
def list_meals
@view.list(@repo.meals)
end
end
class CustomersController
def initialize(repository)
@repository = repository
@view = Customer.View.new
end
def add_customer
info = @view.ask_for_info
customer = Customer.new(info)
@repository.add_customer(customer)
end
def list_customers
customers = @repository.customers
@view.list(customers)
end
end
class EmployeeController
def initialize(repository)
@repo = repository
end
def verify(name, password)
@repo.find_password(name) == password
end
def find_role(name)
@repo.find_role(name)
end
end
class OrdersController
def initialize(order_repo, customer_repo, meal_repo, employee_repo)
@order_repo = order_repo
@customer_repo = customer_repo
@meal_repo = meal_repo
@employee_repo = employee_repo
@view = Order.View.new(CustomerView.new, Meal.View.new)
end
def add_order
customer_id = @view.ask_for_customer(@customer_repo.customers)
customer = @customer_repo.find_by_id(customer_id)
meal_id = @view.ask_for_meal(@meal_repo.meals)
meal = @meal_repo.find_by_id(meal_id)
employee_id = @view.ask_for_employee
employee = @employee_repo.find_by_id(employee_id)
order = Order.new({meal: meal, customer: cusotmer, employee: employee})
customer.add_order(order)
employee.add_order(order)
@order_repo.add_order(order)
end
def list_orders
order = @order_repo.undelivered_orders
@view.list_orders(orders)
end
def list_undelivered_orders
orders = @order_repo.undelivered_orders
@view.list_orders(orders)
end
def list_my_underlivered_orders(employee_name)
orders = @order_repo.undelivered_orders.select{|order|order.employee_name ==employee_name}
@view.list_orders(orders)
end
def mark_order_delivered(employee_name)
list_my_undelivered_orders(employee_name)
id = @view.ask_for_order_id
end
end
s
|
require 'test/unit'
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'dieroll.rb'
class TestDiceSet< Test::Unit::TestCase
def setup
@one_d6 = Dieroll::DiceSet.new(1,6,'+',nil)
@two_d10 = Dieroll::DiceSet.new(2,10,'+',nil)
@minus_two_d8_drop_low = Dieroll::DiceSet.new(2,8,'-','l')
@two_d2 = Dieroll::DiceSet.new(2,2,'+',nil)
@three_d2 = Dieroll::DiceSet.new(3,2,'+',nil)
end
def teardown
end
def test_init
assert_equal 1, @one_d6.instance_variable_get("@number_of_dice")
assert_equal 6, @one_d6.instance_variable_get("@sides")
assert_equal 1, @one_d6.instance_variable_get("@dice").count
assert_equal [0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667],
@one_d6.odds.instance_variable_get("@odds_array").
map{|value| value.round(4)}
assert_equal 1, @one_d6.odds.offset
assert_equal 2, @two_d10.instance_variable_get("@dice").count
assert @one_d6.instance_variable_get("@last_results").empty?
assert_equal nil, @one_d6.instance_variable_get("@last_total")
assert_equal [0.2500, 0.5000, 0.2500],
@two_d2.odds.instance_variable_get("@odds_array")
assert_equal 2, @two_d2.odds.offset
assert_equal [0.1250, 0.3750, 0.3750, 0.1250],
@three_d2.odds.instance_variable_get("@odds_array")
assert_equal 3, @three_d2.odds.offset
end
def test_roll
@one_d6.roll!
@two_d10.roll!
@minus_two_d8_drop_low.roll!
assert_equal 1, @one_d6.instance_variable_get("@last_results").count
assert_equal 2, @two_d10.instance_variable_get("@last_results").count
assert_equal @one_d6.instance_variable_get("@last_total"),
@one_d6.instance_variable_get("@last_results").
inject(0){|sum, element| sum + element}
assert_equal 2, @minus_two_d8_drop_low.
instance_variable_get("@last_results").count
assert_equal 1, @minus_two_d8_drop_low.
instance_variable_get("@last_non_dropped").count
assert_equal @minus_two_d8_drop_low.
instance_variable_get("@last_non_dropped")[0],
@minus_two_d8_drop_low.
instance_variable_get("@last_results")[1]
end
def test_to_s
end
end
|
module GosuMock
# A font can be used to draw text on a Window object very flexibly.
# Fonts are ideal for small texts that change regularly. For large,
# static texts you should use {Gosu::Image#from_text}.
class Font
class << self
attr_accessor :window, :font_name, :height
##
# The font's name. This may be the name of a system font or a filename.
#
# @return [String] the font's name.
attr_reader :name
##
# @return [Fixnum] The font's height in pixels.
attr_reader :height
##
# Load a font from the system fonts or a file.
#
# @param window [Gosu::Window]
# @param font_name [String] the name of a system font, or a path to a TrueType Font (TTF) file. A path must contain at least one '/' character to distinguish it from a system font.
# @param height [Fixnum] the height of the font, in pixels.
def initialize(window, font_name, height);
window = window
font_name = font_name
height = height
end
# @!group Drawing text
##
# Draws a single line of text with its top left corner at (x, y).
#
# @return [void]
# @param text [String]
# @param x [Number] the X coordinate
# @param y [Number] the Y coordinate
# @param z [Number] the Z-order.
# @param factor_x [Float] the horizontal scaling factor.
# @param factor_y [Float] the vertical scaling factor.
# @param color [Color, Fixnum]
# @param mode [:default, :additive] the blending mode to use.
#
# @see #draw_rel
# @see Gosu::Image.from_text
# @see file:reference/Drawing_with_Colors.md Drawing with Colors
# @see file:reference/Z-Ordering.md
def draw(text, x, y, z, factor_x=1, factor_y=1, color=0xffffffff, mode=:default);
end
##
# Draws a single line of text relative to (x, y).
#
# The text is aligned to the drawing location according to the `rel_x` and `rel_y` parameters: a value of 0.0 corresponds to top and left, while 1.0 corresponds to bottom and right. A value of 0.5 naturally corresponds to the center of the text.
#
# All real numbers are valid alignment values and will be interpolated (or extrapolated) accordingly.
#
# @return [void]
# @param rel_x [Float] the horizontal alignment.
# @param rel_y [Float] the vertical alignment.
# @param (see #draw)
#
# @see #draw
# @see file:reference/Drawing_with_Colors.md Drawing with Colors
# @see file:reference/Z-Ordering.md
def draw_rel(text, x, y, z, rel_x, rel_y, factor_x=1, factor_y=1, color=0xffffffff, mode=:default);
end
# @!endgroup
end
end
end |
class Api::V1::UsersController < ApplicationController
require 'oauth'
require 'nokogiri'
def show #sends back the user if the user requesting the record is same as the user loggedin
@user = User.find(params[:id])
render json:{:user => @user}, status: :ok
end
def logged_in
#This method will return the current logged in user if there is any.
respond_to do |format|
if current_user
format.json {render json:{user: current_user}}
else
format.json {render json: {:message => "Nobody logged In"},status: :ok}
end
end
end
def user_signin
#This method will handle the sign in of a user through an ajax request.
#The user from the frontend will enter his/her credentials in the modal. The Ember app will then make an ajax request to our rails app
#with the data entered by the user. Then we will authenticate the user through devise and set the current_user.
# If successfully authenticated we will respond with the user_id to the frontend otherwise we will respond with errors
# encountered.
if request.method != 'POST' or !request.xhr?
render json:{},:status => :not_acceptable
else
sign_out(current_user) if current_user
user = User.find_by_email(params[:user][:email])
if user.nil?
respond_to do |format|
format.json {render json: {:message => "Sorry this User does not exist."}}
end
else
if user.valid_password?(params[:user][:password]) #Check the password validtity
sign_in(:user, user) #Sign in the user
if current_user
respond_to do |format|
format.json {render json: {:message => "Sign in successful"}}
end
end
else
respond_to do |format|
format.json {render json: {:message => "Password invalid"}}
end
end
end
end
end
def user_signup
#This method will handle the user sign up through an ajax request.
#The user from the frontend will enter details in the modal. The Ember app will then make an ajax request to our rails app
#with the data entered by the user. Then we will create the user in this method. If successfully created the response will
#contain msg with value 1. Otherwise we will send the errors encountered in user model creation in JSON format to frontend.
#This method assumes all the data validations have been done by the frontend application. Devise also will do another set of
#validations and checks before creating the user.
if request.method != 'POST' or !request.xhr?
render json:{},:status => :not_acceptable
else
user = User.new(user_params)
message_success= {:msg => 1 }
if user.save
sign_out(current_user) if current_user
sign_in(:user, user)
render json: {:msg => 1}, status: :ok
else
errors = user.errors
render json: errors.messages, status: :ok
end
end
end
def resend_confirmation
respond_to do |format|
if current_user and current_user.confirmed_at.nil?
current_user.send_confirmation_instructions
format.json {render json: {:message => "Sent"}}
else
if !current_user.confirmed_at.nil?
format.json {render json: {:message => "Already Confirmed"}}
end
end
end
end
def forgot_password
user = User.find_by_email(params[:email])
respond_to do |format|
if !user.nil? and user.send_reset_password_instructions
format.json {render json: {:message => "Password reset instructions have been sent to the email."}}
else
format.json {render json: {:message => "User does not exist."}}
end
end
end
def change_password
if params[:user]
if current_user.valid_password? params[:user][:oldPassword]
current_user.password=params[:user][:newPassword]
#current_user.reset_password_token=User.reset_password_token
current_user.reset_password_sent_at = Time.now
if current_user.save
#Whenever user changes password we recompute the md5hash so that previous hashes stored on devices don't work.
#current_user.generate_md5hash
#Notifier.delay.change_password(current_user)
respond_to do |format|
format.json {render json: {:status=>"Password change successful. Please login again with new password."}}
end
else
respond_to do |format|
format.json {render json: {:status=>"There was some error on our side. Please try again later."}}
end
end
else
respond_to do |format|
format.json {render json: {:status=>"It seems you entered the wrong old password"}}
end
end
else
respond_to do |format|
format.json {render :json => {:status=>"Error:Not a valid User"} }
end
end
end
def facebook
if params[:access_token].nil?
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
else
token=params[:access_token]
uri = URI.parse('https://graph.facebook.com/me')
args = {:access_token=> token,:fields=>'id,first_name,last_name,email'}
uri.query = URI.encode_www_form(args)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
begin
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
if response.nil?
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
else
parsed_data= JSON.parse response.body
end
unless parsed_data.has_key?('id') and parsed_data.has_key?('email') and parsed_data.has_key?('first_name') and parsed_data.has_key?('last_name')
raise Exception
end
rescue
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
end
uid=parsed_data['id']
email=parsed_data['email'].downcase
firstname=parsed_data['first_name']
lastname=parsed_data['last_name']
@user = get_auth_user(uid,firstname, lastname,email,token,'facebook')
respond_to do |format|
format.json {render :json=> @user}
end
end
end
def google
if params[:access_token].nil?
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
else
token=params[:access_token]
uri = URI.parse('https://www.googleapis.com/oauth2/v1/userinfo')
args = {:access_token=> token}
uri.query = URI.encode_www_form(args)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
begin
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
if response.nil?
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
else
parsed_data= JSON.parse response.body
end
unless parsed_data.has_key?('id') and parsed_data.has_key?('email')
raise Exception
end
uid=parsed_data['id']
email=parsed_data['email'].downcase
uauth=UserAuth.where({:uid=>uid,:provider=>'google'}).first
rescue => e
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
end
if uauth.nil?
user=User.find_by_email email
if user.nil?
quri = URI.parse("https://www.googleapis.com/plus/v1/people/#{uid}?access_token=#{token}")
#qargs = {:key=> 'AIzaSyA3AogvKKttZlriHJmGqTLnVJa3UWGHT14',:fields=> 'name'}
#quri.query = URI.encode_www_form(qargs)
qhttp = Net::HTTP.new(quri.host, quri.port)
qhttp.use_ssl = true
qhttp.verify_mode = OpenSSL::SSL::VERIFY_NONE
qrequest = Net::HTTP::Get.new(quri.request_uri)
begin
qresponse = qhttp.request(qrequest)
if qresponse.nil?
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
else
parsed_response=JSON.parse qresponse.body
end
unless parsed_response.has_key?('name') and parsed_response['name'].has_key?('givenName') and parsed_response['name'].has_key?('familyName')
raise Exception
end
rescue
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
end
firstname=parsed_response['name']['givenName']
lastname=parsed_response['name']['familyName']
@user=User.create({:firstname=>firstname,:lastname=>lastname,:email=>email})
@user.confirm!
else
@user=user
end
UserAuth.create({:uid=>uid,:provider=>'google',:user_id=>@user.id,:token=>token})
else
@user=uauth.user
end
sign_out current_user if current_user
sign_in @user
respond_to do |format|
format.json {render :json=> {user: @user}}
end
end
end
def linkedin
# extract data from cookie stored in json
consumer_key = '75291j3don9dv6'
consumer_secret = 'GwSLgQ7U08Z2yg1T'
cookie_name = "linkedin_oauth_#{consumer_key}"
begin
credentials_json = cookies[cookie_name]
credentials = JSON.parse(credentials_json)
jsapi_access_token = credentials['access_token']
consumer = OAuth::Consumer.new(consumer_key, consumer_secret)
resp = consumer.request(
:post,
'https://api.linkedin.com/uas/oauth/accessToken',
nil,
{},
{'xoauth_oauth2_access_token' => jsapi_access_token}
)
oauth1_credentials = CGI.parse(resp.body)
['oauth_token', 'oauth_token_secret', 'oauth_expires_in', 'oauth_authorization_expires_in'].each do |key|
oauth1_credentials[key] = oauth1_credentials[key].first
end
#puts "Response: #{oauth1_credentials.inspect}"
access_token = OAuth::AccessToken.new(consumer, oauth1_credentials['oauth_token'], oauth1_credentials['oauth_token_secret'])
# Pick some fields
fields = ['id','first-name', 'last-name','email-address'].join(',')
# Make a request for JSON data
xml_str = access_token.get("/v1/people/~:(#{fields})").body
doc = Nokogiri::XML(xml_str)
uid = doc.xpath("//id").first.content
firstname = doc.xpath("//first-name").first.content
lastname = doc.xpath("//last-name").first.content
email = doc.xpath("//email-address").first.content
rescue
@user={'status'=>'error'}
respond_to do |format|
format.json {render :json=> @user}
end
return
end
@user = get_auth_user(uid,firstname, lastname,email,oauth1_credentials['oauth_token'],'linkedin')
respond_to do |format|
format.json {render :json=> @user}
end
end
def linkedin_callback
if params["oauth_problem"] == "user_refused"
respond_to do |format|
format.html {render 'callback'}
format.json {render :json=> {'status'=>'error'}}
end
return
else
begin
data = request.env["omniauth.auth"]
uid = data.uid
firstname = data.info.first_name
lastname = data.info.last_name
email = data.info.email
access_token = data.extra.access_token.token
rescue
respond_to do |format|
format.html {render 'callback'}
format.json {render :json=> {'status'=>'error'}}
end
return
end
if uid.nil? or firstname.nil? or lastname.nil? or email.nil?
respond_to do |format|
format.html {render 'callback'}
format.json {render :json=> {'status'=>'error'}}
end
return
else
@user = get_auth_user(uid,firstname, lastname,email,access_token,'linkedin')
respond_to do |format|
format.html {render 'callback'}
format.json {render :json=> @user}
end
end
end
end
def get_auth_user(uid,firstname, lastname,email,access_token,provider)
uauth=UserAuth.where({:uid=>uid,:provider=>provider}).first
if uauth.nil?
user=User.find_by_email email
if user.nil?
@user=User.create({:firstname=>firstname,:lastname=>lastname,:email=>email})
@user.confirm!
else
@user=user
end
UserAuth.create({:uid=>uid,:provider=>provider,:user_id=>@user.id,:token=>access_token})
else
@user=uauth.user
end
sign_out current_user if current_user
sign_in @user
return @user
end
def twitter
# consumer_key and consumer_secret are from Twitter.
# You'll get them on your application details page.
consumer_key = '0bV98Yv7mFSDvd1bNc2pFQ'
consumer_secret = '9h5s4Rhg8zgtD1pf9Hjhqqz07oDCpnFvznmkehAyByY'
oauth = OAuth::Consumer.new(consumer_key, consumer_secret,{ :site => "https://api.twitter.com" })
# Ask for a token to make a request
url = "https://localhost:3000/auth/twitter/callback"
request_token = oauth.get_request_token(:oauth_callback => url)
# Take a note of the token and the secret. You'll need these later
session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret
# Send the user to Twitter to be authenticated
redirect_to request_token.authorize_url
end
def twitter_callback
consumer_key = '0bV98Yv7mFSDvd1bNc2pFQ'
consumer_secret = '9h5s4Rhg8zgtD1pf9Hjhqqz07oDCpnFvznmkehAyByY'
begin
oauth = OAuth::Consumer.new(consumer_key, consumer_secret,{ :site => "https://api.twitter.com" })
request_token = OAuth::RequestToken.new(oauth, session[:request_token],session[:request_token_secret])
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
response = access_token.request(:get, "/1.1/account/verify_credentials.json")
user_info = JSON.parse(response.body)
uid = user_info['id_str']
fullname = user_info["name"].split(' ')
first_name, last_name = fullname[0], fullname[1]
user_detail = {}
user_detail['uid'] = uid
user_detail['firstname'] = first_name
user_detail['lastname'] = last_name
uauth=UserAuth.where({:uid=>uid,:provider=>'twitter'}).first
rescue
@oauth_error = true
respond_to do |format|
format.html {render :layout=>false}
end
return
end
if !uauth.nil?
@user=uauth.user
sign_out current_user if current_user
sign_in @user
else
session[:user_info] = user_detail
@user = nil
end
respond_to do |format|
format.html {render :layout=> false}
end
end
def email_twitter_callback
email = params['email']
user_detail = session[:user_info]
uid = user_detail['uid']
firstname = user_detail['firstname']
lastname = user_detail['lastname']
@user = get_auth_user(uid,firstname, lastname,email,nil,'twitter')
respond_to do |format|
format.html {render 'twitter_callback', :layout=>false}
end
end
private
# Using a private method to encapsulate the permissible parameters is
# just a good pattern since you'll be able to reuse the same permit
# list between create and update. Also, you can specialize this method
# with per-user checking of permissible attributes.
def user_params
params.require(:user).permit(:firstname, :lastname, :email, :password, :password_confirmation)
end
end
|
# Write a method that takes one argument, a positive integer, and
# returns a list of the digits in the number.
def digit_list(number)
results = []
number.to_s.split('').each do |number|
results << number.to_i
end
results
end
# or
def digit_list(number)
digits = []
loop do
number, remainder = number.divmod(10)
digits.unshift(remainder)
break if number == 0
end
digits
end
# or
def digit_list(number)
number.to_s.chars.map(&:to_i)
end
# Examples:
puts digit_list(12345) == [1, 2, 3, 4, 5]
puts digit_list(7) == [7]
puts digit_list(375290) == [3, 7, 5, 2, 9, 0]
puts digit_list(444) == [4, 4, 4]
# All of the tests above should print true. |
class AddAttachmentLeaderboardToHomeResources < ActiveRecord::Migration
def self.up
add_column :home_resources, :leaderboard_file_name, :string
add_column :home_resources, :leaderboard_content_type, :string
add_column :home_resources, :leaderboard_file_size, :integer
add_column :home_resources, :leaderboard_updated_at, :datetime
end
def self.down
remove_column :home_resources, :leaderboard_file_name
remove_column :home_resources, :leaderboard_content_type
remove_column :home_resources, :leaderboard_file_size
remove_column :home_resources, :leaderboard_updated_at
end
end
|
class Appointment < ApplicationRecord
require 'date'
require "active_merchant/billing/rails"
belongs_to :initiator, class_name: "User"
belongs_to :receiver, class_name: "User"
validates :initiator_id, presence: true
validates :receiver_id, presence: true
has_one :payment
def create_appointment(parameters, initiator)
if (parameters[:appointment])
self.update(:initiator_id => initiator.id, :receiver_id => parameters[:id], :price => parameters[:appointment][:price], :currency => "USD", :datetime => DateTime.parse(parameters[:appointment][:datetime]))
end
return true
end
def validate_and_pay(payment_params, payment, ip_address)
if (payment_params[:payment])
# payment = Payment.new(payment_parameters(payment_params))
payment = Payment.new(payment_params[:payment])
payment.ip_address = ip_address
payment.appointment_id = self.id
create_card(payment_params[:payment])
if @credit_card.valid?
response = GATEWAY.purchase(price*100, @credit_card, :ip => payment.ip_address)
if (response.success?)
payment.save
attributes[:paid] = true
self.update_attributes(attributes)
return "true"
else
return "Error processing the payment. #{response.message}"
end
else
return "Error: credit card is not valid. #{@credit_card.errors.full_messages.join('. ')}"
end
end
return "true"
end
private
def create_card(params)
@credit_card = ActiveMerchant::Billing::CreditCard.new(
:brand => CreditCardValidations::Detector.new(params[:card_number]).brand,
:number => params[:card_number],
:verification_value => params[:card_verification],
:month => params[:card_expires_on].split("-")[0],
:year => params[:card_expires_on].split("-")[1],
:first_name => params[:first_name],
:last_name => params[:last_name]
)
end
def payment_parameters(payment_params)
payment_params.require(:payment).permit( :first_name, :last_name, :card_expires_on)
end
end
|
require 'leboncoin/htmlutils'
module LeBonCoin
module Search
module SearchItems
class << self
###
# Default constructor
def new link
@link = link
@items = Array.new
return self
end
###
# Create a new item
def createItem item = Hash.new
@items.push item
return item
end
def each
@items.each do |item|
yield item if block_given?
end
end
def size
return @items.size
end
def to_json
require 'json'
return JSON.pretty_generate(@items)
end
def to_rss
require 'rss/maker'
content = RSS::Maker.make("2.0") do |m|
m.channel.title = "leboncoin.fr"
m.channel.link = @link
m.channel.description = "leboncoin.fr"
m.items.do_sort = true
@items.each do |item|
price = ""
if item["price"] != nil
price = item["price"].to_s + " " + item["currency"]
end
postcode = ""
if item["postcode"] != nil
postcode = item["postcode"]
end
i = m.items.new_item
i.title = item["title"]
i.link = item["link"]
begin
i.description = LeBonCoin::HTMLUtils.convert("<img src='" + item["image"] + "'/><br/>" \
+ "<b>Ville</b> : " + item["city"] + "<br/>" \
+ "<b>Code postal</b> : " + postcode + "<br/>" \
+ "<p>" + item["description"] + "</p><hr/>" \
+ "<b>Prix</b> : " + price + "<hr/>")
rescue
require 'json'
puts ">>>> ERROR >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
puts JSON.pretty_generate(item)
puts "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
end
i.date = Time.now #item["date"]
end
end
end
end
end
end
end
|
require 'rbconfig'
require 'pathname'
require 'xsrb/exceptions'
#
module XenStore
# xs_wire.h uses uint32_t
MAX_UINT = (2**32).freeze
NUL = "\x00".freeze
CAPS_FILE = '/proc/xen/capabilities'.freeze
# Check whether we are in dom0
begin
CONTROL_D = File.open(CAPS_FILE, 'rb', &:read) == "control_d\n"
rescue Errno::ENOENT
CONTROL_D = false
end
OPERATIONS = {
debug: 0,
directory: 1,
read: 2,
get_perms: 3,
watch: 4,
unwatch: 5,
transaction_start: 6,
transaction_end: 7,
introduce: 8,
release: 9,
get_domain_path: 10,
write: 11,
mkdir: 12,
rm: 13,
set_perms: 14,
watch_event: 15,
error: 16,
is_domain_introduced: 17,
resume: 18,
set_target: 19,
restrict: 20,
reset_watches: 21,
invalid: MAX_UINT
}.freeze
# XenStore::Utils implements utility methods which are unlikely
# to be required by users but are used by the rest of the module
module Utils
@reqid = -1
@path_regex = Regexp.new '\A[a-zA-Z0-9\-/_@]+\x00?\z'
@watch_path_regex = Regexp.new '\A@(?:introduceDomain|releaseDomain)\x00?\z'
@perms_regex = Regexp.new '\A[wrbn]\d+\z'
@errno_exception_map = Hash[
Errno.constants.collect do |n|
[Errno.const_get(n)::Errno, Errno.const_get(n)]
end.reverse
].freeze
class << self
# Convert an error number or symbol to an Errno exception
#
# @param n [Integer, Symbol] An +Integer+ or +symbol+ representing the
# Errno exception to return.
# @return [Exception] The +Exception+ representing the provided type
# of error.
def error(n)
if n.is_a? Integer
@errno_exception_map[n]
else
Errno.send(n)
end
end
# Get the next request ID to contact XenStore with.
#
# @return [Integer] The next ID in the sequence.
def next_request_id
@reqid += 1
# Ensure no larger than uint32_t which is used in xs_wire.h
@reqid %= MAX_UINT
end
# Get the path of the XenStore unix socket.
#
# @return [String] The path to the XenStore unix socket.
def unix_socket_path
dp = '/var/run/xenstored'
ENV['XENSTORED_PATH'] || File.join(ENV['XENSTORED_RUNDIR'] || dp,
'socket')
end
# Raise an exception if the provided path is invalid.
#
# @param path [String] The XenStore path to check.
# @return [String] The valid path.
def valid_path?(path)
pathname = Pathname.new path
max_len = pathname.absolute? ? 3072 : 2048
if path.length > max_len
raise XenStore::Exceptions::InvalidPath,
"Path too long: #{path}"
end
unless @path_regex =~ path
raise XenStore::Exceptions::InvalidPath,
path.to_s
end
path
end
# Raise an exception if the provided XenStore watch path is invalid.
#
# @param path [String] The XenStore watch path to check.
# @return [String] The valid path.
def valid_watch_path?(path)
if path.starts_with?('@') && (@watch_path_regex !~ path)
raise XenStore::Exceptions::InvalidPath, path.to_s
end
valid_path? path
end
# Check if every member of a list of permissions strings is valid.
#
# @param perms [Array, String] An +Array+ of XenStore permissions
# specifications
# @return [Array] The list of permissions.
def valid_permissions?(perms)
perms = [perms] if perms.is_a? String
perms.each do |perm|
unless perm =~ @perms_regex
raise XenStore::Exceptions::InvalidPermission,
"Invalid permission string: #{perm}"
end
end
end
# Get the XenBus path on this system
#
# @return [String] The path to the XenBus device
def xenbus_path
default = '/dev/xen/xenbus'
host_os = RbConfig::CONFIG['host_os']
case host_os
when 'netbsd'
'/kern/xen/xenbus'
when 'linux'
File.readable?('/dev/xen/xenbus') ? '/proc/xen/xenbus' : default
when /mswin|windows/i
raise NotImplementedError,
"OS '#{RbConfig::CONFIG['host_os']}' is not supported"
else
default
end
end
end
end
end
|
# encoding: utf-8
class Spree::StockEmailsController < ApplicationController
def create
product = Spree::Product.find_by_id(params[:stock_email][:product])
redirect_to :back and return unless product
stock_email = Spree::StockEmail.new
stock_email.email = current_user ? current_user.email : params[:stock_email][:email]
stock_email.product = product
begin
stock_email.save! unless stock_email.email_exists?
flash[:success] = "Você receberá um email quando '#{product.name}' voltar ao estoque!"
rescue => e
flash[:notice] = "Ocorreu um erro ao tentar enviar o email. Por favor tente novamente."
end
redirect_to :back
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :login_required
protected
def login_required
unless logged_in_user
redirect_to login_path, notice: 'The requested action requires you to log in'
end
end
def admin_login_required
unless logged_in_user && logged_in_user.admin
redirect_to root_path
end
end
def logged_in_user
User.find(session[:user_id]) if session[:user_id]
end
end
|
namespace :services do
task :bootstrap => [:bootstrap_users, :bootstrap_relations] do
end
task :bootstrap_users => [:environment] do
puts "=== Boostraping users"
users_count = 0
requisites_count = 0
User.find_in_batches do |users_batch|
users_count += users_batch.size
counter = 0
users_batch.each do |user|
print "." if counter % 100 == 0
counter += 1
code = if Infosell::Requisite.check(user.nickname)
user.nickname
elsif Infosell::Requisite.check(user.email)
user.email
end
user.user_infosell_requisites.create(:infosell_code => code) and requisites_count += 1 if code.present?
STDOUT.flush
end
puts " #{counter} users processed"
end
puts "=== Checked #{users_count} users"
puts "=== Found #{requisites_count} requisites"
end
task :bootstrap_relations => [:environment] do
puts "=== Bootstraping authorized url relations"
class ElementaryResourceRelation < ActiveRecord::Base
establish_connection "old_passport"
end
relations_count = 0
ElementaryResourceRelation.find_in_batches do |relations_batch|
relations_count += relations_batch.size
relations_batch.each do |relation|
r = AuthorizedUrlInfosellResource.new(relation.attributes)
r.id = relation.id
r.save!
end
end
puts "#{relations_count} relations processed"
end
end
|
require 'active_support/inflector'
class Symbol
def include?(sym)
to_s.include?(sym.to_s)
end
def singularize
to_s.singularize.intern
end
def to_c
Kernel.const_get(self)
end
end |
class CommentsController < ApplicationController
def create
comment = Comment.new(comment_params)
if comment.save
render json: comment
else
render json: comment.errors.full_messages, status: 422
end
end
def destroy
comment = Comment.find(params[:id])
comment.destroy
render json: comment
end
def show
comment = Comment.find(params[:id])
if comment
render json: comment
else
render json: comment.errors.full_messages, status: 404
end
end
def index
if params[:user_id]
render json: Comment.gather_comments_author(params[:user_id])
elsif params[:artwork_id]
render json: Comment.gather_comments_artwork(params[:artwork_id])
else
render plain: 'boo ya'
end
end
private
def comment_params
params.require(:comment).permit(:author_id, :artwork_id, :body)
end
end |
# Helper Method
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
[0, 1, 2], # Top row
[3, 4, 5], # Middle row
[6, 7, 8], # Bottom row
[0, 3, 6], # Left column
[1, 4, 7], # Middle column
[2, 5, 8], # Right column
[0, 4, 8], # Left diagonal
[2, 4, 6] # Right diagonal
]
def won?(board)
win_combo = false
WIN_COMBINATIONS.each do |combination|
if board[combination[0]] == "X" && board[combination[1]] == "X" && board[combination[2]] == "X"
win_combo = combination
elsif board[combination[0]] == "O" && board[combination[1]] == "O" && board[combination[2]] == "O"
win_combo = combination
end
end
win_combo
end
def full?(board)
board.all? { |element| element == 'X' || element == 'O' }
end
def draw?(board)
full?(board) && !won?(board)
end
def over?(board)
# won?(board).class == Array || draw?(board) == true || full?(board) == true
won?(board) || full?(board)
end
def winner(board)
won_by = won?(board)
board[won_by[0]] if won_by
end
|
class OrdersController < ApplicationController
respond_to :html
before_filter :authenticate_user!
before_filter :load_order, except: [:index, :new, :create, :export_csv]
def index
@orders = Order.
by_status(params[:status]).
by_order_date.paginate(page: params[:page], per_page: 10)
end
def show
end
def new
@order = Order.new order_date: Date.today
@shipping_address = Address.new
end
def create
if create_order
flash[:notice] = 'The order was created successfully.'
respond_with @order, location: orders_path(status: :incipient)
else
# respond_with doesn't seem to work with nested objects
render :new
end
end
def edit
unless can? :update, @order
redirect_to order_path(@order), alert: 'This order cannot be edited.'
end
@shipping_address = @order.shipping_address || @order.build_shipping_address
end
def update
if can? :update, @order
@order.update_attributes order_params
if params[:shipping_address]
if @order.shipping_address_id
@order.shipping_address.update_attributes shipping_address_params
@order.shipping_address.save!
else
shipping_address = Address.new shipping_address_params
shipping_address.save!
@order.shipping_address = shipping_address
end
end
if @order.save
flash[:notice] = 'The order was updated successfully.'
if params[:charge_freight]
@order.update_freight_charge!
else
@order.clear_freight_charge!
end
end
respond_with @order, location: orders_path(status: :incipient)
else
redirect_to order_path(@order), alert: 'This order cannot be edited.'
end
end
def destroy
if can? :destroy, @order
flash[:notice] = 'The order was removed successfully.' if @order.delete
respond_with @order, location: orders_path(status: :incipient)
else
redirect_to order_path(@order), alert: 'This order cannot be removed.'
end
end
def submit
submitted = @order.submit!
respond_with @order do |format|
format.html do
if submitted
redirect_to orders_path(status: :submitted), notice: 'The order was submitted successfully.'
else
redirect_to order_path(@order), alert: 'The order could not be submitted.'
end
end
end
end
def export
Resque.enqueue ExportProcessor, order_id: @order.id
exported = @order.export!
respond_with @order do |format|
format.html do
if exported
redirect_to orders_path(status: :exporting), notice: 'The order has been marked for export.'
else
redirect_to order_path(@order), alert: 'The order could not be exported.'
end
end
end
end
def manual_export
if @order.manual_export!
redirect_to orders_path(status: @order.status), notice: 'The order has been manually exported.'
else
redirect_to order_path(@order), alert: 'The order could not be marked as exported.'
end
end
def export_csv
orders = Order.find(params[:order_ids].split(','))
exporter = OrderCsvExporter.new(orders)
render text: exporter.content, content_type: 'text/csv'
end
def ship
@order.ship!
render :show
end
private
def create_order
Order.transaction do
@shipping_address = Address.new shipping_address_params
@order = Order.new order_params.merge(shipping_address: @shipping_address)
if @shipping_address.save && @order.save
return true
else
raise ActiveRecord::Rollback
end
end
false
end
def load_order
@order = Order.find(params[:id])
end
def shipping_address_params
params.require(:shipping_address).
permit(:line_1,
:line_2,
:city,
:state,
:postal_code,
:country_code).
merge(recipient: params[:order][:customer_name])
end
def order_params
params.require(:order).
permit(:order_date,
:client_id,
:client_order_id,
:customer_name,
:customer_email,
:delivery_email,
:telephone,
:ship_method_id).
tap do |attr|
if attr[:order_date].present?
attr[:order_date] = Chronic.parse(attr[:order_date])
end
end
end
end
|
# frozen_string_literal: true
class InstanceManager
EC2_INSTANCE_ID = ENV.fetch('EC2_INSTANCE_ID')
def initialize
@ec2 = Aws::EC2::Client.new(region: ENV.fetch('EC2_REGION'),
credentials: Aws::Credentials.new(ENV.fetch('EC2_ACCESS_KEY_ID'),
ENV.fetch('EC2_SECRET_ACCESS_KEY')))
end
# TODO: solve AWS permission problem
def running?
@ec2
.describe_instance_status(instance_ids: [EC2_INSTANCE_ID])
.to_h[:instance_statuses]
.map { |a| a[:instance_id] }
.include?(EC2_INSTANCE_ID)
end
def start
@ec2.start_instances(instance_ids: [EC2_INSTANCE_ID])
end
def stop
@ec2.stop_instances(instance_ids: [EC2_INSTANCE_ID])
end
end
|
# encoding: utf-8
class PolymorphicAttachmentUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
FILE_EXTENSION_LIST = %w(doc docx xls xlsx pdf ppt pptx rar zip 7z)
IMAGE_EXTENSION_LIST = %w(jpg jpeg png gif tif tiff)
FILE_EXTENSION_WHITE_LIST = FILE_EXTENSION_LIST + IMAGE_EXTENSION_LIST
before :cache, :save_original_filename
storage :file
def thumbnail_url
ActionController::Base.helpers.asset_path(thumbnail_url_without_asset_path)
end
def filename
"#{secure_token(10)}.#{file.extension}" if original_filename.present?
end
def thumbnail_url_without_asset_path
if FILE_EXTENSION_LIST.include?(file.extension.downcase)
"assets/polymorphic_attachments/attachment_thumbnails/#{file.extension.downcase}.png"
else
'assets/polymorphic_attachments/attachment_thumbnails/image.png'
end
end
protected
def secure_token(length=16)
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end
def save_original_filename(file)
model.file_name ||= file.original_filename if file.respond_to?(:original_filename)
end
end
|
require 'spec_helper'
describe "Static pages" do
subject { page }
describe "Home page" do
before { visit root_path }
it { should have_selector('legend', text: 'Login') }
#it { should have_selector('h1', text: 'Home') }
#it { should have_selector('title', text: full_title('')) }
#it { should_not have_selector 'title', text: '| Hello World' }
end
describe "Prospect page" do
before { visit prospects_path }
it { should have_selector('legend', text: 'Login') }
#it { should have_selector('h1', text: 'Prospects') }
#it { should have_selector('title', text: full_title('Prospects')) }
end
describe "Agents page" do
before { visit agents_path }
it { should have_selector('legend', text: 'Login') }
#it { should have_selector('h1', text: 'Agents') }
#it { should have_selector('title', text: full_title('Agents')) }
end
describe "Backoffice page" do
before { visit backoffice_path }
it { should have_selector('legend', text: 'Login') }
#it { should have_selector('h1', text: 'Backoffice') }
#it { should have_selector('title', text: full_title('Backoffice')) }
end
end
|
class TaskInListPolicy
attr_reader :user, :task_in_list
def initialize(user, task_in_list)
@user = user
@task_in_list = task_in_list
end
def owner?
user.owner?(task_in_list)
end
end
|
class Campground < ApplicationRecord
reverse_geocoded_by :latitude, :longitude
has_and_belongs_to_many :trips
belongs_to :park
def set_park
cg_point = RGeo::Geographic.spherical_factory(srid: 4326).point(longitude, latitude)
Park.all.each do |park|
if park.boundary
self.update(park: park) if (park.boundary.contains?(cg_point))
end
end
self.park
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def admin?(member)
if member.try(:admin?)
return true
end
return false
end
def role?(member, role) # npr. "član"
if member.try(:role) == role
return true
end
return false
end
protected
# Uporabniku dovoli dostop do strani
def authenticate_member
if session[:member_id]
# set current user object to @current_user object variable
@current_member = Member.find(session[:member_id])
return true
else
redirect_to(:controller => 'sessions', :action => 'login')
return false
end
end
# Uporabniku prepreči dostop do strani, če je že prijavljen
def save_login_state
if session[:member_id]
redirect_to(:controller => 'sessions', :action => 'home')
return false
else
return true
end
end
end
|
class BranchesController < ApplicationController
before_action :set_branch, only: [:show, :edit, :update, :destroy]
# GET /branches
# GET /branches.json
def index
@branches = Branch.order(:id) if current_user.is_admin?
@branches = current_user.company.branches.order(:id) if current_user.is_admin_company?
if @branches.nil?
redirect_back_or_default home_url
end
end
# GET /branches/1
# GET /branches/1.json
def show
if @branch.admin.nil?
@user = User.new
end
end
# GET /branches/new
def new
@branch = Branch.new
params[:company_id] = current_user.company.id if current_user.is_admin_company?
respond_to do |format|
format.html
format.widget { render '_form_js.html.erb', layout: false }
end
end
# GET /branches/1/edit
def edit
respond_to do |format|
format.html
format.widget { render '_form_js.html.erb', layout: false }
end
end
# POST /branches
# POST /branches.json
def create
@branch = Branch.new(branch_params)
respond_to do |format|
if @branch.save
format.html { redirect_to @branch, success: 'Branch was successfully created.' }
format.json { render action: 'show', status: :created, location: @branch }
format.js { render partial: 'shared/create_record_js', locals: { object: @branch } }
else
format.html { render action: 'new' }
format.json { render json: @branch.errors, status: :unprocessable_entity }
format.js { render :js => 'show_record_errors(' + @branch.errors.full_messages.to_json + ');' }
end
end
end
# PATCH/PUT /branches/1
# PATCH/PUT /branches/1.json
def update
respond_to do |format|
if @branch.update(branch_params)
format.html { redirect_to @branch, success: 'Branch was successfully updated.' }
format.json { head :no_content }
format.js { render partial: 'shared/create_record_js', locals: { object: @branch } }
else
format.html { render action: 'edit' }
format.json { render json: @branch.errors, status: :unprocessable_entity }
format.js { render :js => 'show_record_errors(' + @branch.errors.full_messages.to_json + ');' }
end
end
end
# DELETE /branches/1
# DELETE /branches/1.json
def destroy
@branch.destroy
respond_to do |format|
format.html { redirect_to branches_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_branch
@branch = Branch.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def branch_params
params.require(:branch).permit(:name, :company_id, :address, :phone)
end
end
|
require 'byebug'
def select_even_nums(arr)
arr.select(&:even?)
end
def reject_puppies(arr)
arr.reject { |hash| hash["age"] < 3 }
end
def count_positive_subarrays(arr)
arr.count { |sub_arr| sub_arr.sum > 0 }
end
def aba_translate(word)
aba_output = ""
vowels = "aeiou"
word.each_char do |char|
vowels.include?(char) ? aba_output += char + "b" + char : aba_output += char
end
aba_output
end
def aba_array(arr)
arr.map { |word| aba_translate(word) }
end |
class MstEdge
attr_accessor :name1, :name2, :weight
def initialize(name1, name2, weight)
@name1 = name1
@name2 = name2
@weight = weight
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
get '', to: 'product#index'
get 'products', to: 'product#show_all'
post 'products', to: 'product#create'
get 'products/:id', to: 'product#show_by_id'
put 'products/:id' => 'product#update'
delete 'products/:id' => 'product#delete'
end |
class RemoveActivityLogs < ActiveRecord::Migration[5.0]
def change
drop_table :activity_logs
end
end
|
VAGRANTFILE_API_VERSION = "2"
WORKBENCH_IP = "192.168.33.11"
Vagrant.require_version ">= 1.7.3"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
##################################################
# Start Docker host
# - need modern boot2docker image for vagrant; Docker >1.7
# - https://vagrantcloud.com/dduportal/boxes/boot2docker
##################################################
config.vm.define "dockerhost", autostart: false do |dh|
dh.vm.box = "dduportal/boot2docker"
dh.vm.network "private_network", ip: WORKBENCH_IP
dh.vm.synced_folder ".", "/vagrant", type: "virtualbox"
# Map Docker VM service ports to VM host
dh.vm.network :forwarded_port, :host => 8000, :guest => 8000
dh.vm.provider "virtualbox" do |virtualbox|
virtualbox.memory = 2048
end
end
##################################################
# Launch dev containers
# - vagrant up lucee
##################################################
config.vm.define "lucee", autostart: true do |lucee|
lucee.vm.provider "docker" do |docker|
docker.name = "lucee"
docker.build_dir = "."
# local development code, lucee config & logs
docker.volumes = [
"/vagrant/code:/var/www",
"/vagrant/config/lucee/local-lucee-server.xml:/opt/lucee/server/lucee-server/context/lucee-server.xml",
"/vagrant/config/lucee/local-lucee-web.xml.cfm:/opt/lucee/web/lucee-web.xml.cfm",
"/vagrant/logs/lucee:/opt/lucee/web/logs",
"/vagrant/logs/nginx:/var/log/nginx",
"/vagrant/logs/supervisor:/var/log/supervisor",
"/vagrant/logs/tomcat:/usr/local/tomcat/logs"
]
docker.ports = %w(8000:80)
docker.vagrant_machine = "dockerhost"
docker.vagrant_vagrantfile = __FILE__
end
end
# /config
end |
class Car
attr_accessor :name
def initialize(name)
@name = name
end
def hello
puts "Hello! I am #{@name}."
end
#def name
# @name
#end
#def name=(value)
# @name = value
#end
end
car = Car.new('Kitt')
puts car.name
car.name = 'Nakamura'
puts car.name
|
class Photo < ActiveRecord::Base
before_destroy :destroy_cloud_photo
attr_accessible :id, :crop_x, :crop_y, :crop_w, :crop_h, :angle, :public_id, :version, :format, :resource_type, :height, :width, :rate, :name
def destroy_cloud_photo
Cloudinary::Uploader.destroy(public_id) if public_id
end
def path(custom_format=nil)
p = "v#{version}/#{public_id}"
if resource_type == 'image' && custom_format != false
custom_format ||= format
p<< ".#{custom_format}"
end
p
end
def fullpath(options={})
if options.has_key?(:format)
format = options.delete(:format)
else
format = 'png'
end
options = options.reverse_merge(resource_type: resource_type)
Cloudinary::Utils.cloudinary_url(path(format), {transformation: transformations(options)})
end
alias_method :url, :fullpath
def logopath
Cloudinary::Utils.cloudinary_url(path("png"), {transformation: [
{x: (crop_x if crop_x), y: (crop_y if crop_y), width: (crop_w if crop_w), height: (crop_h if crop_h), crop: :crop},
{width: (180), height: (180 ), crop: ('fit')},
{angle: angle}]} )
end
def transformations(options)
crop_attributes = cropped? ? {x: crop_x, y: crop_y, width: crop_w, height: crop_h, crop: :crop} : nil
angle_attributes = angle.present? ? {angle: angle} : nil
[crop_attributes, angle_attributes, options].compact
end
def cropped?
(crop_x.present? || crop_y.present?) && (crop_w.present? || crop_h.present?)
end
end
|
require 'spec_helper'
require 'codily/root'
# Actually testing DSL
describe Codily::Root do
describe "(scinario: runs successfully)" do
subject { described_class.new.run_string(<<-'EOS', "(eval:#{__FILE__})", __LINE__.succ) }
service "test.example.com" do
backend "backend-a" do
address "backend.example.com"
auto_loadbalance false
between_bytes_timeout 100
client_cert "TEST"
comment "comment"
connect_timeout 101
error_threshold 102
first_byte_timeout 103
healthcheck "healthcheck-a"
hostname "backend.example.com"
ipv4 "127.0.0.1"
ipv6 "::1"
max_conn 104
max_tls_version "TLS1.0"
min_tls_version "TLS1.2"
port 443
request_condition "condition-1"
shield "IAD"
ssl_ca_cert "TEST2"
ssl_cert_hostname "test.example.com"
ssl_check_cert true
ssl_ciphers "TEST3"
ssl_client_cert "TEST4"
ssl_client_key "TEST5"
ssl_hostname "test.example.com"
ssl_sni_hostname "test.example.com"
use_ssl true
weight 105
end
cache_setting "cache-setting-a" do
action :pass
stale_ttl 60
ttl 120
cache_condition "name"
end
condition "condition-2" do
comment "comment"
priority 100
statement "beresp.status == 200"
end
dictionary "name"
domain "a.example.org"
domain "b.example.org" do
comment "comment"
end
gzip "gzip-a" do
content_types %w(text/html)
extensions %w(html)
cache_condition "condition-3"
end
header 'header-a' do
action :set
src 'beresp.status'
dst 'resp.X-Test'
ignore_if_set true
priority 100
substitution 'test'
type :request
cache_condition "condition-4"
request_condition "condition-5"
response_condition "condition-6"
end
healthcheck 'healthcheck-b' do
check_interval 60
comment "comment"
expected_response 200
host "test.example.com"
http_version "1.1"
initial 2
method "GET"
path "/health"
threshold 3
timeout 500
window 5
end
request_setting "request-setting-a" do
action :lookup
bypass_busy_wait false
default_host "test.example.com"
force_miss true
force_ssl true
geo_headers true
hash_keys "null"
max_stale_age 60
timer_support true
xff :append
request_condition "condition-7"
end
response_object "name" do
content "test\n"
content_type "text/plain"
status 200
response "Ok"
cache_condition "condition-8"
request_condition "condition-9"
end
vcl "name" do
content "test"
main true
end
settings(
"general.default_ttl" => 3600,
)
end
EOS
specify do
expect { subject }.not_to raise_error
end
end
describe "(scinario: referring element)" do
subject { described_class.new.run_string(<<-'EOS', "(eval:#{__FILE__})", __LINE__.succ) }
service "test" do
condition "condition-a" do
statement "beresp.status == 200"
end
cache_setting "cache-setting-a" do
cache_condition "condition-a"
end
cache_setting "cache-setting-b" do
cache_condition "condition-b" do
statement "beresp.status == 201"
end
end
end
EOS
specify do
expect(subject.list_element(Codily::Elements::CacheSetting).size).to eq 2
expect(subject.list_element(Codily::Elements::Condition).size).to eq 2
expect(subject.list_element(Codily::Elements::CacheSetting)[%w(test cache-setting-a)].cache_condition).to eq 'condition-a'
expect(subject.list_element(Codily::Elements::Condition)[%w(test condition-a)].statement).to eq 'beresp.status == 200'
expect(subject.list_element(Codily::Elements::CacheSetting)[%w(test cache-setting-b)].cache_condition).to eq 'condition-b'
expect(subject.list_element(Codily::Elements::Condition)[%w(test condition-b)].statement).to eq 'beresp.status == 201'
end
end
describe "settings" do
subject { described_class.new.run_string(<<-'EOS', "(eval:#{__FILE__})", __LINE__.succ) }
service "test" do
settings "foo" => 'bar'
end
EOS
specify do
expect(subject.list_element(Codily::Elements::Settings)['test']).to be_a(Codily::Elements::Settings)
expect(subject.list_element(Codily::Elements::Settings)['test'].as_hash).to eq(foo: 'bar')
end
end
end
|
class DonationApplicationsController < ApplicationController
before_action :authenticate_user!
def create
@listing = set_listing
@contact = ContactInfo.find(params[:contact])
submission_status ||= "printed" if @listing.requires_pdf_form?
submission_status ||= "emailed"
phone = @contact.phone
phone += (" ext: " + @contact.extension) if @contact.extension
donation_application = DonationApplication.new(
applicant: current_user,
listing: @listing,
first_name: @contact.first_name,
last_name: @contact.last_name,
title: @contact.title,
email: @contact.email,
phone: phone,
fax: @contact.fax,
submission_status: submission_status
)
if donation_application.save
unless @listing.followers.include?(current_user)
@listing.followers << current_user
end
# Mailer send
if @listing.requires_pdf_form?
download_pdf(donation_application.export_pdf) and return
else
donation_application.update(submission_date: Time.now)
end
flash[:success] = "Your application has been #{submission_status}!"
DonationApplicationMailer.donation_request(@listing, current_user).deliver_now
DonationApplicationMailer.donation_requested(@listing, current_user).deliver_now
else
flash[:danger] = "Your request was unsuccessful, please try again"
end
redirect_to listing_path(@listing)
end
def show
donation_application = DonationApplication.find(params[:id])
display_pdf(donation_application.export_pdf)
end
def update_mailed_submission
listing = set_listing
applicant = current_user
donation_application = get_donation_application(applicant: applicant, listing: listing)
if donation_application.update(submission_status: "mailed", submission_date: Time.now)
flash[:success] = "Your submission status has been updated"
DonationApplicationMailer.donation_pdf_mailed(listing, current_user).deliver_now
else
flash[:danger] = "Your request was unsuccessful, please try again"
end
redirect_to listing_path(listing)
end
def approve_applicant
listing = set_listing
applicant = User.find(params[:id])
donation_application = get_donation_application(applicant: applicant, listing: listing)
if donation_application.update(approval_status: "approved")
flash[:success] = "Application status has been updated for #{donation_application.applicant.email}"
else
flash[:danger] = "Your request was unsuccessful, please try again"
end
redirect_to listing_path(listing)
end
def decline_applicant
listing = set_listing
applicant = User.find(params[:id])
donation_application = get_donation_application(applicant: applicant, listing: listing)
if donation_application.update(approval_status: "declined")
flash[:success] = "Application status has been updated for #{donation_application.applicant.email}"
else
flash[:danger] = "Your request was unsuccessful, please try again"
end
redirect_to listing_path(listing)
end
def reset_applicant
listing = set_listing
applicant = User.find(params[:id])
donation_application = get_donation_application(applicant: applicant, listing: listing)
if donation_application.update(approval_status: nil)
flash[:success] = "Application status has been updated for #{donation_application.applicant.email}"
else
flash[:danger] = "Your request was unsuccessful, please try again"
end
redirect_to listing_path(listing)
end
private
def get_donation_application(args = {})
applicant = args[:applicant]
listing = args[:listing]
listing.donation_applications.find_by(applicant: applicant)
end
def set_listing
Listing.find(params[:listing_id])
end
def download_pdf(pdf)
send_file(pdf, type: 'application/pdf')
end
def display_pdf(pdf)
send_file(pdf, disposition: 'inline', type: 'application/pdf')
end
def donation_application_params
params.require(:donation_application).permit(:submission_status, :submission_date, :approval_status, :approval_status_reason, :contact)
end
end
|
class Student < ActiveRecord::Base
after_create :create_user
has_one :user
has_many :batch_students #, dependent: :destroy
has_many :batches, through: :batch_students
accepts_nested_attributes_for :batch_students, :allow_destroy => true
validates_presence_of :name, :email
private
def create_user
user = User.new
user.name = self.name
user.student_id = self.id
user.email = self.email
user.password = "password"
user.avatar = "image/upload/v1494394329/psqitd4es83x1qrhy1si.jpg"
user.save
end
end |
class ListSellsController < ApplicationController
before_action :set_list_sell, only: [:show, :edit, :update, :destroy]
# GET /list_sells
# GET /list_sells.json
def index
@list_sells = current_user.list_sells.all
end
# GET /list_sells/1
# GET /list_sells/1.json
def show
end
# GET /list_sells/new
def new
@list_sell = current_user.list_sells.new
end
# GET /list_sells/1/edit
def edit
end
# POST /list_sells
# POST /list_sells.json
def create
@list_sell = current_user.list_sells.new(list_sell_params)
respond_to do |format|
if @list_sell.save
format.html { redirect_to list_sells_url, notice: 'List sell was successfully created.' }
format.json { render :show, status: :created, location: @list_sell }
else
format.html { render :new }
format.json { render json: @list_sell.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /list_sells/1
# PATCH/PUT /list_sells/1.json
def update
respond_to do |format|
if @list_sell.update(list_sell_params)
format.html { redirect_to list_sells_url, notice: 'List sell was successfully updated.' }
format.json { render :show, status: :ok, location: @list_sell }
else
format.html { render :edit }
format.json { render json: @list_sell.errors, status: :unprocessable_entity }
end
end
end
# DELETE /list_sells/1
# DELETE /list_sells/1.json
def destroy
@list_sell.destroy
respond_to do |format|
format.html { redirect_to list_sells_url, notice: 'List sell was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_list_sell
@list_sell = ListSell.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def list_sell_params
params.require(:list_sell).permit(:address, :unit, :city, :state, :zip, :price, :virtual_tour_link, :home_type, :no_bed, :no_f_bath, :no_q_bath, :no_h_bath, :finished_sq, :lot_size, :year_built, :remodel_year, :hoa_dues, :basement_area, :garage_area, :description, :website, :my_views, :email, :ph_no, room_details_attributes: [:id, :dish_washer, :rang_oven, :dryer, :refrigerator, :freezer, :trash_compactor, :garbage_disposal, :washer, :microwave, :basement_type, :floor_type, :room_type, :_destroy], sell_visit_times_attributes: [:id, :date, :start_time, :end_time, :_destroy], rental_images_attributes:[:id, :url, :_destroy] )
end
end
|
class StoreTasksAsArray < ActiveRecord::Migration
# warning: this is destructive... you will lose all associations between users and tasks when you run this.
# i'm just too lazy to not do it this way
def self.up
add_column :users, :ordered_task_ids, :text, :default => []
remove_column :tasks, :rank
end
def self.down
add_column :tasks, :rank, :integer
remove_column :users, :ordered_task_ids
end
end
|
FactoryGirl.define do
factory :question do
body "question body"
answer "question answer"
end
end
|
class UpdateEnabledForListings < ActiveRecord::Migration
def change
change_column :listings, :enabled, :boolean, :default => true, :null => false
end
end
|
class Introduction < ApplicationRecord
belongs_to :user,optional: true
belongs_to :board,optional: true
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :category
after_initialize :set_default_values
private
def set_default_values
self.permission ||= false if self.permission.nil?
end
end
|
class PostsController < ApplicationController
before_action :set_post, only: [:show, :stage, :publish, :edit, :update, :destroy]
before_action :logged_in_user, only: [:index, :staging_area, :edit]
# GET /posts
def index
@posts = Post.all
end
def published_posts
@published_posts = Post.published
end
def staging_area
@staged_posts = Post.staged
end
# GET /posts/1
def show
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
end
# POST /posts
def create
@post = Post.new(post_params)
@post.staged = true
if @post.save
redirect_to staging_area_posts_path
# redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
def stage
if @post.update(:staged => 'true')
redirect_to staging_area_posts_path, notice: 'Now staged!'
else
render :stage
end
end
def publish
if @post.update(:published => 'true')
redirect_to posts_path
else
render :edit
end
end
# PATCH/PUT /posts/1
def update
if @post.update(post_params)
redirect_to staging_area_posts_path
else
render :edit
end
end
# DELETE /posts/1
def destroy
@post.destroy
redirect_to posts_url, notice: 'Post was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def post_params
params.require(:post).permit(:id, :title, :content, :tags, :keywords, :upvotes, :brief, :staged, :published)
end
end
|
class AdUser < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :comments,->{ order("created_at DESC") }
has_many :crossfollows, as: :followable, dependent: :destroy
has_many :likes, dependent: :destroy
validates :first_name,:family_name,:first_name_kana,:family_name_kana,:occupation,:position,:nickname, presence: true
has_one_attached :image
def name
"#{family_name} #{first_name}"
end
def name_kana
"#{family_name_kana} #{first_name_kana}"
end
# def crossfollowing?(other_user)
# Crossfollow.find_by(ad_user_id: other_user.id)
# end
# def stcrossfollow!(other_user)
# Crossfollow.create!(st_user_id: other_user.id)
# end
# def adcrossfollow!(other_user)
# Crossfollow.create!(ad_user_id: other_user.id)
# end
def stcrossunfollow!(other_user)
Crossfollow.find_by(st_user_id: other_user.id).destroy
end
def adcrossunfollow!(other_user)
Crossfollow.find_by(ad_user_id: other_user.id).destroy
end
end
|
module Biz
module Periods
class After < Abstract
def timeline
super.forward
end
private
def weeks
Range.new(
Week.since_epoch(schedule.in_zone.local(origin)),
Week.since_epoch(Time.heat_death)
)
end
def relevant?(period)
origin < period.end_time
end
def boundary
@boundary ||= TimeSegment.after(origin)
end
def intervals
@intervals ||= schedule.intervals
end
end
end
end
|
FactoryBot.define do
factory :invoice do
sequence(:id) { |n| n }
status { "shipped" }
created_at { "2012-03-27 14:53:59" }
updated_at { "2012-03-27 14:53:59" }
merchant
customer
end
end
|
require 'rails_helper'
RSpec.describe Deal, type: :model do
describe 'db structure' do
it { is_expected.to have_db_column(:name).of_type(:string) }
it { is_expected.to have_db_column(:description).of_type(:text) }
it { is_expected.to have_db_column(:current_amount).of_type(:decimal) }
it { is_expected.to have_db_column(:previous_amount).of_type(:decimal) }
it { is_expected.to have_db_column(:expiry).of_type(:datetime) }
it { is_expected.to have_db_column(:available_coupons).of_type(:integer) }
it { is_expected.to have_db_column(:sold_coupons).of_type(:integer) }
it { is_expected.to have_db_column(:restaurant_id).of_type(:integer) }
it { is_expected.to have_db_column(:image_file_name).of_type(:string) }
it { is_expected.to have_db_column(:image_content_type).of_type(:string) }
it { is_expected.to have_db_column(:image_file_size).of_type(:integer) }
it { is_expected.to have_db_column(:image_updated_at).of_type(:datetime) }
it { is_expected.to have_db_column(:created_at).of_type(:datetime) }
it { is_expected.to have_db_column(:updated_at).of_type(:datetime) }
end
describe 'associations' do
it { is_expected.to belong_to(:restaurant) }
end
describe 'validations' do
subject { create(:deal) }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_presence_of(:description) }
it { is_expected.to validate_presence_of(:current_amount) }
it { is_expected.to validate_presence_of(:previous_amount) }
it { is_expected.to validate_presence_of(:expiry) }
it { is_expected.to validate_presence_of(:available_coupons) }
it { is_expected.to validate_presence_of(:sold_coupons) }
it { is_expected.to validate_presence_of(:image) }
end
end
|
class Main
helpers do
def navigation(&block)
tag('ul', :class => 'notList clearFix colL main-nav', &block)
end
def nav_item( text, url_options, args = nil )
options =
if args == false
{}
elsif args
active_if(*Array(args))
else
active_if( url_options )
end
options ||= {}
options[:class] = "colL #{options[:class]}"
tag 'li',
link_to(text, url_options),
options
end
def show_toggling
if (@account && user_url(@account) == request.fullpath) or inside?('/liked')
yield
end
end
private
def active_if( *controller_actions )
if inside?(*controller_actions)
{ :class => 'active' }
else
{}
end
end
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :product_name_parsing do
collection do
get "tag/:tag", to: "product_name_parsing#tag"
get "refresh_ingredient_tags", to: "product_name_parsing#refresh_ingredient_tags"
end
end
resources :pack_size_parsing
resources :brand_parsing do
collection do
get "search"
end
end
resources :ingredient
namespace :api do
namespace :v1 do
post 'interpret_pack_size' => 'pack_size#interpret'
end
end
end
|
require('rspec')
require('find_replace')
describe('String#find_replace') do
it('Searches for the argument word in the object string, replaces the word if found') do
expect('Hello World'.find_replace('hello', 'goodbye')).to(eq('goodbye World'))
end
it('Searches for the argument word in the object string, returns original string if not found') do
expect('Hello world'.find_replace('huh', 'goodbye')).to(eq('Hello world'))
end
it('replaces a partial match') do
expect('I am walking my cat to the cathedral'.find_replace('cat', 'dog')).to(eq('I am walking my dog to the doghedral'))
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :parse_user # Parse the user before every controller action
# Parses the current user and stores it in a controller variable
def parse_user
@user = current_user
end
def index
@future_events = Event.future_events
end
end
|
class CredentialService < PutitService
def add_dep_ssh_key(payload)
logger.info('Generating new SSH keys')
k = ManageSSHKeyService.generate_key(
payload[:type],
payload[:bits],
payload[:comment],
payload[:passphrase]
)
ssh_key = DepSSHKey.find_or_create_by!(
name: payload[:name],
keytype: k.type,
bits: k.bits,
comment: k.comment,
private_key: k.private_key,
public_key: k.public_key,
ssh_public_key: k.ssh_public_key,
ssh2_public_key: k.ssh2_public_key,
sha256_fingerprint: k.sha256_fingerprint
)
logger.info(
"New SSH key pair has been generated with name: #{payload[:name]}"
)
ssh_key
end
def add_depuser(payload)
depuser = Depuser.find_or_create_by!(username: payload[:username])
logger.info("Deploy user: #{payload[:username]} created.")
depuser
end
def add_depuser_credential(depuser, credential_name, ssh_key)
credential = depuser.credentials.create!(
sshkey_id: ssh_key.id,
depuser_id: depuser.id,
name: credential_name
)
logger.info("Credential with name: #{credential_name} for SSH key pair with name: #{ssh_key[:name]} and deploy username: #{depuser.username} created.")
credential
end
end
|
class Like < ApplicationRecord
belongs_to :user
belongs_to :item
validates :user_id, :item_id, presence:true
end
|
require 'spec_helper'
describe DoceboRuby::Orgchart do
it 'wraps up Docebo LMS Orgchart' do
expect(DoceboRuby::Orgchart.api).to eq 'orgchart'
end
describe '.create' do
context 'valid params' do
it 'creates node at docebo' do
result = DoceboRuby::Orgchart.create_node\
code: 'FirstNode123',
translation: { english: 'First Node' }
expect(result['success']).to be_truthy
expect(result['org_id']).to eq 123
end
end
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :created_products, foreign_key: 'supplier_id', class_name: 'Product'
has_many :orders, foreign_key: 'ordered_id'
has_many :attended_orders, through: :orders
validates :name, presence: true, length: { minimum: 2 }
end
|
class Lessoncate < ActiveRecord::Base
has_many :lessons
attr_accessible :name
end
|
default['sites'] = []
# Override these defaults to suit your preferences.
#
# These default attributes will be applied to all `sites` members
# on which you have not set a value for the property explicitely.
# System user with ownership of the site files
default['site_defaults']['owner'] = 'http'
# Relative path from site.root where files should be served
default['site_defaults']['web_root'] = 'www'
# Set an optional proxy_pass string to create a reverse
# proxy instead, omitting the web_root
# eg: proxy_pass http://localhost:8000;
default['site_defaults']['proxy_pass'] = false
# Enable to redirect insecure http traffic to https
default['site_defaults']['redirect_insecure'] = false
# Does this site need PHP?
default['site_defaults']['php'] = false
# Is this a Wordpress site?
default['site_defaults']['wordpress'] = false
# Generate a LetsEncrypt certificate?
default['site_defaults']['letsencrypt'] = false
# Any extra system packages this site might need
default['site_defaults']['packages']['install'] = []
# Any system packages this site should remove
default['site_defaults']['packages']['remove'] = []
# Any AUR packages this site should build and install
default['site_defaults']['packages']['aur'] = []
# Skip the 'user' recipe for this site.
default['site_defaults']['skip_user'] = false
# Enable nginx fastcgi cache for this site
default['site_defaults']['fastcgi_cache'] = true
default['site_defaults']['fastcgi_cache_zone'] = 'WEBSITE'
default['site_defaults']['fastcgi_cache_valid'] = '60m'
# Enable nginx fastcgi cache
default['nginx']['fastcgi_cache'] = true
# Cache storage path
default['nginx']['fastcgi_cache_path'] = '/var/cache/nginx'
# Hierarchy levels of a cache
default['nginx']['fastcgi_cache_levels'] = '1:2'
# All active keys and information about data are stored in a shared memory zone,
# whose name and size are configured by the keys_zone parameter. One megabyte
# zone can store about 8 thousand keys.
default['nginx']['fastcgi_keys_zone'] = 'WEBSITE:10m'
# Cached data that are not accessed during the time specified by the inactive parameter get removed from the cache regardless of their freshness
default['nginx']['fastcgi_cache_inactive'] = '60m'
default['nginx']['fastcgi_cache_key'] = '$scheme$request_method$host$request_uri'
default['nginx']['fastcgi_hide_header'] = ''
default['nginx']['fastcgi_ignore_headers'] = 'Cache-Control Expires Set-Cookie'
default['nginx']['fastcgi_cache_use_stale'] = 'error timeout invalid_header http_500'
default['nginx']['load_modules'] = ['/usr/lib/nginx/modules/ngx_http_cache_purge_module.so']
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :first_name, :presence => true
validates :last_name, :presence => true
validates :email, :presence => true
validates :account_type, :presence => true
validates :mmu_id, :presence => true, :if => Proc.new { |user| user.type == :student }
validates :course_name, :presence => true, :if => Proc.new { |user| user.type == :student }
validates_length_of :mmu_id, :is => 8, :if => Proc.new { |user| user.type == :student }
validates_uniqueness_of :email
validates_uniqueness_of :mmu_id, :if => Proc.new { |user| user.type == :student }
has_many :lecture_students
audited
# If no account type is provided, default to student.
before_create do
account_type = 'student' if account_type.blank?
end
before_destroy do
return false if Lecture.where_user(self).count > 0
Lecture.where_user(self).destroy_all
UnitLecturer.where_user(self).destroy_all
end
# Validate account type.
validate do
errors.add(:account_type, 'can only be admin, lecturer or student') if not [:admin, :lecturer, :student].include?(account_type.to_s.downcase.to_sym)
end
def name
[first_name, last_name].join(' ')
end
def make_admin!
update_attributes(:account_type => 'admin')
end
def make_lecturer!
update_attributes(:account_type => 'lecturer')
end
def make_student!
update_attributes(:account_type => 'student')
end
def admin?
type == :admin
end
def admin_or_lecturer?
[:admin, :lecturer].include?(type)
end
def lecturer?
type == :lecturer
end
def student?
type == :student
end
def part_of_unit?(units)
units = [units] unless units.is_a?(Array)
lecture_students.select do |ls|
units.include?(ls.lecture.unit)
end.count > 0
end
def attendance
lectures_in = LectureStudent.where_user(self)
lectures_already_happened = lectures_in.select{ |l| l.lecture.end_time < Time.now }.count
lectures_already_happened_that_was_attended = lectures_in.select{ |l| l.lecture.end_time < Time.now && l.attendance == true }.count
if lectures_already_happened > 0
((lectures_already_happened_that_was_attended.to_f / lectures_already_happened.to_f) * 100).round(1)
else
100.0
end
end
def lecturer_attendance
lectures_taught = Lecture.where_user(self)
attendance = lectures_taught.select{ |l| l.end_time < Time.now }.map do |l|
l.attendance.to_i
end
if attendance.count > 0
attendance.sum.to_f / attendance.count.to_f
else
100.0
end
end
def watchlist?
attendance <= 75 or average_minutes_to_class >= 15
end
def lectures
@lectures ||= lecture_students.all.map{ |ls| ls.lecture }
end
def lectures_with_attendance
@lectures_with_attendance ||= lecture_students.all.map{ |ls| [ls, ls.lecture] }
end
def lectures_now
@lectures_now ||= lectures.select{ |l| l.currently_on? }
end
def lectures_in_past
@lectures_in_past ||= lectures.select{ |l| l.has_started? }
end
def lectures_in_future
@lectures_in_future ||= lectures.reject{ |l| l.has_started? }
end
def lectured_in_past
@lectured_in_past ||= Lecture.where_user(id).all.select{ |l| l.has_started? }
end
def lecturing_in_future
@lecturing_in_future ||= Lecture.where_user(id).all.reject{ |l| l.has_started? }
end
def average_time_at_event
times_arrived_at = lecture_students.select{ |l| l.lecture.end_time < Time.now }.map{ |l| (l.attendance_time - l.lecture.start_time).to_f.presence rescue nil }.select(&:present?)
(times_arrived_at.sum / times_arrived_at.count.to_f) rescue 0.0
end
def average_minutes_to_class
(average_time_at_event / 60.0).round rescue 0
end
def lecturer_average_minutes_to_class
mins = Lecture.where_user(id).map do |l|
l.average_minutes_to_class
end
(mins.sum / mins.count) rescue 0
end
def type
account_type.to_sym rescue :student
end
def self.options_for_types
[["Student", :student], ["Lecturer", :lecturer], ["Administrator", :admin]]
end
def self.where_type(type)
where(account_type: type.downcase.to_s)
end
def self.for_form
all.map{ |u| [u.name, u.id] }
end
def self.for_form_and_part_of_unit(units)
units = [units] unless units.is_a?(Array)
all.select do |u|
units.map do |unit|
true if u.teaches_in_or_leader_of?(unit)
end.flatten.include?(true)
end.map{ |u| [u.name, u.id] }
end
def self.find_by_mmu_id(mmu_id)
where(mmu_id: mmu_id).first
end
def teaches_in_or_leaders_of
a = UnitLecturer.where_user(self).all_from_units
b = Lecture.where_user(self).all.map{ |u| u.unit }
(a + b).flatten.uniq
end
def leaders_of
UnitLecturer.where_user(self).all_from_units
end
def is_unit_leader?
leaders_of.count > 0
end
def lectures_taught_in(unit)
unit.lectures.select{ |l| l.user_id == id }
end
def teaches_in_or_leader_of?(unit)
lectures_taught_in(unit).count > 0 or leaders_of.include?(unit)
end
def attendance_by_lecturer
lecturers = {}
lecture_students.each do |ls|
key = "#{ls.lecture.lecturer.id}:#{ls.lecture.lecturer.name}:#{ls.lecture.unit.id}:#{ls.lecture.unit.unit_name}"
if lecturers.include?(key)
lecturers[key] << ls.lecture
else
lecturers[key] = [ls.lecture]
end
end
lecturers
end
def attendance_by_day
days = {}
(1..5).each{ |n| days[Date::DAYNAMES[n]] = [] }
lecture_students.each do |ls|
begin
days[ls.lecture.start_time.strftime("%A")] << ls.attended?
rescue
end
end
days.each do |day, attendances|
attended = attendances.select{ |d| d == true }.count
total = attendances.count
days[day] = ((attended.to_f / total.to_f) * 100.0).round rescue 100
end
days
end
def attendance_by_day_as_gchart
attendance = attendance_by_day
if attendance.count > 1
Gchart.line(:data => attendance.values, :min_value => 0, :max_value => 100, :title => "Attendance for #{name} by day of the week", :size => "550x200", :labels => attendance.keys)
else
nil
end
end
def attendance_as_gchart
attendance = {}
attendance_names = []
colours = ["535aac", "825959", "843e01", "0a7061", "17334a", "6320df", "f40b59"].first(7).join(',')
lectures_with_attendance.each do |a, lecture|
if attendance.include?(lecture.unit.unit_name)
attendance[lecture.unit.unit_name][lecture.start_time.strftime('%W').to_i].push(a.attended?)
else
attendance[lecture.unit.unit_name] ||= {}
(1..52).each{ |number| attendance[lecture.unit.unit_name][number] = [] }
end
end
if attendance.count > 0
attendance.each do |unit, weeks|
attendance_names.push(unit) unless attendance_names.include?(unit)
attendance[unit] = weeks.select{ |week, attended| attended.count > 0 }
end
max_size = attendance.first.count
all_weeks = attendance.values.first.keys
attendance.each do |unit, weeks|
max_size = weeks.count if weeks.count > max_size
all_weeks << weeks.keys
end
all_weeks = all_weeks.flatten.uniq.sort
attendance.each do |unit, weeks|
all_weeks.each do |week|
if not attendance[unit].keys.include?(week)
attendance[unit][week] = {}
end
end
end
final_attendance = attendance.map do |unit, weeks|
weeks.sort.map do |week, attended|
did_attend = attended.select{ |a| a == true }.count.to_f
altogether = attended.count.to_f
((did_attend / altogether) * 100.0).round rescue 100
end
end
else
final_attendance = []
attendance_names = []
all_weeks = []
end
if final_attendance.count > 1
Gchart.line(:data => final_attendance, :line_colors => colours, :min_value => 0, :max_value => 100, :title => "Attendance for #{name} by week and units", :size => "550x200", :legend => attendance_names, :labels => all_weeks.map{ |k| "Week #{k}" })
else
nil
end
end
protected
def password_required?
new_record? ? true : false
end
end
|
class UsersController < ApplicationController
before_action :set_current_user, only: [:logged_in_index, :new, :edit, :update, :destroy]
def logged_in_index
if @user == nil
flash[:notice] = "please log in to view your account"
return redirect_to :back
end
@reviews = @user.reviews
end
def new
#if they hit "regitster first", redirect to the github auth action in sessions
auth_hash=session[:auth_hash]
if session[:auth_hash] == nil
return redirect_to "/auth/github"
end
#if they are already a current user, tell them so
if User.find_by(uid: auth_hash['uid'], provider: 'github')
flash[:notice]="You are already registered with github"
return redirect_to :back
end
#if they have a github auth build potential user info from github auth
@user=User.build_from_github(session[:auth_hash])
end
def create
@user=User.new
flash[:notice] = "unable to save user"
#take user info from form
@user.name = params[:user][:name]
@user.email = params[:user][:email]
@user.uid = params[:user][:uid]
@user.provider = params[:user][:provider]
if @user.save
session[:user_id] = @user.id
flash[:notice] = "successfully logged in!"
end
return redirect_to index_path
end
def edit
end
def update
flash[:notice]= "details failed to save"
@user.name = params[:user][:name]
@user.email = params[:user][:email]
flash[:notice]= "information updated" if @user.save
end
def destroy
end
def login
end
def logout
end
private
def set_current_user
#This is the logged in user
@user= User.find_by(id: session[:user_id])
end
end
|
# -*- encoding : utf-8 -*-
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.string :uuid, limit: 36, null: false
t.references :owner, null: false
t.references :course, null: false
t.string :type_cd, limit: 20, null: false
t.string :name, limit: 100
t.timestamps null: false
end
end
end
|
class UsersController < ApplicationController
layout "reservations", only: %i(show edit)
before_action :authenticate_user!
def new
@users = User.all
end
def show
@resource = User.find params[:id]
@q = @resource.bills.ransack params[:q]
@bills = @q.result.page(params[:page]).per Settings.user.page
respond_to do |format|
format.js
format.html
end
end
def create
@user = User.new user_params
if @user.save
@user.send_activation_email
flash[:info] = t "global.text_check_email"
redirect_to root_url
else
respond_to :js
end
end
def edit; end
def update
@resource = User.find params[:id]
if @resource.update user_params
flash[:success] = t "global.update_success"
redirect_to @resource
else
flash.now[:danger] = t "global.update_error"
render :edit
end
end
private
def bill_range range
range.present? ? select_range(range) : @resource.bills
end
end
|
require 'spec_helper'
RSpec.describe Rusic::Uploaders::CustomAttributes do
before do
@custom_attributes_uploader = Rusic::Uploaders::CustomAttributes.new(nil)
allow(@custom_attributes_uploader).to receive(:attributes_file) {
attributes_file = File.join(File.dirname(__FILE__), '..', '..', '..', 'fixtures', 'attributes.yml')
YAML.load(File.open(attributes_file))
}
end
it "returns params" do
expect(@custom_attributes_uploader.params).to eq({
custom_attribute_collections: [
{
key: "awesome_group",
title: "Awesome Group Title",
help_title: "Do something awesome",
help_body: "Here is some help to being awesome",
custom_attributes: [
{
"key" => "some_nested_text_1",
"value" => "Example",
"help_text" => "Example Help Text",
"input_type" => "text",
"select_options" => nil
},
{
"key" => "some_other_text_1",
"value" => "Example",
"help_text" => "Example Help Text",
"input_type" => "text",
"select_options" => nil
}
]
},
{
key: "ok_group",
title: "OK Group Title",
help_title: "Do something average",
help_body: "Here is some help to being alright",
custom_attributes: [
{
"key" => "some_nested_text_2",
"value" => "Example2",
"help_text" => "Example Help Text",
"input_type" => "text",
"select_options" => nil
},
{
"key" => "some_other_text_2",
"value" => "Example2",
"help_text" => "Example Help Text",
"input_type" => "text",
"select_options" => nil
}
]
}
]
})
end
end
|
class CreateBooks < ActiveRecord::Migration
# def change
# end
def up
create_table :books do |t|
t.string :title
t.string :text
t.string :author
t.string :genre
t.string :imagelink
t.string :amazonlink
end
end
def down
drop_table :books
end
end
|
class AddBannerToWesellItems < ActiveRecord::Migration
def change
add_column :wesell_items, :banner, :string
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
config.ssh.insert_key = false
config.vm.define "csr1" do |csr1|
csr1.vm.box = "csr1000v"
csr1.vm.boot_timeout = 600
csr1.vm.network :forwarded_port, guest: 22, host: 12200, host_ip: "0.0.0.0", id: 'ssh'
csr1.vm.network "private_network", virtualbox__intnet: "1_2",
ip: "169.254.1.11", auto_config: false
csr1.vm.network "private_network", virtualbox__intnet: "1_4",
ip: "169.254.1.11", auto_config: false
end
end
|
require File.dirname(__FILE__) + '/spec_helper'
describe I18n::Backend::Database do
before(:each) do
@backend = I18n::Backend::Database.new
I18n.backend = @backend
end
after(:each) do
@backend.cache_store.clear
end
describe "with default locale en" do
before(:each) do
I18n.default_locale = "en"
@english_locale = I18n::Backend::Locale.find_or_create!(:code => "en")
end
describe "and locale en" do
before(:each) do
I18n.locale = "en"
end
it "should cache translations" do
@english_locale.translations.create!(:key => 'activerecord.errors.messages.blank', :value => 'is blank moron!')
options = {:attribute=>"I18n::Backend::Locale", :value=>nil,
:scope=>[:activerecord, :errors], :default=>[:"models.translation.blank", :"messages.blank"], :model=>"Translation"}
@backend.translate("en", :"models.translation.attributes.locale.blank", options).should == "is blank moron!"
@backend.cache_store.exist?("en:#{Translation.hk("activerecord.errors.models.translation.attributes.locale.blank")}").should be_true
@backend.cache_store.exist?("en:#{Translation.hk("activerecord.errors.models.translation.blank")}").should be_true
@backend.cache_store.exist?("en:#{Translation.hk("activerecord.errors.messages.blank")}").should be_true
@backend.cache_store.read("en:#{Translation.hk("activerecord.errors.models.translation.attributes.locale.blank")}").should == nil
@backend.cache_store.read("en:#{Translation.hk("activerecord.errors.models.translation.blank")}").should == nil
@backend.cache_store.read("en:#{Translation.hk("activerecord.errors.messages.blank")}").should == "is blank moron!"
end
it "should update a cache record if the translation record changes" do
hash_key = Translation.hk("blah")
@backend.translate("en", "blah")
@backend.cache_store.read("en:#{hash_key}").should == "blah"
translation = @english_locale.translations.find_by_key(Translation.hk("blah"))
translation.value.should == "blah"
translation.update_attribute(:value, "foo")
translation.value.should == "foo"
@backend.cache_store.read("en:#{hash_key}").should == "foo"
end
end
describe "and locale es" do
before(:each) do
I18n.locale = "es"
@spanish_locale = I18n::Backend::Locale.find_or_create!(:code => 'es')
end
it "should cache translations" do
@english_locale.translations.create!(:key => 'activerecord.errors.messages.blank', :value => 'is blank moron!')
options = {:attribute=>"I18n::Backend::Locale", :value=>nil,
:scope=>[:activerecord, :errors], :default=>[:"models.translation.blank", :"messages.blank"], :model=>"Translation"}
@backend.translate("es", :"models.translation.attributes.locale.blank", options).should == "is blank moron!"
@backend.cache_store.exist?("es:#{Translation.hk("activerecord.errors.models.translation.attributes.locale.blank")}").should be_true
@backend.cache_store.exist?("es:#{Translation.hk("activerecord.errors.models.translation.blank")}").should be_true
@backend.cache_store.exist?("es:#{Translation.hk("activerecord.errors.messages.blank")}").should be_true
@backend.cache_store.read("es:#{Translation.hk("activerecord.errors.models.translation.attributes.locale.blank")}").should == nil
@backend.cache_store.read("es:#{Translation.hk("activerecord.errors.models.translation.blank")}").should == nil
@backend.cache_store.read("es:#{Translation.hk("activerecord.errors.messages.blank")}").should == "is blank moron!"
@backend.cache_store.exist?("en:#{Translation.hk("activerecord.errors.models.translation.attributes.locale.blank")}").should be_true
@backend.cache_store.exist?("en:#{Translation.hk("activerecord.errors.models.translation.blank")}").should be_true
@backend.cache_store.exist?("en:#{Translation.hk("activerecord.errors.messages.blank")}").should be_true
@backend.cache_store.read("en:#{Translation.hk("activerecord.errors.models.translation.attributes.locale.blank")}").should == nil
@backend.cache_store.read("en:#{Translation.hk("activerecord.errors.models.translation.blank")}").should == nil
@backend.cache_store.read("en:#{Translation.hk("activerecord.errors.messages.blank")}").should == "is blank moron!"
end
end
end
end
|
class AddFieldsToActors < ActiveRecord::Migration
def change
add_column :actors, :short_name, :string
add_column :actors, :legal_status, :string
add_column :actors, :other_names, :string
end
end
|
# == Schema Information
#
# Table name: restaurants
#
# id :integer not null, primary key
# name :string
# cuisine_id :integer
# accept_10_bis :boolean
# max_delivery_time :integer
# created_at :datetime not null
# updated_at :datetime not null
# address :string
# lon :float
# lat :float
#
class Restaurant < ApplicationRecord
belongs_to :cuisine, foreign_key: :cuisine_id
has_many :reviews, dependent: :destroy
validates :name, :cuisine_id, presence: true
validates :max_delivery_time, numericality: {greater_than_or_equal_to: 0}
validates :name, uniqueness: { scope: :address }
def calculate_restaurant_rating
return 0 if reviews.empty?
(reviews.sum(:rating) / reviews.count.to_f).round
end
def get_cuisine_name
Cuisine.find(cuisine_id).name
end
def get_cuisine_icon
Cuisine.find(cuisine_id).icon
end
end
|
class Admin::FuelsController < Admin::BaseController
before_action :set_fuel, only: [:show, :edit, :update, :destroy]
def index
@fuels = Fuel.all
end
def show
end
def new
@fuel = Fuel.new
end
def edit
end
def create
@fuel = Fuel.new(fuel_params)
respond_to do |format|
if @fuel.save
format.html { redirect_to admin_fuels_path, notice: 'Fuel was successfully created.' }
else
format.html { render :new }
end
end
end
def update
respond_to do |format|
if @fuel.update(fuel_params)
format.html { redirect_to admin_fuels_path, notice: 'Fuel was successfully updated.' }
else
format.html { render :edit }
end
end
end
def destroy
@fuel.destroy
respond_to do |format|
format.html { redirect_to admin_fuels_path, notice: 'Fuel was successfully destroyed.' }
end
end
private
def set_fuel
@fuel = Fuel.find(params[:id])
end
def fuel_params
params.require(:fuel).permit(:name, :min_density, :max_density)
end
end
|
require('pry')
require('MiniTest/autorun')
require('MiniTest/rg')
require_relative("../guest.rb")
require_relative("../group.rb")
require_relative("../host.rb")
require_relative("../room.rb")
class TestGroup < MiniTest::Test
def setup
@group = Group.new(200)
@guest1 = Guest.new("Joe", "Purple Rain", 50)
@guest2 = Guest.new("Bob", "Come as you are", 3)
@guest3 = Guest.new("Karl", "November Rain", 78)
@guest4 = Guest.new("Sally", "Smooth Criminal", 34)
@guest5 = Guest.new("Barbara", "Like a Virgin", 99)
@guest6 = Guest.new("Helen", "You're my Hero", 5)
@group.add_guest(@guest1, @guest2, @guest3, @guest4,@guest5,@guest6)
@room1 = Room.new(8, 200)
@room2 = Room.new(6, 180)
@room3 = Room.new(4, 100)
@room4 = Room.new(5, 120)
@room5 = Room.new(6, 180)
@room6 = Room.new(7, 166)
@room7 = Room.new(4, 110)
@room8 = Room.new(3, 3000000)
@room1.add_group(@group)
@host = Host.new(400)
@host.add_room(@room2, @room3, @room4, @room5, @room6, @room7, @room8,@room1)
end
def test_can_add_guest_to_group
example = Group.new(200)
example.add_guest(@guest1, @guest2, @guest3, @guest4,@guest5,@guest6)
assert_equal(6, example.guests.length)
end
def test_can_remove_guest_from_group
@group.remove_guest("Joe")
assert_equal(5, @group.guests.length)
end
def test_group_money
assert_equal(269, @group.total_map)
end
def test_group_pay
assert_equal(0, @group.group_pay(@room1))
end
end
|
class Reminder < ActiveRecord::Base
attr_accessible :phone_number, :date, :reminder_text
validates :date, presence: true
validates :phone_number, presence: true
validates :reminder_text, presence: true
end
|
class AddCounterColumnToCategories < ActiveRecord::Migration
def change
add_column :categories, :books_count, :integer, :default => 0
#Implemenation of counter cache
Category.reset_column_information
Category.all.each do |c|
Category.update_counters c.id, :books_count => c.books.count
end
end
end
|
# frozen_string_literal: true
module EventHelper
def calendar_tip
<<~TIP.tr("\n", ' ')
Use this address to subscribe to the Camp calendar in another calendar
application (e.g. Google Calendar). Click the button to copy the address
to your clipboard.
TIP
end
def owner_dropdown(form, event)
selected = event.persisted? ? event.user_id : current_user.id
form.collection_select :user_id,
User.order(:first_name, :last_name),
:id,
:full_name,
include_blank: true,
selected: selected,
label: 'Schedule For'
end
end
|
class Project < ActiveRecord::Base
has_many :work_processes, :dependent => :destroy
has_many :approvals, :dependent => :destroy
has_many :attentions, :dependent => :destroy
has_many :companies, :dependent => :destroy
has_many :equipment, :dependent => :destroy
has_many :meetings, :dependent => :destroy
has_many :people, :dependent => :destroy
has_many :site_focuses, :dependent => :destroy
has_many :site_operations, :dependent => :destroy
has_many :site_responsibilities, :dependent => :destroy
has_many :planning_referrals, :dependent => :destroy
has_many :site_referrals, :dependent => :destroy
belongs_to :user
accepts_nested_attributes_for :work_processes,
:approvals,
:attentions,
:companies,
:equipment,
:meetings,
:people,
:site_focuses,
:site_operations,
:site_responsibilities,
:planning_referrals,
:site_referrals, :allow_destroy => true
validates_presence_of :name
def fileshare_prefix
if self[:fileshare_prefix].blank?
self[:fileshare_prefix] = SecureRandom.hex
end
self[:fileshare_prefix]
end
def byggeweb
return if [byggeweb_username, byggeweb_password].grep(/./).empty?
@byggeweb ||= Byggeweb.new byggeweb_username, byggeweb_password, byggeweb_project
end
def fileshare
@fileshare ||= Fileshare::Base.new(fileshare_prefix)
end
def bips_root_sections
[
jsonize_section("Foo"),
jsonize_section("Bar"),
jsonize_section("Test")
]
end
def bips_section(id)
sections = ["Lorem Ipsum", "Overskrift A", "Test", "Punkt 1", "Endnu et punkt", "Test 123"]
sections.map! { |name| jsonize_section name }
sections.reject! { rand(2) == 0 }
sections.shuffle
end
def bips_content(section_id)
headlines = ["Overskrit A", "Overskrit B", "Overskrit C"]
content = [
"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla justo ipsum, rutrum a, consectetuer ac, malesuada vel, lacus. Vestibulum eu ligula. Vestibulum sed enim. Donec metus ante, tempor et, sollicitudin sed, consectetuer a, orci. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin volutpat. Nullam risus. Nam dignissim dolor nec urna. Quisque massa lacus, aliquet vitae, congue sed, consectetuer pharetra, ligula. In hac habitasse platea dictumst. Integer commodo sagittis felis. Vivamus et ipsum. Morbi sodales, purus hendrerit tincidunt aliquam, eros purus bibendum mi, id interdum wisi nunc sit amet tortor. Sed pharetra. Etiam laoreet arcu ut enim. In et eros. Sed vel ligula nec quam venenatis dictum. Praesent risus.",
"Nullam justo magna, dignissim ut, ultricies eget, mollis sit amet, enim. Nulla consectetuer, dui id tempus varius, nunc libero tincidunt orci, nec fringilla eros eros in leo. Nullam vulputate tellus vel est. Donec vel urna vel metus volutpat egestas. In commodo, augue vitae pulvinar blandit, neque elit auctor metus, in bibendum magna tortor et diam. Nulla sapien. Donec ultrices felis a dui. Nam a risus in velit porttitor pretium. Quisque pharetra mi nec nulla. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
"Mauris at mauris. Phasellus justo. Ut urna. Quisque pede dui, dignissim a, ullamcorper et, bibendum vitae, sapien. Proin ut diam. Aenean purus. Ut ante. Mauris consectetuer lectus at est. Nam id leo. Maecenas at eros. In lectus pede, porttitor eu, imperdiet sed, malesuada sed, dui. Suspendisse venenatis, justo nec dapibus bibendum, odio eros ultricies nisl, in porta quam libero vitae erat. Aenean imperdiet tempus elit. Phasellus pellentesque mauris non velit facilisis egestas. Proin ultrices, dolor eu rutrum ullamcorper, velit odio bibendum turpis, in accumsan massa elit nec nulla. Vivamus lacus. Proin accumsan. Nullam magna.",
"Morbi tellus tortor, adipiscing vel, rutrum quis, tempus vitae, purus. Etiam lorem eros, fermentum vitae, euismod ut, varius porta, lorem. In quis diam. Cras scelerisque. Cras pharetra massa id ligula. Ut tortor. Aenean ipsum nunc, rhoncus vel, sagittis non, luctus sed, est. Integer condimentum. Ut nonummy, orci eget iaculis semper, sem sapien mollis ante, ac hendrerit lacus lacus eget tellus. Phasellus scelerisque tempor sapien. Nulla facilisi. Curabitur sagittis pretium lectus. Sed a ante. Aliquam erat volutpat. Quisque hendrerit sem eu odio. Duis rhoncus. Vestibulum scelerisque tortor ut nulla. Mauris risus massa, nonummy in, tincidunt eget, imperdiet eget, massa. Pellentesque at ligula.",
"Nunc lobortis ligula a wisi lobortis lacinia. Cras ut diam. Nam interdum, erat id venenatis convallis, neque elit viverra nisl, in ultrices est odio non arcu. Fusce interdum consequat massa. Mauris interdum. Nunc sagittis ultrices justo. Praesent sagittis. Praesent quis neque non mi imperdiet dictum. Aliquam dictum luctus neque. Morbi lobortis. Fusce consequat fermentum nisl. Praesent vestibulum. Proin pretium tempus elit."
]
content.map! { |content| { :headline => headlines[rand(3)], :body => content, :id => rand(1024) } }
content[rand(5)]
end
# when generating dummy nodes, you can leave the ID blank to get a random ID
def jsonize_section(name, id = nil, open = false, children = [])
{
:data => {
:title => name,
:attr => { :class => 'tree-node' }
},
:attr => { :rel => id || rand(1024) },
:state => (open ? 'open' : 'closed'),
:children => children
}
end
def to_xml(options = {}, &block)
options[:except] ||= []
options[:except].concat([:byggeweb_project, :byggeweb_username, :byggeweb_password]).uniq!
super
end
def to_json(options = {})
options[:except] ||= []
options[:except].concat([:byggeweb_project, :byggeweb_username, :byggeweb_password]).uniq!
super
end
def to_xml_deep
to_xml(
:include => {
:approvals => {},
:attentions => {},
:companies => {},
:equipment => {},
:meetings => {},
:people => {},
:site_focuses => {},
:site_operations => {},
:site_responsibilities => {},
:planning_referrals => {},
:site_referrals => {}
}
)
end
end
|
class UpdateOnlineStatus
prepend SimpleCommand
def initialize(user)
@user = user
end
def call
if (Time.now - user.update_location_at > 5.minutes)
user.assign_attributes online_status: false
else
user.assign_attributes online_status: true
end
if user.save
Report.refresh
user
end
end
private
attr_accessor :user
end
|
class Api::V1::SessionsController < Api::V1::BaseController
skip_before_action :authenticate_user!, only: :create
expose :user, -> { User.find_by(email: params[:email]) }
def create
return render json: user.generate_new_token!, status: :created if user && user.authenticate(params[:password])
head(:unprocessable_entity)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.