text stringlengths 10 2.61M |
|---|
class Table < ActiveRecord::Base
has_many :orders
validates :name , presence:true, uniqueness:true
end
|
# Grabs a full track listing for the provided
# credentials.
module VelocitasCore
class TrackFetcher
# Currently just fetches a global list.
def fetch
Track.all
end
end
end
|
user = node['ubuntu_i3-gaps_workstation']['user']
playerctl_deb_path = "#{node['ubuntu_i3-gaps_workstation']['tmp_dir']}/playerctl.deb"
version = node['ubuntu_i3-gaps_workstation']['playerctl']['version']
# Download playerctl deb package
remote_file playerctl_deb_path do
source "https://github.com/acrisci/playerctl/releases/download/v#{version}/playerctl-#{version}_amd64.deb"
owner user
group user
notifies :install, 'dpkg_package[install_playerctl]', :immediate
not_if 'dpkg -l | grep playerctl'
end
# Install playerctl
dpkg_package 'install_playerctl' do
source playerctl_deb_path
action :nothing
end
# Cleanup playerctl deb package
file playerctl_deb_path do
action :delete
end
|
Copyright (c) 2014 Francesco Balestrieri
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
require 'modules'
require 'set'
class PullRequestController < ApplicationController
include Modules
respond_to :json
def post
payload = ActiveSupport::JSON.decode params[:payload]
if payload["action"] == "closed"
comment = closed_comment_from payload
else # "opened", "reopened", "synchronize"
comment = opened_comment_from payload
end
jira = JiraHelper.instance
processed_issues = Set.new
jira.scan_issues payload["pull_request"]["body"] do | should_resolve, issue_id |
#skip already processed issues
if processed_issues.add?(issue_id)
jira.add_comment issue_id, comment
if should_resolve && jira.resolve_on_merge && payload["action"] == "closed"
jira.resolve issue_id
end
end
end
render :nothing => true, :status => 200
end
def opened_comment_from(json_payload)
pr = json_payload["pull_request"]
user = pr["user"]
repo = pr["head"]["repo"]
JiraHelper.instance.opened_pr_template %
{ user_id: user["login"], user_url: user["html_url"],
repo_name: repo["name"], repo_url: repo["html_url"],
pr_number: json_payload["number"], pr_url: pr["html_url"],
pr_title: pr["title"] }
end
def closed_comment_from(json_payload)
pr = json_payload["pull_request"]
user = pr["user"]
repo = pr["head"]["repo"]
JiraHelper.instance.closed_pr_template %
{ user_id: user["login"], user_url: user["html_url"],
pr_number: json_payload["number"],
pr_url: pr["html_url"], pr_title: pr["title"] }
end
end |
require 'pry'
module BinaryTree
# Definition for binary tree node
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left, @right = nil, nil
end
end
# @param {Integer[]} inorder
# @param {Integer[]} postorder
# @return {TreeNode}
def self.build_tree(in_order, postorder)
in_order_map = {}
in_order.each_with_index{|num, index| in_order_map[num] = index}
self._build_tree_(postorder, 0, postorder.size, in_order, 0, in_order.size, in_order_map)
end
private
def self._build_tree_(preorder, pl, pu, in_order, il, iu, in_order_map)
return nil if pu - pl <= 0
num = preorder[pl]
return TreeNode.new(num) if pu - pl == 1
im = in_order_map[num]
pm = pl + 1 + (im - il)
ltree = self._build_tree_(preorder, pl + 1, pm, in_order, il, im, in_order_map)
rtree = self._build_tree_(preorder, pm, pu, in_order, im + 1, il, in_order_map)
root = TreeNode.new(num)
root.left, root.right = ltree, rtree
root
end
in_order = [9,3,15,20,7]
postorder = [9,15,7,20,3]
BinaryTree.build_tree(in_order, postorder)
end |
class AddShipFeeAndSnToOrders < ActiveRecord::Migration
def change
add_column :orders, :ship_fee, :integer
add_column :orders, :sn, :string
end
end
|
require 'rails_helper'
describe AwardsController, type: :controller do
award = Award.create(:award => "Academy")
describe "GET index" do
it "have 200 response for getting all awards" do
get :index
expect(response).to have_http_status(200)
end
end
describe "GET show" do
it "have 200 response for getting award by id" do
get :show, :params => { :id => award.id }
expect(response).to have_http_status(200)
end
it "have 400 response for getting award by invalid id" do
get :show, :params => { :id => -1 }
expect(response).to have_http_status(400)
end
end
describe "POST create" do
it "have 200 response for creating new award" do
post :create, :params => { :award => "Academy" }
expect(response).to have_http_status(200)
end
it "have 400 response for creating invalid award" do
post :create, :params => { :award => "a" }
expect(response).to have_http_status(400)
end
end
describe "PUT update" do
it "have 200 response for updating" do
put :update, :params => { :id =>award.id, :award => "AcademyUpdated" }
expect(response).to have_http_status(200)
end
it "have 400 response for updating invalid award" do
post :update, :params => { :id => -1, :award => "AcademyUpdated" }
expect(response).to have_http_status(400)
end
it "have 400 response for updating invalid award" do
post :update, :params => { :id => award.id, :award => "a" }
expect(response).to have_http_status(400)
end
end
describe "DELETE destroy" do
it "have 200 response for deleting award by id" do
award = Award.create(award: "Oscar")
delete :destroy, :params => { :id => award.id }
expect(response).to have_http_status(200)
end
it "have 400 response for deleting award by invalid id" do
delete :destroy, id: -1
expect(response).to have_http_status(400)
end
end
end |
require 'spec_helper'
describe Application do
let(:user) { User.make! }
it "should be invalid without a name, user, server and deployment" do
application = Application.new()
application.should have(1).error_on(:name)
application.should have(1).error_on(:user_id)
application.should have(1).error_on(:deployment_id)
application.errors.count.should == 3
application.should_not be_valid
end
context "clone" do
it "should be deep cloned, including all of its associations" do
application = given_resources_for([:application])[:application]
new_application = application.deep_clone
Application.last.should == new_application
new_application.name.should == "Copy of #{application.name}"
new_application.deployment.should == application.deployment
new_application.server.should == application.server
new_application.patterns.count.should == application.patterns.count
new_application.should be_valid
end
it "should be deep cloned with a new name" do
application = Application.make(:user => user)
new_application = application.deep_clone(:name => 'application2')
new_application.name.should == "application2"
end
end
it "should be invalid when server belongs to another deployment" do
application = given_resources_for([:application])[:application]
application2 = given_resources_for([:application])[:application]
application.server = application2.server
application.should have(1).error_on(:server)
application.errors.count.should == 1
application.should_not be_valid
end
end |
class Army < ActiveRecord::Base
# Associations
belongs_to :power
belongs_to :unit
belongs_to :occupation
# Validation
validates :amount, :power_id, :unit_id, presence: true
validate :check_amount
private
def check_amount
errors[:content] << "Amount of units has to be 1 at least." if amount <= 0
end
end
|
class VotesController < ApplicationController
before_action :set_vote, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@votes = Vote.all
end
def show
end
def new
@vote = Vote.new
end
def create
@vote = Vote.create(vote_params)
respond_to do |format|
if @vote.save
format.html { go_back }
format.json { render :show, status: :created, location: @vote }
else
format.html { render :new }
format.json { render json: @vote.errors, status: :unprocessable_entity }
end
end
end
private
#Redirect_to_back
def go_back
#Attempt to redirect
redirect_to :back
#Catch exception and redirect to root
rescue ActionController::RedirectBackError
redirect_to root_path
end
def set_vote
@vote = Vote.find(params[:id])
end
def vote_params
params.require(:vote).permit(:restaurantID, :split, :user)
end
end
|
# frozen_string_literal: true
module Exfiles
VERSION = "0.0.1"
end
|
require_relative 'node'
module Dom
# NoDoc is used by {Dom} and {Dom::Node} to preserve the correct hierachy of
# the tree, while inserting nodes with non (or not yet) existing parents.
#
# For example let's add the node 'foo.bar.baz' in our empty Dom. This will
# result in the following tree:
#
# -foo (NoDoc)
# -bar (NoDoc)
# -baz
#
# If a documented node with the same path is inserted, the NoDoc-node will be replaced by it.
class NoDoc
include Node
attr_reader :name
def initialize(name)
@name = name
super()
end
end
end
|
module PlusganttUtilsHelper
class Utils
def initialize()
end
def get_hollidays_between(earlier_date, later_date)
hollidays = 0
Rails.logger.info("get_hollidays_between: " + Plusgantt.get_hollidays.to_s)
if Plusgantt.get_hollidays
hollidays += Plusgantt.get_hollidays.count{|d| (earlier_date <= d.to_date && d.to_date <= later_date)}
end
return hollidays
end
#Return how many working days are between two date, ignoring hollidays
def calc_days_between_date(earlier_date, later_date)
days_diff = (later_date - earlier_date).to_i
weekdays = 0
if days_diff >= 7
whole_weeks = (days_diff/7).to_i
later_date -= whole_weeks*7
weekdays += whole_weeks*5
end
if later_date >= earlier_date
dates_between = earlier_date..(later_date)
weekdays += dates_between.count{|d| ![0,6].include?(d.wday)}
end
return weekdays
end
def calc_weekenddays_between_date(earlier_date, later_date)
Rails.logger.info("----------------calc_weekenddays_between_date start----------------------------")
days_diff = (later_date - earlier_date).to_i
weekenddays = 0
if days_diff >= 7
whole_weeks = (days_diff/7).to_i
Rails.logger.info("whole_weeks: " + whole_weeks.to_s)
later_date -= whole_weeks*7
Rails.logger.info("new later_date: " + later_date.to_s)
weekenddays += whole_weeks*2
Rails.logger.info("3 - weekenddays: " + weekenddays.to_s)
end
if later_date >= earlier_date
dates_between = earlier_date..(later_date)
weekenddays += dates_between.count{|d| ![1,2,3,4,5].include?(d.wday)}
Rails.logger.info("4 - weekenddays: " + weekenddays.to_s)
end
Rails.logger.info("5 - weekenddays: " + weekenddays.to_s)
return weekenddays
Rails.logger.info("----------------calc_weekenddays_between_date end----------------------------")
end
def get_asignacion(issue)
if issue.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'IssueCustomField')) &&
issue.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'IssueCustomField')).value.to_d > 0
return issue.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'IssueCustomField')).value.to_d
end
if issue.assigned_to && issue.assigned_to.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'UserCustomField')) &&
issue.assigned_to.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'UserCustomField')).value.to_d > 0
return issue.assigned_to.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'UserCustomField')).value.to_d
end
if issue.project.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'ProjectCustomField')) &&
issue.project.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'ProjectCustomField')).value.to_d > 0
return issue.project.custom_value_for(CustomField.find_by_name_and_type('asignacion', 'ProjectCustomField')).value.to_d
end
return Plusgantt.hour_by_day
end
def update_issue_end_date(issue)
#Validate start_date
issue.start_date = cal_start_date(issue.start_date)
Rails.logger.info("----------------update_issue_end_date----------------------------")
Rails.logger.info("start date modified to: " + issue.start_date.to_s)
Rails.logger.info("----------------update_issue_end_date----------------------------")
#calculate end date.
hour_by_day = get_asignacion(issue)
days = (issue.estimated_hours / hour_by_day).ceil
if days <= 1
issue.due_date = issue.start_date
else
end_date = issue.start_date + days.to_i - 1
Rails.logger.info("----------------update_issue_end_date----------------------------")
Rails.logger.info("days: " + days.to_s)
Rails.logger.info("----------------update_issue_end_date----------------------------")
issue.due_date = cal_end_date(issue.start_date, end_date)
end
end
def cal_start_date(start_date)
if start_date.wday == 6
start_date = (start_date + 2).to_date
else
if start_date.wday == 0
start_date = (start_date + 1).to_date
end
end
hollidays = get_hollidays_between(start_date, start_date)
if hollidays.to_i > 0
return cal_start_date((start_date + hollidays).to_date)
else
return start_date.to_date
end
end
def cal_end_date(start_date, end_date)
Rails.logger.info("----------------cal_end_date start----------------------------")
Rails.logger.info("start_date: " + start_date.to_s)
Rails.logger.info("end_date: " + end_date.to_s)
weekenddays = calc_weekenddays_between_date(start_date, end_date)
if weekenddays == 0
Rails.logger.info("1 - weekenddays: " + weekenddays.to_s)
hollidays = get_hollidays_between(start_date, end_date)
Rails.logger.info("Hollydays: " + hollidays.to_s)
if hollidays.to_i > 0
start_date = (end_date + 1).to_date
end_date = (end_date + hollidays.to_i).to_date
weekenddays = calc_weekenddays_between_date(start_date, end_date)
if weekenddays == 0
hollidays = get_hollidays_between(end_date, end_date)
Rails.logger.info("Hollydays: " + hollidays.to_s)
if hollidays.to_i > 0
end_date = (end_date + hollidays.to_i).to_date
return cal_end_date(end_date, end_date)
else
return end_date.to_date
end
else
if end_date.wday == 6
Rails.logger.info("DIA SABADO")
return cal_end_date((end_date + 2).to_date, (end_date + 2 + (weekenddays - 1)).to_date)
else
if end_date.wday == 0
Rails.logger.info("DIA DOMINGO")
return cal_end_date((end_date + 1).to_date, (end_date + 1 + (weekenddays - 1)).to_date)
else
Rails.logger.info("DIA:" + end_date.wday.to_s)
return cal_end_date(end_date, (end_date + weekenddays).to_date)
end
end
end
end;
return end_date.to_date
else
hollidays = get_hollidays_between(start_date, end_date)
Rails.logger.info("Hollydays: " + hollidays.to_s)
if hollidays.to_i > 0
weekenddays += calc_weekenddays_between_date( (end_date + 1).to_date, (end_date + hollidays.to_i).to_date)
end_date = (end_date + hollidays.to_i).to_date
end
if end_date.wday == 6
Rails.logger.info("DIA SABADO")
return cal_end_date((end_date + 2).to_date, (end_date + 2 + (weekenddays - 1)).to_date)
else
if end_date.wday == 0
Rails.logger.info("DIA DOMINGO")
return cal_end_date((end_date + 1).to_date, (end_date + 1 + (weekenddays - 1)).to_date)
else
Rails.logger.info("DIA:" + end_date.wday.to_s)
return cal_end_date(end_date, (end_date + weekenddays).to_date)
end
end
end
Rails.logger.info("----------------cal_end_date end----------------------------")
end
def calc_issue_expected_progress(issue, control_date)
if issue.start_date && control_date >= issue.start_date
if issue.due_before
if control_date >= issue.due_before
return 100.0
else
total_hours = 0.0
if issue.leaf?
return calc_task_expected_progress(issue, control_date)
else
issue.descendants.each do |child_issue|
Rails.logger.info("Issue Padre: " + issue.to_s + ". Issue hijo: " + child_issue.to_s)
if !child_issue.estimated_hours.nil?
total_hours += (calc_task_expected_progress(child_issue, control_date) / 100.0) * child_issue.estimated_hours.to_d
Rails.logger.info("Acumulando las horas del hijo según avance: " + total_hours.to_s)
end
end
if issue.estimated_hours && issue.estimated_hours.to_d > 0
total_hours += (calc_task_expected_progress(issue, control_date) / 100.0) * issue.estimated_hours.to_d
Rails.logger.info("Acumulando las horas propias del issue según avance: " + total_hours.to_s)
end
if issue.total_estimated_hours && issue.total_estimated_hours.to_d > 0
estimated_progress = ( (total_hours / issue.total_estimated_hours.to_d ) * 100.0).round(2)
if estimated_progress > 100.0
estimated_progress = 100.0
end
else
estimated_progress = 0.0
end
return estimated_progress
end
end
else
return 0.0
end
else
return 0.0
end
end
def calc_task_expected_progress(issue, control_date)
if issue.start_date && control_date >= issue.start_date
if issue.due_before
if control_date >= issue.due_before
return 100.0
else
days = calc_days_between_date(issue.start_date, control_date)
hollidays = get_hollidays_between(issue.start_date, control_date)
Rails.logger.info("Hollydays: " + hollidays.to_s)
days -= hollidays.to_i
hour_by_day = get_asignacion(issue)
total_hours = hour_by_day * days
if issue.estimated_hours && issue.estimated_hours.to_i > 0
if total_hours > issue.estimated_hours.to_i
return 100.0
else
return ( ( total_hours / issue.estimated_hours.to_i ) * 100.0).round(2)
end
else
return 0.0
end
end
else
return 0.0
end
else
return 0.0
end
end
def calc_version_expected_progress(version, control_date, issues)
if version.start_date && control_date >= version.start_date
if version.due_date
if control_date >= version.due_date
return 100.0
else
total_hours = 0.0
total_estimated_hours = 0.0
issues.each do |issue|
if !issue.estimated_hours.nil?
total_hours += (calc_task_expected_progress(issue, control_date) / 100.0) * issue.estimated_hours.to_d
total_estimated_hours += issue.estimated_hours.to_d
end
end
if total_estimated_hours.to_d > 0
estimated_progress = ( (total_hours / total_estimated_hours.to_d ) * 100.0).round(2)
if estimated_progress > 100.0
estimated_progress = 100.0
end
else
estimated_progress = 0.0
end
return estimated_progress
end
else
return 0.0
end
else
return 0.0
end
end
def calc_project_expected_progess(project)
end
end
end |
unless node["nfs"]["mounts"].empty?
mounts = node["nfs"]["mounts"]
mounts.each do |mount_point, v|
directory mount_point do
owner v["owner"]
group v["group"]
mode v["mode"]
recursive true
end # directory
mount mount_point do
device v["device"]
fstype "nfs"
if v.has_key? "action"
action Array(v["action"]).inject([]) { |res, str| res << str.to_sym }
end
options v["options"] if v.has_key? "options"
end # mount
if v.has_key? "links"
Array(v["links"]).each do |link_name|
link link_name do
to mount_point
end
end
end
end # mounts.each
end # unless
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
class Project < ActiveRecord::Base
has_and_belongs_to_many :developers, :uniq => true, :order => 'developers.name desc, developers.id desc'
has_and_belongs_to_many :readonly_developers, :class_name => "Developer", :readonly => true
has_and_belongs_to_many :selected_developers, :class_name => "Developer", :select => "developers.*", :uniq => true
has_and_belongs_to_many :non_unique_developers, :order => 'developers.name desc, developers.id desc', :class_name => 'Developer'
has_and_belongs_to_many :limited_developers, :class_name => "Developer", :limit => 1
has_and_belongs_to_many :developers_named_david, :class_name => "Developer", :conditions => "name = 'David'", :uniq => true
has_and_belongs_to_many :developers_named_david_with_hash_conditions, :class_name => "Developer", :conditions => { :name => 'David' }, :uniq => true
has_and_belongs_to_many :salaried_developers, :class_name => "Developer", :conditions => "salary > 0"
has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => 'SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id'
has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => "DELETE FROM developers_projects WHERE project_id = \#{id} AND developer_id = \#{record.id}"
has_and_belongs_to_many :developers_with_callbacks, :class_name => "Developer", :before_add => Proc.new {|o, r| o.developers_log << "before_adding#{r.id || '<new>'}"},
:after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || '<new>'}"},
:before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"},
:after_remove => Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"}
has_and_belongs_to_many :well_payed_salary_groups, :class_name => "Developer", :group => "developers.salary", :having => "SUM(salary) > 10000", :select => "SUM(salary) as salary"
attr_accessor :developers_log
def after_initialize
@developers_log = []
end
end
class SpecialProject < Project
def hello_world
"hello there!"
end
end
|
require 'spec_helper'
describe StaffMember do
before(:each) do
@member = Factory.build(:staff_member)
end
it "validates the presence of name" do
@member.name = ""
@member.should_not be_valid
end
it "validates the presence of bio" do
@member.bio = ""
@member.should_not be_valid
end
context "with stats" do
before(:each) do
@member.stats << Factory(:stat)
@member.stats << Factory(:stat)
@member.save
end
it "has stats" do
@member.stats.should_not be_empty
end
it "returns an array of stats" do
@member.stats.should be_a(Array)
end
end
end
|
# frozen_string_literal: true
class AddCampusRefToSchoolsTable < ActiveRecord::Migration[4.2]
def change
add_column :schools, :campus_id, :int
add_index :schools, [:campus_id]
end
end
|
module ReadyForI18N
class I18nGenerator
EXTRACTORS = [ErbHelperExtractor, HtmlTextExtractor, HtmlAttrExtractor]
PATH_PATTERN = /\/views\/(.*)/
def self.dict
@dict
end
def self.path
@path
end
def self.excute(opt)
setupOptions(opt)
f = @src_path
ReadyForI18N::ExtractorBase.i18n_namespace = file_path_to_message_prefix(f)
@path = f.match(PATH_PATTERN)[1].gsub(/#{@ext}$/, '').split '/' if opt['dot'] && f =~ PATH_PATTERN
result = EXTRACTORS.inject(File.read(f)) do |buffer, extractor|
extractor.new.extract(buffer) { |k, v| @dict.push(k, v, @path) }
end
write_target_file(f, result) if @target_path
@dict.write_to STDOUT
end
def self.file_path_to_message_prefix(file)
segments = File.expand_path(file).split('/').select { |segment| !segment.empty? }
subdir = %w(views helpers controllers models).find do |app_subdir|
segments.index(app_subdir)
end
if subdir.nil?
raise AppFolderNotFound, "No app. subfolders were found to determine prefix. Path is #{File.expand_path(file)}"
end
first_segment_index = segments.index(subdir) + 1
file_name_without_extensions = segments.last.split('.')[0..0]
path_segments = segments.slice(first_segment_index...-1)
(path_segments + file_name_without_extensions).join('.')
end
private
def self.setupOptions(opt)
@src_path = opt['source']
@locale = opt['locale']
if opt['nokey']
@dict = NoKeyDictionary.new(@locale)
else
@dict = LocaleDictionary.new(@locale)
@target_path = opt['destination']
if @target_path && (!@target_path.end_with? File::SEPARATOR)
@target_path = "#{@target_path}#{File::SEPARATOR}"
end
end
@ext = opt['extension'] || '.html.erb'
ExtractorBase.use_dot(true) if opt['dot']
if opt['keymap']
files_content = opt['keymap'].split(':').map { |f| File.read(f) }
ReadyForI18N::ExtractorBase.key_mapper = KeyMapper.new(*files_content)
end
end
def self.write_target_file(source_file_name, content)
full_target_path = File.dirname(source_file_name).gsub(@src_path, @target_path)
FileUtils.makedirs full_target_path
target_file = File.join(full_target_path, File.basename(source_file_name))
File.open(target_file, 'w+') { |f| f << content }
end
end
end |
# Nice wrapper around VolleyWrapper, to use in BluePotion.
#
# result that is returned has these attributes:
# response
# object
# body
# status_code
# headers
# not_modified?
# success?
# failure?
#
# @example
# # Create a session and do a single HTML get. It's better
# # to use the shared session below.
# app.net.get("http://google.com") do |response|
# mp response.object # <- HTML
# end
#
# # To initialize the shared session, which is best to use
# # rather than the one-off above, do this. Once this
# # is done, all your gets, posts, puts, etc will use this
# # share session
# app.net.build_shared("http://baseurl.com") do |shared|
# # You can override the serializer per request
# # Leave blank for string
# shared.serializer = :json
# end
#
# # For shared, use relative paths
# app.net.get("foo.html") do |response|
# mp response.object # <- returns type you set in shared.serializer
# end
#
# # Post
# app.net.post("foo/bar", your_params_hash) do |response|
# mp response.object # <- returns type you set in shared.serializer
# end
#
# # If you have built a shared session, but want to use another
# # session, do this:
# app.net.get("foo.html", session: app.net.single_use_session) do |response|
# mp response.object # <- returns type you set in shared.serializer
# end
#
# # Get json:
# url = "http://openweathermap.org/data/2.1/find/name?q=san%20francisco"
# app.net.get_json(url) do |request|
# # request.object is a hash, parsed from the json
# temp_kelvin = request.object["list"].first["main"]["temp"]
# end
class BluePotionNet
class << self
def session_client
@_session_client ||= VW::SessionClient
end
def session
session_client.shared ? session_client.shared : single_use_session
end
def is_shared?
!session_client.shared.is_nil?
end
def single_use_session
session_client.new(PMApplication.current_application.context, "")
end
def build_shared(url, &block)
session_client.build_shared(PMApplication.current_application.context, url, &block)
end
def get(url, params={}, opts={}, &block)
raise "[BluePotion error] You must provide a block when using app.net.get" unless block
ses = opts.delete(:session) || self.session
ses.get(url, params, opts, &block)
end
def get_json(url, params={}, opts={}, &block)
raise "[BluePotion error] You must provide a block when using app.net.get_json" unless block
ses = opts.delete(:session) || self.session
opts[:serializer] = :json
ses.get(url, params, opts, &block)
end
def post(url, params, opts={}, &block)
raise "[BluePotion error] You must provide a block when using app.net.post" unless block
ses = opts.delete(:session) || self.session
ses.post(url, params, opts, &block)
end
def put(url, params, opts={}, &block)
raise "[BluePotion error] You must provide a block when using app.net.put" unless block
ses = opts.delete(:session) || self.session
ses.put(url, params, opts, &block)
end
def delete(url, params, opts={}, &block)
raise "[BluePotion error] You must provide a block when using app.net.delete" unless block
ses = opts.delete(:session) || self.session
ses.delete(url, params, opts, &block)
end
end
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 StudyTypeController, type: :controller do
stub_controller
build_study_type_question_groups
let!(:before_filters) { find_before_filters }
describe "#determine_study_type_note" do
it 'should call before_action #extract_answers' do
expect(before_filters.include?(:extract_answers)).to eq(true)
end
it "returns study_type note 0" do
params = {ans1: "false", ans2: "false", ans3: "true", ans4: "true", ans5: "true", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Full Epic Functionality: notification, pink header, MyChart access.")
end
it "returns study_type note 1" do
params = {ans1: "true", ans2: "", ans3: "", ans4: "", ans5: "", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("De-identified Research Participant")
end
it "returns study_type note 3" do
params = {ans1: "false", ans2: "true", ans3: "false", ans4: "false", ans5: "false", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Break-The-Glass for research associated encounters")
end
it "returns study_type note 4" do
params = {ans1: "false", ans2: "true", ans3: "false", ans4: "true", ans5: "false", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Break-The-Glass for research associated encounters: no notification, pink header, no MyChart access.")
end
it "returns study_type note 5" do
params = {ans1: "false", ans2: "true", ans3: "false", ans4: "false", ans5: "true", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Break-The-Glass for research associated encounters: no notification, no pink header, MyChart access.")
end
it "returns study_type note 6" do
params = {ans1: "false", ans2: "true", ans3: "false", ans4: "true", ans5: "true", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Break-The-Glass for research associated encounters: no notification, pink header, MyChart access.")
end
it "returns study_type note 7" do
params = {ans1: "false", ans2: "true", ans3: "true", ans4: "false", ans5: "false", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Break-The-Glass for research associated encounters: notification, no pink header, no MyChart access.")
end
it "returns study_type note 8" do
params = {ans1: "false", ans2: "true", ans3: "true", ans4: "true", ans5: "false", ans6: "", ans7: "", controller: "study_type", action: "determine_study_type_note"}
post :determine_study_type_note, params: params, format: :js, xhr: true
expect(assigns(:note)).to eq("Break-The-Glass for research associated encounters: notification, pink header, no MyChart access.")
end
end
end
|
class << ActiveRecord::Base
def each(batch_size = 100, opts = {}, &block)
batch_size ||= 100
opts ||= {}
maximum = opts.delete :maximum
deleting = opts.delete :deleting
hide_counter = opts.delete :hide_counter
total = count opts
offset = 0
while true
ar = all opts.merge(:limit => batch_size, :offset => (deleting ? 0 : offset))
break if ar.blank?
offset += batch_size
break if maximum && (offset > maximum)
ar.each &block
unless hide_counter
processed = (total < offset ? total : offset).to_s.rjust(total.to_s.length)
print "\r * #{processed}/#{total} #{name.downcase.pluralize}"
STDOUT.flush
end
end
puts and STDOUT.flush unless hide_counter || total.zero?
end
end
|
import "Setupfile"
fastlane_version "2.143.0"
default_platform :ios
platform :ios do
before_each do |lane, options|
setup_jenkins(
keychain_path: @keychain_name,
keychain_password: @keychain_password,
add_keychain_to_search_list: true,
)
end
lane :pods do
cocoapods(try_repo_update_on_error: true)
end
lane :setup_build_number do
increment_build_number(build_number: @local_build_number)
end
lane :screenshots do
capture_screenshots
end
lane :project_setup do
pods
setup_build_number
end
lane :upload_screenshots do
deliver(
force: true,
username: @username,
team_name: @team_name,
skip_screenshots: false,
skip_binary_upload: true,
skip_metadata: true,
)
end
lane :build_application do
if @xcode_version != nil
xcversion(version: @xcode_version)
end
disable_automatic_code_signing
if @add_beta_badge
add_badge(dark: true)
end
match(
app_identifier: @app_id,
git_url: @git_url,
git_branch: @git_branch,
username: @username,
type: @match_type,
team_id: @team_id_account,
force_for_new_devices: true,
keychain_name: @keychain_name,
keychain_password: @keychain_password,
verbose: true,
)
update_app_identifier(
plist_path: @plist_path,
app_identifier: @app_id,
)
update_project_provisioning(
xcodeproj: @path_xcodeprojfile,
target_filter: "^#{@target_app}$",
code_signing_identity: "iPhone Distribution",
profile: ENV["sigh_#{@app_id}_#{@match_type}_profile-path"],
)
update_project_team(teamid: @team_id_account)
gym(
clean: true,
scheme: @app_scheme,
include_symbols: true,
skip_profile_detection: true,
export_method: @export_method,
)
case @deploy_on
when "firebase"
firebase_deploy
when "appstore"
appstore_deploy
else
end
if @firebase_plist_path != nil
upload_symbols_to_crashlytics(gsp_path: @firebase_plist_path)
end
post_to_slack
end
#DEPLOY LANES
lane :firebase_deploy do
firebase_app_distribution(
app: @firebase_distribution_key,
groups: @distributions_groups.join(", "),
firebase_cli_token: ENV["FIREBASE_TOKEN"],
release_notes: ENV["RELEASE_NOTES"],
)
end
lane :appstore_deploy do
deliver(
force: true,
username: @username,
team_name: @team_name,
skip_screenshots: true,
skip_metadata: true,
)
end
#SLACK
lane :post_to_slack do |params|
name = params[:name] || @app_name
slack_url = ENV["SLACK_URL"]
slack(
slack_url: slack_url,
message: "#{name} successfully released!",
channel: "#ios-integrations",
success: true,
payload: { # Optional, lets you specify any number of your own Slack attachments.
"Build Date" => Time.new.to_s,
"Built by" => "MacMinion",
},
default_payloads: [:git_branch, :git_author],
)
end
lane :post_error_to_slack do |params|
name = params[:name] || @app_name
slack(
slack_url: ENV["SLACK_URL"],
message: "#{name} build had an error!",
channel: @slack_channel,
success: false,
payload: { # Optional, lets you specify any number of your own Slack attachments.
"Build Date" => Time.new.to_s,
"Built by" => "MacMinion",
},
default_payloads: [:git_branch, :git_author],
)
end
error do |lane, exception|
post_error_to_slack
end
end
|
class TenantSerializer < ActiveModel::Serializer
attributes :name, :age, :total_rent, :apartments_with_rent
has_many :apartments
def total_rent
all_rents = object.leases.map do |lease|
lease.rent
end
all_rents.sum
end
def apartments_with_rent
all_leases = object.leases.map do |lease|
"Apartment: #{Apartment.find(lease.apartment_id).number} - Rent: #{lease.rent}"
end
all_leases
end
end
|
class ClientsController < ApplicationController
before_action :find_client, except: :index
def index
render json: Client.all
end
def show
render json: @client, serializer: TotalMembershipsSerializer
end
def update
@client.update!(client_params)
render json: @client
end
private
def find_client
@client = Client.find(params[:id])
end
def client_params
params.permit(:name, :age)
end
end
|
require 'spec_helper'
describe Table do
before :each do
@table = Table.new 5, 5
end
describe "#new" do
it "took a width and a height and made a table" do
@table.should be_an_instance_of Table
end
end
describe "#width" do
it "returned the width" do
@table.width.should eql 5
end
end
describe "#height" do
it "returned the height" do
@table.height.should eql 5
end
end
describe "#placed_robot?" do
it "starts without a robot on it" do
@table.placed_robot?.should eql false
end
it "returns true after placement" do
@table.place Position.new(1,1)
@table.placed_robot?.should eql true
end
it "returns false after lifting up robot" do
@table.place Position.new(1,1)
@table.lift
@table.placed_robot?.should eql false
end
end
describe "#position" do
it "starts of without a position" do
@table.position.should eql nil
end
context "with a good placement" do
it "can return the position" do
@table.place Position.new(0,0)
@table.position.should eql Position.new(0,0)
end
end
context "with a weird placement" do
it "raises an exception" do
expect {@table.place Position.new(-1,0)}.to raise_error
end
end
end
describe "#place" do
it "can be placed many times without error" do
expect{2.times{|x|@table.place Position.new(x,x)}}.to_not raise_error
end
it "can't be placed with x < 0" do
expect{ @table.place Position.new(-1,1) }.to raise_error
end
it "can't be placed with y < 0" do
expect{ @table.place Position.new(1,-1) }.to raise_error
end
it "can't be placed with x > width" do
expect{ @table.place Position.new(@table.width + 1,-1) }.to raise_error
end
it "can't be placed with y > height" do
expect{ @table.place Position.new(1,@table.height + 1) }.to raise_error
end
end
describe "#lift" do
it "removes the robot's position" do
@table.place Position.new(1,1)
@table.lift
@table.position.should eql nil
end
end
end
|
require 'spec_helper'
describe FeaturesController do
let(:user) { create_user! }
let(:market) { Factory(:market) }
let(:feature) { Factory(:feature, :market => market, :user => user) }
context "standard users" do
it "cannot access a feature for a market" do
sign_in(:user, user)
get :show, :id => feature.id, :market_id => market.id
response.should redirect_to(root_path)
flash[:alert].should eql("The market you were looking for could not be found.")
end
context "with permission to view the market" do
before do
sign_in(:user, user)
Permission.create!(:user => user, :thing => market, :action => "view")
end
def cannot_create_features!
response.should redirect_to(market)
flash[:alert].should eql("You cannot create features on this market.")
end
def cannot_update_features!
response.should redirect_to(market)
flash[:alert].should eql("You cannot modify features on this market.")
end
it "cannot begin to create a feature" do
get :new, :market_id => market.id
cannot_create_features!
end
it "cannot create a feature without permission" do
post :create, :market_id => market.id
cannot_create_features!
end
it "cannot edit a feature without permission" do
get :edit, { :market_id => market.id, :id => feature.id }
cannot_update_features!
end
it "cannot update a feature without permission" do
put :update, { :market_id => market.id, :id => feature.id, :feature => {} }
cannot_update_features!
end
end
end
end
|
class City < ActiveRecord::Base
set_table_name(:city)
set_primary_key(:city_id)
belongs_to :country
# def self.rentals_per_city
# self
# .select("city.*, COUNT(*) AS rental_count")
# .joins("address ON city.city_id = address.city_id")
# .joins("store ON address.address_id = store.address_id")
# .joins("JOIN inventory ON store.store_id = inventory.store_id")
# .joins("rental ON inventory.inventory_id = rental.inventory_id")
# .group("city.city_id")
# .order("rental_count DESC")
# end
end
rentals per city
SELECT city.*, COUNT(*) AS rental_count
FROM city
JOIN address ON city.city_id = address.city_id
JOIN store ON address.address_id = store.address_id
JOIN inventory ON store.store_id = inventory.store_id
JOIN rental ON inventory.inventory_id = rental.inventory_id
GROUP BY city.city_id
ORDER BY rental_count DESC |
# input: string
# output: string with first character of every word capitalised and the rest lowercase
# split every word in the string argument as an array, delimited by whitespace
# use capitalise method for each word
# join all elements in array into string using join method
# data structure: array
# algo:
# set new variable for string array
# split(' ') on argument and make it equal to string array
# iterate through each element
# use capitalise on each one
# use join(' ') to turn array into string
def word_cap(string)
string_array = string.split(' ').map do |word|
word.capitalize
end
string_array.join(' ')
end
# or
def word_cap(words)
words.split.map(&:capitalize).join(' ')
end |
class ChangeFriendsStatusColumnType < ActiveRecord::Migration
def up
change_column :friends, :status, :string
end
def down
change_column :friends, :status, :boolean
end
end
|
class Location < ApplicationRecord
validates :name, presence: true
geocoded_by :address
after_validation :geocode
has_many :activity_locations
has_many :activity, through: :activity_locations
has_many :events
def address
[street, city, state, country].compact.join(',')
end
end
|
class Listing < ActiveRecord::Base
belongs_to :neighborhood
belongs_to :host, :class_name => "User"
has_many :reservations
has_many :reviews, :through => :reservations
has_many :guests, :class_name => "User", :through => :reservations
validates_presence_of :address, :listing_type, :title, :description, :price, :neighborhood_id
before_create :update_host_status
before_destroy :verify_update_status
def average_review_rating
total = reviews.inject(0) { |sum, x| sum + x.rating}
total.to_f / reviews.length unless reviews.length == 0
end
private
def update_host_status
host.update(host: true) unless host.host
end
def verify_update_status
host.update(host: false) unless host.listings.length > 1
end
end
|
class AddOpenedToReview < ActiveRecord::Migration
def change
add_column :reviews, :opened, :boolean, default: :false
end
end
|
require 'csv'
require 'byebug'
namespace :import do
desc "import users from csv"
task users: :environment do
filename = File.join Rails.root, "db/csv/users.csv"
CSV.foreach(filename, headers: true) do |row|
User.create(email: row['email'], password: row['password'], role: row['role'])
end
end
desc "import students from csv"
task students: :environment do
filename = File.join Rails.root, "db/csv/students.csv"
CSV.foreach(filename, headers: true) do |row|
Student.create(fname: row['fname'],mname: row['mname'],lname: row['lname'], street: row['street'], city: row['city'], state: row['state'], zip: row['zip'], phone: row['phone'], major: row['major'], education: row['education'], degree: row['degree'], image: row['image'], user_id: row['user_id'])
end
end
desc "import categories from csv"
task categories: :environment do
filename = File.join Rails.root, "db/csv/categories.csv"
CSV.foreach(filename, headers: true) do |row|
Category.create(name: row['name'])
end
end
desc "import skills from csv"
task skills: :environment do
filename = File.join Rails.root, "db/csv/skills.csv"
CSV.foreach(filename, headers: true) do |row|
Skill.create(name: row["name"], category_id: row['category_id'])
end
end
desc "import student_skills from csv"
task student_skills: :environment do
filename = File.join Rails.root, "db/csv/student_skills.csv"
CSV.foreach(filename, headers: true) do |row|
StudentSkill.create(level: row['level'], student_id: row['student_id'], skill_id: row["skill_id"])
end
end
desc "import businesses from csv"
task businesses: :environment do
filename = File.join Rails.root, "db/csv/businesses.csv"
CSV.foreach(filename, headers: true) do |row|
Business.create(name: row['name'],description: row['description'],tagline: row['tagline'], street: row['street'], city: row['city'], state: row['state'], zip: row['zip'], industry_id: row['industry_id'], user_id: row['user_id'])
end
end
desc "import industries from csv"
task industries: :environment do
filename = File.join Rails.root, "db/csv/industries.csv"
CSV.foreach(filename, headers: true) do |row|
Industry.create(name: row['name'])
end
end
desc "import projects from csv"
task projects: :environment do
filename = File.join Rails.root, "db/csv/projects.csv"
CSV.foreach(filename, headers: true) do |row|
Project.create(name: row['name'], description: row['description'], duration: row["duration"], rate: row["rate"].to_i, start: row["start"], image: row["image"],status: row["status"], business_id: row['business_id'])
end
end
desc "import project_skills from csv"
task project_skills: :environment do
filename = File.join Rails.root, "db/csv/project_skills.csv"
CSV.foreach(filename, headers: true) do |row|
ProjectSkill.create(project_id: row['project_id'], skill_id: row['skill_id'])
end
end
desc "import tasks from csv"
task tasks: :environment do
filename = File.join Rails.root, "db/csv/tasks.csv"
CSV.foreach(filename, headers: true) do |row|
Task.create(name: row['name'])
end
end
desc "import project_tasks from csv"
task project_tasks: :environment do
filename = File.join Rails.root, "db/csv/project_tasks.csv"
CSV.foreach(filename, headers: true) do |row|
ProjectTask.create(task_id: row['task_id'], project_id: row['project_id'])
end
end
end
|
# frozen_string_literal: true
class AddCompletionsCountToChallenges < ActiveRecord::Migration[5.1]
def change
add_column :challenges, :completions_count, :integer, default: 0, null: false
Challenge.reset_column_information
Challenge.find_each.pluck(:id) { |challenge_id| Challenge.reset_counters challenge_id, :completions }
end
end
|
# Object to get password stored in session variable
class GetPasswordInSessionVar
def initialize(token)
@token = token
end
def call
return nil unless @token
decoded_token = JWT.decode @token, ENV['MSG_KEY'], true
payload = decoded_token.first
payload['specially_hashed_password']
end
end
|
module Tokenizer
class Lexer
module TokenLexers
def eol?(chunk)
chunk == "\n"
end
# On eol, check the indent for the next line.
# Because whitespace is not tokenized, it is difficult to determine the
# indent level when encountering a non-whitespace chunk. If we check on
# eol, we can peek at the amount of whitespace present before it is
# stripped.
def tokenize_eol(_chunk)
try_assignment_close
process_indent
Token.new Token::EOL
end
end
end
end
|
require 'rails_helper'
describe 'navigation' do
it 'has login and registration links if the user is not logged in' do
visit root_path
expect(page).to have_link('Login')
expect(page).to have_link('Register')
end
it 'does not has login and registration links if the user is logged in' do
user = FactoryBot.create(:user)
login_as(user)
visit root_path
expect(page).to_not have_link('Login')
expect(page).to_not have_link('Register')
end
it 'it allows the user to login and redirects them to the homepage' do
user = FactoryBot.create(:user)
visit new_user_session_path
fill_in 'user[email]', with: user.email
fill_in 'user[password]', with: 'asdfasdf'
click_on 'Login'
expect(page).to have_content('My Feed')
end
end
|
# frozen_string_literal: true
require 'rsolr'
module FindIt
module Data
# Sends deletion requests to solr
module Delete
def by_record_provider_facet(facet_value)
connection = RSolr.connect(Blacklight.connection_config.without(:adapter))
connection.delete_by_query "record_provider_facet:\"#{facet_value}\""
connection.commit
end
end
end
end
|
require File.expand_path("../.gemspec", __FILE__)
require File.expand_path("../lib/ultimaker/version", __FILE__)
Gem::Specification.new do |gem|
gem.name = "ultimaker"
gem.authors = ["Samuel Kadolph"]
gem.email = ["samuel@kadolph.com"]
gem.summary = readme.summary
gem.homepage = "https://github.com/samuelkadolph/ultimaker"
gem.license = "MIT"
gem.version = Ultimaker::VERSION
gem.files = Dir["lib/**/*"].reject { |f| f =~ /discovery/ }
gem.required_ruby_version = ">= 2.0"
end
|
class StripeCache
def initialize(user)
@user = user
end
def refresh
if user.stripe_customer_id.present? && user.stripe_subscription_id.present?
purge_all
cache_all
end
self
end
def customer
return @customer if @customer
@customer = Rails.cache.fetch(cache_key("customer"), expires_in: 30.minutes) do
Stripe::Customer.retrieve(user.stripe_customer_id)
end
end
def subscription
return @subscription if @subscription
@subscription = Rails.cache.fetch(cache_key("subscription"), expires_in: 30.minutes) do
Stripe::Subscription.retrieve(user.stripe_subscription_id)
end
end
private
attr_reader :user
def purge_all
Rails.cache.delete_matched("#{user.id}/stripe")
end
def cache_all
customer
subscription
end
def cache_key(item)
"user/#{user.id}/stripe/#{item}"
end
end
|
class Character < ActiveRecord::Base
belongs_to :guild
has_many :events
has_many :remoteQueries
belongs_to :user
has_many :attendances
serialize :profession1
serialize :profession2
serialize :talentspec1
serialize :talentspec2
serialize :items
validates_uniqueness_of :name
validates_presence_of :realm
def netto_activity
Integer((self.activity / ((Time.now - self.created_at) / 60 / 60)) * 100) unless self.activity.nil?
end
class TalentSpec
attr_reader :trees,:active,:group,:icon,:prim
def initialize(elem)
@trees = []
@trees[1] = elem[:treeOne].to_i
@trees[2] = elem[:treeTwo].to_i
@trees[3] = elem[:treeThree].to_i
@active = elem[:active].nil? ? false : true
@group = elem[:group].to_i
@icon = elem[:icon]
@prim = elem[:prim]
end
end
class Profession
attr_reader :key, :name, :value, :max
alias_method :to_s, :name
alias_method :to_i, :value
def initialize(elem)
@key = elem[:key]
@name = elem[:name]
@value = elem[:value].to_i
@max = elem[:max].to_i
end
end
class Item
attr_reader :id, :icon, :level
def initialize(elem)
@id = elem[:id].to_i
@icon = elem[:icon]
end
def get_info(elem)
@level = (elem%'itemInfo'%'item')[:level].to_i
end
end
end |
# == Schema Information
#
# Table name: c14_labs
#
# id :bigint not null, primary key
# active :boolean
# name :string
# superseded_by :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_c14_labs_on_active (active)
# index_c14_labs_on_name (name)
# index_c14_labs_on_superseded_by (superseded_by)
#
FactoryBot.define do
factory :c14_lab do
name { Faker::Address.city }
active { [true, false].sample }
end
end
|
class AddLaboratoryToUser < ActiveRecord::Migration
def up
change_table :users do |t|
t.belongs_to :laboratory, index: true
end
end
end
|
require 'spec_helper'
describe SimpleCoffee do
before :each do
@coffee = SimpleCoffee.new
end
describe "#new" do
it "returns a coffee object" do
@coffee.should be_an_instance_of SimpleCoffee
end
end
it "returns the cost" do
@coffee.get_cost().should == 1
end
it "describes the ingredient" do
@coffee.get_ingredients().should eql "Coffee"
end
end
describe CoffeeDecorator do
before :each do
@coffee = SimpleCoffee.new
@coffee_decorator = CoffeeDecorator.new @coffee
end
describe "#new" do
it "returns a CoffeeDecorator object" do
@coffee_decorator.should be_an_instance_of CoffeeDecorator
end
end
describe "#get_cost" do
it "returns the decorated coffee cost" do
end
end
end
describe Milk do
before :each do
@coffee = SimpleCoffee.new
@milk = Milk.new(@coffee)
end
describe "#new" do
it "returns a Milk object" do
@milk.should be_an_instance_of Milk
end
end
describe "#get_cost" do
it "returns cost" do
@milk.get_cost().should == @coffee.get_cost() + 1
end
end
end
describe Sugar do
before :each do
@coffee = SimpleCoffee.new
@sugar = Sugar.new(@coffee)
end
describe "#new" do
it "returns a Sugar object" do
@sugar.should be_an_instance_of Sugar
end
end
describe "#get_cost" do
it "returns cost" do
@sugar.get_cost().should == @coffee.get_cost() + 1
end
end
end |
class Rooms::AlertsController < AlertsController
before_action :set_alertable
private
def set_alertable
@alertable = Room.find(params[:room_id])
end
end
|
class FitnessGoal < ApplicationRecord
has_many :members
validates_presence_of :goal_name
def self.options_for_select
order('LOWER(goal_name)').map { |e| [e.goal_name, e.id]}
end
end
|
require 'test_helper'
class SentinelTest < ActiveSupport::TestCase
context "When assigning attributes" do
setup do
@sentinel = Sentinel::Sentinel
end
should "create attr_accessor's for each valid key" do
sentinel = @sentinel.new(:user => {:name => "John", :active => true}, :forum => {:name => "My Forum"})
assert_equal({:name => "John", :active => true}, sentinel.user)
assert_equal({:name => "My Forum"}, sentinel.forum)
sentinel.user = sentinel.forum = nil
assert_nil sentinel.user
assert_nil sentinel.forum
end
should "not create attr_accessors for methods that already exist" do
sentinel = @sentinel.new(:class => "fake", :to_s => "one", :user => "real")
assert_equal sentinel.user, "real"
assert_equal sentinel.class, Sentinel::Sentinel
assert_not_equal sentinel.to_s, "one"
end
should "reassign predefined attribute values if set" do
@sentinel.attr_accessor_with_default :message, "simple message"
assert_equal "simple message", @sentinel.new.message
assert_equal "complex message", @sentinel.new(:message => "complex message").message
end
end
context "When overriding attributes" do
setup do
@sentinel = Sentinel::Sentinel
end
should "only override for that specific instance" do
sentinel = @sentinel.new(:user => "assigned", :forum => nil)
assert_equal "assigned", sentinel.user
assert_nil sentinel.forum
assert_nil sentinel[:user => nil].user
assert_equal "forum", sentinel[:forum => "forum"].forum
end
should "define an attr_accessor if the attribute doesn't exist" do
sentinel = @sentinel.new
assert_raise NoMethodError do
sentinel.name
end
assert_equal "taken", sentinel[:name => "taken"].name
assert_nil sentinel.name
end
end
end
|
class CreateTagMovements < ActiveRecord::Migration
def change
create_table :tag_movements do |t|
t.float :credit
t.integer :tag_id
t.timestamps
end
end
end |
require_relative './mocks/telldus-mock/lib/telldus_state'
require 'rbtelldus'
shared_examples 'a controll function' do |args|
method = args[:method]
argument = args[:arg]
let(:id) { 1 }
let!(:state) { TelldusSwitchState.new id: 1 }
subject { described_class.send(method, id, *argument) }
context 'device is configured' do
let!(:id) { 1 }
context "and supports .#{method}" do
it { expect(subject).to eq(Telldus::SUCCESS) }
it { expect_to_change }
end
context "and does not support .#{method}" do
let!(:state) { TelldusSwitchState.new id: 1, supported_methods: 0 }
it { expect(subject).to eq(Telldus::METHOD_NOT_SUPPORTED) }
end
end
context 'device is not configured' do
let(:id) { 2 }
it { expect(subject).to eq(Telldus::NOT_FOUND) }
end
end
describe Telldus do
before(:each) { TelldusState.clear }
describe '.on' do
it_behaves_like 'a controll function', method: :on do
let(:expect_to_change) { expect{subject}.to change{state.on}.to(true) }
end
end
describe '.off' do
it_behaves_like 'a controll function', method: :off do
let!(:state) { TelldusSwitchState.new id: 1, on: true }
let(:expect_to_change) { expect{subject}.to change{state.on}.to(false) }
end
end
describe '.dim' do
it_behaves_like 'a controll function', method: :dim, arg:25 do
let(:expect_to_change) { expect{subject}.to change{state.dim}.to(25) }
end
end
describe '.learn' do
it_behaves_like 'a controll function', method: :learn do
let(:expect_to_change) { expect{subject}.to change{state.learning}.to(true) }
end
end
describe '.getName' do
subject { Telldus.getName(id) }
context 'when device is configured' do
let(:id) { 1 }
let!(:device) { TelldusSwitchState.new id: id, name: 'Kitchen' }
it { expect(subject).to eq('Kitchen') }
end
context "when device is not configured" do
let(:id) { 1 }
it { expect(subject).to eq('') }
end
end
describe '.setName' do
let(:name) { 'Living room' }
subject { Telldus.setName(id, name) }
context 'when device is configured' do
let(:id) { 1 }
let!(:device) { TelldusSwitchState.new id: id, name: 'Kitchen' }
it { expect(subject).to eq(true) }
it { expect{subject}.to change{device.name}.from('Kitchen').to(name) }
end
context 'when device is unconfigured' do
let(:id) { 1 }
it { expect(subject).to eq(false) }
end
end
describe '.lastCommand' do
let(:id) { 1 }
let(:mask) { Telldus::TURNON | Telldus::TURNOFF }
subject { Telldus.lastCommand(id, mask) }
context 'when client support last command' do
let!(:device) { TelldusSwitchState.new id: id, last_command: Telldus::TURNON }
it { expect(subject).to eq(Telldus::TURNON) }
end
context "when client does not support last command" do
let!(:device) { TelldusSwitchState.new id: id, last_command: Telldus::DIM }
it { expect(subject).to eq(0) }
end
end
describe '.lastValue' do
let(:last_value) { 128 }
let(:id) { 1 }
let!(:device) { TelldusSwitchState.new id: id, dim: last_value }
subject { Telldus.lastValue(id) }
it { expect(subject).to eq(last_value) }
end
describe '.create' do
let(:new_id) { 1 }
subject { Telldus.create }
it { expect(subject).to eq(new_id) }
it { expect{subject}.to change{TelldusState.has_key?(new_id)}.from(false).to(true) }
end
describe '.remove' do
let(:id) { 1 }
subject { Telldus.remove id }
context 'when device is configured' do
let!(:device) { TelldusSwitchState.new id: id }
it { expect(subject).to eq(true) }
it { expect{subject}.to change{TelldusState.has_key?(id)}.from(true).to(false) }
end
context 'when device is not configured' do
it { expect(subject).to eq(false) }
end
end
describe '.getParam' do
let(:id) { 1 }
let(:name) { 'house' }
let(:value) { 'A' }
subject { Telldus.getParam id, name, 'default' }
context 'when parameter is set' do
let!(:device) { TelldusSwitchState.new id: id, params: { name => value } }
it { expect(subject).to eq(value) }
end
context 'when parameter is not set' do
let!(:device) { TelldusSwitchState.new id: id }
it { expect(subject).to eq('default') }
end
end
describe '.setParam' do
let!(:id) { 1 }
let(:name) { 'house' }
let(:value) { 'A' }
let!(:device) { TelldusSwitchState.new id: id }
subject { Telldus.setParam id, name, value }
it { expect(subject).to eq(true) }
it { expect{subject}.to change{device.params.has_key?(name)}.to(true) }
end
describe '.setModel' do
let(:id) { 1 }
let(:model) { 'codeswitch' }
let!(:device) { TelldusSwitchState.new id: id }
subject { Telldus.setModel(id, model) }
it { expect(subject).to eq(true) }
it { expect{subject}.to change{device.model}.to(model) }
end
describe '.getModel' do
let(:id) { 1 }
let(:model) { 'codeswitch' }
let!(:device) { TelldusSwitchState.new id: id, model: model }
subject { Telldus.getModel(id) }
it { expect(subject).to eq(model) }
end
describe '.getIds' do
subject { Telldus.getIds }
let!(:state1) { TelldusSwitchState.new }
let!(:state2) { TelldusSwitchState.new }
let!(:state3) { TelldusSwitchState.new }
it { expect(subject).to eq([1, 2, 3]) }
end
end
|
# Use these two arrays to generate a deck of cards.
ranks = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K" ]
ranks.rotate!(1)
suits = [ "hearts", "spades", "clubs", "diamonds" ]
players = []
deck = ranks.product(suits) # creating combined deck
shuff_deck = deck.shuffle # creating shuffled deck
player = nil
# I need to get an input from user
while player != 'play'
n = players.length
puts "#{n} players so far. Enter a player name, or type 'play':"
player = gets.chomp
# while checking to see if the input is 'play'
if player != 'play'
players.push({name: player})
end
end
# Start The Game!
puts "#{n} players are playing"
# Each player is given a random card (pushed to their hash)
players.each do |player|
player[:card] = shuff_deck.pop
end
puts "#{players}"
# Cards are then evaluated to see which is highest
# go through players find highest
# select player with highest card
# for each rank in rank.reverse_each
# winners empty array
# for each player in players
# if player card = rank
# winners << player
#
# if winners length > 0
# break
# is it a tie
# if winner length does not equal 1
# print tie between...
# redraw cards
# print winner
player_cards = players.map do |player|
ranks.index(player[:card][0])
end
puts player_cards
high_card = player_cards.max
puts high_card
winner = players.select { |player| player[:card][0] == ranks[high_card]}
puts winner
|
require 'httparty'
require 'singleton'
class MarkusRESTfulAPI
# Stores the api_url and auth_key for later use
def MarkusRESTfulAPI.configure(api_url, auth_key)
@@auth_key = auth_key
api_url = "#{api_url}/" if api_url[-1, 1] != '/'
@@api_url = api_url
end
# Makes a GET request to the provided URL while supplying the authorization
# header, and raising an exception on failure
def MarkusRESTfulAPI.get(url)
response = HTTParty.get(@@api_url + url, :headers =>
{ 'Authorization' => "MarkUsAuth #{@@auth_key}" })
raise response['rsp']['__content__'] unless response.success?
response
end
# Makes a POST request to the provided URL, along with the supplied POST data.
# Also uses the authorization header, and raises an exception on failure
def MarkusRESTfulAPI.post(url, query)
options = { :headers => { 'Authorization' => "MarkUsAuth #{@@auth_key}" },
:body => query }
response = HTTParty.post(@@api_url + url, options)
raise response['rsp']['__content__'] unless response.success?
response
end
# Makes a PUT request to the provided URL, along with the supplied data.
# Also uses the authorization header, and raises an exception on failure
def MarkusRESTfulAPI.put(url, query)
options = { :headers => { 'Authorization' => "MarkUsAuth #{@@auth_key}" },
:body => query }
response = HTTParty.put(@@api_url + url, options)
raise response['rsp']['__content__'] unless response.success?
response
end
# Makes a DELETE request to the provided URL while supplying the authorization
# header, and raising an exception on failure
def MarkusRESTfulAPI.delete(url)
response = HTTParty.delete(@@api_url + url, :headers =>
{ 'Authorization' => "MarkUsAuth #{@@auth_key}" })
puts response
raise response['rsp']['__content__'] unless response.success?
response
end
# A singleton that allows us to get and update user(s)
class Users < MarkusRESTfulAPI
include Singleton
def self.get_by_user_name(user_name)
self.get("users.json?filter=user_name:#{user_name}")['users']['user']
end
def self.get_by_id(id)
self.get("users/#{id}.json")['users']
end
def self.get_all_by_first_name(first_name)
self.get("users.json?filter=first_name:#{first_name}")['users']['user']
end
def self.get_all_admins()
self.get('users.json?filter=type:admin')['users']['user']
end
def self.get_all_tas()
self.get('users.json?filter=type:ta')['users']['user']
end
def self.get_all_students()
self.get('users.json?filter=type:student')['users']['user']
end
def self.create(attributes)
url = 'users.json'
response = self.post(url, attributes)
self.get_by_user_name(attributes['user_name'])
end
def self.update(id, attributes)
attributes.delete('id')
url = "users/#{id}.json"
Users.put(url, attributes)
return
end
end # Users
end # MarkusRESTfulAPI
|
class Followship < ActiveRecord::Base
belongs_to :follower, class_name:"User", foreign_key:"user_id"
belongs_to :following, class_name:"User", foreign_key:"following_user_id"
end
|
require 'ddtrace/monkey'
require 'ddtrace/pin'
require 'ddtrace/tracer'
require 'ddtrace/error'
require 'ddtrace/pipeline'
# \Datadog global namespace that includes all tracing functionality for Tracer and Span classes.
module Datadog
@tracer = Datadog::Tracer.new()
# Default tracer that can be used as soon as +ddtrace+ is required:
#
# require 'ddtrace'
#
# span = Datadog.tracer.trace('web.request')
# span.finish()
#
# If you want to override the default tracer, the recommended way
# is to "pin" your own tracer onto your traced component:
#
# tracer = Datadog::Tracer.new
# pin = Datadog::Pin.get_from(mypatchcomponent)
# pin.tracer = tracer
def self.tracer
@tracer
end
end
# Datadog auto instrumentation for frameworks
if defined?(Rails::VERSION)
if !ENV['DISABLE_DATADOG_RAILS']
if Rails::VERSION::MAJOR.to_i >= 3
require 'ddtrace/contrib/rails/framework'
require 'ddtrace/contrib/rails/middlewares'
module Datadog
# Railtie class initializes
class Railtie < Rails::Railtie
# add instrumentation middlewares
options = {}
config.app_middleware.insert_before(0, Datadog::Contrib::Rack::TraceMiddleware, options)
config.app_middleware.use(Datadog::Contrib::Rails::ExceptionMiddleware)
# auto instrument Rails and third party components after
# the framework initialization
config.after_initialize do |app|
Datadog::Contrib::Rails::Framework.configure(config: app.config)
Datadog::Contrib::Rails::Framework.auto_instrument()
Datadog::Contrib::Rails::Framework.auto_instrument_redis()
Datadog::Contrib::Rails::Framework.auto_instrument_grape()
# override Rack Middleware configurations with Rails
options.update(::Rails.configuration.datadog_trace)
end
end
end
else
Datadog::Tracer.log.warn 'Detected a Rails version < 3.x.'\
'This version is not supported yet and the'\
'auto-instrumentation for core components will be disabled.'
end
else
Datadog::Tracer.log.info 'Skipping Rails auto-instrumentation, DISABLE_DATADOG_RAILS is set.'
end
end
|
# Defines the core upload and view TracksAPIs.
module Commuting
class StoplightAPI < Grape::API
version "v1", vendor: "g9labs"
format :json
helpers do
params :pagination do
optional :page, type: Integer
optional :per_page, type: Integer
end
end
namespace :commuting do
resource :stoplights do
desc "See all stoplight metrics"
params do
use :pagination
end
get do
Commuting::StopEventCluster.page(params[:page]).per(params[:per_page])
end
end
resource :geojson do
desc "See all stoplights, in GeoJSON format"
params do
use :pagination
end
get do
clusters = Commuting::StopEventCluster.query.page(params[:page]).per(params[:per_page])
StoplightFeatureCollection.new(clusters).wrap
end
end
resource :circle_geojson do
desc "See all stoplight circle geometries, in GeoJSON format"
params do
use :pagination
end
get do
clusters = Commuting::StopEventCluster.query.page(params[:page]).per(params[:per_page])
StoplightFeatureCollection.new(clusters).wrap_circles
end
end
end
end
end
|
ActiveAdmin.register Contact do
action_item :only => :show do
link_to('Add New', new_admin_contact_path)
end
action_item :only => [:new, :edit, :show] do
link_to('Back to Index', admin_contacts_path)
end
index do
selectable_column
column :id
column :full_name
column :email
column :phone
column :content do |post|
raw truncate(post.content, omision: "...", length: 50)
end
actions
end
show do
attributes_table :full_name, :phone, :email do
row :content do |cont|
raw cont.content
end
end
end
end
|
describe do
attr :title, 'Journal'
content file('views/article.html.erb')
end
act do
@notes = recent_articles
end
|
require File.dirname(__FILE__) + '/../test_helper'
class AdUnitsTest < ActiveSupport::TestCase
def test_cant_execute
assert_raise(AdUnits::InvalidDslInput) do
AdUnits::execute_viewpoints_ad_unit nil
end
assert_raise(AdUnits::InvalidDslInput) do
AdUnits::execute_viewpoints_ad_unit ''
end
assert_raise(AdUnits::InvalidDslInput) do
AdUnits::execute_viewpoints_ad_unit 'asdfasd'
end
end
def test_can_execute
AdUnits::execute_viewpoints_ad_unit 'viewpoints_ad_unit'
end
# FIXME/flunk: "cache_for" and "override" no longer work.
def test_full_crosslink_dsl
dsl = <<-DSL
viewpoints_ad_unit {
# cache_for 30.days
crosslink_ad_unit {
link_type competitive
show 4
headline "Most Helpful Reviews"
# override 1, "/foo-review-asdf", "Jo’s foo review"
# override 2, "/search?q=foo", "Search for all foo reviews"
category "Electronics"
}
}
DSL
ad = AdUnits::execute_viewpoints_ad_unit dsl
assert ad
assert_equal AdUnits::ViewpointsAdUnit, ad.class
# FIXME see above
# assert_equal 30.days, ad.cache_for
units = ad.sub_units
assert units
assert_equal 1, units.length
unit = units.first
assert unit
assert_equal AdUnits::CrosslinkAdUnit, unit.class
assert_equal :competitive, unit.link_type
assert_equal 4, unit.show
assert_equal 'Most Helpful Reviews', unit.headline
assert_equal 'Electronics', unit.category
# FIXME see above
# overrides = unit.overrides
# assert overrides
# assert_equal 2, overrides.size
end
end
|
require 'rails_helper'
RSpec.describe Bookmark, type: :model do
describe 'validations' do
it { should validate_presence_of(:url) }
end
describe 'relations' do
it { should belong_to(:user) }
#it { should have_one_attached(:screenshot) } come back to this one!!!
it { should have_and_belong_to_many(:tags) }
end
describe '.search' do
# let!(:valid_user) {
# User.create(name: "test", email: "test@test.com", password: "testing")
# }
# let!(:bookmarks) do
# [
# Bookmark.create(title: 'i love dogs', url: 'url.com', user: valid_user),
# Bookmark.create(title: 'dogs are great', url: 'url.com', user: valid_user)
# ]
before do
@valid_user = User.create(name: "test", email: "test@test.com", password: "testing")
@bookmarks = [
Bookmark.create(title: 'i love dogs', url: 'url.com', user: @valid_user),
Bookmark.create(title: 'dogs are great', url: 'url.com', user: @valid_user)
]
end
it 'should match all bookmarks with dogs in title' do
expect(Bookmark.search('dogs')).to match_array(@bookmarks)
end
end
end
|
class Notifier < ActionMailer::Base
def register_notification(recipient)
recipients recipient.email_address_with_name
from "i@soulup.net"
subject "Вы успешно зарегистрировались на сайте soulup.net"
body :account => recipient
content_type "text/html"
end
def activation_notification(recipient)
recipients recipient.email_address_with_name
from "i@soulup.net"
subject "Активация аккаунта на сайте soulup.net"
body :account => recipient
content_type "text/html"
end
end
|
json.array!(@line_services) do |line_service|
json.extract! line_service, :id, :service_id, :cart_id
json.url line_service_url(line_service, format: :json)
end
|
class ConnectCallToVoicemail
def initialize(incoming_call:, adapter: TwilioAdapter.new)
@incoming_call = incoming_call
@adapter = adapter
end
def call
if connect_to_voicemail(incoming_call.from_sid)
Result.success
else
Result.failure("Could not connect call to voicemail")
end
end
private
attr_reader :incoming_call, :adapter
def connect_to_voicemail(sid)
adapter.update_call(
sid: sid,
method: "GET",
url: RouteHelper.voicemail_create_url(incoming_call)
)
end
end
|
require_relative '../rails_helper'
describe SectionsController do
login_admin
describe "GET #index" do
it "populates an array of sections" do
section = create(:section)
get :index
expect(assigns(:sections)).to match_array([section])
end
it "renders the :index view" do
get :index
expect(response).to render_template :index
end
end
describe "GET #show" do
it "assigns the requested section to @section" do
section = create(:section)
get :show, id: section
expect(assigns(:section)).to eq(section)
end
it "renders the :show template" do
get :show, id: create(:section)
expect(response).to render_template :show
end
end
describe "GET #new" do
it "assigns a new Section to @section" do
get :new
expect(assigns(:section)).to be_a_new(Section)
end
it "renders the :new template" do
get :new
expect(response).to render_template :new
end
end
describe "GET #edit" do
it "assigns the requested section to @section" do
section = create(:section)
get :edit, id: section
expect(assigns(:section)).to eq(section)
end
it "renders the :edit template" do
get :edit, id: create(:section)
expect(response).to render_template :edit
end
end
describe "POST #create" do
context "with valid attributes" do
it "saves the new section in the database" do
expect { post :create, section: attributes_for(:section) }.to change(Section, :count).by(1)
end
end
end
describe 'PUT update' do
before :each do
@section = create(:section)
end
context "with valid attributes" do
it "locates the requested @section" do
put :update, id: @section, section: attributes_for(:section)
expect(assigns(:section)).to eq(@section)
end
it "changes the section's attributes" do
expect(@section.name).to_not eq("updated name")
put :update, id: @section, section: attributes_for(:section, name: "updated name")
@section.reload
expect(@section.name).to eq("updated name")
end
it "redirects to the updated section" do
put :update, id: @section, section: attributes_for(:section)
expect(response).to redirect_to @section
end
end
end
end
|
class ChangeColumnsNoAdmin < ActiveRecord::Migration
def change
remove_column :users, :admin_id
end
end
|
require 'rails_helper'
describe StructureFieldPresenter do
let(:audit_structure) { instance_double(AuditStructure) }
describe '#partial' do
it 'returns the corresponding partial name for field types' do
audit_field = instance_double(AuditField, value_type: 'switch')
presenter = described_class.new(audit_structure, audit_field)
expect(presenter.partial).to eq 'checkbox_field'
end
it 'returns text_input for unknown field types' do
audit_field = instance_double(AuditField, value_type: 'spam')
presenter = described_class.new(audit_structure, audit_field)
expect(presenter.partial).to eq 'text_input_field'
end
end
describe '#value' do
let(:audit_field) { instance_double(AuditField) }
it 'returns nil if field_value is not nil' do
presenter = described_class.new(audit_structure, audit_field)
expect(presenter.audit_field_value).to eq nil
end
it 'returns the field_value if it has one' do
audit_field_value = instance_double(AuditFieldValue, value: :foo)
presenter = described_class.new(audit_structure, audit_field, audit_field_value)
expect(presenter.audit_field_value).to eq :foo
end
end
end
|
#ExStart:
require 'aspose_email_cloud'
class Attachment
include AsposeEmailCloud
include AsposeStorageCloud
def initialize
#Get App key and App SID from https://cloud.aspose.com
AsposeApp.app_key_and_sid("", "")
@email_api = EmailApi.new
end
def upload_file(file_name)
@storage_api = StorageApi.new
response = @storage_api.put_create(file_name, File.open("../../../data/" << file_name,"r") { |io| io.read } )
end
# Get email attachment by name.
def get_email_attachment_by_name
file_name = "email_test2.eml"
upload_file(file_name)
attach_name = "README.TXT"
response = @email_api.get_email_attachment(file_name, attach_name)
end
end
attachment = Attachment.new()
puts attachment.get_email_attachment
#ExEnd: |
# frozen_string_literal: true
Given("there is a reference") do
create :any_reference, :with_author_name
end
Given("there is an article reference") do
create :article_reference, :with_author_name
end
Given("there is a book reference") do
create :book_reference, :with_author_name
end
Given(/^(?:this reference exists|these references exist)$/) do |table|
table.hashes.each do |hsh|
if (author_name_name = hsh.delete('author'))
author_name = ReferenceStepsHelpers.find_or_create_author_name(author_name_name)
hsh[:author_names] = [author_name]
end
create :any_reference, hsh
end
end
Given("this article reference exists") do |table|
hsh = table.hashes.first
if (author_name_name = hsh.delete('author'))
author_name = ReferenceStepsHelpers.find_or_create_author_name(author_name_name)
hsh[:author_names] = [author_name]
end
if (journal_name = hsh.delete('journal'))
journal = Journal.find_by(name: journal_name) || create(:journal, name: journal_name)
hsh[:journal] = journal
end
create :article_reference, hsh
end
Given("the following entry nests it") do |table|
hsh = table.hashes.first
create :nested_reference,
title: hsh[:title],
author_string: hsh[:author],
year: hsh[:year],
year_suffix: hsh[:year_suffix],
pagination: hsh[:pagination],
nesting_reference: Reference.last
end
When("I select the reference tab {string}") do |tab_css_selector|
find(tab_css_selector, visible: false).click
end
When('I fill in "reference_nesting_reference_id" with the ID for {string}') do |title|
reference = Reference.find_by!(title: title)
step %(I fill in "reference_nesting_reference_id" with "#{reference.id}")
end
Given("the default reference is {string}") do |key_with_year|
reference = ReferenceStepsHelpers.find_reference_by_key(key_with_year)
References::DefaultReference.stub(:get).and_return(reference)
end
Then("nesting_reference_id should contain a valid reference id") do
id = find("#reference_nesting_reference_id").value
expect(Reference.exists?(id)).to eq true
end
Given("there is a reference referenced in a history item") do
reference = create :any_reference
create :history_item, :taxt, taxt: Taxt.ref(reference.id)
end
|
class Links::Misc::ScMatchups < Links::Base
def site_name
"Sporting Charts"
end
def description
"Matchups"
end
def url
"http://www.sportingcharts.com/nhl/rivalrylisting/"
end
def group
5
end
def position
3
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'rubberband-audio'
describe RubberBand::Options do
describe "basic" do
it "should use quite" do
RubberBand::Options.new.to_s.should =~ /-q/
end
end
describe "configurable parameters" do
it "should support time" do
o = RubberBand::Options.new(:time => "360")
o.to_s.should =~ /--time 360/
end
it "should support tempo" do
o = RubberBand::Options.new(:tempo => 360)
o.to_s.should =~ /--tempo 360/
end
it "should support duration" do
o = RubberBand::Options.new(:duration => 200)
o.to_s.should =~ /--duration 200/
end
it "should support pitch" do
o = RubberBand::Options.new(:pitch => 4)
o.to_s.should =~ /--pitch 4/
end
it "should support frequency" do
o = RubberBand::Options.new(:frequency => 4)
o.to_s.should =~ /--frequency 4/
end
it "should support timemap" do
o = RubberBand::Options.new(:timemap => "/tmp/file0123")
o.to_s.should =~ %r{--timemap "/tmp/file0123"}
end
context "should support crispness" do
it "should accept crisp params" do
o = RubberBand::Options.new(:crisp => 5)
o.to_s.should =~ %r{--crisp 5}
end
end
RubberBand::Options::BINARY_OPTIONS.each do |name|
it "should support #{name} mode" do
o = RubberBand::Options.new(name.to_sym => true)
o.to_s.should =~ /--#{name}/
o = RubberBand::Options.new(name.to_sym => false)
o.to_s.should_not =~ /--#{name}/
end
end
end
end
|
Rails.application.routes.draw do
mount Ckeditor::Engine => '/ckeditor'
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
root 'static_pages#home'
devise_for :trainees, :skip => [:registrations]
devise_for :trainers, :skip => [:registrations]
namespace :trainee do
resources :courses, only:[:show] do
resources :subjects, only:[:index, :show, :update]
end
end
namespace :trainer do
resources :courses do
resources :subjects
resources :assign_trainees
resources :assign_trainers
resources :course_subjects
resource :finish_course, only:[:update]
end
end
namespace :constructor do
resources :subjects
end
end
|
module SNMPTableViewer
# Formatting class for CSV output.
class Formatter::CSV < Formatter
# Output the data (and headings if provided).
# @return [String] the CSV data
def output()
data_with_headings.map(&:to_csv).join
end
end # CSV Formatter
end # module SNMPTableViewer
|
#==============================================================================
# +++ MOG - Picture Effects (v1.0) +++
#==============================================================================
# By Moghunter
# https://atelierrgss.wordpress.com/
#==============================================================================
# O script adicina novos efeitos na função mostrar imagem, possibilitando
# criar animações complexas de maneira simples e rápida.
# O script também adiciona a função definir a posição da imagem baseado
# na posição do character ou na posição real XY da tela.
#==============================================================================
# EFEITOS
#==============================================================================
# 0 - Tremer Tipo A
# 1 - Tremer Tipo B
# 2 - Efeito de Respirar
# 3 - Efeito de Auto Zoom (Loop)
# 4 - Efeito de Fade (Loop)
# 5 - Efeito de Rolar em duas direções.
# 6 - Efeito de Wave.
# 7 - Efeito de Animação por frames, estilo GIF.
#
# É possível utilizar todos os efeitos ao mesmo tempo.
#
#==============================================================================
# UTILIZAÇÃO
#==============================================================================
# Use o comando abaixo através do comando evento.
#
# picture_effect(PICTURE_ID ,EFFECT_TYPE ,POWER , SPEED)
#
# PICTURE_ID = ID da imagem.
# EFFECT TYPE = Tipo de efetio da imagem. (0 a 7)
# POWER = Poder do efeito.
# SPEED = Velocidade do efeito.
#
# Exemplo
#
# picture_effect(1,5,10,50)
#
#==============================================================================
# Efeito de animação por frames. (Efeito tipo 7)
#==============================================================================
# Para ativar o efeito de animação por frames é necessário ter e nomear os
# arquivos da seguinte forma.
#
# Picture_Name.png (A imagem que deve ser escolhida no comando do evento.)
# Picture_Name0.png
# Picture_Name1.png
# Picture_Name2.png
# Picture_Name3.png
# Picture_Name4.png
# ...
#
#==============================================================================
# Posições Especiais para as imagens
#==============================================================================
# Use o comando abaixo para definir a posiçao da imagem.
#
# picture_position(PICTURE ID, TARGET ID)
#
# PICTURE ID = ID da imagem
# TARGET ID = ID do alvo
#
# 0 = Posição normal.
# 1..999 = Posição do evento (ID).
# -1 = Posição do player.
# -2 = Posição fixa da imagem.
#
#==============================================================================
# Cancelar o Efeito
#==============================================================================
# Você pode usar o comando apagar imagem do evento, ou usar o comando abaixo.
#
# picture_effects_clear(PICTURE_ID)
#
#==============================================================================
module MOG_PICURE_EFFECTS
# Definição da posição Z das pictures.
# É possível usar o comando "set_picture_z(value)" para mudar o valor Z
# no meio do jogo
DEFAULT_SCREEN_Z = 100
end
$imported = {} if $imported.nil?
$imported[:mog_picture_effects] = true
#==============================================================================
# ■ Game Picture
#==============================================================================
class Game_Picture
attr_accessor :effect_ex
attr_accessor :anime_frames
attr_accessor :position
#--------------------------------------------------------------------------
# ● Init Basic
#--------------------------------------------------------------------------
alias mog_picture_ex_init_basic init_basic
def init_basic
init_effect_ex
mog_picture_ex_init_basic
end
#--------------------------------------------------------------------------
# ● Erase
#--------------------------------------------------------------------------
alias mog_picture_ex_erase erase
def erase
init_effect_ex
mog_picture_ex_erase
end
#--------------------------------------------------------------------------
# ● Init Effect EX
#--------------------------------------------------------------------------
def init_effect_ex
@effect_ex = [] ; @anime_frames = [] ; @position = [0,nil,0,0]
end
end
#==============================================================================
# ■ Game System
#==============================================================================
class Game_System
attr_accessor :picture_screen_z
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
alias mog_picture_ex_initialize initialize
def initialize
@picture_screen_z = MOG_PICURE_EFFECTS::DEFAULT_SCREEN_Z
mog_picture_ex_initialize
end
end
#==============================================================================
# ■ Game Interpreter
#==============================================================================
class Game_Interpreter
#--------------------------------------------------------------------------
# ● Set Pictures
#--------------------------------------------------------------------------
def set_pictures
return $game_troop.screen.pictures if SceneManager.scene_is?(Scene_Battle)
return $game_map.screen.pictures if SceneManager.scene_is?(Scene_Map)
end
#--------------------------------------------------------------------------
# ● Picture Effect
#--------------------------------------------------------------------------
def picture_effect(id,type, power = nil,speed = nil,misc = nil)
pictures = set_pictures
return if pictures.nil?
power = set_standard_power(type) if power == nil
power = 1 if type == 4 and power < 1
speed = set_standard_speed(type) if speed == nil
pictures[id].effect_ex[0] = nil if type == 1
pictures[id].effect_ex[1] = nil if type == 0
pictures[id].effect_ex[type] = [power,speed,0]
pictures[id].effect_ex[type] = [0,0,0,power * 0.00005,speed, 0,0] if [2,3].include?(type)
pictures[id].effect_ex[type] = [255,0,0,255 / power, power,speed,0] if type == 4
pictures[id].effect_ex[type] = [0,0,power,speed,0] if type == 5
pictures[id].effect_ex[type] = [true,power * 10,speed * 100] if type == 6
pictures[id].anime_frames = [true,[],power,0,0,speed,0] if type == 7
end
#--------------------------------------------------------------------------
# ● Set Standard Power
#--------------------------------------------------------------------------
def set_standard_power(type)
return 6 if type == 2
return 30 if type == 3
return 120 if type == 4
return 10
end
#--------------------------------------------------------------------------
# ● Set Standard Speed
#--------------------------------------------------------------------------
def set_standard_speed(type)
return 3 if [0,1].include?(type)
return 0 if [2,3,4].include?(type)
return 2 if type == 5
return 0 if type == 7
return 10
end
#--------------------------------------------------------------------------
# ● Picture Position
#--------------------------------------------------------------------------
def picture_position(id,target_id)
pictures = set_pictures
return if pictures.nil?
pictures[id].position = [0,nil,0,0] if [-2,0].include?(pictures[id].position[0])
pictures[id].effect_ex.clear
target = 0 ; target = $game_player if target_id == -1
if target_id > 0
$game_map.events.values.each do |e| target = e if e.id == target_id end
end
pictures[id].position[0] = target_id
pictures[id].position[1] = target
end
#--------------------------------------------------------------------------
# ● Set Picture Z
#--------------------------------------------------------------------------
def set_picture_z(value)
$game_system.picture_screen_z = value
end
#--------------------------------------------------------------------------
# ● Picture Effects Clear
#--------------------------------------------------------------------------
def picture_effects_clear(id)
pictures = set_pictures
return if pictures.nil?
pictures[id].effect_ex.clear ; pictures[id].anime_frames.clear
pictures[id].position = [0,nil,0,0]
end
end
#==============================================================================
# ■ Game Map
#==============================================================================
class Game_Map
#--------------------------------------------------------------------------
# ● Setup
#--------------------------------------------------------------------------
alias mog_picture_ex_setup setup
def setup(map_id)
mog_picture_ex_setup(map_id)
clear_picture_position rescue nil
end
#--------------------------------------------------------------------------
# ● Clear Picture Position
#--------------------------------------------------------------------------
def clear_picture_position
pictures = $game_troop.screen.pictures if SceneManager.scene_is?(Scene_Battle)
pictures = $game_map.screen.pictures if SceneManager.scene_is?(Scene_Map)
return if pictures == nil
pictures.each {|p|
p.position = [-1000,nil,0,0] if p.position[0] > 0 or p.position[1] == nil}
end
end
#==============================================================================
# ■ Sprite Picture
#==============================================================================
class Sprite_Picture < Sprite
#--------------------------------------------------------------------------
# ● Dispose
#--------------------------------------------------------------------------
alias mog_picture_ex_dispose dispose
def dispose
mog_picture_ex_dispose
@picture.effect_ex[6][0] = true if @picture.effect_ex[6]
@picture.anime_frames[0] = true if @picture.effect_ex[7]
dispose_pic_frames if !@picture.effect_ex[7]
end
#--------------------------------------------------------------------------
# ● Dispose Pic Frames
#--------------------------------------------------------------------------
def dispose_pic_frames
return if @pic_frames.nil?
@pic_frames.each {|picture| picture.dispose } ; @pic_frames = nil
end
#--------------------------------------------------------------------------
# ● Update Bitmap
#--------------------------------------------------------------------------
alias mog_picture_ex_update_bitmap update_bitmap
def update_bitmap
refresh_effect_ex if @old_name_ex != @picture.name
if !@picture.anime_frames.empty? and self.bitmap
update_picture_animation ; return
end
mog_picture_ex_update_bitmap
create_picture_animation if can_create_frame_picture?
set_wave_effect if can_set_wave_effect?
end
#--------------------------------------------------------------------------
# ● Refresh effect EX
#--------------------------------------------------------------------------
def refresh_effect_ex
(self.wave_amp = 0 ; self.wave_length = 1 ; self.wave_speed = 0) if !@picture.effect_ex[6]
@old_name_ex = @picture.name
create_picture_animation if @picture.effect_ex[7]
set_wave_effect if can_set_wave_effect?
end
#--------------------------------------------------------------------------
# ● Can Create Frame Picture
#--------------------------------------------------------------------------
def can_create_frame_picture?
return false if !@picture.anime_frames[0]
return false if !self.bitmap
return true
end
#--------------------------------------------------------------------------
# ● Update Picture Animation
#--------------------------------------------------------------------------
def update_picture_animation
return if @pic_frames == nil
if @picture.anime_frames[6] > 0 ; @picture.anime_frames[6] -= 1 ; return
end
@picture.anime_frames[4] += 1
return if @picture.anime_frames[4] < @picture.anime_frames[2]
self.bitmap = @pic_frames[@picture.anime_frames[3]]
@picture.anime_frames[4] = 0 ; @picture.anime_frames[3] += 1
if @picture.anime_frames[3] >= @pic_frames.size
@picture.anime_frames[3] = 0 ; @picture.anime_frames[6] = @picture.anime_frames[5]
end
end
#--------------------------------------------------------------------------
# ● Create Picture Animation
#--------------------------------------------------------------------------
def create_picture_animation
dispose_pic_frames ; @pic_frames = [] ; @picture.anime_frames[0] = false
for index in 0...999
@pic_frames.push(Cache.picture(@picture.name + index.to_s)) rescue nil
break if @pic_frames[index] == nil
end
if @pic_frames.size <= 1
dispose_pic_frames ; @pic_frames = nil ; @picture.anime_frames.clear
@picture.effect_ex[7] = nil ; return
end
self.bitmap = @pic_frames[@picture.anime_frames[3]]
update_picture_animation
end
#--------------------------------------------------------------------------
# ● Update Position
#--------------------------------------------------------------------------
def update_position
self.z = @picture.number + $game_system.picture_screen_z
if @picture.effect_ex[0] ; update_shake_effect(0) ; return ; end
if @picture.effect_ex[1] ; update_shake_effect(1) ; return ; end
self.x = pos_x ; self.y = pos_y ; set_oxy_correction
end
#--------------------------------------------------------------------------
# ● Pos X
#--------------------------------------------------------------------------
def pos_x
return @picture.x
end
#--------------------------------------------------------------------------
# ● Pos Y
#--------------------------------------------------------------------------
def pos_y
return @picture.y
end
#--------------------------------------------------------------------------
# ● Set Oxy Correction
#--------------------------------------------------------------------------
def set_oxy_correction
return if @picture.position[0] == -2
self.x += self.ox if @picture.effect_ex[3] or @picture.effect_ex[5]
self.y += self.oy if @picture.effect_ex[2] or @picture.effect_ex[3] or @picture.effect_ex[5]
end
#--------------------------------------------------------------------------
# ● Update Position
#--------------------------------------------------------------------------
def update_shake_effect(type)
@picture.effect_ex[type][2] += 1
return if @picture.effect_ex[type][2] < @picture.effect_ex[type][1]
@picture.effect_ex[type][2] = 0
self.x = pos_x + shake_effect(type)
self.y = @picture.effect_ex[1] ? pos_y + shake_effect(type) : pos_y
set_oxy_correction
end
#--------------------------------------------------------------------------
# ● Shake Effect
#--------------------------------------------------------------------------
def shake_effect(type)
-(@picture.effect_ex[type][0] / 2) + rand(@picture.effect_ex[type][0])
end
#--------------------------------------------------------------------------
# ● Update Other
#--------------------------------------------------------------------------
def update_other
if @picture.effect_ex[4] ; update_opacity_ex
else ; self.opacity = @picture.opacity
end
self.blend_type = @picture.blend_type
if @picture.effect_ex[5] ; update_angle_ex
else ; self.angle = @picture.angle
end
self.tone.set(@picture.tone)
end
#--------------------------------------------------------------------------
# ● Update Angle EX
#--------------------------------------------------------------------------
def update_angle_ex
@picture.effect_ex[5][4] += 1
return if @picture.effect_ex[5][4] < @picture.effect_ex[5][3]
@picture.effect_ex[5][4] = 0 ; @picture.effect_ex[5][1] += 1
case @picture.effect_ex[5][1]
when 0..@picture.effect_ex[5][2]
@picture.effect_ex[5][0] += 1
when @picture.effect_ex[5][2]..(@picture.effect_ex[5][2] * 3)
@picture.effect_ex[5][0] -= 1
when (@picture.effect_ex[5][2] * 3)..(-1 + @picture.effect_ex[5][2] * 4)
@picture.effect_ex[5][0] += 1
else ; @picture.effect_ex[5][0] = 0 ; @picture.effect_ex[5][1] = 0
end
self.angle = @picture.angle + @picture.effect_ex[5][0]
end
#--------------------------------------------------------------------------
# ● Update Opacity EX
#--------------------------------------------------------------------------
def update_opacity_ex
@picture.effect_ex[4][6] += 1
return if @picture.effect_ex[4][6] < @picture.effect_ex[4][5]
@picture.effect_ex[4][6] = 0 ; @picture.effect_ex[4][2] += 1
case @picture.effect_ex[4][2]
when 0..@picture.effect_ex[4][4]
@picture.effect_ex[4][0] -= @picture.effect_ex[4][3]
when @picture.effect_ex[4][4]..(-1 + @picture.effect_ex[4][4] * 2)
@picture.effect_ex[4][0] += @picture.effect_ex[4][3]
else
@picture.effect_ex[4][0] = 255 ; @picture.effect_ex[4][2] = 0
end
self.opacity = @picture.effect_ex[4][0]
end
#--------------------------------------------------------------------------
# ● Update Origin
#--------------------------------------------------------------------------
def update_origin
return if !self.bitmap
if force_center_oxy?
self.ox = @picture.effect_ex[2] ? n_ox : (bitmap.width / 2) + n_ox
self.oy = (bitmap.height / 2) + n_oy
if @picture.position[0] > 0 or @picture.position[0] == -1
execute_move(0,@picture.position[2],-@picture.position[1].screen_x) rescue nil
execute_move(1,@picture.position[3],-@picture.position[1].screen_y) rescue nil
end
return
end
if @picture.effect_ex[2] ; self.oy = (bitmap.height + n_oy) ; return ; end
if @picture.origin == 0
self.ox = n_ox ; self.oy = n_oy
else
self.ox = (bitmap.width / 2) + n_ox
self.oy = (bitmap.height / 2) + n_oy
end
end
#--------------------------------------------------------------------------
# ● Force Center Oxy
#--------------------------------------------------------------------------
def force_center_oxy?
return false if @picture.position.empty?
return true if @picture.position[0] == -1
return true if @picture.position[0] > 0
return true if @picture.effect_ex[3]
return true if @picture.effect_ex[5]
return false
end
#--------------------------------------------------------------------------
# ● N Ox
#--------------------------------------------------------------------------
def n_ox
return @picture.position[2] if @picture.position[0] > 0 and @picture.position[2]
return @picture.position[2] if @picture.position[0] == -1 and @picture.position[2]
return $game_map.display_x * 32 if @picture.position[0] == -2
return 1000 if @picture.position[0] == -1000
return 0
end
#--------------------------------------------------------------------------
# ● N Oy
#--------------------------------------------------------------------------
def n_oy
return @picture.position[3] if @picture.position[0] > 0 and @picture.position[3]
return @picture.position[3] if @picture.position[0] == -1 and @picture.position[3]
return $game_map.display_y * 32 if @picture.position[0] == -2
return 1000 if @picture.position[0] == -1000
return 0
end
#--------------------------------------------------------------------------
# ● Execute Move
#--------------------------------------------------------------------------
def execute_move(type,cp,np)
sp = 5 + ((cp - np).abs / 5)
if cp > np ; cp -= sp ; cp = np if cp < np
elsif cp < np ; cp += sp ; cp = np if cp > np
end
@picture.position[2] = cp if type == 0
@picture.position[3] = cp if type == 1
end
#--------------------------------------------------------------------------
# ● Update Zoom
#--------------------------------------------------------------------------
alias mog_picture_ex_update_zoom update_zoom
def update_zoom
if @picture.effect_ex[2] ; update_breath_effect ; return ; end
if @picture.effect_ex[3] ; update_auto_zoom_effect ; return ; end
mog_picture_ex_update_zoom
end
#--------------------------------------------------------------------------
# ● Update Breath Effect
#--------------------------------------------------------------------------
def update_breath_effect
self.zoom_x = @picture.zoom_x / 100.0
self.zoom_y = @picture.zoom_y / 101.0 + auto_zoom(2)
end
#--------------------------------------------------------------------------
# ● Update Auto Zoom Effect
#--------------------------------------------------------------------------
def update_auto_zoom_effect
self.zoom_x = @picture.zoom_x / 100.0 + auto_zoom(3)
self.zoom_y = @picture.zoom_y / 100.0 + auto_zoom(3)
end
#--------------------------------------------------------------------------
# ● Auto Zoom
#--------------------------------------------------------------------------
def auto_zoom(type)
if @picture.effect_ex[type][6] == 0
@picture.effect_ex[type][6] = 1
@picture.effect_ex[type][0] = rand(50)
end
if @picture.effect_ex[type][5] < @picture.effect_ex[type][4]
@picture.effect_ex[type][5] += 1
return @picture.effect_ex[type][1]
end
@picture.effect_ex[type][5] = 0
@picture.effect_ex[type][2] -= 1
return @picture.effect_ex[type][1] if @picture.effect_ex[type][2] > 0
@picture.effect_ex[type][2] = 2 ; @picture.effect_ex[type][0] += 1
case @picture.effect_ex[type][0]
when 0..25 ; @picture.effect_ex[type][1] += @picture.effect_ex[type][3]
when 26..60 ; @picture.effect_ex[type][1] -= @picture.effect_ex[type][3]
else ; @picture.effect_ex[type][0] = 0 ; @picture.effect_ex[type][1] = 0
end
@picture.effect_ex[type][1] = 0 if @picture.effect_ex[type][1] < 0
@picture.effect_ex[type][1] = 0.25 if @picture.effect_ex[type][1] > 0.25 if type == 2
return @picture.effect_ex[type][1]
end
#--------------------------------------------------------------------------
# ● Can Set Wave Effect?
#--------------------------------------------------------------------------
def can_set_wave_effect?
return false if !@picture.effect_ex[6]
return false if !@picture.effect_ex[6][0]
return false if !self.bitmap
return true
end
#--------------------------------------------------------------------------
# ● Set Wave Effect
#--------------------------------------------------------------------------
def set_wave_effect
@picture.effect_ex[6][0] = false
self.wave_amp = @picture.effect_ex[6][1]
self.wave_length = self.bitmap.width
self.wave_speed = @picture.effect_ex[6][2]
end
end |
# frozen_string_literal: true
class User < ApplicationRecord
devise :database_authenticatable, :validatable
has_many :contacts
has_many :tasks
has_many :touched_contacts, class_name: 'Contact', foreign_key: :touched_id
has_one_attached :avatar
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
## class: Userを入れないとインスタンスメソッドのテストが出来ないようです。
factory :twitter_user, class: User do
sequence(:nickname) { |i| "nickname#{i}" }
sequence(:image_url) { |i| "http://example.com/image#{i}.jpg" }
after(:create) do|user|
FactoryGirl.create(:twitter_auth, user: user)
end
end
factory :facebook_user, class: User do
sequence(:nickname) { |i| "nickname#{i}" }
sequence(:image_url) { |i| "http://example.com/image#{i}.jpg" }
after(:create) do|user|
FactoryGirl.create(:facebook_auth, user: user)
end
end
factory :user, class: User do
sequence(:nickname) { |i| "nickname#{i}" }
sequence(:image_url) { |i| "http://example.com/image#{i}.jpg" }
after(:create) do|user|
FactoryGirl.create(:twitter_auth, user: user)
end
end
end
|
# frozen_string_literal: true
require 'test_helper'
class LabelTest < ActiveSupport::TestCase
test 'label is valid' do
valid_label = Label.new(
value: 'Sport'
)
assert valid_label.valid?
end
test 'label is invalid' do
valid_label = Label.new(
value: ''
)
assert_not valid_label.valid?
valid_label.value = '1' * 256 # too long
assert_not valid_label.valid?
end
test 'Many to many relations' do
expensive_label = labels(:expensive)
smart_label = labels(:smart)
car_product = products(:car)
watch_product = products(:watch)
car_product.labels.push(expensive_label)
car_product.labels.push(smart_label)
smart_label.products.push(watch_product)
assert_equal(2, smart_label.products.length)
assert_equal(2, car_product.labels.length)
assert_equal(1, watch_product.labels.length)
assert_equal(1, expensive_label.products.length)
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :military do
consultant
rank
branch
clearance_level
investigation_date { 1.years.ago }
service_start_date { 6.months.ago }
end
end
|
# frozen_string_literal: true
# config/db/migrate/enable_uuid.rb
class EnableUuid < ActiveRecord::Migration[6.0]
def change
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
enable_extension 'uuid-ossp' unless extension_enabled?('uuid-oosp')
end
end
|
FactoryBot.define do
factory :project do
user
sequence(:name) { |n| "project-#{n}" }
title { "title" }
trait :released do
released_at { Time.current }
end
trait :deployed do
after(:create) { |project| create(:deployment, :finished, project: project) }
end
trait :deployment_failed do
after(:create) { |project| create(:deployment, :failed, project: project) }
end
trait :published do
released
deployed
end
trait :discarded do
discarded_at { Time.current }
end
end
end
|
class RoutineTasksController < ApplicationController
include RoutineTasksHelper
before_action :authenticate_user!
before_action :set_routine_task, only: [:edit, :destroy]
def edit
end
def create
@routine_task = RoutineTask.verify_routine_task(
RoutineTask.new(routine_task_params), current_user.id)
set_routine_task_list
if @routine_task && @routine_task.save
render :index, layout: false
else
render :new, layout: false
end
end
def destroy
@routine_task.destroy
set_routine_task_list
render :index, layout: false
end
private
def set_routine_task
@routine_task = current_user.routine_tasks.find(params[:id])
end
def routine_task_params
params.require(:routine_task).permit(
:name, :memo, :start_time, :end_time, :routine_id)
end
end
|
class CreateCourses < ActiveRecord::Migration
def change
create_table :courses do |t|
t.integer :user_id, null: false
t.integer :area_id, null: false
t.string :name, null: false
t.float :distance, null: false
t.string :image_url, null: false
t.timestamps null: false
end
add_index :courses, :user_id
add_index :courses, :area_id
end
end
|
#!/usr/bin/env ruby1.9.3
# For small experiments, run as ./OhlohJavaRepoFetcher.rb --max_repos 20
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'optparse'
# this script fetches all git repositories of projects with
# "java" (as tag | in title | in project description) from ohloh
PROJECTS_PER_PAGE = 10
$countProjectsWithoutGitRepos = 0
$countProjects = 0
def parseProject projectUrl
$stderr.puts "Analyze Repo #{projectUrl} ..."
pageNumber = 1
doc = getDoc(projectUrl, pageNumber)
if (doc.nil?)
raise "Could not load project #{projectUrl}"
end
title = projectUrl.strip.gsub(/\/p\//,"")
numRepos = doc.css("div.span4").text.strip.slice(/of (\d+)/, 1).to_i
remaining = numRepos
if (remaining < 1)
$countProjectsWithoutGitRepos += 1
return
end
links = doc.css("td.span4")
while (remaining > 0)
enlistment = doc.css(".enlistment")
for e in enlistment
type = e.css("td:not(.status)").css(".span2").text.gsub(/\r/,"").gsub(/\n/,"")
link = e.css("td.span4").text.gsub(/\r/,"").gsub(/\n/,"").gsub(/\[.*?\]/,"")
puts "#{title}\t#{type}\t#{link}"
end
begin
pageNumber += 1
doc = getDoc(projectUrl, pageNumber)
end until doc or pageNumber > numRepos * PROJECTS_PER_PAGE
remaining -= PROJECTS_PER_PAGE
end
end
def getDoc (project, pageNumber)
link = "http://www.ohloh.net#{project}/enlistments?sort=type&page=#{pageNumber}"
begin
return Nokogiri::HTML(open(link))
rescue Exception => msg #
$stderr.puts "Error occurred in getDoc(#{project}, #{pageNumber}): #{msg}"
return nil
end
end
def scanRepos
start_page_nr = 1
max_page_nr = Nokogiri::HTML(open("http://www.ohloh.net/p?query=java")).
text.strip.slice(/\bShowing page 1 of \b([\d,]*)/, 1).gsub(/,/,"").to_i
for i in (start_page_nr..max_page_nr)
$stderr.puts "Analyze page #{i}/#{max_page_nr} ..."
doc = Nokogiri::HTML(open("http://www.ohloh.net/p?query=java&page=#{i}"))
projects = doc.css("div.project>h2")
for p in projects
begin
projectUrl = p.child['href'].to_str
parseProject projectUrl
$countProjects += 1
if $max_repos > 0 && $countProjects>= $max_repos
return
end
rescue Exception => msg
$stderr.puts "Error occurred on page #{i}: #{msg}"
end
end
$stdout.flush
end
end
if __FILE__ == $0
OptionParser.new do |opts|
$max_repos = -1
opts.on("--max_repos NUM",
"How many repos do you want? Choose -1 for all.") do |num|
$max_repos = num.to_i
end
end.parse!
scanRepos
$stderr.puts "#{$countProjectsWithoutGitRepos} of #{$countProjects} projects had no Git repository."
end
|
# frozen_string_literal: true
class ApplicationController < ActionController::Base
def access_denied(exception)
respond_to do |format|
format.json { head :forbidden, content_type: "text/html" }
format.html { redirect_to root_url, notice: exception.message }
format.js { head :forbidden, content_type: "text/html" }
end
end
def authenticate_user_from_token!
given_token = request.headers["X-AUTH-TOKEN"]
if given_token
token = find_auth_token(given_token)
return _not_authorized unless token&.user
sign_in token.user, store: false
end
false
end
def _not_authorized
render json: { error: "You need to sign in or sign up before continuing." }, status: :unauthorized
end
def _cant_access_this_data
render json: { error: "You do not have permission to access this data." }, status: :forbidden
end
def _unprocessable_data
render json: { error: "Unprocessable data." }, status: :unprocessable_data
end
def _not_found
render json: { error: "Not found." }, status: :not_found
end
private
def find_auth_token(given_token)
token_hash = Digest::SHA1.hexdigest given_token
AuthToken.where("token = ? and expires >= ?", token_hash, Time.now.utc).first
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'clocker/version'
Gem::Specification.new do |spec|
spec.name = 'clocker'
spec.version = Clocker::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = ['Michael Chadwick']
spec.email = ['mike@codana.me']
spec.homepage = 'http://rubygems.org/gems/clocker'
spec.summary = 'Calculate how long a command or block of code takes to run'
spec.description = 'Give Clocker some code to process, and it will run it and display how long it took to finish.'
spec.files = `git ls-files`.split("\n")
spec.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
spec.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.license = 'MIT'
spec.add_development_dependency "bundler", "~> 2.1"
spec.add_development_dependency "rake", "~> 12.3"
end
|
class AuthenticateUser
def initialize(email, password)
@email = email
@password = password
end
# Service entry point
def call
data
end
private
attr_reader :email, :password
# verify user credentials
def user
user = User.find_by(email: email)
return user if user && user.authenticate(password)
# raise Authentication error if credentials are invalid
raise(ExceptionHandler::InvalidToken, Message.invalid_credentials)
end
def data
token = JsonWebToken.encode(user_id: user.id) if user
exp = JsonWebToken.decode(token)[:exp]
avatar = $base_url + user.avatar.url
@user = user.as_json(:include => { :roles => { :include => :permissions } }).merge("avatar" => avatar ).as_json
return {token: token,exp: (Time.at(exp)-Time.now).to_i, user: @user, type: 'Bearer'}
end
end
|
module ThreeScale
module Backend
module Stats
module Aggregators
module Base
SERVICE_GRANULARITIES =
[:eternity, :month, :week, :day, :hour].map do |g|
Period[g]
end.freeze
private_constant :SERVICE_GRANULARITIES
# For applications and users
EXPANDED_GRANULARITIES = (SERVICE_GRANULARITIES +
[Period[:year], Period[:minute]]).freeze
private_constant :EXPANDED_GRANULARITIES
GRANULARITY_EXPIRATION_TIME = { Period[:minute] => 180 }.freeze
private_constant :GRANULARITY_EXPIRATION_TIME
# We are not going to send metrics with granularity 'eternity' or
# 'week' to Kinesis, so there is no point in storing them in Redis
# buckets.
EXCLUDED_FOR_BUCKETS = [Period[:eternity], Period[:week]].freeze
private_constant :EXCLUDED_FOR_BUCKETS
# Aggregates a value in a timestamp for all given keys using a specific
# Redis command to store them. If a bucket_key is specified, each key will
# be added to a Redis Set with that name.
#
# @param [Integer] value
# @param [Time] timestamp
# @param [Array] keys array of {(service|application|user) => "key"}
# @param [Symbol] cmd
# @param [String, Nil] bucket
def aggregate_values(value, timestamp, keys, cmd, bucket)
keys_for_bucket = []
keys.each do |metric_type, prefix_key|
granularities(metric_type).each do |granularity|
key = counter_key(prefix_key, granularity.new(timestamp))
expire_time = expire_time_for_granularity(granularity)
store_key(cmd, key, value, expire_time)
unless EXCLUDED_FOR_BUCKETS.include?(granularity)
keys_for_bucket << key
end
end
end
store_in_changed_keys(keys_for_bucket, bucket) if bucket
end
# Return Redis command depending on raw_value.
# If raw_value is a string with a '#' in the beginning, it returns 'set'.
# Else, it returns 'incrby'.
#
# @param [String] raw_value
# @return [Symbol] the Redis command
def storage_cmd(raw_value)
Backend::Usage.is_set?(raw_value) ? :set : :incrby
end
def storage
Backend::Storage.instance
end
protected
def granularities(metric_type)
metric_type == :service ? SERVICE_GRANULARITIES : EXPANDED_GRANULARITIES
end
def store_key(cmd, key, value, expire_time = nil)
storage.send(cmd, key, value)
storage.expire(key, expire_time) if expire_time
end
def expire_time_for_granularity(granularity)
GRANULARITY_EXPIRATION_TIME[granularity]
end
def store_in_changed_keys(keys, bucket)
bucket_storage.put_in_bucket(keys, bucket)
end
private
def bucket_storage
Stats::Storage.bucket_storage
end
end
end
end
end
end
|
# frozen_string_literal: true
module ApplicationHelper
def title_app
I18n.t('app')
end
def view_active?(controller)
params[:controller] == controller ? 'active' : nil
end
def devise_active?
params[:controller].include?('devise') ? 'active' : nil
end
def size_types
Pet.size_types
end
def kind_of_pets
Pet.kind_of_pets
end
def genders
Pet.genders
end
def enum_size(key)
I18n.t("size_type.#{key}")
end
def enum_kind(key)
I18n.t("kind_of_pet.#{key}")
end
def enum_gender(key)
I18n.t("gender.#{key}")
end
end
|
class RemoveRepoIdFromHooks < ActiveRecord::Migration
def up
remove_column :hooks, :repo_id
end
def down
add_column :hooks, :repo_id, :string
end
end
|
class Is
class Point
attr_reader :longitude, :latitude
def initialize(lat, long)
@latitude = lat.to_f
@longitude = long.to_f
end
def in?(area)
area = Is::Area.new(area) unless area.is_a?(Is::Area) # :)
area.contains? self
end
end
end
|
class AccountCredential < ActiveRecord::Base
belongs_to :user
TYPES = {
fb: 'facebook',
tw: 'twitter'
}
attr_accessible :token, :uid, :account_type, :token_secret, :user_id
validates :uid, :uniqueness => { :scope => :account_type,
:message => "The social network account you have registered with us already exists in our system" },
:presence => true
validates :account_type, :inclusion => { :in => TYPES.values }
end |
class PlaylistViewOption
def message
"View Playlist"
end
def perform
puts "\nPlaylist\n==========================\n"
Playlist.songs.each_with_index do |song, index|
puts "#{index + 1}: #{song.title}"
end
puts
end
end
|
AppTitle = "Hello World"
IMAGE_URLS = {
antani: "https://upload.wikimedia.org/wikipedia/it/thumb/1/1b/Amicimiei-Tognazzi.jpg/310px-Amicimiei-Tognazzi.jpg" # antani is a word that makes no sense (like foo)
}
def Image(tag)
url = IMAGE_URLS.fetch tag
{
type: "image",
url: url,
}
end
def Label(text)
{
type: "label",
text: text,
}
end
def RefreshButton(label: "Refresh")
{
type: "label",
text: label,
action: {
type: "$reload",
},
}
end
def Section(items)
{
sections: [{
items: items
}]
}
end
HelloImage = {
head: {
title: AppTitle,
},
body: Section([
Label(AppTitle),
Label("image example:"),
Image(:antani),
RefreshButton(),
]),
}
|
module DockerClient
def self.create(server_url, options = {})
Base.new(server_url, options)
end
class Base
def initialize(server_url, options)
@server_url = server_url
@connection = Docker::Connection.new(server_url, options)
validate_version!
end
def validate_version!
Docker.info(@connection)
rescue Docker::Error::DockerError
raise Docker::Error::VersionError, "Expected API Version: #{Docker::API_VERSION}"
end
def server_url
@server_url
end
def connection
@connection
end
def container(id_or_name)
Container.new(@connection, "id_or_name" => id_or_name)
end
def info
Docker.info(@connection)
end
def version
Docker.version(@connection)
end
#Container Command
def create(image, command = nil, options = {})
name = options["--name"]
workdir = options["-w"] || options["--workdir"]
ports = options["-p"] || options["--publish"]
volumes = options["-v"] || options["--volume"]
envs = options["-e"] || options["--env"]
pull_policy = options["pull_policy"]
container = Container.new(@connection, "image" => image, "command" => command, "name" => name, "workdir" => workdir, "volmes" => volumes, "ports" => ports, "envs" => envs, "pull_policy" => pull_policy)
container.create
container
end
def run(image, command = nil, options = {})
privileged = options["--privileged"]
container = create(image, command, options)
container.start("privileged" => privileged)
container
end
def ps(*options)
all = options.include?("-a") || options.include?("-all")
Docker::Container.all({"all"=>all}, @connection)
end
def rm(id_or_name, *options)
force = options.include?("-f") || options.include?("--force")
container = Docker::Container.get(id_or_name, {}, @connection)
container.remove("force" => force)
end
def rm_all
ps("-a").each do |container|
container.remove("force" => true)
end
end
def port(id_or_name, port = nil)
container = self.container(id_or_name)
unless port.nil? then
return container.get_host_network(port)
end
network_settings = container.get_port_mapping
end
#Image Command
def pull(image, options = {})
image = Image.new(@connection, {"image" => image}.merge(options))
image.pull_by_policy
end
end
end
|
class CreateWeixinXiaodianProduct < ActiveRecord::Migration[5.1]
def change
create_table :weixin_xiaodian_products do |t|
t.string :product_id, :limit => 100
t.string :name, :limit => 200
t.text :properties
t.string :sku_info, :limit => 300
end
end
end
|
class Studio < ActiveRecord::Base
attr_accessible :name
has_many :movies
end
|
Rails.application.routes.draw do
resources :blueprints
root "blueprints#index"
end
|
require 'server_spec_helper'
require 'pry-byebug'
# require 'pg'
describe ListMore::Server do
def app
ListMore::Server.new
end
let(:dbhelper) { ListMore::Repositories::DBHelper.new 'listmore_test' }
let(:user_1) { ListMore::Entities::User.new({:username => "Ramses", :password_digest => "pitbull"})}
let(:user_2) { ListMore::Entities::User.new({:username => "Daisy", :password_digest => "collie"})}
let(:users) { [user_1, user_2] }
before(:all) do
dbhelper.clear_tables
users.each{ |user| ListMore.users_repo.save user }
end
# before(:each) do
# dbhelper.clear_tables
# users.each{ |user| ListMore.users_repo.save user }
# end
describe "GET /" do
xit "loads the homepage" do
get '/'
expect(last_response).to be_ok
expect(last_response.body).to include "Loading.."
end
end
describe "POST /signup" do
xit "makes a successful post request to signup endpoint" do
params = {
:username => "Duevyn",
:password => "Cooke",
:password_conf => "Cooke"
}
post '/signup', params
response = last_response.body
response = JSON.parse(response)
# {"token"=>"31fcf684ff4e62591528c2f183ca5468", "user"=>{"id"=>41, "username"=>"Duevyn", "email"=>nil}}
expect(response['token']).to be_a String
expect(response['user']).to be_a Hash
expect(response['user']['id'].to_i).to be_a Integer
expect(response['user']['username']).to eq "Duevyn"
end
end
describe "POST /signin" do
xit "makes a successful post request to signin endpoint" do
user = ListMore::Entities::User.new({username: 'nick'})
user.update_password("mks123")
ListMore.users_repo.save user
params = {
:username => "nick",
:password => "mks123"
}
post '/signin', params
response = last_response.body
response = JSON.parse(response)
expect(response['token']).to be_a String
expect(response['user']).to be_a Hash
expect(response['user']['id'].to_i).to be_a Integer
expect(response['user']['username']).to eq "nick"
end
end
describe "GET /users" do
xit "makes a successfull get request to the users endpoint" do
get '/users'
expect(last_response).to be_ok
data = last_response.body
#data "{\"users\":[{\"id\":19,\"username\":\"Ramses\"},{\"id\":20,\"username\":\"Daisy\"}]}"
data = JSON.parse(data)
# expect(data['users'].count).to eq 2
data['users'].each do |user|
expect(user['id'].to_i).to be_a Integer
expect(user['username']).to be_a String
expect(user['password']).to be_nil
end
end
end
describe "GET /users/:id" do
xit "makes a successful get request to an individul user endpoint" do
params = {
:id => users[0]['id']
}
get '/users/' + params[:id], params
response = last_response.body
# "{\"user\":{\"id\":111,\"username\":\"Ramses\",\"email\":null}}"
data = JSON.parse(last_response.body)
expect(data['user']).to be_a Hash
expect(data['user']['username']).to eq "Ramses"
expect(data['user']['id'].to_i).to be_a Integer
expect(data['user']['email']).to be_nil
end
end
describe "GET /users/:id/lists" do
xit "gets all lists of a user from endpoint" do
first_user = users[0]
second_user = users[1]
list_1 = ListMore::Entities::List.new({name: "First List", user_id: first_user['id'] })
list_2 = ListMore::Entities::List.new({name: "Second List", user_id: first_user['id'] })
list_3 = ListMore::Entities::List.new({name: "Share List", user_id: second_user['id'] })
receive_list = ListMore.lists_repo.save list_1
ListMore.lists_repo.save list_2
share_list = ListMore.lists_repo.save list_3
params = {
'user_id' => receive_list['user_id'],
'list_id' => share_list['id']
}
shared_list_data = ListMore::ShareList.run params
params = {
'user' => first_user
}
# binding.pry
get '/users/' + first_user.id + '/lists' #, params
response = JSON.parse(last_response.body)
expect()
binding.pry
end
end
describe "POST /users/:id/lists" do
xit "makes a successful post request to the endpoint creating a new list" do
user = users[0]
params = {
'name' => 'Post List',
'user_id' => user['id']
}
ListMore::CreateList.run params
end
end
end
|
FactoryBot.define do
factory :shop do
user_id { 1 }
name { 'ラーメン大王' }
prefecture { 1 }
address { '札幌市1丁目' }
phone { '000-000-1234' }
image { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec/fixtures/ramen-01.jpg')) }
end
end
|
require 'exifr'
class Picture < ActiveRecord::Base
has_and_belongs_to_many :details
has_and_belongs_to_many :tags
belongs_to :divelog
belongs_to :divesite
has_one :exif
has_attached_file :image, :styles => { :medium => "720x540>", :thumb => "105x80>" }
after_save :process_exif
def process_exif
cnt = Exif.where(:picture_id => self.id).count
if cnt == 0
file = self.image.path
exif = EXIFR::JPEG.new file
pic_exif = self.build_exif
pic_exif.camera_brand = exif.make
pic_exif.camera_model = exif.model
pic_exif.shot_date_time = exif.date_time
pic_exif.save
end
end
end
|
class SevensController < ApplicationController
def index
@sevens = Seven.all
end
def new
@seven = Seven.new
end
def create
@seven = Seven.new(seven_params)
if @seven.save
redirect_to sevens_path
else
render 'new'
end
end
def seven_params
params.require(:seven).permit(:name)
end
def show
@seven = Seven.find(params[:id])
end
def edit
@seven = Seven.find(params[:id])
end
def update
@seven = Seven.find(params[:id])
@seven.update(seven_params)
redirect_to '/sevens'
end
def destroy
@seven = Seven.find(params[:id])
@seven.destroy
flash[:notice] = "Seven deleted successfully"
redirect_to '/sevens'
end
end
|
class RankingValue < ActiveRecord::Base
# associations
belongs_to :ranking
belongs_to :ranked_object, :polymorphic => true
# validations
validates :value, :position, :ranking, :ranked_object, :presence => true
validates_uniqueness_of :position, :scope => [:ranking_id]
# scoping by ranking
scope :for_ranking, ->(ranking) { where(:ranking_id => ranking.try(:id)) }
end |
require File.dirname(__FILE__) + "/../../spec_helper"
require File.dirname(__FILE__)+ '/../fixtures/classes'
describe "Equality" do
it "maps Object#eql? to System.Object.Equals for Ruby classes" do
o = EqualitySpecs::RubyClassWithEql.new
EqualityChecker.equals(o, :ruby_marker).should be_true
end
it "maps Object#eql? to System.Object.Equals for Ruby classes that derive from CLR types" do
o = EqualitySpecs::RubyDerivedClass.new
EqualityChecker.equals(o, :ruby_marker).should be_true
end
it "allows Object#eql? to return any type" do
EqualityChecker.equals(EqualitySpecs::RubyClassWithEql.new("hello"), 123).should be_true
EqualityChecker.equals(EqualitySpecs::RubyClassWithEql.new(321), 123).should be_true
EqualityChecker.equals(EqualitySpecs::RubyClassWithEql.new(nil), 123).should be_false
EqualityChecker.equals(EqualitySpecs::RubyClassWithEql.new(false), 123).should be_false
end
it "uses reference equality for Array" do
o = EqualitySpecs::RubyClassWithoutEql.new
a = [o]
EqualityChecker.equals(a, [o]).should be_false
end
it "uses reference equality for Hash" do
o = EqualitySpecs::RubyClassWithEql.new
h1 = { o => o }
h2 = { o => o }
class << o
def eql?() raise "eql? should not be called" end
end
EqualityChecker.equals(h1, h2).should be_false
end
it "maps System.Object.Equals to Object#eql? for CLR objects" do
o = EmptyClass.new
o2 = EmptyClass.new
(o.eql? o).should == EqualityChecker.equals(o, o)
(o.eql? nil).should == EqualityChecker.equals(o, nil)
(o.eql? o2).should == EqualityChecker.equals(o, o2)
end
it "maps System.Object.Equals to Object#eql? for Ruby sub-classes" do
EqualityChecker.equals(EqualitySpecs::EqualityCheckerSubtype.new, "ClrMarker".to_clr_string).should be_true
(EqualitySpecs::EqualityCheckerSubtype.new == "ClrMarker".to_clr_string).should be_true
end
it "maps System.Object.Equals to Object#eql? for Ruby sub-classes with #eql?" do
EqualityChecker.equals(EqualitySpecs::EqualityCheckerSubtypeWithEql.new, "ClrMarker".to_clr_string).should be_false
EqualityChecker.equals(EqualitySpecs::EqualityCheckerSubtypeWithEql.new, :ruby_marker).should be_true
end
it "does not map System.Object.Equals to Object#eql? for monkey-patched CLR objects" do
# Virtual methods cannot be overriden via monkey-patching. Therefore the Equals virtual call from EqualityChecker is routed to the default implementation on System.Object.
o = EmptyClass.new
class << o
def eql?(other)
flunk
end
end
EqualityChecker.equals(o, EmptyClass.new).should be_false
end
it "maps System.Object.Equals to Object#eql? for Object" do
# Object.new returns RubyObject whose Equals is overridden to call eql? dynamically.
o = Object.new
class << o
def eql?(other)
true
end
end
EqualityChecker.equals(o, Object.new).should be_true
end
it "allows both Object#eql? and System.Object.Equals to be overriden separately" do
o = EqualitySpecs::RubyClassWithEqlAndEquals.new
(o.eql? :ruby_marker).should be_true
EqualityChecker.equals(o, :clr_marker).should be_true
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.