text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.feature "User edits an existing song" do
scenario "they see the updated data for the song and a link to the artist page" do
artist = create(:artist)
song = create(:song)
updated_title = "Three Little Birds"
visit song_path(song)
click_on "Edit"
fill_in "song_title", with: updated_title
click_on "Update Song"
expect(current_path).to eq song_path(song)
expect(page).to have_content updated_title
# Then I should see a link to the song artist's individual page
# expect(page).to have_link artist.name, href: artist_path(artist)
end
end
|
module Adminpanel
class User < ActiveRecord::Base
include Adminpanel::Base
has_secure_password
belongs_to :role, touch: true
default_scope do
includes(:role)
end
#role validation
validates_presence_of :role_id
#name validations
validates_presence_of :name
validates_length_of :name, maximum: 25
#password validations
validates_confirmation_of :password, on: :create
validates_presence_of :password, on: :create
validates_length_of :password, minimum: 6, on: :create
#password_confirmation validations
validates_presence_of :password_confirmation, on: :create
#email validations
validates_presence_of :email
validates_uniqueness_of :email
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates_format_of :email, with: VALID_EMAIL_REGEX
before_save{ email.downcase! }
before_save :create_remember_token
def self.form_attributes
[
{
'name' => {
'type' => 'text_field',
'label' => 'Nombre',
'placeholder' => 'Nombre'
}
},
{
'email' => {
'type' => 'email_field',
'label' => 'Correo',
'placeholder' => 'Correo'
}
},
{
'password' => {
'type' => 'password_field',
'label' => I18n.t('model.attributes.password'),
'placeholder' => I18n.t('model.attributes.password'),
'show' => 'false'
}
},
{
'password_confirmation' => {
'type' => 'password_field',
'placeholder' => I18n.t('model.attributes.password_confirmation'),
'label' => I18n.t('model.attributes.password_confirmation'),
'show' => 'false'
}
},
{
'role_id' => {
'type' => 'select',
'options' => Proc.new { |user| Role.all },
'label' => I18n.t('model.attributes.role_id')
}
},
]
end
def self.new_remember_token
SecureRandom.urlsafe_base64
end
def self.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
def self.display_name
I18n.t('model.User')
end
def self.icon
'user'
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
end
|
class AddHintToQuestions < ActiveRecord::Migration
def change
add_column :notequestions, :hint, :string
add_column :notequestions, :solution_explain, :string
end
end
|
module Dry
module System
module Plugins
# @api public
module Decorate
# @api public
def decorate(key, decorator:)
original = _container.delete(key.to_s)
if original.is_a?(Dry::Container::Item) && original.options[:call] && decorator.is_a?(Class)
register(key) do
decorator.new(original.call)
end
else
decorated = decorator.is_a?(Class) ? decorator.new(original) : decorator
register(key, decorated)
end
end
end
end
end
end
|
require 'dockerspec'
require 'dockerspec/serverspec'
describe docker_build('.', tag: 'zuazo/irssi-tor') do
let(:home) { '/home/irssi' }
it do
should have_entrypoint(
'/usr/bin/proxychains_wrapper -u irssi /usr/bin/irssi'
)
end
it { should have_env 'IRSSI_HOME' => home }
it { should have_env 'IRSSI_CONF_DIR' }
it { should have_env 'IRSSI_SCRIPTS_DIR' }
describe docker_build(File.dirname(__FILE__), tag: 'irssi-tor_test') do
describe docker_run('irssi-tor_test', family: :alpine) do
before(:all) { sleep 20 }
describe package('irssi') do
it { should be_installed }
end
describe user('irssi') do
it { should exist }
it { should have_home_directory home }
it { should have_login_shell '/bin/sh' }
end
describe file('/home/irssi/.irssi') do
it { should be_directory }
it { should be_owned_by 'irssi' }
it { should be_grouped_into 'irssi' }
end
describe file('/home/irssi/.irssi/scripts') do
it { should be_directory }
it { should be_owned_by 'irssi' }
it { should be_grouped_into 'irssi' }
end
describe process('/usr/bin/irssi') do
it { should be_running }
its(:user) { should eq 'irssi' }
end
end
end
end
|
require 'test_helper'
class ApicastV1DeploymentServiceTest < ActiveSupport::TestCase
class_attribute :rolling_updates
self.rolling_updates = false
def setup
Logic::RollingUpdates.stubs(skipped?: !rolling_updates)
@provider = FactoryBot.create(:provider_account)
@provider.proxies.update_all(apicast_configuration_driven: false)
@service = ApicastV1DeploymentService.new(@provider)
Logic::RollingUpdates.stubs(skipped?: true)
end
def test_deploy_success
proxy = FactoryBot.create(:proxy, service: @provider.first_service, api_test_success: true)
stub_request(:get, "http://test.proxy/deploy/TEST?provider_id=#{@provider.id}")
.to_return(status: 200)
assert_empty @provider.proxy_logs
assert @service.deploy(proxy)
assert proxy.deployed_at, 'marks proxy as deployed'
assert @provider.proxy_configs.present?
assert @provider.proxy_configs_conf.present?
assert proxy.errors.empty?, 'no errors'
assert @provider.proxy_logs.present?
assert proxy.api_test_success, 'should keep api_test_success'
end
def test_deploy_failure
proxy = FactoryBot.create(:proxy, service: @provider.first_service, api_test_success: true)
stub_request(:get, "http://test.proxy/deploy/TEST?provider_id=#{@provider.id}")
.to_return(status: 500)
assert_empty @provider.proxy_logs
refute @service.deploy(proxy)
refute proxy.deployed_at, 'does not mark proxy as deployed'
assert proxy.errors.presence
refute @provider.proxy_configs.present?, 'empties proxy configs'
refute @provider.proxy_configs_conf.present?, 'empties proxy configs'
assert @provider.proxy_logs.present?
refute proxy.api_test_success, 'should reset api_test_success'
end
def test_lua_content
assert_match "-- provider_key: #{@provider.provider_key}", @service.lua_content
end
def test_conf_content
host = URI(@provider.first_service!.proxy.sandbox_endpoint).host
assert_match "server_name #{host}", @service.conf_content
end
test 'conf_content having services integrated via plugin' do
FactoryBot.create(:service, account: @provider, deployment_option: 'plugin_ruby')
deployment_service = ApicastV1DeploymentService.new(@provider)
assert_nothing_raised do
host = URI(@provider.first_service!.proxy.sandbox_endpoint).host
assert_match "server_name #{host}", deployment_service.conf_content
end
end
ConfContentFailure = Class.new(StandardError)
def test_conf_content_failure
::Apicast::SandboxProviderConfGenerator.any_instance.expects(:emit).raises(ConfContentFailure)
assert_raise ConfContentFailure do
@service.deploy(Proxy.new)
end
end
class WithRollingUpdate < ApicastV1DeploymentServiceTest
self.rolling_updates = true
end
end
|
json.meta do
json.total @order_set_items.total_count
json.current_page page
json.per_page per_page
end
json.urls do
if @order_set_items.total_count > (page * per_page)
json.next url_for(params: {page: page + 1})
end
if page > 1
json.prev url_for(params: {page: page - 1})
end
end
json.data do
json.array! @order_set_items do |order_set_item|
json.partial! "order_set_item", order_set_item: order_set_item
end
end |
class UsersController < ApplicationController
require 'date'
before_action :authenticate_user!, except: [:new, :create, :forgot_password, :send_email, :password_reset]
before_action :find_restrictions, only: [:preferences, :delete_restriction]
def new
@user = User.new
end
def create
@user = User.new user_params
if @user.save
session[:user_id] = @user.id
Mealplan.create(user: current_user)
redirect_to root_path
else render :new
end
end
def forgot_password
end
def send_email
if User.find_by(email: params[:email]) == nil
redirect_to forgot_password_path, alert: "it does not look like this email is registered. double-check if you entered it correctly."
else
PasswordResetMailer.password_reset(User.find_by(email: params[:email])).deliver_later
redirect_to root_path, notice: 'An email to reset your password is making its way to your inbox.'
end
end
def password_reset
if current_user
@user = current_user
end
if params[:email].present?
@user = User.find_by(email: params[:email])
if @user.present?
if params[:new_password] != params[:password_confirmation]
@msg = "please make sure password confirmation matches with new password."
render :password_reset
elsif (params[:new_password] == params[:password_confirmation] && @user.update({password: params[:new_password]}))
redirect_to new_session_path, notice: 'your password is updated. keep it handy. :)'
end
else
return redirect_to password_reset_path, alert: 'it does not look like this email is registered. double-check if you entered it correctly.'
end
end
end
def setting
end
def preferences
if params[:dr_id]
restriction = Dietaryrestriction.find_by(id: params[:dr_id])
if restriction != nil
if !current_user.dietaryrestrictions.include?(Dietaryrestriction.find(restriction.id))
current_user.dietaryrestrictions << Dietaryrestriction.find(restriction.id)
else
delete_restriction
end
end
# link = Userdietaryrestrictionlink.new(user: current_user, dietaryrestriction: @restriction)
if current_user.save
redirect_to user_preferences_path and return
else
render :preferences and return
end
end
if params[:tag_id]
# byebug
tag = Tag.find_by(id: params[:tag_id])
if tag != nil
if !current_user.tags.include?(Tag.find(tag.id))
current_user.tags << Tag.find(tag.id)
else
delete_tag
end
end
# if (params.has_key? 'tags')
# tag_ids = params[:tags].reject(&:blank?).uniq
# if current_user.tag_ids.to_s != ''
# tag_ids.each do |id|
# current_user.tags << Tag.find_by(id: id)
# end
# end
if (current_user.save)
redirect_to user_preferences_path and return
else
render :preferences and return
end
end
end
# def add_tags
# p 'i got here.'
# if current_user.update tags_params
# redirect_to 'user/preferences'
# else
# render :preferences
# end
# end
def delete_restriction
restriction = Dietaryrestriction.find(params[:dr_id])
current_user.userdietaryrestrictionlinks.find_by(dietaryrestriction_id: params[:dr_id]).destroy
# redirect_to user_preferences_path
end
def delete_tag
tag = Tag.find(params[:tag_id])
current_user.usertaggings.find_by(tag_id: params[:tag_id]).destroy
# redirect_to user_preferences_path
end
def update
if current_user.update update_user_params
# if current_user.authenticate(params[:password]) == false
# render :setting, alert: 'please enter a correct current password.' and return
# end
# if (params[:password] == params[:new_password] && params[:password] != "")
# render :setting, alert: 'your new password has to be different from your current password.' and return
# end
# if params[:new_password] != params[:password_confirmation]
# render :setting, alert: 'please make sure password confirmation matches with new password.'
# end
redirect_to :setting, notice: 'your information is updated.'
else
render :setting
end
end
def favourites
@favourites = current_user.favourite_recipes
end
def completions
@completions = current_user.completed_recipes
end
def add_leftover
params = leftover_params
if params[:ingredient]
leftover = Leftover.new(user: current_user)
ingredient = Ingredient.find_by(name: params[:ingredient])
if ingredient != nil
leftover.ingredient = ingredient
else
return @error ='sorry, this ingredient does not exist in our system yet. if you find a recipe that uses it, please let us know.'
end
if params[:quantity]
leftover.quantity = params[:quantity]
end
if params[:expiry_date]
leftover.expiry_date = params[:expiry_date]
end
if leftover.save
if leftover.quantity != ''
if leftover.expiry_date.present? && leftover.expiry_date != ''
str = "#{leftover&.quantity.to_s} #{leftover&.unit.to_s} of #{leftover.ingredient.name} (expiring #{leftover.expiry_date})"
else
str = "#{leftover&.quantity.to_s} #{leftover&.unit.to_s} of #{leftover.ingredient.name}"
end
else
if leftover.expiry_date.present? && leftover.expiry_date != ''
str = "#{leftover.ingredient.name} (expiring #{leftover.expiry_date})"
else
str = "#{leftover.ingredient.name}"
end
redirect_to add_leftover_path, notice: "#{str} is added to your leftovers."
end
else
@leftover = leftover
render :add_leftover and return
end
end
end
def update_leftover
params = update_leftover_params
@leftover = Leftover.find_by(id: params[:id])
if @leftover.update(quantity: params[:quantity], unit: params[:unit], expiry_date: params[:expiry_date])
redirect_to add_leftover_path
else
render :add_leftover
end
end
def delete_leftover
@leftover = Leftover.find_by(id: params[:id])
@leftover.destroy
redirect_to add_leftover_path
end
private
def user_params
params.require(:user).permit(:last_name, :first_name, :email, :password, :password_confirmation, :avatar)
end
# def password_params
# params.require(:user).permit(:password, :new_password, :password_confirmation)
# end
# def can_update
# (current_user == current_user.authenticate(params[:password])) && (params[:password] != params[:new_password]) && (params[:new_password] == params[:password_confirmation]) && current_user.update({password: params[:new_password]})
# end
def update_user_params
params.permit(:last_name, :first_name, :email, :avatar)
end
def find_restrictions
@restrictions = current_user.dietaryrestrictions
end
# def tags_params
# params.require(:user).permit(:tags)
# end
def leftover_params
params.permit(:ingredient, :quantity, :unit, :expiry_date)
end
def update_leftover_params
params.permit(:id, :quantity, :unit, :expiry_date)
end
end
|
class AddImageToArticleComments < ActiveRecord::Migration
def change
add_column :article_comments, :image, :string
end
end
|
require_relative 'logger/logfile'
require_relative 'file_operations'
require_relative 'network_activity'
require_relative 'os_finder'
require_relative 'process_runner'
module EDRTest
class Tester
def initialize
@logfile = EDRTest::Logger::Logfile.new
@curr_os = OSFinder.set_os
end
def execute
greet_user
start_choice = welcome_prompt
case start_choice
when '1'
perform_automated_run
when '2'
initiate_manual_run
else
puts 'Sorry, that seems to be an invalid input!'
end
end
private
def perform_automated_run
@logfile.start_log
EDRTest::ProcessRunner.new(logfile: @logfile).run_process # run and log default command
EDRTest::NetworkActivity.new(logfile: @logfile, os: @curr_os).send_data
fo = EDRTest::FileOperations.new(path: 'test', filetype: 'txt', logfile: @logfile)
fo.create_file
fo.modify_file(contents: 'Hello, World!')
fo.delete_file
@logfile.stop_log
puts 'Automated run succesfully completed!'
end
def initiate_manual_run
puts 'Which activity would you like to simulate? 1) Process 2) Network 3) File Ops X) Exit'
user_answer = gets.chomp
@logfile.start_log
while user_answer.upcase != 'X'
case user_answer
when '1'
EDRTest::ProcessRunner.new(logfile: @logfile).prompt_user
when '2'
EDRTest::NetworkActivity.new(logfile: @logfile, os: @curr_os).run
when '3'
EDRTest::FileOperations.new(path: 'test', filetype: 'txt', logfile: @logfile).prompt_user
else
puts 'Sorry, that seems to be an invalid input!'
end
puts 'Which activity would you like to simulate? 1) Process 2) Network 3) File Ops X) Exit'
user_answer = gets.chomp
end
@logfile.stop_log
end
def greet_user
puts 'Welcome! This is a utility to help regression test the EDR agent on this machine. It'\
" operates by generating some various activity-\nfile operations, running commands, and"\
" transferring data over the network.\nThese activities can be run manually one at a time,"\
" or they can be run automatically using default values.\n\n"
end
def welcome_prompt
puts 'Would you like to 1) Perform an automated test run or 2) Run tests manually?'
gets.chomp
end
end
end
EDRTest::Tester.new.execute |
class RuleEngine
def next_states_by_neighbour
result = {}
result.default = :dead
(2..3).inject(result) do |memo, num|
memo[num] = :alive
memo
end
end
def next_state_for_cell_with(property)
next_states_by_neighbour[property[:neighbours]]
end
end
class Cell
attr_reader :position
def initialize(x,y)
@position = [x,y]
end
end
class Grid
def neighbours_for(x,y)
0
end
end |
#this example demonstrates the use of until loop and until modifier loop
#syntax of until loop
=begin
until condition do
body of loop will be executed until the condition is false
end
=end
#syntax of until-modifier loop
=begin
begin
loop body will be executed until condition is false
end until condition
=end
#example with until loop
$i=0
$count=5
until $count < $i do
$i+=1
puts("inside loop1- value of $i is #{$i}")
end
#example with until-modifier loop
$i=0
begin
$i+=1
puts("inside loop2- value of $i is #{$i}")
end until $count < $i
|
class Teacher < ActiveRecord::Base
validates :name, uniqueness: true
validates :email, uniqueness: true
has_many :students
end |
class ChangeStringForSubscriptionIdToUsers < ActiveRecord::Migration
def self.up
change_column :users, :subscription_id, :string
end
def self.down
change_column :users, :subscription_id, :integer
end
end
|
ActiveAdmin.register ViewHistory do
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if params[:action] == 'create' && current_user.admin?
# permitted
# end
actions :all, except: [:show, :new, :create, :edit, :update, :destroy]
index do
# selectable_column
column 'ID', :id
column '用户', sortable: false do |vh|
if vh.user.present?
vh.user.try(:nickname) || vh.user.try(:hack_mobile)
else
''
end
end
column '类型', sortable: false do |vh|
vh.viewable_type == 'Video' ? "点播" : "直播"
end
column '视频流标题', sortable: false do |vh|
vh.viewable.try(:title)
end
column '播放进度 ( 秒 )', :playback_progress
column '时间', :created_at
end
end
|
class Array
def self.warp(*args)
return 'Warp drive is not available yet. Did you mean Array.wrap?'
end
def sort_with_nil(nil_on_start=true)
sort{|a, b| a && b ? a <=> b : (a ? (nil_on_start ? 1 : -1) : (nil_on_start ? -1 : 1))}
end
def sort_by_with_nil(default, &block)
raise ArgumentError, 'The variable \'default\' cannot be nil!' if default.nil?
sort_by do |a|
block_result = block.call(a)
block_result || default
end
end
def max_with_nil
max{|a, b| a && b ? a <=> b : (a ? 1 : -1)}
end
def max_by_with_nil(default, &block)
raise ArgumentError, 'The variable \'default\' cannot be nil!' if default.nil?
max_by do |a|
block_result = block.call(a)
block_result || default
end
end
def min_with_nil
min{|a, b| a && b ? a <=> b : (a ? -1 : 1)}
end
def min_by_with_nil(default, &block)
raise ArgumentError, 'The variable \'default\' cannot be nil!' if default.nil?
min_by do |a|
block_result = block.call(a)
block_result || default
end
end
end
|
class AnswerQuestion < ActiveRecord::Migration[5.1]
def change
add_reference :answers, :question
end
end
|
require 'rails/generators'
module Twirp
class RspecGenerator < Rails::Generators::Base
desc 'Install twirp rspec helpers into rails_helper.rb'
def inject_rspec_helper
in_root do
unless File.exist?('spec/rails_helper.rb')
log :inject_rspec, 'spec/rails_helper.rb is not found'
return
end
require_sentinel = %r{require 'rspec/rails'\s*\n}m
include_sentinel = /RSpec\.configure\s*do\s*\|config\|\s*\n/m
inject_into_file 'spec/rails_helper.rb',
"require 'twirp_rails/rspec/helper'\n",
after: require_sentinel, verbose: true, force: false
inject_into_file 'spec/rails_helper.rb',
" config.include TwirpRails::RSpec::Helper, type: :rpc, file_path: %r{spec/rpc}\n",
after: include_sentinel, verbose: true, force: false
end
end
end
end
|
class ChangeNullsThesaurus < ActiveRecord::Migration[5.0]
def change
change_column_null :thesaurus, :name, false
change_column_null :thesaurus, :cvalue, false
change_column_null :thesaurus, :f, false
change_column_default :thesaurus, :f, true
end
end
|
require "spec_helper"
describe Gpdb::InstanceOwnership do
let!(:old_owner) { gpdb_instance.owner }
let!(:owner_account) { FactoryGirl.create(:instance_account, :gpdb_instance => gpdb_instance, :owner => old_owner) }
let!(:new_owner) { FactoryGirl.create(:user) }
describe ".change_owner(instance, new_owner)" do
let(:gpdb_instance) { FactoryGirl.create(:gpdb_instance, :shared => true) }
it "creates a GreenplumInstanceChangedOwner event" do
request_ownership_update
event = Events::GreenplumInstanceChangedOwner.by(old_owner).last
event.greenplum_instance.should == gpdb_instance
event.new_owner.should == new_owner
end
context "with a shared gpdb instance" do
it "switches ownership of gpdb instance and account" do
request_ownership_update
gpdb_instance.owner.should == new_owner
owner_account.owner.should == new_owner
end
end
context "with an unshared instance" do
let(:gpdb_instance) { FactoryGirl.create(:gpdb_instance, :shared => false) }
context "when switching to a user with an existing account" do
before do
FactoryGirl.create(:instance_account, :gpdb_instance => gpdb_instance, :owner => new_owner)
end
it "switches ownership of instance" do
request_ownership_update
gpdb_instance.owner.should == new_owner
end
it "keeps ownership of account" do
request_ownership_update
owner_account.owner.should == old_owner
end
end
context "when switching to a user without an existing account" do
it "complains" do
expect {
request_ownership_update
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
def request_ownership_update
Gpdb::InstanceOwnership.change(old_owner, gpdb_instance, new_owner)
gpdb_instance.reload
owner_account.reload
end
end
|
# Encoding: utf-8
require 'spec_helper'
require 'component_helper'
require 'java_buildpack/container/jboss'
describe JavaBuildpack::Container::Jboss do
include_context 'component_helper'
it 'detects WEB-INF',
app_fixture: 'container_tomcat' do
expect(component.detect).to include("jboss=#{version}")
end
it 'does not detect when WEB-INF is absent',
app_fixture: 'container_main' do
expect(component.detect).to be_nil
end
it 'extracts JBoss from a GZipped TAR',
app_fixture: 'container_tomcat',
cache_fixture: 'stub-jboss.tar.gz' do
component.compile
expect(sandbox + 'bin/standalone.sh').to exist
end
it 'manipulates the standalone configuration',
app_fixture: 'container_tomcat',
cache_fixture: 'stub-jboss.tar.gz' do
component.compile
configuration = sandbox + 'standalone/configuration/standalone.xml'
expect(configuration).to exist
contents = configuration.read
expect(contents).to include('<socket-binding name="http" port="${http.port}"/>')
expect(contents).to include('<virtual-server name="default-host" enable-welcome-root="false">')
end
it 'creates a "ROOT.war.dodeploy" in the deployments directory',
app_fixture: 'container_tomcat',
cache_fixture: 'stub-jboss.tar.gz' do
component.compile
expect(sandbox + 'standalone/deployments/ROOT.war.dodeploy').to exist
end
it 'copies only the application files and directories to the ROOT webapp',
app_fixture: 'container_tomcat',
cache_fixture: 'stub-jboss.tar.gz' do
FileUtils.touch(app_dir + '.test-file')
component.compile
root_webapp = app_dir + '.java-buildpack/jboss/standalone/deployments/ROOT.war'
web_inf = root_webapp + 'WEB-INF'
expect(web_inf).to exist
expect(root_webapp + '.test-file').not_to exist
end
it 'returns command',
app_fixture: 'container_tomcat' do
expect(component.release).to eq("#{java_home.as_env_var} JAVA_OPTS=\"test-opt-2 test-opt-1 -Dhttp.port=$PORT\" " \
'$PWD/.java-buildpack/jboss/bin/standalone.sh -b 0.0.0.0')
end
end
|
class Player < ActiveRecord::Base
has_many :games
has_many :scores, through: :games
validates :name, presence: true
validates :hand, inclusion: { in: %w(left right),
message: "%{value} is not a valid hand" }
validates :grade, numericality: { greater_than_or_equal_to: 0,
less_than_or_equal_to: 100,
message: "%{value} must be in the range of 0 to 100" }
validates :email, presence: true, email: true
end
|
require 'test_helper'
class GithubAction::AssignPrLabelTest < ActiveSupport::TestCase
def test_actionable_events_constant
assert_equal GithubAction::AssignPrLabel::ACTIONABLE_EVENTS, ['pull_request']
end
def test_labels_to_assign_constant
assert_equal GithubAction::AssignPrLabel::LABELS_TO_ASSIGN, ['Selenium Scripts Needed']
end
def test_acts_on_fails_for_invalid_event
refute GithubAction::AssignPrLabel.acts_on?('xyz', {})
end
def test_acts_on_fails_for_invalid_params
refute GithubAction::AssignPrLabel.acts_on?('pull_request', {pull_request: {}})
refute GithubAction::AssignPrLabel.acts_on?('pull_request', {pull_request: {merged_at: Time.now}})
refute GithubAction::AssignPrLabel.acts_on?('pull_request', {pull_request: {merged_at: nil}, action: 'closed'})
end
def test_acts_on_suceeds_for_valid_params
assert GithubAction::AssignPrLabel.acts_on?('pull_request', {pull_request: {merged_at: Time.now}, action: 'closed'})
end
end
|
class ModifyColumnsUsers < ActiveRecord::Migration
def change
change_table :users do |t|
t.column :force_change_password, "ENUM('Y','N')"
end
end
end
|
# == Schema Information
#
# Table name: polls
#
# id :integer not null, primary key
# name :string(255)
# hidden_vote :boolean
# user_id :integer
# created_at :datetime
# updated_at :datetime
# finished_at :datetime
#
class Poll < ActiveRecord::Base
attr_accessible :name, :hidden_vote, :finished_at
belongs_to :user
has_many :options, :dependent => :destroy
has_many :voters, :dependent => :destroy
has_many :votes, :dependent => :destroy
accepts_nested_attributes_for :options
accepts_nested_attributes_for :voters
validates :name, :presence => true,
:length => { :maximum => 100 }
validates :hidden_vote, :presence => true
validates :user_id, :presence => true
default_scope :order => 'polls.created_at DESC'
end
|
class ChangeDateToDatetimeInRides < ActiveRecord::Migration
def self.up
change_column :rides, :date, :datetime
end
def self.down
change_column :rides, :date, :date
end
end
|
# frozen_string_literal: true
require 'rspec_sonarqube_formatter'
RSpec.describe RspecSonarqubeFormatter, type: :helper do
before :each do
@output = StringIO.new
@formatter = RspecSonarqubeFormatter.new(@output)
@example = RSpec::Core::ExampleGroup.describe.example_group 'anonymous group', :exclude
@notification = RSpec::Core::Notifications::GroupNotification.new @example.example
@formatter.start(2)
@formatter.example_group_started(@notification)
@formatter.example_started(@example)
end
it 'loads the RspecSonarqubeFormatter class' do
expect(RspecSonarqubeFormatter.name).to eq('RspecSonarqubeFormatter')
end
describe 'passing example' do
before :each do
@formatter.example_passed(@example)
@formatter.stop(@example)
@output.rewind
@output = @output.read.strip
end
it 'is expected to start with an XML header' do
expect(@output).to start_with '<?xml version="1.0" encoding="UTF-8"?>'
expect(@output).to match '<testExecutions version="1">'
expect(@output).to end_with '</testExecutions>'
end
it 'is expected to have a testExecutions section' do
expect(@output).to match '<testExecutions version="1">'
end
it 'is expected to end the testExecutions section' do
expect(@output).to end_with '</testExecutions>'
end
it 'is expected to contain a file section' do
expect(@output).to match '<file path=".+">'
end
it 'is expected to contain a testCase' do
expect(@output).to match '<testCase name=".*" duration="[\d]+" />'
end
it 'is expected to end the file section' do
expect(@output).to match '</file>'
end
end
describe 'failing example' do
before :each do
@notification = RSpec::Core::Notifications::FailedExampleNotification.new @example.example
@formatter.example_failed(@notification)
@formatter.stop(@example)
@output.rewind
@output = @output.read.strip
end
it 'is expected to start with an XML header' do
expect(@output).to start_with '<?xml version="1.0" encoding="UTF-8"?>'
expect(@output).to match '<testExecutions version="1">'
expect(@output).to end_with '</testExecutions>'
end
it 'is expected to have a testExecutions section' do
expect(@output).to match '<testExecutions version="1">'
end
it 'is expected to end the testExecutions section' do
expect(@output).to end_with '</testExecutions>'
end
it 'is expected to contain a file section' do
expect(@output).to match '<file path=".+">'
end
it 'is expected to contain a testCase' do
expect(@output).to match '<testCase name=".*" duration="[\d]+">'
end
it 'is expected to contain a failure message' do
expect(@output).to match '<failure message=".*" stacktrace=".+" />'
end
it 'is expected to end the testCase' do
expect(@output).to match '</testCase>'
end
it 'is expected to end the file section' do
expect(@output).to match '</file>'
end
end
describe 'pending example' do
before :each do
@notification = RSpec::Core::Notifications::PendingExampleFailedAsExpectedNotification.new @example.example
@formatter.example_pending(@notification)
@formatter.stop(@example)
@output.rewind
@output = @output.read.strip
end
it 'is expected to start with an XML header' do
expect(@output).to start_with '<?xml version="1.0" encoding="UTF-8"?>'
expect(@output).to match '<testExecutions version="1">'
expect(@output).to end_with '</testExecutions>'
end
it 'is expected to have a testExecutions section' do
expect(@output).to match '<testExecutions version="1">'
end
it 'is expected to end the testExecutions section' do
expect(@output).to end_with '</testExecutions>'
end
it 'is expected to contain a file section' do
expect(@output).to match '<file path=".+">'
end
it 'is expected to contain a testCase' do
expect(@output).to match '<testCase name=".*" duration="[\d]+">'
end
it 'is expected to contain a skipped message' do
expect(@output).to match '<skipped message=".*" />'
end
it 'is expected to end the testCase' do
expect(@output).to match '</testCase>'
end
it 'is expected to end the file section' do
expect(@output).to match '</file>'
end
end
end
|
class Api::V1::MoviesController < ApplicationController
def index
@movies = Movie.all
render json: @movies, status: :ok
end
def show
@movie = Movie.find(params[:id])
render json: @movie, status: :ok
end
def review
review = Review.create({
content: params[:content],
user: User.first,
movie_id: params[:id].to_i,
stars: params[:stars]
})
if review.save
render json: review, status: :ok
else
render json: {errors: review.errors.full_messages[0]}
end
end
end
|
# frozen_string_literal: true
require "net/http"
class HttpClient
def self.construct_url(base_url, params)
parsed_url = URI.parse(base_url)
new_params = params.map { |key, value| "#{key}=#{value}" }
parsed_url.query = new_params.unshift(parsed_url.query).compact.join("&")
parsed_url.to_s
rescue URI::InvalidURIError
Rails.logger.warn("Invalid URL #{base_url}. Unable to process.")
nil
end
def self.fetch_page(url)
Nokogiri::HTML(Net::HTTP.get(URI(url)))
rescue URI::InvalidURIError
Rails.logger.warn("Invalid URL #{url}. Unable to process.")
nil
rescue Net::OpenTimeout
Rails.logger.warn("Timeout attempting to fetch #{url}. Please try again.")
nil
end
end
|
module Confirmable
extend ActiveSupport::Concern
included do
# validation
validates :name, presence: true
validates :email, presence: true
validates :memo, presence: true
# new -> confirm
validates :submitted, acceptance: true
# confirm -> create
validates :confirmed, acceptance: true
after_validation :confirming
private
def confirming
if submitted == ''
self.submitted = errors.include?(:submitted) && errors.size == 1 ? '1' : ''
end
if confirmed == ''
self.submitted = nil
self.confirmed = nil
end
errors.delete :submitted
errors.delete :confirmed
end
end
end
|
# Conway's Game of Life
# Supported types: [:block, :toad, :blinker, :random]
#
class GameOfLife
@@x = 6;
@@y = 6;
@@oscillator_count = 50
attr_accessor :type
#
# initialize
#
def initialize
end
#
# oscillate
#
def oscillate
construct_array_with_default_live_cells
next_array = @start_array
(1..@@oscillator_count).to_a.each do |i|
p "----------#{i}-----------"
next_array = apply_rule(next_array)
print_array next_array
end
end
private
#
# construct_array_with_default_live_cells
#
def construct_array_with_default_live_cells
@start_array = construct_array
case @type
when :blinker
@start_array[1][2] = 1
@start_array[2][2] = 1
@start_array[3][2] = 1
when :block
@start_array[1][1] = 1
@start_array[1][2] = 1
@start_array[2][1] = 1
when :toad
@start_array[2][2] = 1
@start_array[2][3] = 1
@start_array[2][4] = 1
@start_array[3][1] = 1
@start_array[3][2] = 1
@start_array[3][3] = 1
else
@start_array = construct_array(:random)
end
@start_array
end
#
# print_array
# @param {Array} array
#
def print_array(array)
array.each do |value|
p value.join("").gsub("0", ".")
end
end
#
# construct_array
# @param {Symbol} type (optional)
#
def construct_array(type=nil)
start_array = []
(0..@@x - 1).each do |x|
a = []
(0..@@y - 1).each do |y|
if type == :random
a << rand(2)
else
a << 0
end
end
start_array << a
end
start_array
end
#
# border?
# @param {Integer} x
# @param {Integer} y
#
def border?(x, y)
return true if (x-1).negative? || (y-1).negative?
return true if (x+1) == @@x || (y+1) == @@y
end
#
# apply_rule
#
def apply_rule(prev_array)
next_array = construct_array
(0..@@x-1).each do |x|
(0..@@y-1).each do |y|
next if border?(x, y)
neighbours = get_neighbours(prev_array, x, y)
if prev_array[x][y] == 1
if [2, 3].include? neighbours # Any live cell with two or three live neighbours survives
next_array[x][y] = 1
elsif neighbours > 3 # Any live cell with more than three live neighbours dies, as if by overpopulation
next_array[x][y] = 0
else # Any live cell with fewer than two live neighbours dies, as if by underpopulation
next_array[x][y] = 0
end
else
if neighbours == 3 #Any dead cell with three live neighbours becomes a live cell
next_array[x][y] = 1
else
next
end
end
end
end
next_array
end
#
# get_neighbours
# @param {integer} x
# @param {integer} y
# @param {Array} array
#
def get_neighbours(array, x, y)
sum = 0
return sum if border?(x, y)
[0, -1, +1].each do |px|
[0, -1, +1].each do |py|
next if px == 0 && py == 0
sum += array[x + (px)][y + (py)]
end
end
sum
end
end
game_of_life = GameOfLife.new
if ARGV[0].nil?
p "Considering default type :blinker"
game_of_life.type = :blinker
else
game_of_life.type = ARGV[0].to_sym
end
game_of_life.oscillate |
class DeleteAwsVault < AwsRequest
def call
begin
glacier.delete_vault(account_id: '-', vault_name: vault.name)
vault.destroy
rescue Aws::Glacier::Errors::ServiceError => e
log_aws_error(e)
add_aws_error(e)
end
end
private
attr_reader :vault_id
def post_initialize_hook(args)
@vault_id = args.fetch(:vault_id)
end
def vault
@vault ||= Vault.where(id: vault_id).first
end
end
|
require 'spec_helper'
RSpec.describe Smite::Client do
let(:dev_id) { 1234 }
let(:auth_key) { 'ABCD' }
describe '#initialize' do
it 'accepts only valid languages' do
[1,2,3,7,9,10,11,12,13].each do |lang|
client = described_class.new(dev_id, auth_key, lang)
expect(client.lang).to eq(lang)
end
end
it 'defaults the langauge to English' do
[14..20].each do |lang|
client = described_class.new(dev_id, auth_key, lang)
expect(client.lang).to eq(1)
end
end
end
describe '#valid_session?' do
let(:client) { described_class.new(dev_id, auth_key) }
it 'returns true if the session is created' do
expect(client.valid_session?).to eq(true)
end
it 'returns false if the session is not created' do
allow(client).to receive(:created).and_return(Time.now - 20 * 60)
expect(client.valid_session?).to eq(false)
end
end
describe '#create_session' do
let(:client) { described_class.new(dev_id, auth_key) }
it 'sets the session_id on initialize' do
expect(client.session_id).not_to be_nil
end
it 'returns the session_id if set' do
allow(client).to receive(:valid_session?).and_return(true)
expect(client).not_to receive(:api_call)
client.create_session
end
end
end |
require_relative '../../../gilded_rose'
require_relative '../../../lib/vault/item_behavior'
describe Vault::ItemBehavior do
subject { described_class.new(item) }
describe '#new' do
before(:each) do
subject
end
context 'when item quality starts bigger than MAX_QUALITY' do
let(:item) { Item.new('new item', 10, 100) }
it 'assigns MAX_QUALITY by default' do
expect(item.quality).to eq(described_class::MAX_QUALITY)
end
end
context 'when item quality starts lower than MIN_QUALITY' do
let(:item) { Item.new('new item', 10, -10) }
it 'assigns MIN_QUALITY by default' do
expect(item.quality).to eq(described_class::MIN_QUALITY)
end
end
end
describe '#update_quality' do
before(:each) do
subject.update_quality
end
context 'when the day end' do
let(:item) { Item.new('new item', 10, 10) }
it 'decrease by 1' do
expect(item.quality).to eq 9
end
context 'and quality is already 0' do
let(:item) { Item.new('new item', 10, 0) }
it 'returns 0' do
expect(item.quality).to eq 0
end
end
context 'initial quality exceeds MAX_QUALITY' do
let(:item) { Item.new('new item', 10, 99) }
it 'returns (MAX_QUALITY - 1)' do
expect(item.quality).to eq 49
end
end
end
end
describe '#decrease_sell_in' do
let(:item) { Item.new('new item', 10, 10) }
it 'decrease by 1' do
expect(subject.decrease_sell_in).to eq 9
end
end
describe '#perform' do
let(:item) { Item.new('new item', 5, 10) }
it 'updates quality and sell_in attributes' do
subject.perform
expect(item.sell_in).to eq 4
expect(item.quality).to eq 9
end
end
end
|
require 'rails_helper'
RSpec.describe OrderV1API, type: :request do
describe "查询小C的订单详情" do
before(:all) do
@zhengzhou_userinfo = FactoryGirl.create(:userinfo, {:province => '河南省', :city => '郑州市'})
end
after(:all) do
@zhengzhou_userinfo.destroy
end
it "除退款成功外的情况" do
#发送一个查找请求
post '/api/v1/order/search_order', {:orderid => '576929ce5b628250468a0dfb'}
#验证返回状态
expect(response.status).to eq(200)
# CityV1APIHelper.set_city_info @zhengzhou_userinfo
# #期望是郑州酒运达
# expect(response.body).to eq(Entities::City.represent(@zhengzhou_userinfo).to_json)
end
end
end
|
def bombard(row, col, m)
bomb = m[row][col]
damage = 0
(-1..1).each do |row_offset|
(-1..1).each do |col_offset|
is_the_same_cell = row_offset.zero? && col_offset.zero?
target = { row: row + row_offset, col: col + col_offset }
next unless !is_the_same_cell && in_range(target[:row], target[:col], m)
damage += calculate_damage(m[target[:row]][target[:col]], bomb)
end
end
damage
end
def calculate_damage(target, bomb)
target >= bomb ? bomb : target
end
def in_range(row, col, m)
in_row_range = 0 <= row && row <= m.size - 1
in_col_range = 0 <= col && col <= m[0].size - 1
in_row_range && in_col_range
end
def matrix_bombing_plan(m)
matrix_sum = m.flatten.reduce(:+)
result = {}
m.size.times do |row|
m[0].size.times do |col|
result[[row, col]] = matrix_sum - bombard(row, col, m)
end
end
result
end
puts matrix_bombing_plan([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]) == { [0, 0] => 42,
[0, 1] => 36,
[0, 2] => 37,
[1, 0] => 30,
[1, 1] => 15,
[1, 2] => 23,
[2, 0] => 29,
[2, 1] => 15,
[2, 2] => 26 }
|
# frozen_string_literal: true
COMPLEMENT = lambda do |predicate|
lambda do |args|
!predicate.call(args)
end
end
|
class RtReviewLoader
def self.load(id)
new(id).load
end
def self.enqueue(id)
RtReviewLoadWorker.perform_async(id)
end
attr_reader :movie
def initialize(id)
@movie = Movie.find(id)
end
def load
return unless movie.rt_api_review_link
response = Typhoeus::Request.new(
"#{movie.rt_api_review_link}?apikey=#{Rotten.api_key}",
method: :get,
headers: { Accept: 'application/json' }
).run
CriticReviewParser.parse(movie, JSON.parse(response.body))
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,:omniauthable,
:omniauth_providers => [:facebook]
#This method is for creating a new user athenticated with facebook and we are going to describe each step in its construction
#This method will be called from the controller and it's a class method because it don't needs to be instanced
#We will send one parameter (auth) que arrives from the Facebook API; this parameter has all the information of the user, we will use the information of provider and uid.
#We will be a query (with a where) to the data base with and we will combinate with a method of the active record, this one will found the first element inside data base o it creates a new element.
#We'll ask if the paramter that we send it has the structure auth[:info] and we'll fill the user's information
#Finaly we are going to a password for completing the user's creation.
#This method are going to call from users' controller.
def self.from_omniath(auth)
where(provider: auth[:provider], uid: auth[:uid]).first_or_create do |user|
if auth[:info]
user.email = auth[:info][:email]
user.first_name = auth[:info][:name]
end
user.password = Devise.friendly_token[0,20]
end
end
end
|
# frozen_string_literal: true
require 'stannum/constraints/uuid'
require 'support/examples/constraint_examples'
RSpec.describe Stannum::Constraints::Uuid do
include Spec::Support::Examples::ConstraintExamples
subject(:constraint) do
described_class.new(**constructor_options)
end
let(:constructor_options) { {} }
let(:expected_options) do
{ expected_format: described_class::UUID_FORMAT }
end
describe '::NEGATED_TYPE' do
include_examples 'should define frozen constant',
:NEGATED_TYPE,
'stannum.constraints.is_a_uuid'
end
describe '::TYPE' do
include_examples 'should define frozen constant',
:TYPE,
'stannum.constraints.is_not_a_uuid'
end
describe '::UUID_FORMAT' do
include_examples 'should define frozen constant',
:UUID_FORMAT,
-> { an_instance_of(Regexp) }
describe 'when matched with an empty string' do
it { expect(''.match? described_class::UUID_FORMAT).to be false }
end
describe 'when matched with string with invalid characters' do
let(:string) { '00000000-0000-0000-0000-00000000000O' }
it { expect(string.match? described_class::UUID_FORMAT).to be false }
end
describe 'when matched with a string with insufficient length' do
let(:string) { '00000000-0000-0000-0000-00000000000' }
it { expect(string.match? described_class::UUID_FORMAT).to be false }
end
describe 'when matched with a string with excessive length' do
let(:string) { '00000000-0000-0000-0000-0000000000000' }
it { expect(string.match? described_class::UUID_FORMAT).to be false }
end
describe 'when matched with a string with invalid format' do
let(:string) { '000000000000-0000-0000-0000-00000000' }
it { expect(string.match? described_class::UUID_FORMAT).to be false }
end
describe 'when matched with a lowercase UUID string' do
let(:string) { '01234567-89ab-cdef-0123-456789abcdef' }
it { expect(string.match? described_class::UUID_FORMAT).to be true }
end
describe 'when matched with an uppercase UUID string' do
let(:string) { '01234567-89AB-CDEF-0123-456789ABCDEF' }
it { expect(string.match? described_class::UUID_FORMAT).to be true }
end
end
describe '.new' do
it 'should define the constructor' do
expect(described_class)
.to be_constructible
.with(0).arguments
.and_any_keywords
end
end
include_examples 'should implement the Constraint interface'
include_examples 'should implement the Constraint methods'
describe '#match' do
let(:match_method) { :match }
let(:expected_errors) { { type: described_class::TYPE } }
let(:expected_messages) do
expected_errors.merge(message: 'is not a valid UUID')
end
describe 'with a non-string object' do
let(:expected_errors) do
{
data: {
required: true,
type: String
},
type: Stannum::Constraints::Type::TYPE
}
end
let(:expected_messages) do
expected_errors.merge(message: 'is not a String')
end
let(:actual) { :a_symbol }
include_examples 'should not match the constraint'
end
describe 'with an empty string' do
let(:actual) { '' }
include_examples 'should not match the constraint'
end
describe 'with string with invalid characters' do
let(:actual) { '00000000-0000-0000-0000-00000000000O' }
include_examples 'should not match the constraint'
end
describe 'with a string with insufficient length' do
let(:actual) { '00000000-0000-0000-0000-00000000000' }
include_examples 'should not match the constraint'
end
describe 'with a string with excessive length' do
let(:actual) { '00000000-0000-0000-0000-0000000000000' }
include_examples 'should not match the constraint'
end
describe 'with a string with invalid format' do
let(:actual) { '000000000000-0000-0000-0000-00000000' }
include_examples 'should not match the constraint'
end
describe 'with a lowercase UUID string' do
let(:actual) { '01234567-89ab-cdef-0123-456789abcdef' }
include_examples 'should match the constraint'
end
describe 'with an uppercase UUID string' do
let(:actual) { '01234567-89AB-CDEF-0123-456789ABCDEF' }
include_examples 'should match the constraint'
end
end
describe '#negated_match' do
let(:match_method) { :negated_match }
let(:expected_errors) { { type: described_class::NEGATED_TYPE } }
let(:expected_messages) do
expected_errors.merge(message: 'is a valid UUID')
end
describe 'with a non-string object' do
let(:actual) { :a_symbol }
include_examples 'should match the constraint'
end
describe 'with an empty string' do
let(:actual) { '' }
include_examples 'should match the constraint'
end
describe 'with string with invalid characters' do
let(:actual) { '00000000-0000-0000-0000-00000000000O' }
include_examples 'should match the constraint'
end
describe 'with a string with insufficient length' do
let(:actual) { '00000000-0000-0000-0000-00000000000' }
include_examples 'should match the constraint'
end
describe 'with a string with excessive length' do
let(:actual) { '00000000-0000-0000-0000-0000000000000' }
include_examples 'should match the constraint'
end
describe 'with a string with invalid format' do
let(:actual) { '000000000000-0000-0000-0000-00000000' }
include_examples 'should match the constraint'
end
describe 'with a lowercase UUID string' do
let(:actual) { '01234567-89ab-cdef-0123-456789abcdef' }
include_examples 'should not match the constraint'
end
describe 'with an uppercase UUID string' do
let(:actual) { '01234567-89AB-CDEF-0123-456789ABCDEF' }
include_examples 'should not match the constraint'
end
end
end
|
class Item < ActiveRecord::Base
belongs_to :repair_order
has_many :uploads
has_many :text_uploads
end
|
require 'faraday'
require_relative 'error'
require_relative 'version'
Dir[File.expand_path('../resources/*.rb', __FILE__)].each { |f| require f }
module Closeio
class Client
include Closeio::Client::Activity
include Closeio::Client::BulkAction
include Closeio::Client::Contact
include Closeio::Client::CustomActivity
include Closeio::Client::CustomActivityType
include Closeio::Client::CustomField
include Closeio::Client::EmailAccount
include Closeio::Client::EmailTemplate
include Closeio::Client::Event
include Closeio::Client::IntegrationLink
include Closeio::Client::Lead
include Closeio::Client::LeadStatus
include Closeio::Client::Opportunity
include Closeio::Client::OpportunityStatus
include Closeio::Client::Organization
include Closeio::Client::Report
include Closeio::Client::Sequence
include Closeio::Client::SequenceSchedule
include Closeio::Client::SequenceSubscription
include Closeio::Client::SmartView
include Closeio::Client::Task
include Closeio::Client::User
include Closeio::Client::Webhook
include Closeio::Client::Filter
attr_reader :api_key, :logger, :ca_file, :errors, :utc_offset
def initialize(api_key, logger = true, ca_file = nil, errors = false, utc_offset: 0)
@api_key = api_key
@logger = logger
@ca_file = ca_file
@errors = errors
@utc_offset = utc_offset
end
def get(path, options = {})
connection.get(path, options).body
end
def post(path, req_body)
connection.post do |req|
req.url(path)
req.body = req_body
end.body
end
def put(path, options = {})
connection.put(path, options).body
end
def delete(path, options = {})
connection.delete(path, options).body
end
def paginate(path, options = {})
results = []
skip = 0
begin
res = get(path, options.merge!(_skip: skip))
unless res['data'].nil? || res['data'].empty?
results.push res['data']
skip += res['data'].count
end
end while res['has_more']
{ has_more: false, total_results: res['total_results'], data: results.flatten }
end
private
def assemble_list_query(query, options)
options[:query] = if query.respond_to? :map
query.map { |k, v| "#{k}:\"#{v}\"" }.join(' ')
else
query
end
options
end
def connection
Faraday.new(
url: 'https://api.close.com/api/v1',
headers: {
accept: 'application/json',
'User-Agent' => "closeio-ruby-gem/v#{Closeio::VERSION}",
'X-TZ-Offset' => utc_offset.to_s
},
ssl: { ca_file: ca_file }
) do |conn|
conn.request :authorization, :basic, api_key, ''
conn.request :json
conn.response :logger if logger
conn.response :json
conn.use FaradayMiddleware::CloseioErrorHandler if errors
conn.adapter Faraday.default_adapter
end
end
end
end
|
require "application_system_test_case"
class ConscesionariaTest < ApplicationSystemTestCase
setup do
@conscesionarium = conscesionaria(:one)
end
test "visiting the index" do
visit conscesionaria_url
assert_selector "h1", text: "Conscesionaria"
end
test "creating a Conscesionarium" do
visit conscesionaria_url
click_on "New Conscesionarium"
fill_in "Anos de mercado", with: @conscesionarium.anos_de_mercado
fill_in "Cidade", with: @conscesionarium.cidade
fill_in "Endereco", with: @conscesionarium.endereco
fill_in "Nome", with: @conscesionarium.nome
click_on "Create Conscesionarium"
assert_text "Conscesionarium was successfully created"
click_on "Back"
end
test "updating a Conscesionarium" do
visit conscesionaria_url
click_on "Edit", match: :first
fill_in "Anos de mercado", with: @conscesionarium.anos_de_mercado
fill_in "Cidade", with: @conscesionarium.cidade
fill_in "Endereco", with: @conscesionarium.endereco
fill_in "Nome", with: @conscesionarium.nome
click_on "Update Conscesionarium"
assert_text "Conscesionarium was successfully updated"
click_on "Back"
end
test "destroying a Conscesionarium" do
visit conscesionaria_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Conscesionarium was successfully destroyed"
end
end
|
# frozen_string_literal: true
require 'spec_helper'
require 'timecop'
RSpec.describe 'RailsAdmin::Adapters::ActiveRecord::Property', active_record: true do
describe 'string field' do
subject { RailsAdmin::AbstractModel.new('Player').properties.detect { |f| f.name == :name } }
it 'returns correct values' do
expect(subject.pretty_name).to eq 'Name'
expect(subject.type).to eq :string
expect(subject.length).to eq 100
expect(subject.nullable?).to be_falsey
expect(subject.serial?).to be_falsey
end
end
describe 'serialized field' do
subject { RailsAdmin::AbstractModel.new('User').properties.detect { |f| f.name == :roles } }
it 'returns correct values' do
expect(subject.pretty_name).to eq 'Roles'
expect(subject.type).to eq :serialized
expect(subject.nullable?).to be_truthy
expect(subject.serial?).to be_falsey
end
end
describe '#read_only?' do
before do
class HasReadOnlyColumn < Tableless
column :name, :varchar
attr_readonly :name
end
end
it 'returns correct values' do
expect(RailsAdmin::AbstractModel.new('Player').properties.detect { |f| f.name == :name }).not_to be_read_only
expect(RailsAdmin::AbstractModel.new('HasReadOnlyColumn').properties.detect { |f| f.name == :name }).to be_read_only
end
end
end
|
class CheckItemResult < ActiveRecord::Base
belongs_to :user
belongs_to :check_item
belongs_to :survey
validates_presence_of :user
validates_presence_of :survey
validates_presence_of :check_item
before_validation(on: :create) do
self.user_id = survey.user_id unless survey.blank?
end
end
|
class AddDateColumnsToMoney < ActiveRecord::Migration
def self.up
[:easy_money_expected_expenses, :easy_money_expected_revenues, :easy_money_other_expenses, :easy_money_other_revenues].each do |tbl|
add_column(tbl, :tyear, :integer, {:null => true}) unless column_exists?(tbl, :tyear)
add_column(tbl, :tmonth, :integer, {:null => true}) unless column_exists?(tbl, :tmonth)
add_column(tbl, :tweek, :integer, {:null => true}) unless column_exists?(tbl, :tweek)
add_column(tbl, :tday, :integer, {:null => true}) unless column_exists?(tbl, :tday)
end
EasyMoneyExpectedExpense.reset_column_information
EasyMoneyExpectedRevenue.reset_column_information
EasyMoneyOtherExpense.reset_column_information
EasyMoneyOtherRevenue.reset_column_information
[EasyMoneyExpectedExpense, EasyMoneyExpectedRevenue, EasyMoneyOtherExpense, EasyMoneyOtherRevenue].each do |t|
t.where('spent_on IS NOT NULL').each do |m|
m.spent_on = m.spent_on
m.save
end
end
end
def self.down
[:easy_money_expected_expenses, :easy_money_expected_revenues, :easy_money_other_expenses, :easy_money_other_revenues].each do |tbl|
remove_column tbl, :tyear
remove_column tbl, :tmonth
remove_column tbl, :tweek
remove_column tbl, :tday
end
end
end
|
class ChangeDetailsFromStringToTextInEscapes < ActiveRecord::Migration
def self.up
change_column :escapes, :details, :text
end
def self.down
change_column :escapes, :details, :string
end
end |
module Noizee
module_function
CONFIG_PATH = "#{ENV['HOME']}/.noizee"
def make_some_noise *args
require 'fileutils'
FileUtils.touch Noizee::CONFIG_PATH
require_relative 'noizee/gestalt'
gestalt = Noizee::Gestalt.new
require_relative 'noizee/internal'
Noizee::Internal.event "Noizee initialized."
while true do
puts gestalt.pop if gestalt.listen
end
end
end
|
##
# NilClass ISO Test
assert('NilClass', '15.2.4') do
NilClass.class == Class
end
assert('NilClass#&', '15.2.4.3.1') do
not NilClass.new.& and not NilClass.new.&(nil)
end
assert('NilClass#^', '15.2.4.3.2') do
NilClass.new.^(true) and not NilClass.new.^(false)
end
assert('NilClass#|', '15.2.4.3.3') do
NilClass.new.|(true) and not NilClass.new.|(false)
end
assert('NilClass#nil?', '15.2.4.3.4') do
NilClass.new.nil?
end
assert('NilClass#to_s', '15.2.4.3.5') do
NilClass.new.to_s == ''
end
|
class AddColumnAge < ActiveRecord::Migration[6.0]
def change
add_column :trainers, :age, :integer, default: 18
end
end
|
class ProductPhoto < ApplicationRecord
validates :product, presence: true
belongs_to :product, inverse_of: :product_photos
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "default_photo.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
|
class ContentType < ActiveRecord::Base
#Added by Jan Uhlar
ZPRAVA = 1
SLOUPEK = 2
KOMENTAR = 3
GLOSA = 4
ANALYZA = 5
ESEJ = 6
RECENZE = 7
KRITIKA = 8
REPORTAZ = 9
DOKUMENT = 10
ROZHOVOR = 11
FEJETON = 12
ZIVE = 13
TIP = 14
VZPOMINKA = 15
VYPRAVENI = 16
POLEMIKA = 17
YOUTUBEDNES = 19
STESTI = 21
PORTRET = 22
POVIDKA = 24
POEZIE = 28
DOPISY = 29
VIDEO = 30
############
has_many :articles
def video?
return self.id == YOUTUBEDNES || self.id == POEZIE || self.id == VIDEO
end
def self.author_image_types
[SLOUPEK,KOMENTAR,GLOSA,DOPISY]
end
def self.opinion_types
self.author_image_types
end
def self.message_types
[ZPRAVA]
end
def self.author_nick_types
[ZPRAVA,GLOSA,YOUTUBEDNES,TIP,VIDEO]
end
def self.article_full_name
[SLOUPEK, KOMENTAR, DOPISY, KRITIKA, RECENZE, REPORTAZ, ESEJ, ANALYZA, FEJETON, VZPOMINKA]
end
def self.author_types
[SLOUPEK,KOMENTAR,ESEJ,ANALYZA,RECENZE,KRITIKA,FEJETON,VZPOMINKA,VYPRAVENI,PORTRET,POVIDKA,STESTI,DOPISY]
end
def self.ignore_down_boxes
[ZPRAVA,SLOUPEK,KOMENTAR,GLOSA,DOPISY,TIP,POEZIE]
end
def self.other_types
ContentType.all(:select=>"id",:conditions=>["id NOT IN (?)",self.opinion_types + self.message_types]).map{|a| a.id}
end
end
|
class GamesController < ApplicationController
before_action :authenticate_user!
before_action :load_user
before_action :verify_user
before_action :load_game
before_action :verify_game
def show
@matches = @game.matches
@title = @game.name
end
private
def load_game
@game = current_user.games.find_by(name: params[:game_name])
end
def load_user
@user = User.find_by(token: params[:user_token])
end
def verify_game
render file: 'public/404.html' and return if !@game.present?
end
end
|
# frozen_string_literal: true
require 'spec/spec_helper'
require 'lib/expander'
RSpec.describe Expander do
describe '#call' do
context 'when expanding minutes' do
subject(:expand_minutes) { described_class.new(format).call.fetch(:minutes) }
context 'when every minute' do
let(:format) { '* * * * *' }
specify { expect(expand_minutes).to eq((0..59).to_a) }
end
context 'when exactly at 29th minute' do
let(:format) { '29 * * * *' }
specify { expect(expand_minutes).to eq([29]) }
end
context 'when every minute between 10 and 15' do
let(:format) { '10-15 * * * *' }
specify { expect(expand_minutes).to eq([10, 11, 12, 13, 14, 15]) }
end
context 'when every 20 minutes' do
let(:format) { '*/20 * * * *' }
specify { expect(expand_minutes).to eq([0, 20, 40]) }
context 'and also 15 minutes' do
let(:format) { '*/20,*/15 * * * *' }
specify { expect(expand_minutes).to eq([0, 15, 20, 30, 40, 45]) }
end
end
end
context 'when expanding hours' do
subject(:expand_hours) { described_class.new(format).call.fetch(:hours) }
context 'when every hour' do
let(:format) { '* * * * *' }
specify { expect(expand_hours).to eq((0...24).to_a) }
end
end
context 'when expanding day of month' do
subject(:expand_days_of_month) { described_class.new(format).call.fetch(:days_of_month) }
context 'when every day' do
let(:format) { '* * * * *' }
specify { expect(expand_days_of_month).to eq((1...31).to_a) }
end
end
end
end
|
class ChangeArrivalTime < ActiveRecord::Migration[5.2]
def change
change_column :session_councilmen, :arrival, :time, default: '00:00:00'
# Ex:- change_column("admin_users", "email", :string, :limit =>25)
end
end
|
class OfferController < ApplicationController
def initialize
super
@var = OfferDecorator.new
@var.link = {
I18n.t("cmn_sentence.listTitle", model:Offer.model_name.human)=>{controller:"offer", action:"index"},
I18n.t("cmn_sentence.newTitle", model:Engineer.model_name.human)=>{controller:"offer", action:"new"},
I18n.t('cmn_sentence.listTitle',model: Office.model_name.human) => {controller:'office', action:'index'},
I18n.t('cmn_sentence.listTitle', model: Business.model_name.human) => {controller:'business', action: 'index'}
}
end
def index
@var.title = t('cmn_sentence.listTitle',model:Offer.model_name.human)
if request.post?
cond_list = {cd: CondEnum::LIKE}
free_word = {keyword: [:eng_cd, :person_info, ]}
cond_set = self.createCondition(params, cond_list,free_word)
@offers = Offer.where(cond_set[:cond_arr])
@var.search_cond = cond_set[:cond_param]
else
@var.search_cond = nil
end
@offers = Offer.all if @var.search_cond.nil?
@var.view_count = @offers.count
end
def new
@var.title=t("cmn_sentence.newTitle",model:Offer.model_name.human)
@var.mode="new"
bus_id = params[:business_id].blank? ? Business.select(:id).first(1) : params[:business_id]
@offer=Offer.new(business_id: bus_id)
end
def create
@offer=Offer.new
save_offer(params)
respond_to do |format|
format.html {redirect_to action: "edit", id: @offer.id}
format.json {render :show, status: :created, location: @offer}
end
rescue => e
raise e if Rails.env == 'development'
respond_to do |format|
format.html {render 'new'}
format.json {render json: format, status: :unprocessable_entity}
end
end
def show
end
def edit
@var.title = I18n.t("cmn_sentence.editTitle",
model:Offer.model_name.human,
id:params[:id]
)
@var.mode = params[:id]
@offer = Offer.find(params[:id])
@var.offer_object = @offer
render "new"
end
def update
@offer = Offer.find(params[:id])
save_offer(params)
respond_to do |format|
format.html {redirect_to action: "edit", id: params[:id]}
format.json {render :show, status: :created, location: @offer}
end
rescue => e
raise e if Rails.env == 'development'
respond_to do |format|
format.html {redirect_to action: "edit", id: params[:id]}
format.json {render json: format, status: :unprocessable_entity}
end
end
def destroy
end
private
def save_offer(params)
Offer.transaction do
@offer.attributes = Offer.parameters(params, :offer)
@offer.save!
end
end
end
|
class ThomasController < ApplicationController
before_action :set_thoma, only: %i[ show edit update destroy ]
# GET /thomas or /thomas.json
def index
@thomas = Thoma.all
end
# GET /thomas/1 or /thomas/1.json
def show
end
# GET /thomas/new
def new
@thoma = Thoma.new
end
# GET /thomas/1/edit
def edit
end
# POST /thomas or /thomas.json
def create
@thoma = Thoma.new(thoma_params)
respond_to do |format|
if @thoma.save
format.html { redirect_to @thoma, notice: "Thoma was successfully created." }
format.json { render :show, status: :created, location: @thoma }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @thoma.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /thomas/1 or /thomas/1.json
def update
respond_to do |format|
if @thoma.update(thoma_params)
format.html { redirect_to @thoma, notice: "Thoma was successfully updated." }
format.json { render :show, status: :ok, location: @thoma }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @thoma.errors, status: :unprocessable_entity }
end
end
end
# DELETE /thomas/1 or /thomas/1.json
def destroy
@thoma.destroy
respond_to do |format|
format.html { redirect_to thomas_url, notice: "Thoma was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_thoma
@thoma = Thoma.find(params[:id])
end
# Only allow a list of trusted parameters through.
def thoma_params
params.require(:thoma).permit(:first_name, :last_name, :age, :url)
end
end
|
module StoreDemo
class PricingRule
@@rules ||= {}
def initialize(name, conditional, affect, product_code)
@@rules[name] = {conditional: conditional, affect: affect, product_code: product_code}
end
def self.get_totals(co_rules, co_items)
price_list = []
co_rules.each do |rule|
price_list << apply_rule(@@rules[rule][:conditional], @@rules[rule][:affect], @@rules[rule][:product_code], co_items)
product = StoreDemo::Product.find_by_code(@@rules[rule][:product_code])
co_items.delete(product)
end
co_items.each do |product, count|
puts "#{product.name} is #{product.price} with #{count}"
price_list << product.price * count
end
puts price_list
price_list
end
def self.validate(pricing_rules)
pricing_rules.each do |rule|
raise 'Rule Doesn\'t Exist' unless @@rules.keys.include?(rule)
end
end
private
def self.apply_rule(conditional, affect, code, co_items)
product = StoreDemo::Product.find_by_code(code)
adjust_price(affect, product, co_items[product]) if check_conditional(conditional, co_items[product])
end
def self.adjust_price(affect, product, count)
affect.call(product, count).to_i
end
def self.check_conditional(conditional, count)
conditional.call(count)
end
end
end |
class ListsController < ApplicationController
before_action :is_authenticated?
before_action :get_list, except: [ :index, :new, :create ]
def new
@list = List.new
end
def create
@list = List.new ( list_params )
if @list.save
redirect_to lists_url ( @list )
else
flash.now[:alert] = @list.errors
render :new
end
end
def index
@lists = List.all.entries
end
def show
end
def edit
@lists = List.all.entries
end
def update
if current_user.update_attributes( list_params)
redirect_to list_form_url, notice: "Your list has been updated"
else
flash.now[:alert] = "Sorry. Can't update your list"
render :edit
end
end
def destroy
@list.destroy
redirect_to lists_url, notice: "Deleted #{@list.list_id}."
end
private
def get_list
@list = List.find( params[:id] )
end
def list_params
params.require(:list).permit( :list_id, :list_name, :user_id, :product_id)
end
end |
require 'spec_helper'
describe Flatrack::View::TagHelper do
include Flatrack::FixtureHelper
describe '#html_tag' do
let(:expected){ render_template 'html_tag.html' }
context 'using haml' do
it 'should properly render' do
template_content = render_template 'html_tag.html.haml'
expect(template_content).to eq expected
end
end
context 'using erb' do
it 'should properly render' do
template_content = render_template 'html_tag.html.erb'
expect(template_content).to eq expected
end
end
context 'with a preserved tag' do
let(:expected){ render_template 'preserved_tag.html' }
it 'should properly render' do
template_content = render_template 'preserved_tag.html.haml'
expect(template_content).to eq expected
end
end
end
describe '#image_tag' do
let(:expected){ render_template 'image_tag.html' }
context 'using haml' do
it 'should properly render' do
template_content = render_template 'image_tag.html.haml'
expect(template_content).to eq expected
end
end
end
describe '#javascript_tag' do
let(:expected){ render_template 'javascript_tag.html' }
context 'using haml' do
it 'should properly render' do
template_content = render_template 'javascript_tag.html.haml'
expect(template_content).to eq expected
end
end
end
describe '#stylesheet_tag' do
let(:expected){ render_template 'stylesheet_tag.html' }
context 'using haml' do
it 'should properly render' do
template_content = render_template 'stylesheet_tag.html.haml'
expect(template_content).to eq expected
end
end
end
end |
class Position < ActiveRecord::Base
include Coded
serialize :reaches
# Starting position may change depending on the situation, for now though
# we'll always leave it as "Standing Apart"
def self.starting_position
lookup('standing_apart')
end
# Not sure if we're going to need this support class or not. At first
# available actions were off of the support class, but that's in the process
# of changing now.
# def support_class
# "Positions::#{code.camelize}".constantize
# end
# def available_actions
# support_class.available_actions
# end
# === Position Seed ===
def self.manufacture data
create!(
code: data[:code],
name: data[:name],
description: data[:description],
reaches: data[:reaches])
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_cache_buster
# Method to prevent browser caching
def set_cache_buster
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end # end method
unless Rails.env == "test" or Rails.env == "development"
begin
# handle other ActiveRecord errors
rescue_from ActiveRecord::ActiveRecordError, :with => :internal_error
# handle not found error
rescue_from ActiveRecord::RecordNotFound, :with => :page_404
end # end block
def internal_error
# render data in different format
respond_to do |format|
format.html { render :file => "#{Rails.root}/public/500.html", :status => 500 }
end # end respond_to block
end # end mehtod
def page_404
# render data in different format
respond_to do |format|
format.html { render :file => "#{Rails.root}/public/404.html", :status => 404 }
end # end respond_to block
end # end mehtod
end # end unless block
end
https://ap1.salesforce.com/02u90000000Vg6V
00D90000000kTQ9 |
class Medium < ActiveRecord::Base
validates :name, length: { minimum: 1 }
has_many :artworks,
inverse_of: :medium,
dependent: :destroy
end
|
class CreateTheLevelUps < ActiveRecord::Migration
def change
create_table :the_level_ups do |t|
t.integer :app_id
t.string :api_key
t.string :client_secret
t.string :app_access_token
t.timestamps
end
end
end
|
module Api
module V1
class GallerySerializer < Api::V1::BaseSerializer
attributes :id, :title
belongs_to :user
end
end
end
|
class AddReferralToVillageItems < ActiveRecord::Migration
def change
add_column :village_items, :referral_id, :integer
add_column :village_items, :owner_id, :integer
end
end
|
require "spec_helper"
describe ContasController do
describe "routing" do
it "routes to #index" do
get("/contas").should route_to("contas#index")
end
it "routes to #new" do
get("/contas/new").should route_to("contas#new")
end
it "routes to #show" do
get("/contas/1").should route_to("contas#show", :id => "1")
end
it "routes to #edit" do
get("/contas/1/edit").should route_to("contas#edit", :id => "1")
end
it "routes to #create" do
post("/contas").should route_to("contas#create")
end
it "routes to #update" do
put("/contas/1").should route_to("contas#update", :id => "1")
end
it "routes to #destroy" do
delete("/contas/1").should route_to("contas#destroy", :id => "1")
end
end
end
|
class DropNotifications < ActiveRecord::Migration[5.0]
def change
drop_table :notifications
remove_column :accounts, :unseen_notifications_count, :integer, default: 0, null: false
end
end
|
require 'rails_helper'
RSpec.describe Status, type: :model do
subject { create :status }
context 'with right parameters' do
it 'creates a status' do
expect(subject.status).to eq(Status.last.status)
end
end
context 'with wrong parameters' do
it "can't have the same status" do
same_status = build :status, status: subject.status
expect(same_status).to_not be_valid
end
it "can't have status empty" do
empty_status = build :status, status: ''
expect(empty_status).to_not be_valid
end
end
end
|
#!/usr/bin/env ruby
require 'bibtex'
require 'citeproc'
require 'csl/styles'
require 'optparse'
require 'set'
require 'sqlite3'
usage = """Usage: bibtex-to-sqlite [--style=CSL-STYLE] [--separator=SEPARATOR] [--name=DB-NAME] file.bib [sql-query]"""
options={:style => 'gost-r-7-0-5-2008', :separator => '|'}
OptionParser.new do |opts|
opts.banner = usage
opts.on("-sSTYLE", "--style=STYLE", "Set bibliography format style") do |s|
options[:style] = s
end
opts.on("-SSEPARATOR", "--separator=SEPARATOR", "Query output separator") do |s|
options[:separator] = s
end
opts.on("-nNAME", "--database-name=NAME", "SQLITE3 database name") do |s|
options[:name] = s
end
end.parse!
inputs=ARGV
if ARGV.length != 1 && ARGV.length != 2
puts usage
exit 1
end
bib_file = ARGV[0]
if not options[:name]
options[:name] = File.basename(bib_file, '.bib') + '.sqlite3'
end
if ARGV.length == 2
query = ARGV[1]
else
query = ''
end
bibliography = BibTeX.open(bib_file).convert(:latex)
bibliography.replace_strings
cp = CiteProc::Processor.new style: options[:style], format: 'text'
cp.import bibliography.to_citeproc
fields = Set.new
bibliography.each do |entry|
fields.merge(entry.field_names.map{ |f| f.to_s.downcase })
end
fields.add('author')
fields.add('title')
fields.add('booktitle')
fields.add('journal')
fields.add('doi')
def escape(s)
s.gsub(/'/, "''")
end
sql = []
sql = []
sql.push("DROP TABLE IF EXISTS bibtex")
sql.push("""
CREATE TABLE IF NOT EXISTS bibtex (
key TEXT,
type TEXT,
gost TEXT,
%s
);""" % fields.map{ |f| "#{f} TEXT" }.sort.join(",\n"))
bibliography.each do |entry|
names = entry.field_names
tmp = entry[:author].map do |name|
name.display_order
end
entry.delete(:author)
entry.add('author', tmp.join(', '))
sql.push("""
INSERT INTO bibtex (
key,
type,
gost,
%s
)
VALUES (
'%s',
'%s',
'%s',
%s
);
""" % [names.map{ |f| f.to_s }.join(",\n"),
escape(entry.key),
escape(entry.type.to_s.downcase),
escape((cp.render :bibliography, id: entry.id)[0]),
names.map{ |i| "'" + escape(entry[i].strip) + "'" }.join(",\n")])
end
if query.strip == ''
puts sql.join('')
else
db = SQLite3::Database.new(options[:name])
for q in sql
db.execute(q)
end
db.execute(query) do |row|
puts row.map{|value|
if value
value
else
''
end
}.join(options[:separator])
end
db.close
end
# vim:filetype=ruby
|
require 'spec_helper'
describe 'EmployeeIntegration', :type => :feature do
it 'sign up employee' do
visit '/'
expect(page).to have_content 'Welcome to Textile.Co'
click_link 'Sign up'
current_path.should == '/employees/sign_up'
expect(page).to have_content 'Sign up'
fill_in :employee_name, :with => 'name'
fill_in :employee_email, :with => 'email@gmail.com'
fill_in :employee_employee_number, :with => '1234'
fill_in :employee_password, :with => 'password1234'
fill_in :employee_password_confirmation, :with => 'password1234'
click_button 'Create my account'
page.has_css?('div#field_with_errors').should be_falsey
end
it 'should display sign up errors' do
visit '/'
click_link 'Sign up'
click_button 'Create my account'
page.has_css?('#error_explanation').should be_truthy
expect(page).to have_content "Email can't be blank"
expect(page).to have_content "Password can't be blank"
expect(page).to have_content "Name can't be blank"
expect(page).to have_content "Employee number can't be blank"
end
it 'log in employee and make complaint' do
visit '/'
click_link 'Log in'
current_path.should == '/employees/sign_in'
fill_in :employee_email, :with => 'email@gmail.com'
fill_in :employee_password, :with => 'password1234'
click_button 'Log in'
current_path.should == '/employees/1234'
page.has_css?('p.notice').should be_truthy
expect(page).to have_content 'If you have any complaint, please click the link.'
find('.complaint_link',:visible => true).click
expect(current_path).to include('complaints')
fill_in :complaint_content, :with => 'example'
click_button 'Send'
end
it "should show error in invalid log in" do
visit '/'
click_link 'Log in'
click_button 'Log in'
page.has_css?('p.alert').should be_truthy
end
end |
# Implement your object-oriented solution here!
class Prime
def initialize(num)
@num = num
end
def is_prime?(i)
!(2..(i**0.5)).any? {|d| i % d == 0}
end
def number
i = 3
arr = [2]
until arr.size == @num
arr << i if is_prime?(i)
i += 2
end
arr.last
end
end |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable#, :omniauthable, omniauth_providers: [:twitter]
has_attached_file :avatar,
styles: { medium: '300xx300>', thumb: '100x100>' },
default_url: '/missing.png'
validates_attachment_content_type :avatar,
content_type: %r{¥Aimage¥/.*¥z}
has_many :projects, dependent: :destroy
has_many :posts, inverse_of: :user
def created_month
created_at.strftime('%Y年%m月')
end
has_many :user_teams
has_many :teams, through: :user_teams
end
|
class Record < ActiveRecord::Base
belongs_to :user
belongs_to :project
validates :user_id, presence: true
validates :project_id, presence: true, :uniqueness => {:scope => [:user_id, :date]}
validates :date, presence: true
end
|
class AddRefCustomerAndOwnerToQuotationRequests < ActiveRecord::Migration[6.0]
def change
add_reference :quotation_requests, :customer, foreign_key: true
add_reference :quotation_requests, :store_owner, foreign_key: true
end
end
|
class MoviesController < ApplicationController
$count = 0
def show
id = params[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
# will render app/views/movies/show.<extension> by default
end
def index
if ($count == 0)
session.clear
$count += 1
end
@all_ratings = Movie.all_ratings
@ratings_to_show = @all_ratings
@sort_by = ""
redirect = false
if (params[:sort] != nil) # first detect whether view passes new :sort params
@sort_by = params[:sort]
session[:sort] = @sort_by
elsif (session[:sort] != nil) # if no new :sort, check saved :sort status
@sort_by = session[:sort]
redirect = true
else
@sort_by = nil
end
if (@sort_by == 'title')
@Movie_Title_CSS = 'hilite'
elsif (@sort_by == 'release_date')
@Release_Date_CSS = 'hilite'
end
if (params[:ratings] != nil) # similar to check :sort above
@ratings_to_show = params[:ratings].keys
session[:ratings] = @ratings_to_show
# @movies = Movie.with_ratings(@ratings_to_show).order(@sort_by)
elsif (session[:ratings] != nil)
if (redirect)
@ratings_to_show = session[:ratings]
redirect = true
else
@ratings_to_show = []
session[:ratings] = @ratings_to_show
end
# else
# @movies = Movie.all.order(@sort_by)
end
if (redirect)
redirect_to movies_path(sort: @sort_by, ratings: Hash[@ratings_to_show.collect{ |item| [item, 1]}])
else
return @movies = Movie.with_ratings(@ratings_to_show).order(@sort_by)
end
# @movies = Movie.all
end
def new
# default: render 'new' template
end
def create
@movie = Movie.create!(movie_params)
flash[:notice] = "#{@movie.title} was successfully created."
redirect_to movies_path
end
def edit
@movie = Movie.find params[:id]
end
def update
@movie = Movie.find params[:id]
@movie.update_attributes!(movie_params)
flash[:notice] = "#{@movie.title} was successfully updated."
redirect_to movie_path(@movie)
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
flash[:notice] = "Movie '#{@movie.title}' deleted."
redirect_to movies_path
end
private
# Making "internal" methods private is not required, but is a common practice.
# This helps make clear which methods respond to requests, and which ones do not.
def movie_params
params.require(:movie).permit(:title, :rating, :description, :release_date)
end
end
|
module Admin::TemplatesHelper
def templates_scripts
<<-JS
var template_parts_index = 0;
var template_part_partial = new Template(#{blank_template_part});
function new_template_part(){
var parts = $('parts');
if(parts.down('.template_part')){
var id = parts.select('.template_part').last().id;
template_parts_index = parseInt(id.split("_").last());
}
template_parts_index += 1;
new Insertion.Bottom('parts', template_part_partial.evaluate({index: template_parts_index}));
}
function zeroPad(num,count){
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function fix_template_part_indexes(){
var parts = $('parts');
var new_index = 0;
parts.select(".template_part").each(function(row){
new_index += 1;
row.select("input, select, textarea").each(function(input){
input.name = input.name.sub(/\\d+/, zeroPad(new_index,2));
});
});
}
function reorder_template_part(element, direction){
var parts = $('parts');
var template_part = $(element).up('.template_part');
switch(direction){
case 'up':
if(template_part.previous())
template_part.previous().insert({ before: template_part });
break;
case 'down':
if(template_part.next())
template_part.next().insert({ after: template_part });
break;
case 'top':
parts.insert({ top: template_part });
break;
case 'bottom':
parts.insert({ bottom: template_part });
break;
default:
break;
}
fix_template_part_indexes();
}
JS
end
def filter_options
[['none', '']] + TextFilter.descendants.map { |f| f.filter_name }.sort
end
def part_type_options
PartType.find(:all, :order => "name ASC").map {|t| [t.name, t.id]}
end
def blank_template_part
ostruct = OpenStruct.new(:index => '#{index}')
@blank_template_part ||= (render :partial => "template_part", :object => ostruct).to_json
end
def order_links(template)
returning String.new do |output|
%w{move_to_top move_higher move_lower move_to_bottom}.each do |action|
output << link_to(image("#{action}.png", :alt => action.humanize),
url_for(:action => action, :id => template),
:method => :post)
end
end
end
end
|
class User < ApplicationRecord
REGEX_USERNAME = /\w+/
has_many :messages
validates :username, presence: true,
uniqueness: { case_sensitive: false },
format: { with: /\A#{REGEX_USERNAME}\z/i },
length: { minimum: 3, maximum: 15 }
validates :password, presence: true,
length: { minimum: 6 }
has_secure_password
end
|
class CreateUnclaimedCommissions < ActiveRecord::Migration
def change
create_table :unclaimed_commissions do |t|
t.references :user, index: true, foreign_key: true
t.string :order_num
t.integer :rakuten_commission
t.integer :system_improvement_fee
t.integer :tax
t.boolean :destroy_check, default: false, null: false
t.timestamps null: false
end
end
end
|
class Caterer < ActiveRecord::Base
has_many :CatererDates, dependent: :destroy
belongs_to :Vendor
end
|
class CreateSurveys < ActiveRecord::Migration
def change
create_table :surveys do |t|
t.string :name
t.references :survey_type
t.integer :scale_weightage
t.text :merit_weightage
t.references :political_party
t.string :survey_scale
t.timestamps
end
add_index :surveys, :survey_type_id
add_index :surveys, :political_party_id
end
end
|
class FixHealthRatingStandardColumns < ActiveRecord::Migration[5.2]
def up
remove_column :health_rating_standards, :float
remove_column :health_rating_standards, :weight
add_column :health_rating_standards, :weight, :float, default: 0, null: false
end
end
|
# encoding: UTF-8
require_relative "../initialize.rb"
class Google
def initialize(_city, _type)
@type =_type
@city = _city
@con = Connector.makeConnect(DBConfig::HOSTNAME, DBConfig::DB_USER, DBConfig::DB_PASS, DBConfig::DB_NAME)
@source = "google"+_type
@linkTable = "#{@city}_#{@source}_link"
@detailTable = "#{@city}_#{@source}_detail"
end
def createTable
hash = {
"name" => "varchar(500)",
"address" => "varchar(500)",
"phones" => "varchar(200)",
"websites" => "varchar(200)",
"score" => "varchar(10)",
"longtitude" => "varchar(200)",
"latitude" => "varchar(200)",
"images" => "varchar(500)",
"star" =>"varchar(500)"
}
Crawl.createTableByHash(@con, @detailTable, hash)
end
def getDetail
@con.query ("truncate table `#{@detailTable}`")
# Config Selenium Browser
wait = Selenium::WebDriver::Wait.new(:timeout => 15) # seconds
profile = Selenium::WebDriver::Firefox::Profile.from_name "default"
profile['permissions.default.stylesheet'] = 2
driver = Selenium::WebDriver.for(:firefox, :profile => profile) #
# Get first link from database
res_arg = @con.query ("select * from `google_arguments` where `type` = '#{@type}' ")
res_arg.collect do |arg_row|
initialink = arg_row['link']
puts initialink
driver.navigate.to initialink
sleep(1)
page = 0
while true
page = page + 1
begin
string = driver.page_source
wait.until{
begin
doc = Nokogiri::HTML(string)
# doc.css("div[class='text-place-summary-details']").map{|item|
doc.xpath("//div[@class='noprint res'][1]/div").map { |item|
hash = Hash.new
hash['name'] =getName(item)
puts hash['name']
hash['address'] = getAddress(item)
hash['phones'] = getPhones(item)
hash['websites'] = getWebsite(item)
latLng_r = Crawl.getLatLngFromAddress(hash['address'])
hash['latitude'] = latLng_r[0]
hash['longtitude'] = latLng_r[1]
if @type != Category::RESORT
# hash['score'] = getScore(item)
# hash['images'] = getImages(item)
end
Crawl.genDataInsert(@con, hash, @detailTable)
puts hash
}
rescue Exception => e
puts e.message
puts e.backtrace.inspect
end
}
# element = driver.find_element(:xpath, "//a[@class='text-place-pagination-button'][2]")
element = driver.find_element(:xpath, "//td[@class='b'][1]/a[1]")
if page > 1
element = driver.find_element(:xpath, "//td[@class='b'][2]/a[1]")
end
if element.attribute("style") == "display: none;"
break
end
element.click()
sleep(1)
rescue Exception => e
puts e.message
puts e.backtrace.inspect
break
end
end
end
driver.quit
Crawl.deleteDuplicateFrom2Field(@con, @detailTable,'address', 'name')
DBFunction.genSQL("rawdata", @detailTable)
end
def getImages(item)
return item.css("img[class='text-place-thumbnail']")[0].attr('src')
end
# def getLatLong(item)
# lat = item.attr('lat')
# long = item.attr('lng')
# return [lat, long]
# end
def getStar(item)
end
def getScore(item)
return item.css("div[class='text-place-summary']")[0].css("span[class='text-place-score']")[0].inner_text
end
def getWebsite(item)
website = item.css("span[class='pp-headline-item pp-headline-authority-page']")[0]
if website != nil
website = website.inner_text
else
website = ""
end
if (website != "")
website = "http://" + website
end
return website
end
def getAddress(item)
if @type == Category::ATM
return item.css("span[class='pp-headline-item pp-headline-address']")[0].inner_text
end
return item.css("span[class='text-place-address']")[0].inner_text
end
def getName(item)
if @type == Category::ATM
return item.css("span[class='pp-place-title']")[0].inner_text
end
return item.css("h3[class='text-place-title']")[0].inner_text
end
def getPhones(item)
phone_s = ""
phone = item.css("span[class='telephone']")[0]
if phone != nil
phone_s = MyString.stripString(phone.inner_text.gsub("()", ""))
end
return phone_s
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.provider "virtualbox" do |v|
v.memory = 1024
end
config.vm.provision "shell", path: "vagrant/locale.sh", privileged: false
config.vm.provision "shell", path: "vagrant/provisioner.sh"
config.vm.provision "shell", path: "vagrant/postgresql.sh"
config.vm.provision "shell", path: "vagrant/nodejs.sh"
config.vm.provision "shell", path: "vagrant/bower.sh"
config.vm.provision "shell", path: "vagrant/imagemagick.sh"
config.vm.provision "shell", path: "vagrant/ruby.sh", privileged: false
config.vm.provision "file", source: "~/.gitconfig", destination: "~/.gitconfig"
config.vm.network :forwarded_port, host: 3003, guest: 3000
end
|
class FriendshipsController < ApplicationController
def create
friend = User.find_by(email: friend_params[:email])
if friend.present?
if current_user.friends_emails.include?(friend.email) || friend.email == current_user.email
flash[:error] = "Unable to Add User"
else
new_friend = Friendship.new(user_id: current_user.id, friend_id: friend.id)
new_friend.save
flash[:success] = "#{friend.email[/[^@]+/]} Added as Friend"
end
else
flash[:error] = 'User not found'
end
redirect_to dashboard_path
end
private
def friend_params
params.permit(:email)
end
end
|
require 'rails_helper'
RSpec.describe Product, type: :model do
subject {
Product.new(name: "Socks", price_cents: 1000, quantity: 10, category_id: 1)
}
describe 'Validations' do
context "adding a new product" do
it "is valid if all field are present" do
expect(subject).to be_valid
end
it "is not valid without a name" do
subject.name = nil
expect(subject).to_not be_valid
end
it "is not valid without a price" do
subject.price_cents = nil
expect(subject).to_not be_valid
end
it "is not valid without a quantity" do
subject.quantity = nil
expect(subject).to_not be_valid
end
it "is not valid without a category" do
subject.category = nil
expect(subject).to_not be_valid
end
end
end
end
|
class RoomsController < ApplicationController
before_action :authenticate_user!
def index
@rooms = Room.all
end
def show
@room = Room.find(params[:id])
@room_message = RoomMessage.new room: @room
@room_messages = @room.room_messages.includes(:user)
end
def new
@room = Room.new
end
def create
@room = current_user.rooms.create(rooms_params)
if @room.errors.any?
render "new"
else
redirect_to root_path
end
end
def edit
@room = current_user.rooms.find_by_id(params[:id])
if @room
render "edit"
else
redirect_to root_path
end
end
def update
@room = current_user.rooms.find_by_id(params[:id])
if @room
@room.update(rooms_params)
if @room.errors.any?
render "edit"
else
redirect_to root_path
end
else
redirect_to root_path
end
end
def destroy
Room.find(params[:id]).destroy
end
end
private
def set_room
id = params[:id]
@room = Room.find(id)
end
def rooms_params()
params.require(:room).permit(:title)
end
|
require_relative 'player_big'
class PlayerSprite < Sprite
attr_accessor :animation
def initialize(x, y, image = nil)
image = Image.load("images/tamachang_big.png")
image.set_color_key([255,255,255])
super
self.angle = 0
@cell_x = x % self.image.width
@cell_y = y % self.image.height
#@player = Player_big.new("COM6")
end
def run_forward
case self.angle
when 0
self.x += self.image.width
@cell_x += 1
when 90
self.y += self.image.height
@cell_y += 1
when 180
self.x -= self.image.width
@cell_x -= 1
when 270
self.y -= self.image.height
@cell_y -= 1
else
raise "invalid angle"
end
@player.run_forward
end
def run_backward
case self.angle
when 0
self.x -= self.image.width
@cell_x -= 1
when 90
self.y -= self.image.height
@cell_y -= 1
when 180
self.x += self.image.width
@cell_x += 1
when 270
self.y += self.image.height
@cell_y += 1
else
raise "invalid angle"
end
@player.run_backward
end
def turn_right
self.angle += 90
adjust_angle
@player.turn_right
end
def turn_left
self.angle -= 90
adjust_angle
@player.turn_left
end
def close
@player.close if @player
end
def move_to(target_cell)
return unless movable?(target_cell)
dx = target_cell[0] - @cell_x
dy = target_cell[1] - @cell_y
if dx == 1
case self.angle
when 0
run_forward
when 90
turn_left
run_forward
when 180
run_backward
when 270
turn_right
run_forward
else
raise "invalid angle"
end
elsif dx == -1
case self.angle
when 0
run_backward
when 90
turn_right
run_forward
when 180
run_forward
when 270
turn_left
run_forward
else
raise "invalid angle"
end
elsif dy == 1
case self.angle
when 0
turn_right
run_forward
when 90
run_forward
when 180
turn_left
run_forward
when 270
run_backward
else
raise "invalid angle"
end
elsif dy == -1
case self.angle
when 0
turn_left
run_forward
when 90
run_backward
when 180
turn_right
run_forward
when 270
run_forward
else
raise "invalid angle"
end
end
end
def movable?(target_cell)
return false if @animation
dx = target_cell[0] - @cell_x
dy = target_cell[1] - @cell_y
return (dx ** 2 + dy ** 2) == 1
end
def animate(destination)
dest_x = destination[0] * 160
dest_y = destination[1] * 160
complete_x = false
complete_y = false
if self.x - dest_x < 0
self.x += 1
elsif self.x == dest_x
complete_x = true
else
self.x -= 1
end
if self.y - dest_y < 0
self.y += 1
elsif self.y == dest_y
complete_y = true
else
self.y -= 1
end
if [complete_x, complete_y] == [true, true]
return false
else
return true
end
end
private
def adjust_angle
self.angle += 360
self.angle %= 360
end
end |
module Rets
module Metadata
class RetsClass
attr_accessor :tables
attr_accessor :name
attr_accessor :visible_name
attr_accessor :description
attr_accessor :resource
def initialize(rets_class_fragment, resource)
self.resource = resource
self.tables = []
self.name = rets_class_fragment["ClassName"]
self.visible_name = rets_class_fragment["VisibleName"]
self.description = rets_class_fragment["Description"]
end
def self.find_table_container(metadata, resource, rets_class)
metadata[:table].detect { |t| t.resource == resource.id && t.class == rets_class.name }
end
def self.build(rets_class_fragment, resource, metadata)
rets_class = new(rets_class_fragment, resource)
table_container = find_table_container(metadata, resource, rets_class)
if table_container
table_container.tables.each do |table_fragment|
rets_class.tables << TableFactory.build(table_fragment, resource)
end
end
rets_class
end
def print_tree
puts " Class: #{name}"
puts " Visible Name: #{visible_name}"
puts " Description : #{description}"
tables.each(&:print_tree)
end
def find_table(name)
tables.detect { |value| value.name == name }
end
end
end
end
|
class AddColumnsToDivision < ActiveRecord::Migration
def change
add_column :divisions, :url, :string, default: ''
add_column :divisions, :reference, :integer
end
end
|
class FixReviews < ActiveRecord::Migration[5.0]
def change
remove_foreign_key(:specialists, :reviews)
remove_column(:specialists, :review_id, :integer, {:index=>true})
add_reference :reviews, :specialist, foreign_key: true, index: true
end
end
|
# frozen_string_literal: true
class PersonSerializer < BaseSerializer
attributes :id, :first_name, :last_name, :full_name, :gender, :current_age, :city, :state_code, :country_code
%i[phone email birthdate].each { |att| attribute att, if: :show_personal_info? }
link(:self) { api_v1_person_path(object) }
has_many :efforts
end
|
class Account < ActiveRecord::Base
attr_accessible :name
belongs_to :user
has_many :projects, :dependent => :destroy
validates_uniqueness_of :name
end
|
class SubstancesPrintView < Dry::View::Controller
configure do |config|
config.paths = ["#{App.root}/app/templates"]
config.layout = "print"
config.template = "substances_print"
end
expose :results
end
|
#!/usr/bin/env ruby
VERSION_NOTE = %(\
金魚草 v2.1.0
Copyright 2020, Rew Howe
https://github.com/rewhowe/snapdragon
).freeze
require_relative 'src/errors'
require_relative 'src/interpreter/errors'
require_relative 'src/interpreter/processor'
require_relative 'src/tokenizer/errors'
require_relative 'src/tokenizer/reader/factory'
require_relative 'src/tokenizer/lexer'
require_relative 'src/util/i18n'
require_relative 'src/util/logger'
require_relative 'src/util/options'
require_relative 'src/util/repl'
require_relative 'src/util/token_printer'
options = Util::Options.parse_arguments
if options[:version]
puts VERSION_NOTE
exit
end
Util::I18n.setup options
Util::Logger.setup options
Util::Logger.debug(Util::Options::DEBUG_3) { options }
Errors.register_custom_errors Tokenizer::Errors
Errors.register_custom_errors Interpreter::Errors
begin
reader = Tokenizer::Reader::Factory.make options
lexer = Tokenizer::Lexer.new reader, options
if options[:tokens]
Util::TokenPrinter.print_all lexer
exit
end
processor = Interpreter::Processor.new lexer, options
if options[:input] == Util::Options::INPUT_INTERACTIVE
Util::Repl.run reader, processor
else
result = processor.execute
exit result.result_code if result.is_a? Interpreter::ReturnValue
end
rescue => e
raise e if options[:debug] != Util::Options::DEBUG_OFF
abort e.message.red if e.is_a? Errors::BaseError
abort Util::I18n.t 'internal_errors.unknown'
end
|
class Users::FavouritesController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
before_action :set_user
before_action :set_favourite, except: :index
def index
@favourites = @user.favourites.positioned.page params[:page]
end
def destroy
@favourite.destroy
render nothing: true
end
private
def set_user
@user = current_user
end
def set_favourite
@favourite = @user.favourites.find(params[:id])
end
def redirect_paths
user_favourites_path(@user)
end
def favourite_params
params.require(:favourite).permit!
end
end
|
garage_inventory = []
garage_inventory << {:name => 'computer', :price => '100.00', :quantity => 1}
garage_inventory << {:name => 'book', :price => '3.50', :quantity => 5}
# Using the array, print out a list of each item with their price and quantity available using each.
garage_inventory.each do |item|
item.each do |key, value|
puts "#{key}: #{value}"
end
end
# Print out the number of types of items you have using count.
puts garage_inventory.count
# Print the total value of each item on stock: price * quantity.
garage_inventory.each do |item|
value = item[:price].to_f * item[:quantity]
puts "Total value for #{item[:name]}s in stock is: $#{value}."
end
# Print out the total value of inventory: all the items quantity * their prices, respectively.
total_inv_val = garage_inventory.collect do |item|
value = item[:price].to_f * item[:quantity]
end
puts "Total inventory value is #{total_inv_val.reduce(0, :+)}." |
class PathBuilder
def initialize(args)
args.each_pair do |k,v|
instance_variable_set "@#{k}", v
end
end
def build_list_page
File.join @host, "dashboard/project/list/all/#{@project}"
end
def expand relative_build_log_uri
File.join @host, relative_build_log_uri
end
def expand_cobertura relative_build_log_uri
match = /\/log(\d*)L.*$/.match relative_build_log_uri
File.join @host, "artifacts/#{@project}/#{match[1]}/cobertura/frame-summary.html"
end
end |
class Review < ActiveRecord::Base
has_ancestry
belongs_to :app, :counter_cache => true
belongs_to :reviewer, :class_name => "User"
attr_accessible :body, :parent_id
default_scope { order("upvotes_count DESC") }
has_many :upvotes, :as => :upvotable
# return a string of how long ago this review was made
def created_ago_s
delta = (Time.now - created_at)
seconds_in_minute = 60
seconds_in_hour = 60 * seconds_in_minute
seconds_in_day = seconds_in_hour * 24
seconds_in_week = seconds_in_day * 7
seconds_in_year = seconds_in_week * 52
if delta < seconds_in_minute
return "#{(delta).to_i} seconds ago"
elsif delta < seconds_in_hour
return "#{(delta / seconds_in_minute).to_i} minutes ago"
elsif delta < seconds_in_day
return "#{(delta / seconds_in_hour).to_i} hours ago"
elsif delta < seconds_in_week
return "#{(delta / seconds_in_day).to_i} days ago"
else
return "a while ago"
end
end
end
|
MESSAGES = {
"welcome" => {
"en" => "Welcome to Calculator! Enter your name:"
},
"hello" => {
"en" => "Hello"
},
"enter_num1" => {
"en" => "What's the first number?"
},
"enter_num2" => {
"en" => "What's the second number?"
},
"invalid_name" => {
"en" => "Make sure to use a valid name."
},
"invalid_number" => {
"en" => "Hmm... that doesn't look like a valid number."
},
"invalid_operation" => {
"en" => "Must choose 1, 2, 3 or 4"
},
"adding" => {
"en" => "Adding the two numbers..."
},
"subtracting" => {
"en" => "Subtracting the two numbers..."
},
"multiplying" => {
"en" => "Multiplying the two numbers..."
},
"dividing" => {
"en" => "Dividing the two numbers..."
},
"result_prefix" => {
"en" => "The result is:"
},
"calculate_again?" => {
"en" => "Do you want to perform another calculation? (Y to calculate again)"
},
"operator_prompt" => {
"en" => <<-MSG
What operation would you like to perform?
1) add
2) subtract
3) multiply
4) divide
MSG
},
"goodbye" => {
"en" => "Thank you for using the calculator. Goodbye!"
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.