text stringlengths 10 2.61M |
|---|
require 'test_helper'
class UserAchievementsControllerTest < ActionDispatch::IntegrationTest
setup do
@user_achievement = user_achievements(:one)
end
test "should get index" do
get user_achievements_url
assert_response :success
end
test "should get new" do
get new_user_achievement_url
assert_response :success
end
test "should create user_achievement" do
assert_difference('UserAchievement.count') do
post user_achievements_url, params: { user_achievement: { achievement_id: @user_achievement.achievement_id, user_id: @user_achievement.user_id } }
end
assert_redirected_to user_achievement_url(UserAchievement.last)
end
test "should show user_achievement" do
get user_achievement_url(@user_achievement)
assert_response :success
end
test "should get edit" do
get edit_user_achievement_url(@user_achievement)
assert_response :success
end
test "should update user_achievement" do
patch user_achievement_url(@user_achievement), params: { user_achievement: { achievement_id: @user_achievement.achievement_id, user_id: @user_achievement.user_id } }
assert_redirected_to user_achievement_url(@user_achievement)
end
test "should destroy user_achievement" do
assert_difference('UserAchievement.count', -1) do
delete user_achievement_url(@user_achievement)
end
assert_redirected_to user_achievements_url
end
end
|
# -*- coding: utf-8 -*-
require 'spec_helper'
describe SugarReciever do
context "wrong cases." do
it "should be raised when not onto the match block." do
expect { subject.case?("dummy") }.should raise_error NoMethodError
end
it "can't nest of the 'case?' method." do
subject.match("dummy") do
subject.case?("dummy") do
pending "ネスと不可能にする意味ある?" do
expect { subject.case?("dummy") {} }.should raise_error NoMethodError
end
end
end
end
end
context "right cases." do
example do
expect { subject.match("dummy") {} }.should_not raise_error
end
example do
expect { subject.match("dummy") { subject.case?("dummy") {} } }.should_not raise_error
end
example do
subject.match("dummy") do
subject.case?("dummy") do
expect { subject.match("dummy"){} }.should_not raise_error
end
end
end
end
context "side effect should not exist." do
example do
expect { subject.match("dummy") {} }.should_not raise_error
expect { subject.case?("dummy") }.should raise_error NoMethodError
end
end
describe "#match" do
end
describe "#case?" do
end
describe "#default" do
describe "return value" do
it "should return the result of the matching case process if that has matched." do
subject.instance_eval do
(match "hoge" do
case?("hoge") { "bar" }
default { "fuga" }
end).should == "bar"
end
end
it "should return the result of the default process." do
subject.instance_eval do
(match "hoge" do
case?("foo") { "bar" }
default { "fuga" }
end).should == "fuga"
end
end
end
end
describe "#finally" do
describe "return value" do
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_time_zone
#before_filter :set_current_user
#before_filter :authenticate_user!
before_filter :get_current_user
protected
def get_current_user
#debugger
#puts "Hi"
# Authorization.current_user = current_user
end
def set_time_zone
setting = Setting.first
Time.zone = setting.time_zone if setting.present?
#Admin uses default time zone set in application.rb
end
def mailer_set_url_options
ActionMailer::Base.default_url_options[:host] = request.host_with_port.to_s
end
def user_permission
section = Section.where("controller_name = ? && action = ?",params[:controller],params[:action]).first
if !current_user.nil? && !section.nil? && !current_user.role.nil? && current_user.role.sections.include?(section)
return true
elsif !current_user.nil? && current_user.is_admin?
return true
elsif !current_user.nil? && params[:controller]=="servers"&& params[:action]=="index"
return true
else
flash[:error] = "You are not allowed to access this action."
if (request.xhr?)
render :text => "You are not allowed to access this action."
return
else
redirect_to(servers_url) && return
end
end
end
def after_sign_in_path_for(resource)
add_login_history
command_path
end
def after_sign_out_path_for(resource)
new_user_session_path
end
def authenticate_admin_user!
authenticate_user!
unless current_user.is_admin?
flash[:alert] = "This area is restricted to administrators only."
redirect_to command_path
end
end
def current_admin_user
return nil if user_signed_in? && !current_user.is_admin?
current_user
end
def add_login_history
LoginHistory.create({:user_id=>current_user.id,:ip_address=>request.ip,:login_date=>Time.zone.now})
end
def find_ec2
@user = current_user
if !@user.access_key_id.blank? && !@user.secret_access_key.blank?
@aws_keys = {:access_key_id => "#{@user.access_key_id}", :secret_access_key => "#{@user.secret_access_key}"}
@ec2 = AWS::EC2.new(:access_key_id => "#{@user.access_key_id}", :secret_access_key => "#{@user.secret_access_key}")
@elb = AWS::ELB.new(@aws_keys)
end
end
end
|
class SessionsController < ApplicationController
def new
render :new
end
def create
user = User.find_by_credentials(
params[:user][:email],
params[:user][:password]
)
if user.nil?
flash.now[:errors] = ["Invalid credentials."]
render :new
else
login!(user)
redirect_to bands_url
end
end
def destroy
current_user.reset_session_token!
session[:session_token] = nil
redirect_to new_session_url
end
end
|
class CreateMensagemFaleConoscos < ActiveRecord::Migration
def change
create_table :mensagem_fale_conoscos do |t|
t.string :remetente, :limit => 50, :null=>false
t.string :email, :limit => 50, :null => false
t.string :assunto, :limit => 40, :null => false
t.text :mensagem, :null => false
t.timestamps
end
end
end
|
class ChangeMeteterAnomalyToInspects < ActiveRecord::Migration
def change
change_column :inspects, :meter_anomaly, :text
end
end
|
class Store
def initialize
@categories = Category.distinct.pluck(:name)
get_price_range
end
private
def get_price_range
row = Product.select("min(price) as min_price, max(price) as max_price")[0]
@min_price = row.min_price || 1000
@max_price = row.max_price || 100000
end
end
|
class Favorite < ApplicationRecord
belongs_to :post
belongs_to :user
def self.dayly_ranking
self.group(:post_id).where(created_at: Time.now.all_day).order('count_post_id DESC').limit(10).count(:post_id)
end
def self.monthly_ranking
self.group(:post_id).where(created_at: Time.now.all_month).order('count_post_id DESC').limit(10).count(:post_id)
end
def self.whole_ranking
self.group(:post_id).order("count_post_id DESC").limit(10).count(:post_id)
end
end
|
describe 'integration' do
describe Rubyflare, :vcr, order: :defined do
# Given I have valid Cloudflare credentials
# When I create a Rubyflare instance
# And get my Cloudflare user details
# Then I should have valid response
context 'given I have valid Cloudflare credentials' do
let(:email) { ENV['CLOUDFLARE_EMAIL'] }
let(:api_key) { ENV['CLOUDFLARE_API_KEY'] }
context 'when I create a Rubyflare instance' do
let(:connection) { described_class.connect_with(email, api_key) }
context 'and GET my Cloudflare user details' do
it 'should return a valid response' do
response = connection.get('user')
expect(response).to be_successful
end
end
context 'and update(PATCH) my user details' do
it 'should return a valid response' do
response = connection.patch('user', { first_name: 'Trevor' })
expect(response).to be_successful
end
end
context 'and create(POST) a new zone' do
it 'should return a valid response' do
response = connection.post('zones', { name: 'supercooldomain.com' })
expect(response).to be_successful
end
end
context 'and remove(DELETE) a zone' do
it 'should return a valid response' do
domain_zone = connection.get('zones', { name: 'supercooldomain.com' })
response = connection.delete("zones/#{domain_zone.result[:id]}")
expect(response).to be_successful
end
end
end
end
end
end
|
module KPM
module SystemProxy
module MemoryInformation
class << self
def fetch
memory_info = nil
if OS.windows?
memory_info = fetch_windows
elsif OS.linux?
memory_info = fetch_linux
elsif OS.mac?
memory_info = fetch_mac
end
memory_info
end
def get_labels
labels = [{:label => :memory_detail},
{:label => :value}]
labels
end
private
def fetch_linux
mem_data = `cat /proc/meminfo 2>&1`.gsub("\t",'')
mem = get_hash(mem_data)
mem
end
def fetch_mac
mem_data = `vm_stat 2>&1`.gsub(".",'')
mem = get_hash(mem_data)
mem.each_key do |key|
mem[key][:value] = ((mem[key][:value].to_i * 4096) / 1024 / 1024).to_s + 'MB'
mem[key][:memory_detail] = mem[key][:memory_detail].gsub('Pages','Memory')
end
mem_total_data = `system_profiler SPHardwareDataType | grep " Memory:" 2>&1`
mem_total = get_hash(mem_total_data)
mem = mem_total.merge(mem)
mem
end
def fetch_windows
mem_data = `systeminfo | findstr /C:"Total Physical Memory" /C:"Available Physical Memory"`
mem = get_hash(mem_data)
mem
end
def get_hash(data)
mem = Hash.new
unless data.nil?
data.split("\n").each do |info|
infos = info.split(':')
mem[infos[0].to_s.strip] = {:memory_detail => infos[0].to_s.strip, :value => infos[1].to_s.strip}
end
end
mem
end
end
end
end
end |
class CreateArtists < ActiveRecord::Migration[4.2]
def up
# for when migration is changed forward
end
def down
# for when migration is rolled back
end
def change
# for minor migration changes
# "The change method is the primary way of writing migrations. It works for the majority of cases, where Active Record knows how to reverse the migration automatically"
create_table :artists do |t|
t.string :name
t.string :genre
t.integer :age
t.string :hometown
end
end
end
|
#!/usr/bin/env ruby
# require 'ftools'
class Task
TASKS = Hash.new
attr_reader :prerequisites
def initialize(task_name)
@name = task_name
@prerequisites = []
@actions = []
end
def enhance(deps=nil, &block)
@prerequisites |= deps if deps
@actions << block if block_given?
self
end
def name
@name.to_s
end
def invoke
@prerequisites.each { |n| Task[n].invoke }
execute if needed?
end
def execute
return if @triggered
@triggered = true
@actions.collect { |act| result = act.call(self) }.last
end
def needed?
true
end
def timestamp
Time.now
end
class << self
def [](task_name)
TASKS[intern(task_name)] or fail "Don't know how to rake #{task_name}"
end
def define_task(args, &block)
case args
when Hash
fail "Too Many Target Names: #{args.keys.join(' ')}" if args.size > 1
fail "No Task Name Given" if args.size < 1
task_name = args.keys[0]
deps = args[task_name]
else
task_name = args
deps = []
end
deps = deps.collect {|d| intern(d) }
get(task_name).enhance(deps, &block)
end
def get(task_name)
name = intern(task_name)
TASKS[name] ||= self.new(name)
end
def intern(task_name)
(Symbol === task_name) ? task_name : task_name.intern
end
end
end
class FileTask < Task
def needed?
return true unless File.exist?(name)
latest_prereq = @prerequisites.collect{|n| Task[n].timestamp}.max
return false if latest_prereq.nil?
timestamp < latest_prereq
end
def timestamp
File.new(name.to_s).mtime
end
end
def task(args, &block)
Task.define_task(args, &block)
end
def desc(args, &block)
end
def file(args, &block)
FileTask.define_task(args, &block)
end
def sys(cmd)
puts cmd
system(cmd) or fail "Command Failed: [#{cmd}]"
end
def rake
begin
here = Dir.pwd
while ! File.exist?("Rakefile")
Dir.chdir("..")
fail "No Rakefile found" if Dir.pwd == here
here = Dir.pwd
end
puts "(in #{Dir.pwd})"
load "./Rakefile"
ARGV.push("default") if ARGV.size == 0
ARGV.each { |task_name| Task[task_name].invoke }
rescue Exception => ex
puts "rake aborted ... #{ex.message}"
puts ex.backtrace.find {|str| str =~ /Rakefile/ } || ""
end
end
if __FILE__ == $0 then
rake
end
|
require 'debit'
describe Debit do
before(:each) do
@debit = Debit.new('02/04/2018', 500, 800)
end
describe '#new' do
it 'initializes date' do
expect(@debit.date).to eq '02/04/2018'
end
it 'initializes amount' do
expect(@debit.amount).to eq 500
end
it 'initializes balance' do
expect(@debit.balance).to eq 800
end
end
end
|
class Membership < ActiveRecord::Base
belongs_to :client
belongs_to :service
belongs_to :rate
has_many :classrecords
has_many :detail_sales
end
|
require 'spec_helper'
require_relative '../../lib/paths'
using StringExtension
module Jabverwock
RSpec.describe 'js base test' do
it 'id case 1' do
expect(KSUtil.isID('id')).to eq true
end
it 'id case 2' do
expect( KSUtil.isID('id_s')).to eq true
end
it 'id case 3' do
expect( KSUtil.isID('name')).to eq false
end
it 'cls' do
expect( KSUtil.isCls('cls')).to eq true
end
it 'cls case 2' do
expect( KSUtil.isCls('cls_s')).to eq true
end
it 'cls case 3' do
expect( KSUtil.isCls('name')).to eq false
end
it 'name' do
expect( KSUtil.isName('name')).to eq true
end
it 'name case 2' do
expect( KSUtil.isName('name_s')).to eq true
end
it 'name case 3' do
expect( KSUtil.isName('cls')).to eq false
end
it'initialize case 1' do
js = JsBase.new('id__sample')
expect(js.id).to eq 'sample'
end
it'initialize case 2' do
js = JsBase.new(:id__sample)
expect(js.id).to eq 'sample'
end
it'initialize case 3' do
js = JsBase.new(:attr__test)
expect(js.id).to eq ''
end
it'initialize case tagName case 1' do
js = JsBase.new(:name__sample)
expect(js.name).to eq 'sample'
end
it'initialize case tagName case 2 ' do
para = P.new.attr(:name__sample)
expect(para.js.name).to eq 'sample'
end
it'initialize case tagName default value is class name ' do
para = P.new
expect(para.js.name).to eq 'p'
end
it'initialize case tagName default value is class name case 2 ' do
h = HTML.new
expect(h.js.name).to eq 'html'
end
it'initialize case tagName default value is class name case 3 ' do
h = DOCTYPE.new
expect(h.js.name).to eq 'doctype'
end
it'initialize case tagName default value is class name case 4 ' do
h = TABLE.new
expect(h.js.name).to eq 'table'
end
it 'js.doc.byTagName set by default name' do
para = P.new
para.js.doc.byTagName
expect(para.jdoc.orders[0]).to eq "document.getElementByTagName('p');"
end
it 'js.doc.byTagName set by default name case 2' do
para = HTML.new
para.js.doc.byTagName
expect(para.jdoc.orders[0]).to eq "document.getElementByTagName('html');"
end
#### sequence hash ###
it 'seqHash init test' do
jsb = JsBase.new
a = jsb.seqHash 'shi'
expect(a).to eq ({ js1: 'shi' })
end
it 'seqHash twice' do
jsb = JsBase.new
jsb.seqHash 'shi'
a = jsb.seqHash 'gooo'
expect(a).to eq ({ js2: 'gooo' })
end
### firstHashValue ##
it 'firstHashValue' do
jsb= JsBase.new
jsb.recBy 'shi'
jsb.recBy 'Goo'
jsb.recBy 'DDD'
expect(jsb.record).to eq 'shi'
end
it 'recordLast' do
jsb= JsBase.new
jsb.recBy 'shi'
jsb.recBy 'Goo'
jsb.recBy 'DDD'
expect(jsb.orders[2]).to eq 'DDD'
end
### recBy ####
it 'recBy case 1' do
jsb = JsBase.new
jsb.recBy 'shi'
expect(jsb.orders[0]).to eq 'shi'
expect(jsb.orders).to eq ['shi']
end
it 'recBy case 2' do
jsb = JsBase.new
jsb.recBy 'shi'
jsb.recBy 'Goo'
expect(jsb.orders[0]).to eq 'shi'
expect(jsb.orders[1]).to eq 'Goo'
expect(jsb.orders).to eq ['shi', 'Goo']
end
it 'recBy case 3' do
jsb = JsBase.new
jsb.recBy 'shi'
jsb.recBy 'Goo'
jsb.recBy 'DDD'
expect(jsb.orders[0]).to eq 'shi'
expect(jsb.orders[1]).to eq 'Goo'
expect(jsb.orders).to eq ['shi', 'Goo', 'DDD']
end
end
end
|
class QuestionsController < ApplicationController
# runs in the order defined
before_action :find_question, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user, except: [:index, :show]
before_action :authorize_user, only: [:edit, :update, :destroy]
#we can specify :only or :except to be more specific about the actions which the before_action applies to
def index
@questions = Question.recent(10).page(params[:page]).per(10)
respond_to do |format|
format.html
format.json { render json: @questions }
end
end
def new
@question = Question.new
end
def create
@question = Question.new(question_params)
# we don't have access to the @current_user, but we access it through the method
@question.user = current_user
if @question.save
# redirect_to question_path({id: @question.id})
# redirect_to question_path({id: @question})
# redirect_to question_path(@question)
flash[:success] = "That's a really thoughtful question -- thanks"
redirect_to @question
else
# matches the template (not the action) specified
# or can specify full path "questions/new" etc.
flash[:danger] = "Question not created -- Check errors below"
render :new # will go to default behaviour if not specified
end
# redirect issues another HTTP `GET` request - render remains in cycle
# will work through mass assignment
# question = Question.new
# question.title = params[:question][:title]
# question.body = params[:question][:body]
# question.save
end
# GET: /questions/13
def show
# find throws an exception when its not found.
@question = Question.find(params[:id])
@answer = Answer.new
respond_to do |format|
format.html
format.json { render json: { question: @question, answers: @question.answers } }
end
end
def edit
# finds question to be edited
# @question = Question.find(params[:id])
end
def update
# fetch question first to update it#update with sanitized#strong params to update title/body#redirect to question show page
# @question = Question.find(params[:id])
if @question.update(question_params)
redirect_to(question_path(@question), { notice: "Question updated" })
else
render :edit
end
end
def destroy
# question = Question.find(params[:id])
@question.destroy
redirect_to root_path, flash: { danger: "Question Deleted" }
end
private
def question_params
params.require(:question).permit([:title, :body, :image, :category_id,
{ tag_ids: [] } ])
end
#params => {"question"=>{"title"=>"Hello World", "body"=>"this is a test"}}
# question = Question.new([:params])
# using params.require ensures there is a key called `question` in my params. the `permit` method will only allow parameters that are explicitly listed. In this case, title and body.
# local methods and variables are the same
def find_question
@question = Question.find(params[:id])
end
def authorize_user
# use cancancan to check
unless can? :manage, @question
# if @question.user != current_user
redirect_to root_path , alert: "Access Denied"
end
end
#####MOVED TO APPLICATION CONTROLLER!
# # exception for DoubleRenderError in the callbacks
# def authenticate_user
# # unless session[:user_id]
# unless user_signed_in?
# redirect_to new_session_path
# end
# end
end
|
class User < ActiveRecord::Base
def first_name
full_name.split(" ").first
end
end |
class CreateEnquiries < ActiveRecord::Migration
def self.up
create_table :enquiries do |t|
t.string :first_name, :null => false
t.string :last_name, :null => false
t.string :company, :null => false
t.integer :phone_no, :null => false
t.string :city, :null => false
t.text :query, :null => false
t.string :email, :null => false
t.timestamps
end
end
def self.down
drop_table :enquiries
end
end
|
Given(/^I am on register page$/) do
@driver.navigate.to 'http://demo.redmine.org/account/register'
end
When(/^I submit registration form with valid data$/) do
register_user
end
Then(/^I see message "([^"]*)"$/) do |message|
@wait.until {@driver.find_element(:id, 'flash_notice').displayed?}
expect(@driver.find_element(:id, 'flash_notice').text).to eql message
end
And(/^I am logged in$/) do
current_login= @driver.find_element(:css, '#loggedas .user').text
expect(current_login).to eql @login
end
|
files = ["../lib/cell_grid_view", "../lib/cell_grid"]
begin
files.each do |filename|
require_relative filename
end
rescue NoMethodError
files.each do |filename|
require filename
end
end
require "test/unit"
class TestCellGridView < Test::Unit::TestCase
def setup
@grid_view = CellGridView.new
end
def test_initialize
assert_not_nil(@grid_view)
end
def test_set_width_and_height
assert_cell_dimensions(0, 0)
set_cell_dimensions(20, 10)
assert_cell_dimensions(20, 10)
end
def test_set_width_and_height_in_constructor
@grid_view = CellGridView.new(:cell_width => 25, :cell_height => 35)
assert_cell_dimensions(25, 35)
end
def test_set_grid_view_position
assert_grid_position(0, 0)
set_grid_position(50, 75)
assert_grid_position(50, 75)
end
def test_set_grid_position_in_constructor
@grid_view = CellGridView.new(:x => 40, :y => 34)
assert_grid_position(40, 34)
end
def test_total_width_and_height
cell_grid = CellGrid.new(:rows => 3, :columns => 3)
@grid_view = CellGridView.new(:cell_grid => cell_grid, :cell_width => 20, :cell_height => 10)
assert_total_width_and_height(60, 30)
cell_grid.rows = 5
cell_grid.columns = 4
assert_total_width_and_height(80, 50)
end
def test_cell_colors
@grid_view = CellGridView.new(:color_alive => 0xffffff00, :color_dead => 0xff00ffff, :color_revived => 0xffff00ff)
assert_color_alive_dead_revived(0xffffff00, 0xff00ffff, 0xffff00ff)
set_color_alive_dead_revived(0xff0000ff, 0xffff0000, 0xff00ff00)
assert_color_alive_dead_revived(0xff0000ff, 0xffff0000, 0xff00ff00)
end
private
def set_cell_dimensions(cell_width, cell_height)
@grid_view.cell_width = cell_width
@grid_view.cell_height = cell_height
end
def set_grid_position(x, y)
@grid_view.x = x
@grid_view.y = y
end
def set_color_alive_dead_revived(color_alive, color_dead, color_revived)
@grid_view.color_alive = color_alive
@grid_view.color_dead = color_dead
@grid_view.color_revived = color_revived
end
def assert_cell_dimensions(cell_width, cell_height)
assert_equal(cell_width, @grid_view.cell_width)
assert_equal(cell_height, @grid_view.cell_height)
end
def assert_grid_position(x, y)
assert_equal(x, @grid_view.x)
assert_equal(y, @grid_view.y)
end
def assert_total_width_and_height(total_width, total_height)
assert_equal(total_width, @grid_view.total_width)
assert_equal(total_height, @grid_view.total_height)
end
def assert_color_alive_dead_revived(color_alive, color_dead, color_revived)
assert_equal(color_alive, @grid_view.color_alive)
assert_equal(color_dead, @grid_view.color_dead)
assert_equal(color_revived, @grid_view.color_revived)
end
end
|
module PPC
module Operation
attr_accessor :id
def initialize( params )
raise 'please specific a search engine' if params[:se].nil?
@se = params[:se]
@id = params[:id]
@auth = {
username: params[:username],
password: params[:password],
# 在qihu360的api中,apikey就是auth[:token]
token: params[:token],
target: params[:target]
}
# add support for qihu360
if @se == 'qihu'
raise "you are using qihu service, please enter api_key" if params[:api_key].nil?
raise "you are using qihu service, please enter api_secret" if params[:api_secret].nil?
@auth[:api_key] = params[:api_key]
@auth[:api_secret] = params[:api_secret]
@auth[:token] = qihu_refresh_token if params[:token].nil?
end
end
def qihu_refresh_token
cipher_aes = OpenSSL::Cipher::AES.new(128, :CBC)
cipher_aes.encrypt
cipher_aes.key = @auth[:api_secret][0,16]
cipher_aes.iv = @auth[:api_secret][16,16]
encrypted = (cipher_aes.update(Digest::MD5.hexdigest( @auth[:password])) + cipher_aes.final).unpack('H*').join
url = "https://api.e.360.cn/account/clientLogin"
response = HTTParty.post(url,
:body => {
:username => @auth[:username],
:passwd => encrypted[0,64]
},
:headers => {'apiKey' => @auth[:api_key] }
)
data = response.parsed_response
data["account_clientLogin_response"]["accessToken"]
end
def download( param = nil )
"""
download all objs of an account
"""
eval("::PPC::API::#{@se.capitalize}::Bulk").download( @auth, param )
end
def call(service)
eval "::PPC::API::#{@se.capitalize}::#{service.capitalize}"
end
def method_missing(method_name, *args, &block)
method = method_name.to_s
unit = self.class.to_s.downcase[/(account|plan|group|keyword|creative|sublink)/]
case method
when "info"
unit == "account" ? call( unit ).send( method, @auth ) : call( unit ).send( method, @auth, [@id].flatten )
when "get", "delete", "enable", "pause", "status", "quality"
call( unit ).send( method, @auth, [@id].flatten )
when "update"
call( unit ).send( method, @auth, [args[0].merge(id: @id)].flatten )
when "activate"
call( unit ).enable( @auth, [@id].flatten )
else
super
end
end
# +++++ Plan opeartion funcitons +++++ #
module Plan_operation
def method_missing(method_name, *args, &block)
if method_name.to_s[/_plan$/]
call( "plan" ).send(method_name.to_s[/^(get|add|update|delete|enable|pause)/], @auth, [args].flatten )
else
super
end
end
end
# +++++ Group opeartion funcitons +++++ #
module Group_operation
def method_missing(method_name, *args, &block)
if method_name.to_s[/_group$/]
call( "group" ).send(method_name.to_s[/^(get|add|update|delete|enable|pause)/], @auth, [args].flatten )
else
super
end
end
end
# +++++ Keyword opeartion funcitons +++++ #
module Keyword_operation
def method_missing(method_name, *args, &block)
if method_name.to_s[/_keyword$/]
call( "keyword" ).send(method_name.to_s[/^(get|add|update|delete|enable|pause)/], @auth, [args].flatten )
else
super
end
end
end
# +++++ Creative opeartion funcitons +++++ #
module Creative_operation
def method_missing(method_name, *args, &block)
if method_name.to_s[/_creative$/]
call( "creative" ).send(method_name.to_s[/^(get|add|update|delete|enable|pause)/], @auth, [args].flatten )
else
super
end
end
end
# +++++ Sublink opeartion funcitons +++++ #
module Sublink_operation
def method_missing(method_name, *args, &block)
if method_name.to_s[/_sublink$/]
call( "sublink" ).send(method_name.to_s[/^(get|add|update|delete|enable|pause)/], @auth, [args].flatten )
else
super
end
end
end
# +++++ Picture opeartion funcitons +++++ #
module Picture_operation
def method_missing(method_name, *args, &block)
if method_name.to_s[/_picture$/]
call( "picture" ).send(method_name.to_s[/^(add|delete)/], @auth, [args].flatten )
else
super
end
end
end
end # Opeartion
end # PPC
# requires are moved to the end of the file
# because if we load files before defining the
# module ::PPC::Operation. Errors of 'uninitialized constance'
# will occur
require 'ppc/operation/report'
require 'ppc/operation/account'
require 'ppc/operation/group'
require 'ppc/operation/plan'
require 'ppc/operation/keyword'
require 'ppc/operation/creative'
require 'ppc/operation/sublink'
|
require 'rails_helper'
describe Meaning do
describe "associations" do
it { should belong_to(:category) }
it { should have_many(:words) }
end
describe "validations" do
it { should validate_presence_of(:text) }
# it { should validate_uniqueness_of(:text) }
end
end
|
class Sigmoid
# class qui crée des function sigmoid (allant de 0 a 1 en passant par une zone de transition +ou- rapide) , la moyen (mean) centre la function et la porter (range) defini la gamme de valeur qui entreront dans la partie variable de la function. La variable de ponderation (weight) définit l'importance du résultat dans le score final.
attr_accessor :mean
attr_accessor :range
attr_accessor :weight
def initialize(mean=0,range=1,weight=0.1)
@mean=mean
@range=range
@weight=weight
end
def compute_for(var=0)
1.0+weight*(1.0/(1.0+Math.exp(-range*(var-mean)))-1)
end
end |
class Review < ActiveRecord::Base
validates :stars, presence: true
validates :author, presence: true
validates :body, presence: true
belongs_to :products
end
|
# -*- encoding: utf-8 -*-
$:.push('lib')
require "semillagen/version"
Gem::Specification.new do |s|
s.name = "semillagen"
s.version = SemillaGen::VERSION.dup
s.date = "2012-03-22"
s.summary = "Simple ActionScript project generation."
s.email = "support@semilla.com"
s.homepage = "http://github.com/vicro/SemillaGen/"
s.authors = ['Victor G. Rosales']
s.description = <<-EOF
SemillaGen let's you create (Actionscript3.0 based) projects and classes with ease.
SemillaGen generated projects or classes are customizable via templates.
The default templates setup the project for Continuous Integration using FlexUnit.
the default class template creates a class and a test case automatically.
usage:
To create a new project run:
$ semillagen project MyAwesomeProject
$ ls
MyAwesomeProject
To create a new class with test case:
$ cd MyAwesomeProject
$ semillagen class com.semilla.MillionDollarClass
You will see that semillagen created the following files:
src/com/semilla/MillionDollarClass.as
test-src/com/semilla/MillionDollarClassTest.as
The default template is ready for building as soon as created.
To build and test your project we use rake.
$ rake
Rake will build a debug and release versions of your project. It will also create a FlexUnit test swf and run the test.
You will see the results of the tests and also you will see some xml files under the [test-report] folder. These reports
are JUnit compatible.
You can use a CI tool like Jenkins to automatically build and test your project.
EOF
dependencies = [
# Examples:
# [:runtime, "rack", "~> 1.1"],
# [:development, "rspec", "~> 2.1"],
[:semilla, "semilla", "~> 0.0.7"],
[:rake, "rake", "~> 0.9.2"]
]
s.files = Dir['**/*']
s.test_files = Dir['test/**/*'] + Dir['spec/**/*']
s.executables = Dir['bin/*'].map { |f| File.basename(f) }
s.require_paths = ["lib"]
## Make sure you can build the gem on older versions of RubyGems too:
s.rubygems_version = "1.8.15"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.specification_version = 3 if s.respond_to? :specification_version
dependencies.each do |type, name, version|
if s.respond_to?("add_#{type}_dependency")
s.send("add_#{type}_dependency", name, version)
else
s.add_dependency(name, version)
end
end
end
|
module Reports
module Refreshable
# Refresh a materialized view.
#
# By default this will be done within a transaction, unless the `transaction` arg is set to false
def refresh(transaction: true)
return refresh_view unless transaction
ActiveRecord::Base.transaction do
refresh_view
end
end
private
def refresh_view
ActiveRecord::Base.connection.execute("SET LOCAL TIME ZONE '#{Period::REPORTING_TIME_ZONE}'")
Scenic.database.refresh_materialized_view(table_name, concurrently: refresh_concurrently?, cascade: false)
end
def refresh_concurrently?
ActiveModel::Type::Boolean.new.cast(ENV.fetch("REFRESH_MATVIEWS_CONCURRENTLY", true))
end
end
end
|
require 'spec_helper'
describe "Authentication" do
subject { page }
describe "With omniauth" do
before { visit root_path }
describe "sign up with valid credentials" do
let(:user) { FactoryGirl.build(:user) }
before do
configure_valid_mock_fb_auth(user)
end
it "should create a user" do
expect { click_link "Sign in with FB" }.to change(User, :count)
end
describe "and redirect back to user page" do
before { click_link "Sign in with FB" }
it { should have_content "Successfully signed in with facebook" }
it { should have_selector "h1", text: user.name }
describe "followed by setting up a password user should be able to login with login/password" do
before do
user = User.last
visit edit_user_path(user)
fill_user_info_form(user.name, user.email, 'example')
click_button "Save changes"
click_link "Sign out"
sign_in(user, 'example')
end
it { should have_selector('div.alert.alert-success', text: 'Successfully signed in') }
end
describe "not followed by setting up a password" do
before do
click_link "Sign out"
end
describe "user should not be able to login with login/password" do
before { sign_in user }
it { should have_selector('title', text: "Sign in") }
it { should have_selector('div.alert.alert-error', text: 'Invalid') }
end
end
describe "followed by sign out and sign in again" do
before do
click_link "Sign out"
end
it "should not create a user" do
expect { click_link "Sign in with FB" }.not_to change(User, :count)
end
describe "and redirect back to user page" do
before { click_link "Sign in with FB" }
it { should have_content "Successfully signed in with facebook" }
it { should have_selector "h1", text: user.name }
end
end
end
end
describe "sign with used already email to sign up" do
let(:user) { FactoryGirl.create(:user) }
before do
configure_valid_mock_fb_auth(user)
end
it "should not create a user" do
expect { click_link "Sign in with FB" }.not_to change(User, :count)
end
describe "and redirect back to root page" do
before { click_link "Sign in with FB" }
it { should have_content "Email your facebook has provided was already used to signup" }
it { should_not have_selector "h1", text: user.name }
end
end
describe "sign up with invalid credentials" do
let(:user) { FactoryGirl.build(:user) }
before do
configure_invalid_mock_fb_auth
end
it "should not create a user" do
expect { click_link "Sign in with FB" }.not_to change(User, :count)
end
describe "and redirect back to root page" do
before { click_link "Sign in with FB" }
it { should have_content "Error" }
it { should_not have_selector "h1", text: user.name }
end
end
end
end
|
require 'line_item'
describe LineItem do
context "containing 2 items named Flux Capacitor that cost $50 each" do
subject do
item = OpenStruct.new(name: "Flux Capacitor", price: 50, indication: :an_indication)
LineItem.new(2, item)
end
its(:quantity) { should == 2 }
its(:item_name) { should == "Flux Capacitor" }
its(:item_price) { should == 50 }
its(:total) { should == 100 }
end
context "with extra steps" do
subject do
item = OpenStruct.new(indication: :an_indication)
LineItem.new(1, item)
end
its(:item_indication) { should == :an_indication }
end
end
|
class CommentsController < ApplicationController
def create
@support = Support.find(params[:support_id])
@comment = current_user.comments.new(support_comment_params)
@comment.support_id = @support.id
@comment.save
redirect_back(fallback_location: root_path)
end
def destroy
@support = Support.find(params[:support_id])
@comment = current_user.comments.find_by(support_id: @support.id)
@comment.destroy
redirect_back(fallback_location: root_path)
end
private
def support_comment_params
params.require(:comment).permit(:body)
end
end
|
require 'rails_helper'
RSpec.describe GuildsController, type: :controller do
sign_in_user
let(:game) { create :game }
let(:guild) { create :guild, user: @user }
let(:another_user) { create :user }
describe 'POST #create' do
context 'guild with valid data' do
it 'save new guild for user' do
expect { post :create, params: { user_id: @user.id, guild: attributes_for(:guild).merge(game_id: game.id) } }
.to change(@user.guilds, :count).by(1)
end
it 'save only one guild for not premium user' do
guild
expect { post :create, params: { user_id: @user.id, guild: attributes_for(:guild).merge(game_id: game.id) } }
.to_not change(@user.guilds, :count)
end
it 'save more then one guild for premium user' do
@user.toggle! :premium
guild
expect { post :create, params: { user_id: @user.id, guild: attributes_for(:guild).merge(game_id: game.id) } }
.to change(@user.guilds, :count).by(1)
end
end
context 'guild with invalid data' do
it 'will not saved' do
expect { post :create, params: { user_id: @user.id, guild: attributes_for(:invalid_guild) } }
.to_not change(@user.guilds, :count)
end
end
end
describe 'PATCH #update' do
context 'user is owner' do
it 'changes guild attribute' do
patch :update, params: { user_id: @user.id, id: guild, guild: { title: 'Jar band' } }
guild.reload
expect(guild.title).to eq 'Jar band'
end
end
context 'user is not owner' do
let(:guild) { create :guild, user: another_user }
it 'cant change character attribute' do
patch :update, params: { user_id: @user.id, id: guild, guild: { title: 'Jar band' } }
guild.reload
expect(guild.title).to_not eq 'Jar band'
end
end
end
describe 'DELETE #destroy' do
context 'user owner' do
let!(:guild) { create :guild, user: @user }
it 'delete character' do
expect { delete :destroy, params: { user_id: @user.id, id: guild } }
.to change(Guild, :count).by(-1)
end
end
context 'not owner' do
let!(:guild) { create :guild, user: another_user }
it 'cant delete character' do
expect { delete :destroy, params: { user_id: @user.id, id: guild } }
.to_not change(Guild, :count)
end
end
end
end
|
class ChangeResponseFieldsToQuestions < ActiveRecord::Migration
def change
rename_table :response_fields, :questions
end
end
|
# encoding: utf-8
require 'spec_helper'
describe PostsController do
let(:post) { Fabricate(:post) }
let(:comments) do
5.times { post.comments << Fabricate(:comment) }
post.save
end
context "GET index" do
before(:each) { get :index }
it { assigns(:posts).should eq([post]) }
it { response.should render_template :index }
end
context "GET show" do
before(:each) { get :show, id: post.id }
it { response.should render_template :show }
it { assigns(:post).should eq(post) }
# FIXME: it { assigns(:comments).should eq([comments]) }
end
end
|
class User < ActiveRecord::Base
belongs_to :organization
has_many :assigned_tickets, class_name: 'Ticket', foreign_key: 'assignee_id'
has_many :tags, as: :source
def render_object
puts self.class.name
puts '----------------'
ApplicationHelper.print_object(self)
if organization
puts "Organization Name: #{organization.name}"
end
puts 'Tags'
puts '----------------'
tags.each do |tag|
ApplicationHelper.print_object(tag)
end
if !assigned_tickets.empty?
puts 'Assigned Tickets'
puts '----------------'
assigned_tickets.each do |ticket|
ApplicationHelper.print_object(ticket)
end
end
end
end |
class AddRequirementCountToRegions < ActiveRecord::Migration[5.0]
def change
add_column :regions, :requirements_count, :integer
end
end
|
require "spec_helper"
require "input_processor"
class InputProcessor
public :parse_day_in_week, :parse_user_type_and_dates, :dates_to_a
end
describe InputProcessor do
subject { InputProcessor.new }
let(:valid_input) { "Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed)" }
context "#parse" do
it "should return and hash with user_type of string and days of string array" do
subject.parse(valid_input).should == {
:user_type => "Regular",
:days => ["mon", "tues", "wed"]
}
end
it "should raise error with invalid value" do
input = "Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009wed)"
expect { subject.parse(input) }.to raise_error
end
end
context "parse_user_type_and_dates" do
it "shoud have right result" do
result = subject.parse_user_type_and_dates(valid_input)
result[:user_type].should == "Regular"
result[:dates].should == "16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed)"
end
it "should strip space" do
space_input = " Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed) "
result = subject.parse_user_type_and_dates space_input
result[:user_type].should == "Regular"
result[:dates].should == "16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed)"
end
it "should raise error with invalid input" do
invalid_input = "aba asdfsd"
expect { subject.parse_user_type_and_dates invalid_input }.to raise_error
end
end
context "dates_to_a" do
it "get array if not nill" do
subject.dates_to_a("16Mar2009(mon), 17Mar2009(tues)").should == ["16Mar2009(mon)", "17Mar2009(tues)"]
end
it "is nil if input is nil" do
subject.dates_to_a(nil).should be_nil
end
end
context "parse_day_in_week" do
valid_input = "16Mar2009(mon)"
invalid_input = "2123"
it "should return mon" do
subject.parse_day_in_week(valid_input).should == "mon"
end
it "should raise error with invalid input" do
expect { subject.parse_day_in_week(invalid_input) }.to raise_error
end
it "should raise error with invalid day in week" do
expect { subject.parse_day_in_week("16Mar2009(xxx)") }.to raise_error
end
end
end
|
require 'rails_helper'
RSpec.describe Indicator, type: :model do
before :each do
@user = create(:user)
@indicator_1 = create(:indicator, user_id: @user.id)
@indicator_2 = create(:indicator, name: 'Indicator two', user_id: @user.id)
@act = create(:act_meso, user_id: @user.id, indicators: [@indicator_1, @indicator_2])
@relation_1 = ActIndicatorRelation.find_by(indicator_id: @indicator_1.id, act_id: @act.id)
@relation_2 = ActIndicatorRelation.find_by(indicator_id: @indicator_2.id, act_id: @act.id)
end
it 'Create Indicator' do
expect(@indicator_1.name).to eq('Indicator one')
expect(@indicator_1.acts.first.name).to eq('Second one')
expect(@indicator_1.actions?).to eq(true)
end
it 'Order indicator by name' do
expect(Indicator.order(name: :asc)).to eq([@indicator_1, @indicator_2])
expect(Indicator.count).to eq(2)
end
it 'Indicator name validation' do
@indicator_reject = build(:indicator, name: '', user_id: @user.id)
@indicator_reject.valid?
expect {@indicator_reject.save!}.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Name can't be blank")
end
it 'Indicator with user' do
expect(@indicator_2.user.name).to eq('Pepe Moreno')
expect(@user.indicators.count).to eq(2)
end
it 'Deactivate activate indicator' do
@indicator_2.deactivate
expect(Indicator.count).to eq(2)
expect(Indicator.filter_inactives.count).to eq(1)
expect(@indicator_2.deactivated?).to be(true)
@indicator_2.activate
expect(@indicator_2.activated?).to be(true)
expect(Indicator.filter_actives.count).to be(2)
end
context 'Add indicators to acts' do
before :each do
@unit = create(:unit, user: @user)
@act_2 = create(:act_macro, user_id: @user.id)
@relation_3 = create(:act_indicator_relation, user_id: @user.id, indicator_id: @indicator_1.id, act_id: @act_2.id, unit_id: @unit.id)
end
it 'Get indicators with act relations' do
expect(@indicator_1.acts.count).to eq(2)
expect(@indicator_1.act_indicator_relations.count).to eq(2)
expect(@indicator_1.act_indicator_relations.last.start_date).not_to be_nil
expect(@indicator_1.act_indicator_relations.last.target_value).to eq(100.001)
expect(@indicator_1.act_indicator_relations.last.target_unit_symbol).to eq('€')
expect(@indicator_1.act_indicator_relations.last.target_unit_name).to eq('Euro')
end
end
context 'Indicator with categories' do
before :each do
@category_1 = create(:category, type: 'SocioCulturalDomain')
@indicator = create(:indicator, name: 'Indicator third', user_id: @user.id, categories: [@category_1])
@category_2 = create(:category, name: 'Category second', indicators: [@indicator])
end
it 'Get indicators with act relations' do
expect(@indicator.categories.count).to eq(2)
expect(@indicator.socio_cultural_domains.count).to eq(1)
expect(@indicator.other_domains.count).to eq(1)
end
end
context 'Add tags to indicator' do
before :each do
@category_1 = create(:category, type: 'SocioCulturalDomain')
@indicator = create(:indicator, name: 'Indicator third', user_id: @user.id, categories: [@category_1])
@indicator.tag_list.add('tag one', 'tag two')
end
it 'Get indicators with act relations' do
expect(@indicator.tag_list.count).to eq(2)
expect(@indicator.tag_list).to eq(['tag one', 'tag two'])
end
end
end
|
module SecureApi
class Encryptor
def initialize
@secret = SecureApi.encryption_secret
@len = ActiveSupport::MessageEncryptor.key_len
end
def encrypt(password)
salt = SecureRandom.hex(@len)
key = ActiveSupport::KeyGenerator.new(@secret).generate_key(salt, @len)
crypt = ActiveSupport::MessageEncryptor.new(key)
encrypted_data = crypt.encrypt_and_sign(password)
"#{salt}$$#{encrypted_data}"
end
def decrypt(password)
salt, encrypted_password = password.split "$$"
key = ActiveSupport::KeyGenerator.new(@secret).generate_key(salt, @len)
crypt = ActiveSupport::MessageEncryptor.new(key)
crypt.decrypt_and_verify(encrypted_password)
end
def compare(password, psw)
password == decrypt(psw)
end
end
end
|
require 'spec_helper'
describe Spaceship::TunesClient do
describe '#login' do
it 'raises an exception if authentication failed' do
expect do
subject.login('bad-username', 'bad-password')
end.to raise_exception(Spaceship::Client::InvalidUserCredentialsError, "Invalid username and password combination. Used 'bad-username' as the username.")
end
it "raises a different exception if the server doesn't respond with any cookies" do
stub_request(:post, "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/4.0.1.13.3.13.3.2.1.1.3.1.1").
with(body: {"theAccountName" => "user", "theAccountPW" => "password"},
headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/x-www-form-urlencoded', 'User-Agent' => 'spaceship'}).
to_return(status: 200, body: 'random Body', headers: {} )
# This response doesn't set any header information and is therefore useless
expect do
subject.login('user', 'password')
end.to raise_exception(Spaceship::TunesClient::ITunesConnectError, "random Body\n")
end
it "raises a different exception if the server responds with cookies but they can't be parsed" do
stub_request(:post, "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/4.0.1.13.3.13.3.2.1.1.3.1.1").
with(body: {"theAccountName" => "user", "theAccountPW" => "password"},
headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/x-www-form-urlencoded', 'User-Agent' => 'spaceship'}).
to_return(status: 200, body: 'random Body', headers: {'Set-Cookie' => "myacinfo=asdf; That's a big mess;"} )
# This response doesn't set any header information and is therefore useless
expect do
subject.login('user', 'password')
end.to raise_exception(Spaceship::TunesClient::ITunesConnectError, "random Body\nmyacinfo=asdf; That's a big mess;")
end
end
describe "#send_login_request" do
it "sets the correct cookies when getting the response" do
expect(subject.cookie).to eq(nil)
subject.send_login_request('spaceship@krausefx.com', 'so_secret')
expect(subject.cookie).to eq(itc_cookie)
end
end
describe "Logged in" do
subject { Spaceship::Tunes.client }
let(:username) { 'spaceship@krausefx.com' }
let(:password) { 'so_secret' }
before do
Spaceship::Tunes.login(username, password)
end
it 'returns the session cookie' do
expect(subject.cookie).to eq(itc_cookie)
end
it "#hostname" do
expect(subject.class.hostname).to eq('https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/')
end
it "#login_url" do
expect(subject.login_url).to eq("https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/4.0.1.13.3.13.3.2.1.1.3.1.1")
end
describe "#handle_itc_response" do
it "raises an exception if something goes wrong" do
data = JSON.parse(itc_read_fixture_file('update_app_version_failed.json'))['data']
expect do
subject.handle_itc_response(data)
end.to raise_error "The App Name you entered has already been used. The App Name you entered has already been used. You must provide an address line. There are errors on the page and for 2 of your localizations."
end
it "does nothing if everything works as expected and returns the original data" do
data = JSON.parse(itc_read_fixture_file('update_app_version_success.json'))['data']
expect(subject.handle_itc_response(data)).to eq(data)
end
end
end
end
|
# frozen_string_literal: true
# @private
# An internal join model not to be used directly
class ClaimRespondent < ApplicationRecord
belongs_to :claim
belongs_to :respondent
default_scope { order(created_at: :asc) }
end
|
# frozen_string_literal: true
module Arclight
##
# An extendable mixin intended to share terminology behavior between
# the CustomDocument and CustomComponent classes
module SharedTerminologyBehavior
def add_unitid(t, prefix)
t.unitid(path: prefix + 'did/unitid', index_as: %i[displayable searchable])
end
def add_extent(t, prefix)
t.extent(path: prefix + 'did/physdesc/extent', index_as: %i[displayable searchable])
end
# date indexing
def add_dates(t, prefix)
t.normal_unit_dates(path: prefix + 'did/unitdate/@normal')
t.unitdate_bulk(path: prefix + 'did/unitdate[@type=\'bulk\']', index_as: %i[displayable])
t.unitdate_inclusive(path: prefix + 'did/unitdate[@type=\'inclusive\']', index_as: %i[displayable])
t.unitdate_other(path: prefix + 'did/unitdate[not(@type)]', index_as: %i[displayable])
t.unitdate(path: prefix + 'did/unitdate', index_as: %i[displayable])
end
def add_searchable_notes(t, prefix) # rubocop: disable Metrics/MethodLength
# various searchable notes
%i[
accessrestrict
accruals
acqinfo
altformavail
appraisal
arrangement
bibliography
bioghist
custodhist
fileplan
note
odd
originalsloc
otherfindaid
phystech
prefercite
processinfo
relatedmaterial
scopecontent
separatedmaterial
userestrict
].each do |k|
# many of the notes support various markup so we want everything but the heading
t.send(k, path: "#{prefix}#{k}/*[local-name()!=\"head\"]", index_as: %i[displayable searchable])
end
# various searchable notes in the did
%i[
abstract
materialspec
physloc
].each do |k|
t.send(k, path: "#{prefix}did/#{k}", index_as: %i[displayable searchable])
end
t.did_note(path: "#{prefix}did/note", index_as: %i[displayable searchable]) # conflicts with top-level note
end
end
end
|
Pod::Spec.new do |s|
s.name = 'VPImageCropper'
s.version = '0.1'
s.platform = :ios
s.source = { :git => 'https://github.com/kevinnguy/VPImageCropper.git' }
s.source_files = 'VPImageCropper/*.{h,m}'
s.requires_arc = true
end
|
# -*- coding: utf-8 -*-
require 'gtk2'
require 'cairo'
class Gtk::TimeLine < Gtk::VBox
end
require 'mui/gtk_crud'
require 'mui/cairo_cell_renderer_message'
require 'mui/gtk_timeline_utils'
require 'mui/gtk_postbox'
require 'mui/cairo_inner_tl'
require 'mui/gtk_dark_matter_prification'
# タイムラインに表示するメッセージの数
UserConfig[:timeline_max] ||= 200
=begin rdoc
タイムラインのGtkウィジェット。
=end
class Gtk::TimeLine
include Gtk::TimeLineUtils
include Gtk::TimelineDarkMatterPurification
attr_reader :tl
# 現在アクティブなTLで選択されているすべてのMessageオブジェクトを返す
def self.get_active_mumbles
if Gtk::TimeLine::InnerTL.current_tl
InnerTL.current_tl.get_active_messages
else
[] end end
def initialize(imaginary=nil)
super()
@tl = InnerTL.new
@tl.imaginary = imaginary
closeup(postbox).pack_start(init_tl)
end
def init_tl
@tl.postbox = postbox
scrollbar = Gtk::VScrollbar.new(@tl.vadjustment)
@tl.model.set_sort_column_id(2, order = Gtk::SORT_DESCENDING)
@tl.model.set_sort_func(2){ |a, b|
order = a[2] <=> b[2]
if order == 0
a[0] <=> b[0]
else
order
end
}
@tl.set_size_request(100, 100)
@tl.get_column(0).sizing = Gtk::TreeViewColumn::FIXED
@tl.ssc(:expose_event){
emit_expose_miraclepainter
false }
init_remover
@shell = Gtk::HBox.new.pack_start(@tl).closeup(scrollbar) end
# TLに含まれているMessageを順番に走査する。最新のものから順番に。
def each(index=1)
@tl.model.each{ |model,path,iter|
yield(iter[index]) } end
def include?(message)
@tl.include? message end
# TLのログを全て消去する
def clear
@tl.clear
self end
# 新しいものから順番にpackしていく。
def block_add_all(messages)
removes, appends = *messages.partition{ |m| m[:rule] == :destroy }
remove_if_exists_all(removes)
retweets, appends = *appends.partition{ |m| m[:retweet] }
add_retweets(retweets)
appends.sort_by{ |m| -get_order(m) }.deach(&method(:block_add))
end
# リツイートを追加する。 _messages_ には Message の配列を指定し、それらはretweetでなければならない
def add_retweets(messages)
messages.reject{|message|
include?(message.retweet_source)
}.deach do |message|
block_add(message.retweet_source) end end
# Messageオブジェクト _message_ が更新されたときに呼ばれる
def modified(message)
path = @tl.get_path_by_message(message)
if(path)
@tl.update!(message, 2, get_order(message)) end
self end
# _message_ が新たに _user_ のお気に入りに追加された時に呼ばれる
def favorite(user, message)
self
end
# _message_ が _user_ のお気に入りから削除された時に呼ばれる
def unfavorite(user, message)
self
end
# つぶやきが削除されたときに呼ばれる
def remove_if_exists_all(messages)
messages.each{ |message|
path = @tl.get_path_by_message(message)
tl_model_remove(@tl.model.get_iter(path)) if path } end
# TL上のつぶやきの数を返す
def size
@tl.model.to_enum(:each).inject(0){ |i, r| i + 1 } end
# このタイムラインをアクティブにする
def active
get_ancestor(Gtk::Window).set_focus(@tl)
end
# このTLが既に削除されているなら真
def destroyed?
@tl.destroyed? or @tl.model.destroyed? end
def method_missing(method_name, *args, &proc)
@tl.__send__(method_name, *args, &proc) end
protected
# _message_ をTLに追加する
def block_add(message)
if not @tl.destroyed?
if(!any?{ |m| m == message })
case
when message[:rule] == :destroy
remove_if_exists_all([message])
when message.retweet?
add_retweets([message])
else
_add(message) end end end
self end
# Gtk::TreeIterについて繰り返す
def each_iter
@tl.model.each{ |model,path,iter|
yield(iter) } end
private
def _add(message)
scroll_to_zero_lator! if @tl.realized? and @tl.vadjustment.value == 0.0
miracle_painter = @tl.cell_renderer_message.create_miracle_painter(message)
iter = @tl.model.append
iter[Gtk::TimeLine::InnerTL::URI] = message.uri.to_s
iter[Gtk::TimeLine::InnerTL::MESSAGE] = message
iter[Gtk::TimeLine::InnerTL::ORDER] = get_order(message)
iter[Gtk::TimeLine::InnerTL::MIRACLE_PAINTER] = miracle_painter
@tl.set_iter_dict(iter)
@remover_queue.push(message)
self
end
# TLのMessageの数が上限を超えたときに削除するためのキューの初期化
# オーバーしてもすぐには削除せず、1秒間更新がなければ削除するようになっている。
def init_remover
@remover_queue = TimeLimitedQueue.new(1024, 1){ |messages|
Delayer.new{
if not destroyed?
remove_count = size - (timeline_max || UserConfig[:timeline_max])
if remove_count > 0
to_enum(:each_iter).to_a[-remove_count, remove_count].each{ |iter|
tl_model_remove(iter) } end end } } end
if not method_defined? :tl_model_remove
# _iter_ を削除する。このメソッドを通さないと、Gdk::MiraclePainterに
# destroyイベントが発生しない。
# ==== Args
# [iter] 削除するレコード(Gtk::TreeIter)
def tl_model_remove(iter)
Plugin.call(:gui_timeline_message_removed, @tl.imaginary, iter[Gtk::TimeLine::InnerTL::MESSAGE])
iter[InnerTL::MIRACLE_PAINTER].destroy
@tl.model.remove(iter) end end
# スクロールなどの理由で新しくTLに現れたMiraclePainterにシグナルを送る
def emit_expose_miraclepainter
@exposing_miraclepainter ||= []
if @tl.visible_range
current, last = @tl.visible_range.map{ |path| @tl.model.get_iter(path) }
messages = Set.new
while current[0].to_i >= last[0].to_i
messages << current[1]
break if not current.next! end
(messages - @exposing_miraclepainter).each do |exposed|
@tl.cell_renderer_message.miracle_painter(exposed).signal_emit(:expose_event) if exposed.is_a? Diva::Model
end
@exposing_miraclepainter = messages end end
def postbox
@postbox ||= Gtk::VBox.new end
Delayer.new{
plugin = Plugin::create(:core)
plugin.add_event(:message_modified){ |message|
Gtk::TimeLine.timelines.each{ |tl|
tl.modified(message) if not(tl.destroyed?) and tl.include?(message) } }
plugin.add_event(:destroyed){ |messages|
Gtk::TimeLine.timelines.each{ |tl|
tl.remove_if_exists_all(messages) if not(tl.destroyed?) } }
}
Gtk::RC.parse_string <<EOS
style "timelinestyle"
{
GtkTreeView::vertical-separator = 0
GtkTreeView::horizontal-separator = 0
}
widget "*.timeline" style "timelinestyle"
EOS
end
|
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
admin = User.create!(:name => "Administrator",
:email => "admin@amazonmustdie.com",
:password => "password2",
:password_confirmation => "password2")
admin.toggle!(:admin)
User.create!(:name => "Owais Ahmed",
:email => "owais@hotmail.com",
:password => "password",
:password_confirmation => "password")
99.times do |n|
name = "John Doe"
email = "example-#{n+1}@hotmail.com"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end |
module Fog
module Compute
class ProfitBricks
class Real
# Add an existing user to a group.
#
# ==== Parameters
# * group_id<~String> - Required, The ID of the specific group you want to add a user to.
# * user_id<~String> - Required, The ID of the specific user to add to the group.
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the created resource.
# * href<~String> - URL to the object's representation (absolute path).
# * metadata<~Hash> - Hash containing metadata for the user.
# * etag<~String> - ETag of the user.
# * creationDate<~String> - A time and date stamp indicating when the user was created.
# * lastLogin<~String> - A time and date stamp indicating when the user last logged in.
# * properties<~Hash> - Hash containing the user's properties.
# * firstname<~String> - The first name of the user.
# * lastname<~String> - The last name of the user.
# * email<~String> - The e-mail address of the user.
# * administrator<~Boolean> - Indicates if the user has administrative rights.
# * forceSecAuth<~Boolean> - Indicates if secure (two-factor) authentication was enabled for the user.
# * secAuthActive<~Boolean> - Indicates if secure (two-factor) authentication is enabled for the user.
# * entities<~Hash> - Hash containing resources the user owns, and groups the user is a member of.
# * owns<~Hash> - Hash containing resources the user owns.
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the created resource.
# * href<~String> - URL to the object's representation (absolute path).
# * items<~Array>
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the created resource.
# * href<~String> - URL to the object's representation (absolute path).
# * groups<~Hash> - Hash containing groups the user is a member of.
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the created resource.
# * href<~String> - URL to the object's representation (absolute path).
# * items<~Array>
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the created resource.
# * href<~String> - URL to the object's representation (absolute path).
#
# {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v4/#add-user-to-group]
def add_user_to_group(group_id, user_id)
usr = {
:id => user_id
}
request(
:expects => [202],
:method => 'POST',
:path => "/um/groups/#{group_id}/users",
:body => Fog::JSON.encode(usr)
)
end
end
class Mock
def add_user_to_group(group_id, user_id)
response = Excon::Response.new
response.status = 202
if group = data[:groups]['items'].find do |grp|
grp["id"] == group_id
end
else
raise Excon::Error::HTTPStatus, "The requested resource could not be found"
end
if user = data[:users]['items'].find do |usr|
usr["id"] == user_id
end
else
raise Excon::Error::HTTPStatus, "The requested resource could not be found"
end
group['users'] << user
user['groups'] << group
response.body = user
response
end
end
end
end
end
|
class AddTypeToWaitTime < ActiveRecord::Migration
def change
add_column :wait_times, :type, :string
end
end
|
class Company < ActiveRecord::Base
has_many :applications
has_many :applicants, through: :applications
end
|
require 'rails_helper'
RSpec.describe PublicationsController, :type => :controller do
let(:valid_attributes) {
attributes_for(:publication)
}
let(:invalid_attributes) {
attributes_for(:invalid_publication)
}
context 'unauthenticated' do
it 'redirects to sign in page when unauthenticated' do
get :index
expect(response).to redirect_to(new_user_session_path)
end
end
context 'authenticated' do
before(:each) do
sign_in
end
describe 'GET index' do
it 'assigns all publications as @publications' do
publication = create(:publication)
get :index
expect(assigns(:publications)).to eq([publication])
end
end
describe 'GET show' do
it 'assigns the requested publication as @publication' do
publication = create(:publication)
get :show, id: publication
expect(assigns(:publication)).to eq(publication)
end
end
describe 'GET new' do
it 'assigns a new publication as @publication' do
get :new
expect(assigns(:publication)).to be_a_new(Publication)
end
end
describe 'GET edit' do
it 'assigns the requested publication as @publication' do
publication = create(:publication)
get :edit, id: publication
expect(assigns(:publication)).to eq(publication)
end
end
describe 'POST create' do
describe 'with valid params' do
it 'creates a new Publication' do
expect {
post :create, publication: valid_attributes
}.to change(Publication, :count).by(1)
end
it 'creates a new Publication with the valid attributes' do
post :create, publication: valid_attributes
new_publication = assigns(:publication).reload
expect(new_publication.name).to eq valid_attributes[:name]
expect(new_publication.author).to eq valid_attributes[:author]
expect(new_publication.edition).to eq valid_attributes[:edition]
end
it 'redirects to the created publication' do
post :create, publication: valid_attributes
expect(response).to redirect_to(Publication.last)
end
end
describe 'with invalid params' do
it 'does not save the publication in the database' do
expect {
post :create, publication: invalid_attributes
}.to_not change(Publication, :count)
end
it 'assigns a newly created but unsaved publication as @publication' do
post :create, publication: invalid_attributes
expect(assigns(:publication)).to be_a_new(Publication)
end
it 're-renders the new template' do
post :create, publication: invalid_attributes
expect(response).to render_template('new')
end
end
end
describe 'PATCH update' do
let(:existing_publication) do
create(:publication, name: 'My pub')
end
describe 'with valid params' do
let(:new_publication_name) { Faker::Lorem.characters(20)}
let(:new_publication) do
build(:publication, name: new_publication_name)
end
let(:updated_publication_params) do
attributes_for(:publication, name: 'New Name', author: 'Jimmo', edition: '9786')
end
it 'updates the requested publication' do
patch :update, id: existing_publication, publication: updated_publication_params
existing_publication.reload
expect(existing_publication.name).to eq 'New Name'
expect(existing_publication.author).to eq 'Jimmo'
expect(existing_publication.edition).to eq '9786'
end
it 'assigns the requested publication as @publication' do
patch :update, id: existing_publication, publication: updated_publication_params
expect(assigns(:publication)).to eq(existing_publication)
end
it 'redirects to the publication' do
patch :update, id: existing_publication, publication: updated_publication_params
expect(response).to redirect_to(existing_publication)
end
end
describe 'with invalid params' do
let(:updated_publication_params) do
attributes_for(:publication, name: nil)
end
it 'does not update the requested publication' do
patch :update, id: existing_publication, publication: updated_publication_params
existing_publication.reload
expect(existing_publication.name).to eq 'My pub'
end
it 'assigns the publication as @publication' do
patch :update, id: existing_publication, publication: updated_publication_params
expect(assigns(:publication)).to eq(existing_publication)
end
it 're-renders the edit template' do
patch :update, id: existing_publication, publication: updated_publication_params
expect(response).to render_template('edit')
end
end
end
describe 'DELETE destroy' do
it 'destroys the requested publication' do
publication = create(:publication)
expect {
delete :destroy, id: publication
}.to change(Publication, :count).by(-1)
end
it 'redirects to the publications list' do
publication = create(:publication)
delete :destroy, id: publication
expect(response).to redirect_to(publications_url)
end
end
end
end
|
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 5}
validates :body, presence: true
def previous_post
self.class.where("id < ?", id).order(created_at: :desc).first
end
def next_post
self.class.where("id > ?", id).order(created_at: :desc).last
end
end
|
class TodoItemsController < ApplicationController
before_action :find_todo_list
def index
@todo_list = TodoList.find(params[:todo_list_id])
end
def new
@todo_item = @todo_list.todo_items.new
end
def create
@todo_item = @todo_list_todo_items.new(todo_item_params)
if todo_item.save
flash[:success] = "Todo Item was added to Todo List."
redirect_to todo_list_todo_items_path
else
flash[:error] = "There was an error creating Todo Item."
redirect_to @todo_list
end
end
def complete
@todo_item = @todo_list.todo_items.find(params[:id])
@todo_item.update_attribute(:completed_at, Time.now)
redirect_to todo_list_todo_items_path, notice: "Todo item marked as complete."
end
def destroy
@todo_item = @todo_list.todo_items.find(params[:id])
if @todo_item.destroy
flash[:success] = "Todo list was deleted."
else
flash[:error] = "Todo list could not be deleted."
end
redirect_to todo_list_todo_items_path
end
def edit
@todo_item = @todo_list_todo_item.find(params[:id])
end
private
def find_todo_list
@todo_list = current_user.todo_list.find(params[:todo_list_id])
end
def todo_item_params
params[:todo_item].permit(:content)
end
end
|
class Field < ApplicationRecord
has_many :projects
has_many :courses
has_many :users,
validates :name, presence: true
belongs_to :curator, class_name: 'User', foreign_key: 'curator_id'
end
|
require 'test_helper'
class PrepCoursesControllerTest < ActionController::TestCase
setup do
@prep_course = prep_courses(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:prep_courses)
end
test "should get new" do
get :new
assert_response :success
end
test "should create prep_course" do
assert_difference('PrepCourse.count') do
post :create, prep_course: { description: @prep_course.description, text: @prep_course.text, title: @prep_course.title }
end
assert_redirected_to prep_course_path(assigns(:prep_course))
end
test "should show prep_course" do
get :show, id: @prep_course
assert_response :success
end
test "should get edit" do
get :edit, id: @prep_course
assert_response :success
end
test "should update prep_course" do
patch :update, id: @prep_course, prep_course: { description: @prep_course.description, text: @prep_course.text, title: @prep_course.title }
assert_redirected_to prep_course_path(assigns(:prep_course))
end
test "should destroy prep_course" do
assert_difference('PrepCourse.count', -1) do
delete :destroy, id: @prep_course
end
assert_redirected_to prep_courses_path
end
end
|
require 'rails_helper'
RSpec.describe Location, type: :model do
context "#adjacent locations" do
before(:each) do
location = Location.new(x: 2, y: 5)
@expected_locations = [Location.new(x: 1, y: 6), Location.new(x: 2, y: 6),
Location.new(x: 3, y: 6), Location.new(x: 1, y: 5),
Location.new(x: 3, y: 5), Location.new(x: 1, y: 4),
Location.new(x: 2, y: 4), Location.new(x: 3, y: 4)]
@adjacent_locations = location.adjacent
end
it "should have 8 adjacent locations" do
expect(@adjacent_locations.count).to eq(8)
end
it "should have the correct adjacent locations" do
expect(@adjacent_locations).to match_array(@expected_locations)
end
end
context "#equality" do
let(:location) {Location.new(x: 2, y: 3)}
it "should be equal to itself" do
expect(location).to eq(location)
end
it "should be equal to location with same coordinates" do
expect(location).to eq(Location.new(x: 2, y: 3))
end
it "should not be equal to a nil object" do
expect(location).to_not eq(nil)
end
it "should not be equal to object of other class" do
expect(location).to_not eq(Class.new)
end
it "should not be equal if x and y coordinates are swapped" do
expect(location).to_not eq(Location.new(x: 3, y: 2))
end
it "should not be equal if y coordinate is different" do
expect(location).to_not eq(Location.new(x: 2, y: 2))
end
it "should not be equal if x coordinate is different" do
expect(location).to_not eq(Location.new(x: 3, y: 3))
end
end
describe '#validation' do
context '#with valid attributes' do
it 'should be valid for numerical values' do
location = Location.new(x: 2, y: 3)
expect(location).to be_valid
end
end
context '#with invalid attributes' do
it 'should not be valid for string values' do
location = Location.new(x: "two", y: "three")
expect(location).to_not be_valid
end
it 'should generate an error message' do
location = Location.new(x: nil, y: 3)
location.valid?
expect(location.errors[:x]).to include("can't be blank")
end
it 'should generate an error message' do
location = Location.new(x: 2, y: nil)
location.valid?
expect(location.errors[:y]).to include("can't be blank")
end
it 'should generate an error message' do
location_1 = Location.create(x: 2, y: 3)
location_2 = Location.new(x: 2, y: 3)
location_2.valid?
expect(location_2.errors[:x]).to include("location already exists")
end
end
end
end
|
require 'minitest/autorun'
require './lib/fast_config'
FastConfig.config_dir = "test/test_config"
require_relative "sample_dir.rb"
class FastConfigDirSettingTest < MiniTest::Unit::TestCase
# def setup
# end
#
# def teardown
# end
def test_settings_read_from_config
assert_equal 13, SampleDir.settings[:alpha]
end
def test_settings_readable_in_class
assert_equal 14, SampleDir.setting_plus_1(:alpha)
end
def test_settings_createable
assert_nil SampleDir.settings[:omega]
SampleDir.settings[:omega] = "Little Red Riding Hood"
assert_equal "Little Red Riding Hood", SampleDir.settings[:omega]
end
def test_settings_changeable
assert_equal "http://www.sample.com", SampleDir.settings[:gamma]
SampleDir.settings[:gamma] = 100
assert_equal 100, SampleDir.settings[:gamma]
end
end
|
#
# Be sure to run `pod lib lint SemaphoreCompletion.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "SemaphoreCompletion"
s.version = "1.0"
s.summary = "SemaphoreCompletion"
s.description = <<-DESC
SYMLSemaphoreCompletion performs a completion block when a group of tasks have finished. It's conceptually similar to XCTest's expectations.
DESC
s.homepage = "https://github.com/inquisitivesoft/SemaphoreCompletion"
s.license = 'MIT'
s.author = { "Harry Jordan" => "harry@inquisitivesoftware.com" }
s.source = { :git => "https://github.com/inquisitivesoft/SemaphoreCompletion.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/inquisitivesoft'
s.platform = :ios, '7.0'
s.requires_arc = true
s.source_files = 'Classes/*.{m,h}'
s.public_header_files = 'Classes/**/*.h'
end
|
require 'faker'
require 'json'
require 'csv'
require 'yaml'
require 'date'
require "synthetic/data/version"
require 'digest'
module Synthetic
class Error < StandardError; end
def self.bulk(folder)
Dir.entries(folder).select {|f|
if not File.directory? "#{folder}/#{f}" and not [".",".."].include? f then
puts "Process #{f}"
self.generate("#{folder}/#{f}")
end
}
end
def self.generate(rules_file)
Faker::Config.locale = 'en-CA'
definition = YAML.load_file(rules_file)
if self.check(rules_file, definition) == false
return
end
headers = []
for field in definition['fields'].keys do
headers.push(field)
end
options = {
:write_headers => true,
:headers => headers.join(',')
}
start = Time.now.to_i
output = "outputs/" + definition['output']
CSV.open(output, "wb", options) do |csv|
for i in 1..definition['records'] do
row = []
for f in definition['fields'].keys do
field = definition['fields'][f]
type = field['type'].split '.'
args = {}
for key in field.keys do
if not ['type','unique'].include? key then
if field[key].is_a? String and field[key].start_with? '@' then
args[:"#{key}"] = row[headers.index(field[key][1..-1])]
else
args[:"#{key}"] = field[key]
end
end
end
obj = Faker.const_get(type[0])
if field['unique'] then
obj = obj.public_send('unique')
end
if field.keys.length == 1 then
row.push(obj.public_send(type[1]))
else
row.push(obj.public_send(type[1], args))
end
end
csv.puts(row)
if i % 1000 == 0 then
elapsed = Time.now.to_i - start
puts("Completed #{i} records. Total elapsed #{elapsed} seconds.")
end
end
end
puts "CSV file written (#{output})"
self.register(rules_file, definition)
end
def self.register(filename, obj)
hash = Digest::SHA256.hexdigest obj.to_yaml
if File.exists? 'outputs/data-version.txt'
data_hash = JSON.parse(File.read('outputs/data-version.txt'))
else
data_hash = {}
end
data_hash[filename] = hash
File.open('outputs/data-version.txt',"w") do |f|
f.write(JSON.pretty_generate(data_hash))
end
end
def self.check(filename, obj)
hash = Digest::SHA256.hexdigest obj.to_yaml
if File.exists? 'outputs/data-version.txt'
data_hash = JSON.parse(File.read('outputs/data-version.txt'))
if data_hash.key? filename and hash == data_hash[filename]
puts("#{filename} - Already generated")
return false
end
end
return true
end
end
|
# frozen_string_literal: true
class Contribution < ApplicationRecord
belongs_to :house
validates :house_id, presence: true
validates :date_paid, presence: true
monetize :amount_cents, numericality: true
end
|
# Copyright © 2011-2019 MUSC Foundation for Research Development~
# All rights reserved.~
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~
# disclaimer in the documentation and/or other materials provided with the distribution.~
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~
# derived from this software without specific prior written permission.~
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~
require 'rails_helper'
RSpec.describe Dashboard::ProtocolsController do
describe 'POST #create' do
context 'success' do
before( :each ) do
@logged_in_user = build_stubbed( :identity )
protocol = build( :study_with_blank_dates )
project_role_attributes = { "0" => { identity_id: @logged_in_user.id, role: 'primary-pi', project_rights: 'approve' } }
@protocol_attributes = protocol.attributes.merge( { project_roles_attributes: project_role_attributes } )
allow( StudyTypeQuestionGroup ).to receive( :active_id ).
and_return( "active group id" )
allow_any_instance_of(Protocol).to receive(:rmid_server_status).and_return(false)
log_in_dashboard_identity( obj: @logged_in_user )
end
it 'creates a new protocol record' do
expect{ post :create, params: {
protocol: @protocol_attributes
}, xhr: true }.
to change{ Protocol.count }.by( 1 )
end
it 'creates a new service request record' do
expect{ post :create, params: {
protocol: @protocol_attributes
}, xhr: true }.
to change{ ServiceRequest.count }.by( 1 )
end
it 'creates a new project role record' do
expect{ post :create, params: {
protocol: @protocol_attributes
}, xhr: true }.
to change{ ProjectRole.count }.by( 1 )
end
it 'creates an extra project role record if the current user is not assigned to the protocol' do
@protocol_attributes[:project_roles_attributes]["0"][:identity_id] = build_stubbed(:identity).id
expect{ post :create, params: {
protocol: @protocol_attributes
}, xhr: true }.
to change{ ProjectRole.count }.by( 2 )
end
it 'receives the correct flash message' do
post :create, params: { protocol: @protocol_attributes }, xhr: true
expect(flash[:success]).to eq(I18n.t('protocols.created', protocol_type: @protocol_attributes['type']))
end
end
context 'unsuccessful' do
before( :each ) do
@logged_in_user = build_stubbed( :identity )
@protocol = build( :study_with_blank_dates )
allow( StudyTypeQuestionGroup ).to receive( :active_id ).
and_return( "active group id" )
allow_any_instance_of(Protocol).to receive(:rmid_server_status).and_return(false)
log_in_dashboard_identity( obj: @logged_in_user )
end
it 'gives the correct error message' do
post :create, params: { protocol: @protocol.attributes }, xhr: true
expect(assigns(:errors)).to eq(assigns(:protocol).errors)
end
it 'does not create a new protocol record' do
expect{ post :create, params: {
protocol: @protocol.attributes
}, xhr: true }.
not_to change{ Protocol.count }
end
it 'does not create a new service request record' do
expect{ post :create, params: {
protocol: @protocol.attributes
}, xhr: true }.
not_to change{ ServiceRequest.count }
end
it 'does not create a new project role record' do
expect{ post :create, params: {
protocol: @protocol.attributes
}, xhr: true }.
not_to change{ ProjectRole.count }
end
end
end
end |
class Hash
def keys_of(*arguments)
map {|key, val| arguments.include?(val) ? key : nil }.compact
end
end
|
class Album < ActiveRecord::Base
has_attached_file :image, default_url: "missing.jpg"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :title, :creator_id, :year, presence: false
belongs_to :creator
end
|
class User < ApplicationRecord
include Gravtastic
gravtastic
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :name, presence: true, length: { maximum: 20 }
has_many :posts
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :friendships
has_many :received_friendships, -> { where status: 'pending' }, class_name: 'Friendship', foreign_key: 'friend_id'
has_many :pending_friends, through: :received_friendships, source: :user
has_many :sent_friendships, -> { where status: 'pending' }, class_name: 'Friendship', foreign_key: 'user_id'
has_many :requested_friends, through: :sent_friendships, source: :friend
has_many :confirmed_friendships, -> { where status: 'confirmed' }, class_name: 'Friendship'
has_many :friends, through: :confirmed_friendships
def send_friendship_request(user_id)
friend = Friendship.new(user_id: id, friend_id: user_id)
friend.save
end
def friends_and_own_posts
Post.where(user: (friends.to_a << self))
# This will produce SQL query with IN. Something like: select * from posts where user_id IN (1,45,874,43);
end
end
|
class CreateEmployeeSlots < ActiveRecord::Migration
def change
create_table :employee_slots do |t|
t.integer :employee_id
t.integer :slot_id
t.timestamps
end
add_index :employee_slots, :employee_id
add_index :employee_slots, :slot_id
end
end
|
require "rails_helper"
RSpec.describe AppointmentNotification::Worker, type: :job do
describe "#perform" do
before do
Flipper.enable(:notifications)
allow(Statsd.instance).to receive(:increment).with(anything)
end
def mock_successful_twilio_delivery
twilio_client = double("TwilioClientDouble")
response_double = double("TwilioResponse")
allow(response_double).to receive(:status).and_return("queued")
allow(response_double).to receive(:sid).and_return("1234")
allow(Twilio::REST::Client).to receive(:new).and_return(twilio_client)
allow(twilio_client).to receive_message_chain("messages.create").and_return(response_double)
end
it "only sends 'scheduled' notifications" do
mock_successful_twilio_delivery
pending_notification = create(:notification, status: "pending")
cancelled_notification = create(:notification, status: "cancelled")
expect(Statsd.instance).to receive(:increment).with("notifications.skipped.not_scheduled")
described_class.perform_async(pending_notification.id)
described_class.perform_async(cancelled_notification.id)
described_class.drain
expect(pending_notification.reload.status).to eq("pending")
expect(cancelled_notification.reload.status).to eq("cancelled")
end
it "logs but creates nothing when notifications and experiment flags are disabled" do
Flipper.disable(:notifications)
Flipper.disable(:experiment)
notification = create(:notification, status: :scheduled)
expect(Statsd.instance).to receive(:increment).with("notifications.skipped.feature_disabled")
expect {
described_class.perform_async(notification.id)
described_class.drain
}.not_to change { Communication.count }
end
it "raises an error if appointment notification is not found" do
expect {
described_class.perform_async("does-not-exist")
described_class.drain
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
|
class AddVideosCountToTutorials < ActiveRecord::Migration
def change
add_column :tutorials, :videos_count, :integer
end
end
|
class CreateParts < ActiveRecord::Migration
def change
create_table :parts do |t|
t.string :name
t.datetime :in_date
t.decimal :in_qty, :precision => 8, :scale => 1
t.string :spec
t.integer :input_by_id
t.decimal :stock_qty, :precision => 8, :scale => 1
t.string :manufacturer
t.text :note
t.string :storage_location
t.string :inspection
t.timestamps
end
end
end
|
begin
require 'jslint/tasks'
JSLint.config_path = "config/initializers/jslint.yml"
rescue LoadError
task :jslint do
puts "appears your environment is not properly set up. jslint is currently set up only to run in dev environments. please run ./script/bundle to right your dev environment."
end
end
|
# frozen_string_literal: true
class Chronometer
class Event
attr_reader :cls, :method, :name, :category, :event_type, :context
def initialize(cls: nil, method: nil, name: nil, category: nil, event_type: nil, context: nil)
@cls = cls
@method = method
@name = name
@category = category
@event_type = event_type
@context = context
end
end
private_constant :Event
end
|
class TweetsController < ApplicationController
before_action :authenticate_user!, only: [:favorite, :create]
def index
@tweets = Tweet
.includes(:user)
.page(params[:page])
.per(10)
.order(created_at: :desc)
end
def create
tweet = current_user.tweets.create(tweet_params)
redirect_to timeline_path, notice: 'Tweeted your tweet!'
end
def favorite
@tweet = Tweet.find(params[:id])
current_user.toggle_favorite(@tweet)
render layout: false
end
private
def tweet_params
params.require(:tweet).permit(:body)
end
end
|
class LikesController < ApplicationController
before_action :set_topic
before_action :set_bookmark
def create
@like = current_user.likes.build(bookmark_id: @bookmark.id)
authorize @like
respond_to do |format|
if @like.save
format.html { redirect_to [@bookmark.topic, @bookmark], notice: 'Bookmark has been liked' }
format.js
else
format.html { redirect_to [@bookmark.topic, @bookmark], error: 'Error unliking bookmark' }
format.js
end
end
end
def destroy
@like = current_user.likes.find_by(bookmark_id: @bookmark.id)
authorize @like
respond_to do |format|
if @like.destroy
format.html { redirect_to [@bookmark.topic, @bookmark], notice: 'Bookmark has been unliked' }
format.js
else
format.html { redirect_to [@bookmark.topic, @bookmark], error: 'Error unliking bookmark' }
format.js
end
end
end
private
def set_topic
@topic = Topic.friendly.find(params[:topic_id])
end
def set_bookmark
@bookmark = @topic.bookmarks.find(params[:bookmark_id])
end
end
|
module Devise
# autoload :Oauth, 'devise/oauth'
mattr_accessor :oauth1_providers
@@oauth1_providers = []
mattr_reader :oauth1_configs
@@oauth1_configs = ActiveSupport::OrderedHash.new
mattr_reader :oauth1_helpers
@@oauth1_helpers = Set.new
def self.oauth1(provider, *args)
@@helpers << DeviseOauth1able::Controllers::UrlHelpers
@@oauth1_helpers << DeviseOauth1able::InternalHelpers
@@oauth1_providers << provider
@@oauth1_providers.uniq!
@@oauth1_helpers.each { |h| h.define_oauth1_helpers(provider) }
@@oauth1_configs[provider] = DeviseOauth1able::Config.new(*args)
end
end
Devise.add_module :oauth1able, :controller => :oauth1, :model => 'devise_oauth1able/model', :route => :oauth1
require 'devise_oauth1able/rails'
require 'devise_oauth1able/model'
require 'devise_oauth1able/routes'
require 'devise_oauth1able/config'
require 'devise_oauth1able/internal_helpers'
require 'devise_oauth1able/controllers/url_helpers'
|
require 'spec_helper'
describe "Places" do
it "if one is returned by the API, it is shown on the page" do
BeermappingApi.stub(:places_in).with("kumpula").and_return(
[ Place.new(:id => 1, :name => "Oljenkorsi") ]
)
visit places_path
fill_in('city', with: 'kumpula')
click_button "Search"
expect(page).to have_content "Oljenkorsi"
end
it "if there are two returned by the API, both are shown on the page" do
BeermappingApi.stub(:places_in).with("malminkartano").and_return(
[ Place.new(:id => 1, :name => "Red Lion"), Place.new(:id => 2, :name => "Perä baari") ]
)
visit places_path
fill_in('city', with: 'malminkartano')
click_button "Search"
expect(page).to have_content "Red Lion"
expect(page).to have_content "Perä baari"
end
it "if none are returned by the API, it is shown on page" do
BeermappingApi.stub(:places_in).with("vantaa").and_return(
[]
)
visit places_path
fill_in('city', with: 'vantaa')
click_button "Search"
expect(page).to have_content "No locations in vantaa"
end
end
|
class PurchaseOrdersController < ApplicationController
before_action :authenticate_user!
def index
if params[:status]
@purchase_orders = PurchaseOrder.where(status: params[:status])
else
@purchase_orders = PurchaseOrder.all
end
end
def show
@purchase_order = PurchaseOrder.find(params[:id])
end
def update
@purchase_order = PurchaseOrder.find(params[:id])
respond_to do |format|
if @purchase_order.update_attributes(purchase_params.merge(user_id: current_user.id))
format.html { redirect_to @purchase_order}
else
format.html { render action: "edit" }
end
end
end
private
def purchase_params
params.require(:purchase_order).permit(:user_id, :total_price, :status, :open_at,
:closed_at, :canceled_at, :transport_at,
:created_at, :updated_at,
purchase_order_items_attributes:
[:product_id, :amount, :sub_total_price,
:purchase_order_id, :_destroy, :id])
end
end
|
##### Page
And(/^they are on the Lost Stolen page dt$/) do
visit(CardReplacementPage)
on(CardReplacementPage).wait_for_ajax 50
on(CardReplacementPage).wait_for_page_to_load_no_faq
end
Then(/^the page title will include '(.*)' dt$/) do |title|
if not @browser.h1(:id=>"pageTitle").text.include? title
fail('Titledoes not match')
end
end
And(/^customer navigates to "(.*?)" page dt.$/) do |text |
# @browser.url.should include text
@browser.windows.last.url == text
end
##### Drawers
And(/^the "(.*?)" drawer is open dt$/) do |title|
on(CardReplacementPage).wait_until do
puts @browser.div(:class=>"step active").div(:class=>"heading").text
puts title
@browser.div(:class=>"step active").div(:class=>"heading").text.include? title
end
if not @browser.div(:class=>"step active").div(:class=>"heading").text.include? title
fail('Drawer should be open, but is not.')
end
end
Then(/^the "(.*?)" drawer is closed dt$/) do |title|
if @browser.div(:class=>"step active").div(:class=>"heading").div(:class=>"pending").h2(:class=>"pending-text").text.include? title
fail('Drawer should be close, but is not.')
end
end
And(/^the open drawer header is numbered "(.*?)" dt$/) do |number|
if not @browser.div(:class=>"step active").span(:class=>"num").text == number
fail('Drawer number does not match')
end
end
And(/^the "(.*?)" button is not visible dt$/) do |title|
@browser.buttons(:text=>title).each do |button|
if(button.visible?)
fail('Button is visible, but should not be.')
end
end
end
Then(/^the "(.*?)" button is visible and enabled dt$/) do |buttonText|
on(CardReplacementPage).wait_until do
@browser.div(:class=>"step active").button(:text=>buttonText).visible?
end
if not @browser.div(:class=>"step active").button(:text=>buttonText).visible?
fail('Button is not visible, but should be.')
end
end
And(/^the "(.*?)" button is clicked dt$/) do |buttonText|
@browser.execute_script("window.scrollBy(0,600)")
on(CardReplacementPage).wait_until do
@browser.div(:class=>"step active").button(:text=>buttonText).visible?
end
@browser.div(:class=>"step active").button(:text=>buttonText).click
on(CardReplacementPage).wait_for_page_to_load_no_faq
sleep 8
end
Then (/^drawer "(.*?)" is renamed to "(.*?)" dt$/) do |number,text|
on(CardReplacementPage).wait_until do
@browser.div(:class=>"step comp", :index=> number.to_i - 1).exists? and @browser.div(:class=>"step comp", :index=> number.to_i - 1).text.include? text
end
if not @browser.div(:class=>"step comp", :index=> number.to_i - 1).text.include? text
fail('Drawer title incorrectly named')
end
end
And(/^the customer click on edit link dt$/) do
puts @browser.a(:id=>"whatHappenedDrawerEdit")
@browser.a(:id=>"whatHappenedDrawerEdit").click
end
And(/^the customer click "Edit" link on drawer "(.*?)" dt$/) do |number|
# @browser.div(:class=>"edit",:index=> number.to_i - 1).click
puts browser_type_set = ENV['browser']
if ((browser_type_set.to_s.include? "chrome") || (browser_type_set.to_s.include? "ie"))
@browser.div(:class => "edit", :index => number.to_i - 1).click
end
if (browser_type_set.to_s.include? "firefox")
if (number == '1')
@browser.a(:id => 'whatHappenedDrawerEdit').fire_event 'onclick'
end
if (number == '2')
@browser.a(:id => 'chooseYourCardEdit').fire_event 'onclick'
end
end
end
And(/^the customer mouses over the services menu item dt$/) do
# @browser.li(:id=>"Services").hover
puts browser_type_set = ENV['browser']
if ((browser_type_set.to_s.include? "chrome") || (browser_type_set.to_s.include? "ie"))
@browser.li(:id=>"Services").hover
end
if (browser_type_set.to_s.include? "firefox")
@browser.li(:id=>"Services").fire_event 'onmouseover'
end
end
And(/^the customer clicks the Lost Stolen submenu item dt$/) do
on(CardReplacementPage).wait_until do
@browser.li(:id=>"my_services_lost_stolen_replacement_card").visible?
end
@browser.li(:id=>"my_services_lost_stolen_replacement_card").a(:id=>"my_services_lost_stolen_replacement_card_link").click
puts "Clicking"
end
|
class Post < ApplicationRecord
belongs_to :category
belongs_to :user
acts_as_taggable
validates :title, presence: true
validates :content, presence: true
paginates_per 20
scope :index_all, -> {
select(:id, :title, :updated_at, :user_id, :category_id)
.order(updated_at: :desc)
.includes(:user, :category)
}
end
|
class CreateBuilds < ActiveRecord::Migration
def change
create_table :builds do |t|
t.string :teamcity_id
t.integer :number
t.boolean :running, :default => false
t.string :percentageComplete
t.string :status
t.integer :build_type_id
t.string :branchName
t.boolean :defaultBranch, :default => false
t.string :startDate
t.string :href
t.string :webUrl
t.timestamps
end
end
end
|
class Delivery < ActiveRecord::Base
include CrossAssociatedModel
include CertificateVerification
belongs_to :message
belongs_to_resource :organization
flagstamp :delivered
flagstamp :confirmed
validate :verified_organization_certificate_on_confirmation
before_create :set_organization_title
after_create :deliver
named_scope :queued, :conditions => {:confirmed_at => nil}
cache_and_delegate :title, :to => :organization, :prefix => true, :allow_nil => true
def verified_organization_certificate_on_confirmation
verified_organization_certificate? if confirmed?
end
def url
organization.delivery_url
end
def https?
organization.https?
end
def deliver
Delayed::Job.enqueue Jobs::MessageDeliveryJob.new(id)
end
def to_xml options = {}
options[:indent] ||= 2
xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
xml.instruct! unless options[:skip_instruct]
xml.delivery do
xml.tag! :id, id
xml.tag! :organization_id, organization_id
message.to_xml :builder => xml, :skip_instruct => true
end
end
private
def set_organization_title
write_attribute :organization_title, organization.title if organization
end
end
|
require 'spec_helper'
describe Album do
before do
@album = Album.new(title: "Hurray")
end
subject { @album }
it { should be_valid }
# shoulda relations
it { should belong_to(:user)}
it { should have_one(:main_photo).class_name('Photo')}
it { should have_many(:photos)}
it { should have_many(:videos)}
# relations
it { should respond_to(:user)}
it { should respond_to(:main_photo)}
it { should respond_to(:photos)}
it { should respond_to(:videos)}
# attributes
it { should respond_to(:title)}
it { should respond_to(:like_count)}
describe "empty title" do
before { @album.title = " "}
it { should_not be_valid }
end
# FACTORY (:album)
describe "Factory" do
let(:fake_album) { FactoryGirl.create(:album) }
subject { fake_album }
it { should be_valid }
end
end
|
class AddIndexToOperation < ActiveRecord::Migration[5.2]
def change
add_index :operations, :user_id
add_index :operations, :book_id
end
end
|
class AddShiftTypeToShifts < ActiveRecord::Migration
def change
add_column :shifts, :shift_type, :string
end
end
|
Given /^I am (not?) at the home page$/ do |word|
visit root_path
if word.present?
click_link 'about'
current_path.should_not == '/'
else
current_path.should == '/'
end
end
When /^I visit the home page$/ do
visit '/'
end
When(/^I observe the products field$/) do
within(:css, '#product-container')
@products = find(:css, '.product-title').collect { |title| title.value }
end
Then(/^I should see (new?) products displayed$/) do |word|
within(:css, '#product-container')
if word.present?
@products.should_not =~ find(:css, '.product-title').collect { |title| title.value }
else
page.should have_content('#product-container')
end
end
|
require './src/tokenizer/scope'
require './src/tokenizer/errors'
RSpec.describe Tokenizer::Scope, 'variables and function scopes' do
before :example do
@current_scope = Tokenizer::Scope.new
end
describe '#variable?' do
it 'can recognize declared variables' do
@current_scope.add_variable 'ホゲ'
expect(@current_scope.variable?('ホゲ')).to be_truthy
end
it 'can recognize variables from parent scopes' do
@current_scope.add_variable 'ホゲ'
child_scope = Tokenizer::Scope.new @current_scope
expect(child_scope.variable?('ホゲ')).to be_truthy
end
end
describe '#function?' do
it 'can recognize defined functions' do
@current_scope.add_function 'ほげる'
expect(@current_scope.function?('ほげる')).to be_truthy
end
it 'can recognize defined functions by their conjugations' do
@current_scope.add_function 'ほげる'
expect(@current_scope.function?('ほげて')).to be_truthy
end
it 'can recognize defined functions regardless of parameter order' do
parameters = [
{ name: 'a', particle: 'から' },
{ name: 'a', particle: 'と' },
{ name: 'a', particle: 'に' },
{ name: 'a', particle: 'へ' },
{ name: 'a', particle: 'まで' },
{ name: 'a', particle: 'で' },
{ name: 'a', particle: 'を' },
]
@current_scope.add_function 'ほげる', parameters
expect(@current_scope.function?('ほげて', parameters.reverse)).to be_truthy
end
it 'can recognize functions defined in parent scopes' do
@current_scope.add_function 'ほげる'
child_scope = Tokenizer::Scope.new @current_scope
expect(child_scope.function?('ほげて')).to be_truthy
end
end
describe '#add_function' do
it 'can shadow functions in delcared parent scopes' do
@current_scope.add_function 'ほげる'
child_scope = Tokenizer::Scope.new @current_scope
expect { child_scope.add_function 'ほげる' } .to_not raise_error
end
it 'raises an error when a duplicate function exists' do
@current_scope.add_function 'ほげる'
expect { @current_scope.add_function 'ほげる' } .to raise_error Tokenizer::Errors::FunctionDefAmbiguousConjugation
end
it 'raises an error when a function with a duplicate conjugation exists' do
@current_scope.add_function 'かう'
expect { @current_scope.add_function 'かる' } .to raise_error Tokenizer::Errors::FunctionDefAmbiguousConjugation
end
it 'can override duplicate conjugations of previously declared functions' do
@current_scope.add_function 'かう'
expect { @current_scope.add_function 'かる', [], force?: true } .to_not raise_error
end
end
describe '#remove_function' do
it 'can remove functions and their conjugations' do
@current_scope.add_function 'ふがる'
expect(@current_scope.function?('ふがる')).to be_truthy
expect(@current_scope.function?('ふがって')).to be_truthy
expect(@current_scope.function?('ふがった')).to be_truthy
@current_scope.remove_function 'ふがる'
expect(@current_scope.function?('ふがる')).to be_falsy
expect(@current_scope.function?('ふがって')).to be_falsy
expect(@current_scope.function?('ふがった')).to be_falsy
end
it 'will not remove functions with different signatures' do
@current_scope.add_function 'ほげる', [{ particle: 'を' }]
@current_scope.add_function 'ほげる', [{ particle: 'で' }]
expect(@current_scope.function?('ほげる', [{ particle: 'を' }])).to be_truthy
expect(@current_scope.function?('ほげる', [{ particle: 'で' }])).to be_truthy
@current_scope.remove_function 'ほげる', [{ particle: 'を' }]
expect(@current_scope.function?('ほげる', [{ particle: 'を' }])).to be_falsy
expect(@current_scope.function?('ほげる', [{ particle: 'で' }])).to be_truthy
end
it 'will not remove functions with ambiguous conjugations' do
@current_scope.add_function 'かう'
@current_scope.add_function 'かる', [], force?: true
expect(@current_scope.function?('かう')).to be_truthy
expect(@current_scope.function?('かる')).to be_truthy
expect(@current_scope.function?('かって')).to be_truthy
expect(@current_scope.function?('かった')).to be_truthy
@current_scope.remove_function 'かう'
expect(@current_scope.function?('かう')).to be_falsy
expect(@current_scope.function?('かる')).to be_truthy
expect(@current_scope.function?('かって')).to be_truthy
expect(@current_scope.function?('かった')).to be_truthy
end
end
end
|
# frozen_string_literal: true
# Immutable balance of user's account
class UserBalance < ActiveRecord::Base
belongs_to :user
belongs_to :payer, class_name: 'User'
validates :user, presence: true
validates :payer, presence: true
register_currency :pln
monetize :balance_cents
scope :newest_for, lambda { |payer_id|
where(payer_id: payer_id).order('created_at desc').first
}
def self.balances_for(user)
payers_ids(user).map do |payer_id|
user.user_balances.newest_for(payer_id)
end
end
def self.payers_ids(user)
user.user_balances.select('payer_id').uniq.map(&:payer_id)
end
def self.debts_to(user)
debtors_ids(user).map do |debtor_id|
debtor = User.find(debtor_id)
debtor.user_balances.newest_for(user)
end
end
def self.debtors_ids(user)
user.balances_as_payer.select('user_id').uniq.map(&:user_id)
end
end
|
#!/usr/bin/ruby
class Rectangle
def initialize(length=1, breadth=1)
@length = length
@breadth = breadth
end
def perimeter
2 * (@length + @breadth)
end
def area
@length * @breadth
end
def self.introduce
"I am a rectangle"
end
end
class Square < Rectangle
def initialize(side=1)
super(side, side)
end
end
r1 = Rectangle.new(2, 3)
puts r1.perimeter
puts r1.area
r2 = Rectangle.new(1, 5)
puts r2.area
puts r1.area
puts Rectangle.introduce
r3 = Rectangle.new
puts r3.perimeter
r4 = Square.new(5)
puts r4.perimeter
|
class ReviewProcessController < ApplicationController
skip_load_and_authorize_resource
before_action :set_and_authorize_review
def create
if ReviewProcess.new(@review).start!
flash[:success] = _('The review has been started.')
else
flash[:failure] = _('The review could not be started.')
end
redirect_to review_path(@review)
end
def update
if ReviewProcess.new(@review).confirm!
redirect_to review_path(@review, download_report: true)
else
flash[:failure] = _('The review could not be confirmed.')
redirect_to review_path(@review)
end
end
private
def set_and_authorize_review
@review = Review.find(params[:id])
authorize! :manage, @review
end
end
|
module PaginationResponder
# Receives a relation and sets the pagination scope in the collection
# instance variable. For example, in PostsController it would
# set the @posts variable with Post.all.paginate(params[:page]).
def to_html
if get? && resource.is_a?(ActiveRecord::Relation)
if controller.respond_to? :paginated_scope
controller.paginated_scope(resource)
else
paginated = resource.page(controller.params[:page])
controller.instance_variable_set("@#{controller.controller_name}", paginated)
end
end
super
end
end
|
class Api::V1::Items::ItemsMerchantsController < ApplicationController
def show
item = Item.find(params["item_id"])
@merchant = item.merchant
end
end
|
class Owner < ActiveRecord::Base
belongs_to :user
belongs_to :blog
has_many :comments, as :commentable
end
|
$LOAD_PATH.unshift(File.expand_path('../', __FILE__))
require 'spec_helper'
require 'netlink'
class TestMessage < Netlink::Message
end
describe Netlink::Message do
describe '#initialize' do
class InitializerTestMessage < Netlink::Message
attribute :test_attr, Netlink::Attribute::String, :type => 2
end
it 'should allow setting both headers and attributes' do
attr = "test"
hdr = Netlink::NlMsgHdr.new
msg = InitializerTestMessage.new(:nl_header => hdr, :test_attr => attr)
msg.nl_header.should == hdr
msg.test_attr.should == attr
end
end
describe '#encode' do
it 'should pad the message on a 32 bit boundary' do
msg = Netlink::Message.new
msg.payload = "HI"
msg.encode.length.should == Netlink::Util.align(msg.nl_header.num_bytes + msg.payload.length)
end
it 'should not update the header length of unencoded message' do
msg = Netlink::Message.new
msg.payload = "HI"
old_len = msg.nl_header.len
msg.encode
msg.nl_header.len.should == old_len
end
end
describe '#decode' do
it 'should decode encoded messages' do
orig_msg = Netlink::Message.new
orig_msg.payload = "HI"
encoded = orig_msg.encode
decoded = Netlink::Message.decode(encoded)
decoded.payload.should == Netlink::Util.pad(orig_msg.payload)
end
it 'should raise IOError if supplied with partial data' do
# Less than a header's worth
short_msg = "A"
expect do
Netlink::Message.decode(short_msg)
end.to raise_error(IOError)
# Partial payload
msg = Netlink::Message.new
msg.payload = "HELLO THERE"
encoded = msg.encode.slice(0, msg.nl_header.len - 4)
expect do
Netlink::Message.decode(encoded)
end.to raise_error(IOError)
end
end
describe '.header' do
it 'should define accessors for declared headers' do
TestMessage.header :test, Netlink::NlMsgHdr
testmsg = TestMessage.new
testmsg.test.class.should == Netlink::NlMsgHdr
testmsg.test = 1
testmsg.test.should == 1
end
it 'should raise an error if one attempts to redeclare an existing header' do
expect do
HeaderTest.header :test, Netlink::NlMsgHdr
end.to raise_error
end
end
describe '.attribute' do
it 'should define accessors for declared attributes' do
TestMessage.attribute :attr, Netlink::Attribute::String, :type => 1
testmsg = TestMessage.new
testmsg.attr.should be_nil
testmsg.attr = "HI"
testmsg.attr.should == "HI"
end
end
describe 'when subclassed' do
class TestMessageParent < Netlink::Message
header :parent_header, Netlink::NlMsgHdr
attribute :parent_attribute, Netlink::Attribute::String, :type => 2
end
class TestMessageChild < TestMessageParent
header :child_header, Netlink::NlMsgHdr
attribute :child_attribute, Netlink::Attribute::String, :type => 3
end
it 'should inherit any previously defined headers or attributes' do
TestMessageChild.headers.should == [:nl_header, :parent_header, :child_header]
msg = TestMessageChild.new
msg.nl_header.class.should == Netlink::NlMsgHdr
msg.parent_header.class.should == Netlink::NlMsgHdr
TestMessageChild.attributes.should == [:parent_attribute, :child_attribute]
end
it 'should not add any headers or attributes to its parent' do
TestMessageParent.headers.should == [:nl_header, :parent_header]
TestMessageParent.attributes.should == [:parent_attribute]
end
it 'should include headers_size from its parent' do
TestMessageChild.headers_size.should == TestMessageParent.headers_size + Netlink::NlMsgHdr.new.num_bytes
end
end
end
|
class PlayersController < ApplicationController
def index
@team = Team.get!(params[:team_id])
@players = @team.players(:limit => 5)
render :json => @players
end
end
|
class Stripe < ActiveRecord::Base
belongs_to :belt
has_many :moves
validates_presence_of :belt, :title
end
|
class Award < ApplicationRecord
validates :name, :company_name, :company_website, :address, :ticket_quantity, :email, :message, :phone_number, :presence => true
end |
class ClientsController < ApplicationController
load_and_authorize_resource
def index
@clients = @clients.page(params[:page]).per(30)
end
def new
end
def create
@client.save
respond_with @client, location: -> { ok_url_or_default clients_path }
end
def edit
end
def update
@client.update(client_params)
respond_with @client, location: -> { ok_url_or_default clients_path }
end
def destroy
@client.destroy
respond_with @client, location: -> { ok_url_or_default clients_path }
end
protected
def client_params
params[:client].permit(:access_token, :hostname, :disabled) if params[:client]
end
end
|
source_root = File.expand_path(File.dirname(__FILE__) + "/..")
$LOAD_PATH.unshift("#{source_root}/lib")
$LOAD_PATH.unshift("#{source_root}/test")
Thread.abort_on_exception = true
require 'spec_helper'
require 'crash_watch/utils'
require 'crash_watch/gdb_controller'
require 'shellwords'
describe CrashWatch::GdbController do
before :each do
@gdb = CrashWatch::GdbController.new
end
after :each do
@gdb.close
if @process
Process.kill('KILL', @process.pid)
@process.close
end
end
def run_script_and_wait(code, snapshot_callback = nil, &block)
@process = IO.popen(%Q{exec ruby -e #{Shellwords.escape code}}, 'w')
@gdb.attach(@process.pid)
thread = Thread.new do
sleep 0.1
if block
block.call
end
@process.write("\n")
end
exit_info = @gdb.wait_until_exit(&snapshot_callback)
thread.join
exit_info
end
describe "#execute" do
it "executes the desired command and returns its output" do
expect(@gdb.execute("echo hello world")).to eq("hello world\n")
end
end
describe "#attach" do
before :each do
@process = IO.popen("sleep 9999", "w")
end
it "returns true if attaching worked" do
expect(@gdb.attach(@process.pid)).to be_truthy
end
it "returns false if the PID doesn't exist" do
Process.kill('KILL', @process.pid)
sleep 0.25
expect(@gdb.attach(@process.pid)).to be_falsey
end
end
describe "#wait_until_exit" do
it "returns the expected information if the process exited normally" do
exit_info = run_script_and_wait('STDIN.readline')
expect(exit_info.exit_code).to eq(0)
expect(exit_info).not_to be_signaled
end
it "returns the expected information if the process exited with a non-zero exit code" do
exit_info = run_script_and_wait('STDIN.readline; exit 3')
expect(exit_info.exit_code).to eq(3)
expect(exit_info).not_to be_signaled
expect(exit_info.backtrace).not_to be_nil
expect(exit_info.backtrace).not_to be_empty
end
it "returns the expected information if the process exited because of a signal" do
exit_info = run_script_and_wait(
'STDIN.readline;' +
'require "rubygems";' +
'require "ffi";' +
'module MyLib;' +
'extend FFI::Library;' +
'ffi_lib "c";' +
'attach_function :abort, [], :void;' +
'end;' +
'MyLib.abort')
expect(exit_info).to be_signaled
expect(exit_info.backtrace).to match(/abort/)
end
it "ignores non-fatal signals" do
exit_info = run_script_and_wait('trap("INT") { }; STDIN.readline; exit 2') do
Process.kill('INT', @process.pid)
end
expect(exit_info.exit_code).to eq(2)
expect(exit_info).not_to be_signaled
expect(exit_info.backtrace).not_to be_nil
expect(exit_info.backtrace).not_to be_empty
end
it "returns information of the signal that aborted the process, not information of ignored signals" do
exit_info = run_script_and_wait(
'trap("INT") { };' +
'STDIN.readline;' +
'require "rubygems";' +
'require "ffi";' +
'module MyLib;' +
'extend FFI::Library;' +
'ffi_lib "c";' +
'attach_function :abort, [], :void;' +
'end;' +
'MyLib.abort'
) do
Process.kill('INT', @process.pid)
end
expect(exit_info).to be_signaled
expect(exit_info.backtrace).to match(/abort/)
end
end
end if CrashWatch::Utils.gdb_installed?
|
# == Schema Information
#
# Table name: shops
#
# id :integer not null, primary key
# name :string
# branches_count :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
#
class Shop < ActiveRecord::Base
has_many :branches
validates :name, presence: true, uniqueness: true
end
|
module BancSabadell
module Operations
module All
module ClassMethods
def all(options = {})
keyword_options = options.delete(scope_attribute)
req = BancSabadell.request(:post, generate_url_keyword(keyword_options), options)
res = req.perform
while req.more_pages?
sleep(BancSabadell::API_THROTTLE_LIMIT)
new_req = BancSabadell.request(:post, generate_url_keyword(keyword_options), options.merge(page: 'next'))
new_res = new_req.perform
res['data'].concat(new_res['data'])
res['head'] = new_res['head']
end
results_from res
end
private
def results_from(response)
(response['data'] || []).map do |row|
treated_row = row.map do |key, value|
{ attribute_translations[key.to_sym].to_s => value }
end.inject(:merge)
new(treated_row)
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
end
end
|
class Calender
DAYS_LIST = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def initialize(year, month)
@year = year
@month = month
end
def getDays()
return DAYS_LIST[@month - 1]
end
def getStartWday()
return Date.new(@year, @month, 1).wday
end
def week()
days = getDays
wday = getStartWday
week = []
days.times do |day|
week.push({
'day' => day + 1,
'wday' => wday
})
if wday < 6
wday += 1
elsif
wday = 0
end
end
return week
end
end
|
require "test_helper"
describe Toastmasters::Mediators::Participations do
include TestHelpers
before do
@meeting = Meeting.create(date: Date.today)
@member = Member.create(first_name: "Edward", last_name: "Daniels", email: "edward.daniels@gmail.com")
end
describe ".all" do
it "lists all participations" do
Participation.create(meeting: @meeting, role: "Speaker", member: @member)
Participation.create(meeting: @meeting, role: "Evaluator", member: @member)
participations = Mediators::Participations.all(meeting_id: @meeting.id)
assert_equal ["Speaker", "Evaluator"], participations.map(&:role)
end
end
describe ".create" do
it "creates the record" do
participation = Mediators::Participations.create(@meeting.id, {role: "Speaker", member_id: @member.id})
refute participation.new?
end
it "raises validation errors" do
assert_raises(Error::ValidationFailed) { Mediators::Participations.create(nil, {}) }
end
end
describe ".update" do
it "updates the record" do
participation = Participation.create(meeting: @meeting, role: "Speaker", member: @member)
Mediators::Participations.update(participation.id, role: "Evaluator")
assert_equal "Evaluator", participation.reload.role
end
it "raises validation errors" do
participation = Participation.create(meeting: @meeting, role: "Speaker", member: @member)
assert_raises(Error::ValidationFailed) { Mediators::Participations.update(participation.id, {meeting_id: nil}) }
end
end
describe ".delete" do
it "destroys the record" do
participation = Participation.create(meeting: @meeting, role: "Speaker", member: @member)
participation = Mediators::Participations.delete(participation.id)
refute participation.exists?
end
end
end
|
require 'rails_helper'
RSpec.describe Item, type: :model do
describe '#create' do
before do
@item = FactoryBot.build(:item)
@item.image = fixture_file_upload('sample.png')
end
describe '商品出品登録' do
context '商品出品登録がうまくいくとき' do
it 'goods,details,category_id,status_id,shipping_fee_burden_id,shipping_area_id, \
days_to_ship_id,price,user_idが存在すれば登録できる' do
expect(@item).to be_valid
end
it 'imageが存在すれば登録できる' do
expect(@item.image).to be_valid
end
end
context '商品出品登録がうまくいかないとき' do
it 'imageが空だと登録できない' do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include('出品画像を入力してください')
end
it 'goodsが空だと登録できない' do
@item.goods = ''
@item.valid?
expect(@item.errors.full_messages).to include('商品名を入力してください')
end
it 'detailsが空だと登録できない' do
@item.details = ''
@item.valid?
expect(@item.errors.full_messages).to include('商品の説明を入力してください')
end
it 'category_idが空だと登録できない' do
@item.category_id = ''
@item.valid?
expect(@item.errors.full_messages).to include('カテゴリーを入力してください')
end
it 'status_idが空だと登録できない' do
@item.status_id = ''
@item.valid?
expect(@item.errors.full_messages).to include('商品の状態を入力してください')
end
it 'shipping_fee_burden_idが空だと登録できない' do
@item.shipping_fee_burden_id = ''
@item.valid?
expect(@item.errors.full_messages).to include('配送料の負担を入力してください')
end
it 'shipping_area_idが空だと登録できない' do
@item.shipping_area_id = ''
@item.valid?
expect(@item.errors.full_messages).to include('発送元の地域を入力してください')
end
it 'days_to_ship_idが空だと登録できない' do
@item.days_to_ship_id = ''
@item.valid?
expect(@item.errors.full_messages).to include('発送までの日数を入力してください')
end
it 'priceが空だと登録できない' do
@item.price = ''
@item.valid?
expect(@item.errors.full_messages).to include('販売価格を入力してください')
end
it 'priceが¥300より小さいと登録できない' do
@item.price = '299'
@item.valid?
expect(@item.errors.full_messages).to include('販売価格は適正な販売価格を入力してください')
end
it 'priceが¥9,999,999より大きいと登録できない' do
@item.price = '10,000,000'
@item.valid?
expect(@item.errors.full_messages).to include('販売価格は適正な販売価格を入力してください')
end
it 'priceが全角数字だと登録できない' do
@item.price = '300'
@item.valid?
expect(@item.errors.full_messages).to include('販売価格は適正な販売価格を入力してください')
end
it 'ユーザーが紐付いていないと登録できない' do
@item.user = nil
@item.valid?
expect(@item.errors.full_messages).to include('ユーザーを入力してください')
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe("User Order's Show Page") do
it "Displays the details of that order" do
user_1 = User.create!(name: 'Bob', address: '123 Who Cares Ln', city: 'Denver', state: 'CO', zip: '12345', email: 'regularbob@me.com', password: 'secret')
visit '/login'
fill_in :email, with: user_1.email
fill_in :password, with: user_1.password
click_button "Log In"
bike_shop = Merchant.create!(name: "Meg's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203)
tire = bike_shop.items.create!(name: "Gatorskins", description: "They'll never pop!", price: 100, image: "https://www.rei.com/media/4e1f5b05-27ef-4267-bb9a-14e35935f218?size=784x588", inventory: 12)
dog_shop = Merchant.create(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210)
pull_toy = dog_shop.items.create(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32)
order_1 = Order.create!(name: 'Bob', address: '123 Who Cares Ln', city: 'Denver', state: 'CO', zip: '12345')
order_2 = Order.create!(name: 'Joe', address: '123 Who Cares Ln', city: 'Denver', state: 'CO', zip: '12345')
item_order_1 = order_1.item_orders.create!(item: tire, price: tire.price, quantity: 4)
order_1.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 3)
order_2.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 2)
user_order_1 = user_1.user_orders.create!(order: order_1, user: user_1)
user_1.user_orders.create!(order: order_2, user: user_1)
visit "/profile/orders/#{order_1.id}"
within "#item-#{item_order_1.item_id}" do
expect(page).to have_content(item_order_1.item.name)
expect(page).to have_content("Gatorskins")
expect(page).to have_content(item_order_1.item.description)
expect(page).to have_content(item_order_1.item.image)
expect(page).to have_content("Item quantity: 4")
expect(page).to have_content(item_order_1.item.price)
expect(page).to have_content("Item subtotal: $400")
end
end
it "I see a button allowing user to cancel the order" do
user_1 = User.create!(name: 'Bob', address: '123 Who Cares Ln', city: 'Denver', state: 'CO', zip: '12345', email: 'regularbob@me.com', password: 'secret')
visit '/login'
fill_in :email, with: user_1.email
fill_in :password, with: user_1.password
click_button "Log In"
bike_shop = Merchant.create!(name: "Meg's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203)
tire = bike_shop.items.create!(name: "Gatorskins", description: "They'll never pop!", price: 100, image: "https://www.rei.com/media/4e1f5b05-27ef-4267-bb9a-14e35935f218?size=784x588", inventory: 12)
dog_shop = Merchant.create(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210)
pull_toy = dog_shop.items.create(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32)
order_1 = Order.create!(name: 'Bob', address: '123 Who Cares Ln', city: 'Denver', state: 'CO', zip: '12345')
order_2 = Order.create!(name: 'Joe', address: '123 Who Cares Ln', city: 'Denver', state: 'CO', zip: '12345')
item_order_1 = order_1.item_orders.create!(item: tire, price: tire.price, quantity: 4)
order_1.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 3)
order_2.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 2)
user_order_1 = user_1.user_orders.create!(order: order_1, user: user_1)
user_1.user_orders.create!(order: order_2, user: user_1)
visit "/profile/orders/#{order_1.id}"
expect(item_order_1.status).to eq("Pending")
expect(page).to have_button("Cancel Order")
expect(page).to have_content("Order Status: Pending")
expect(page).to have_content(order_1.status)
click_button "Cancel Order"
expect(current_path).to eq("/profile")
order_1.reload
item_order_1.reload
expect(page).to have_content("Order successfully cancelled")
expect(item_order_1.status).to eq("Unfulfilled")
expect(order_1.status).to eq("Cancelled")
visit "/profile/orders"
within "#order-#{order_1.id}" do
expect(page).to have_content("Order Status: Cancelled")
end
end
end
|
Rails.application.routes.draw do
devise_for :users, controllers: {
sessions: 'users/sessions',
registrations: 'users/registrations',
confirmations: 'users/confirmations'
}
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root to: "home#index"
resources :order, only: [:index, :show, :create,:edit, :update]
resources :product, only: [:edit, :update]
end
|
class Sysadmin::ClientsController < Sysadmin::BaseController
set_tab :clients
helper_method :sort_column, :sort_direction
def index
@clients = Company.order(sort_column + " " + sort_direction).page(params[:page]).per(20)
@clients = @clients.where("name LIKE ?", "%#{params[:term]}%") if params[:term].present?
respond_to do |format|
format.html # index.html.erb
end
end
def show
@client = Company.includes(:invoices).find(params[:id])
@invoices = @client.invoices.order("created_at DESC").page(params[:page]).per(20)
end
private
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def sort_column
Company.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.