text stringlengths 10 2.61M |
|---|
class AuthenticationsController < ApplicationController
def index
@authentications = Authentication.all
end
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
if current_user && (current_user.id != authentication.user_id)
redirect_to :root, :notice => "Someone has been already added this #{omniauth['provider']} account."
else
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
end
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to "/home/index"
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
def destroy
@authentication = Authentication.find(params[:id])
@authentication.destroy
redirect_to :back, :notice => "Successfully destroyed authentication."
end
protected
# This is necessary since Rails 3.0.4
# See https://github.com/intridea/omniauth/issues/185
# and http://www.arailsdemo.com/posts/44
def handle_unverified_request
true
end
end
|
require "features_helper"
RSpec.feature "To test overdue appointment functionality", type: :feature do
let(:ihmi) { create(:organization, name: "IHMI") }
let(:ihmi_facility_group) { create(:facility_group, organization: ihmi, name: "Bathinda") }
let(:test_facility) { create(:facility, facility_group: ihmi_facility_group, name: "test_facility") }
let(:owner) { create(:admin, :power_user, facility_group: ihmi_facility_group) }
login = AdminPage::Sessions::New.new
appoint_page = AppointmentsPage::Index.new
nav_page = Navigations::DashboardPageNavigation.new
context "Page verification" do
before(:each) do
visit root_path
login.do_login(owner.email, owner.password)
end
it "landing page -with no overdue patient" do
nav_page.click_main_menu_tab("Overdue patients")
appoint_page.verify_overdue_landing_page
expect(page).to have_content("Overdue patients")
expect(page).to have_content("All facilities")
expect(page).to have_content("20 per page")
expect(page).to have_content("No overdue patients found")
end
it "landing page -Facility and page dropdown " do
create_list(:facility, 2, facility_group: ihmi_facility_group)
nav_page.click_main_menu_tab("Overdue patients")
expect(appoint_page.get_all_facility_count).to eq(2)
appoint_page.select_page_dropdown
expect(appoint_page.get_all_page_dropdown).to eq(2)
end
it "landing page -patient list - with all facility category" do
patients = create_list(:patient, 2, registration_facility: test_facility, registration_user: owner)
patients.each do |patient|
create(:appointment, :overdue, facility: test_facility, patient: patient, scheduled_date: 10.days.ago, user: owner)
end
patients.each do |patient|
create(:blood_pressure, :critical, facility: test_facility, patient: patient, user: owner)
end
nav_page.click_main_menu_tab("Overdue patients")
expect(appoint_page.get_all_patient_count.size).to eq(2)
end
it "landing page -pagination" do
patients = create_list(:patient, 22, registration_facility: test_facility, registration_user: owner)
patients.each do |patient|
create(:appointment, :overdue, facility: test_facility, patient: patient, scheduled_date: 10.days.ago, user: owner)
end
patients.each do |patient|
create(:blood_pressure, :critical, facility: test_facility, patient: patient, user: owner)
end
nav_page.click_main_menu_tab("Overdue patients")
expect(page).to have_content("All facilities")
expect(page).to have_content("20 per page")
expect(appoint_page.get_all_patient_count.size).to eq(20)
expect(appoint_page.get_page_link_count.size).to eq(4)
expect(page).to have_content("Next")
expect(page).to have_content("Last")
end
it "landing page - overdue patient card detail" do
# creating overdue patient test data for test_facility, belongs to IHMI
var_patients = create(:patient, registration_facility: test_facility)
var_appointment = create(:appointment, :overdue, facility: test_facility, patient: var_patients, scheduled_date: 10.days.ago)
var_bp = create(:blood_pressure, :critical, facility: test_facility, patient: var_patients)
nav_page.click_main_menu_tab("Overdue patients")
find("option[value=#{ihmi_facility_group.slug}]").click
within(".card") do
expect(page).to have_content(var_patients.full_name)
expect(page).to have_content(var_patients.age)
expect(page).to have_content("Registered on:")
expect(page).to have_content(var_patients.registration_date)
expect(page).to have_content("Last BP:")
expect(page).to have_content(var_bp.to_s)
expect(page).to have_content(var_bp.facility.name)
expect(page).to have_content(var_patients.address.street_address)
expect(page).to have_content("Call result")
expect(find("a.btn-phone").text).to eq(var_patients.phone_numbers.first.number)
expect(appoint_page.get_overdue_days).to eq(var_appointment.days_overdue.to_s + " days overdue")
end
end
end
context "verify overdue patient list to exclude patients > 12 months overdue" do
before(:each) do
visit root_path
login.do_login(owner.email, owner.password)
end
it "patient is exact 365 days overdue" do
var_patients = create(:patient, registration_facility: test_facility)
create(:blood_pressure, :critical, facility: test_facility, patient: var_patients)
create(:appointment, :overdue, facility: test_facility, patient: var_patients, scheduled_date: 365.days.ago)
nav_page.click_main_menu_tab("Overdue patients")
find("option[value=#{ihmi_facility_group.slug}]").click
expect(page).to have_content(var_patients.full_name)
end
it "366 days overdue" do
var_patients = create(:patient, registration_facility: test_facility)
create(:blood_pressure, :critical, facility: test_facility, patient: var_patients)
create(:appointment, :overdue, facility: test_facility, patient: var_patients, scheduled_date: 366.days.ago)
nav_page.click_main_menu_tab("Overdue patients")
find("option[value=#{ihmi_facility_group.slug}]").click
expect(page).not_to have_content(var_patients.full_name)
end
it "0 days overdue" do
var_patients = create(:patient, registration_facility: test_facility)
create(:blood_pressure, :critical, facility: test_facility, patient: var_patients)
create(:appointment, :overdue, facility: test_facility, patient: var_patients, scheduled_date: 0.days.ago)
nav_page.click_main_menu_tab("Overdue patients")
find("option[value=#{ihmi_facility_group.slug}]").click
expect(page).not_to have_content(var_patients.full_name)
end
end
end
|
class Company < ApplicationRecord
belongs_to :country, optional: true
belongs_to :company, optional: true
has_many :companies, dependent: :destroy
has_many :appointments, dependent: :destroy
has_many :offshore_fields, dependent: :destroy
validates :company_name, presence: true
end
|
#!/usr/bin/env ruby
# encoding: UTF-8
#
# Copyright © 2012-2014 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative 'utils'
class FogProviderJoyent < Coopr::Plugin::Provider
include FogProvider
# plugin defined resources
@ssh_key_dir = 'ssh_keys'
class << self
attr_accessor :ssh_key_dir
end
def create(inputmap)
flavor = inputmap['flavor']
image = inputmap['image']
hostname = inputmap['hostname']
fields = inputmap['fields']
begin
# Our fields are fog symbols
fields.each do |k, v|
instance_variable_set('@' + k, v)
end
# Create the server
log.debug "Creating #{hostname} on Joyent using flavor: #{flavor}, image: #{image}"
log.debug 'Invoking server create'
begin
server = connection.servers.create(
package: flavor,
dataset: image,
name: hostname,
key_name: @ssh_keypair
)
end
# Process results
@result['result']['providerid'] = server.id.to_s
@result['result']['ssh-auth']['user'] = @task['config']['sshuser'] || 'root'
@result['result']['ssh-auth']['identityfile'] = File.join(Dir.pwd, self.class.ssh_key_dir, @ssh_key_resource) unless @ssh_key_resource.nil?
@result['status'] = 0
rescue Excon::Errors::Unauthorized
msg = 'Provider credentials invalid/unauthorized'
@result['status'] = 201
@result['stderr'] = msg
log.error(msg)
rescue Fog::Compute::Joyent::Errors::Conflict => e
msg = "Conflict: #{e.inspect}"
@result['status'] = 202
@result['stderr'] = msg
log.error(msg)
rescue => e
log.error('Unexpected Error Occurred in FogProviderJoyent.create: ' + e.inspect)
@result['stderr'] = "Unexpected Error Occurred in FogProviderJoyent.create: #{e.inspect}"
else
log.debug "Create finished successfully: #{@result}"
ensure
@result['status'] = 1 if @result['status'].nil? || (@result['status'].is_a?(Hash) && @result['status'].empty?)
end
end
def confirm(inputmap)
providerid = inputmap['providerid']
fields = inputmap['fields']
begin
# Our fields are fog symbols
fields.each do |k, v|
instance_variable_set('@' + k, v)
end
# Confirm server
log.debug "Invoking server confirm for id: #{providerid}"
server = connection.servers.get(providerid)
# Wait until the server is ready
fail "Server #{server.name} is in ERROR state" if server.state == 'ERROR'
log.debug "waiting for server to come up: #{providerid}"
start = Time.now
server.wait_for(600) { ready? }
log.debug "server wait took #{Time.now - start} seconds"
bootstrap_ip = ip_address(server)
if bootstrap_ip.nil?
log.error 'No IP address available for bootstrapping.'
fail 'No IP address available for bootstrapping.'
else
log.debug "Bootstrap IP address #{bootstrap_ip}"
end
wait_for_sshd(bootstrap_ip, 22)
log.debug "Server #{server.name} sshd is up"
# Process results
@result['ipaddresses'] = {
'access_v4' => bootstrap_ip,
'bind_v4' => bootstrap_ip
}
@result['result']['ssh_host_keys'] = {
'rsa' => ssh_keyscan(bootstrap_ip)
}
# do we need sudo bash?
sudo = 'sudo -E' unless @task['config']['ssh-auth']['user'] == 'root'
set_credentials(@task['config']['ssh-auth'])
# login with pseudotty and turn off sudo requiretty option
log.debug "Attempting to ssh to #{bootstrap_ip} as #{@task['config']['ssh-auth']['user']} with credentials: #{@credentials} and pseudotty"
Net::SSH.start(bootstrap_ip, @task['config']['ssh-auth']['user'], @credentials) do |ssh|
sudoers = true
begin
ssh_exec!(ssh, 'test -e /etc/sudoers', 'Checking for /etc/sudoers')
rescue CommandExecutionError
log.debug 'No /etc/sudoers file present'
sudoers = false
end
cmd = "#{sudo} sed -i -e '/^Defaults[[:space:]]*requiretty/ s/^/#/' /etc/sudoers"
ssh_exec!(ssh, cmd, 'Disabling requiretty via pseudotty session', true) if sudoers
end
# Validate connectivity
Net::SSH.start(bootstrap_ip, @task['config']['ssh-auth']['user'], @credentials) do |ssh|
ssh_exec!(ssh, 'ping -c1 www.joyent.com', 'Validating external connectivity and DNS resolution via ping')
ssh_exec!(ssh, "#{sudo} hostname #{@task['config']['hostname']}", 'Temporarily setting hostname')
# Check and make sure firstboot is done running
beginning = Time.now
ssh_exec!(ssh, 'cproc="smartdc/firstboot"; uproc="cloud-init"; for i in {1..240}; do if pgrep $cproc > /dev/null || pgrep $uproc > /dev/null; then sleep 1; else break; fi; done', 'Waiting until ${cproc} or ${uproc} are done running')
log.debug "firstboot & cloud-init process check took #{Time.now - beginning} seconds"
# Check for /dev/vdb
begin
vdb1 = true
vdb = false
# test for vdb1
begin
ssh_exec!(ssh, 'test -e /dev/vdb1', 'Checking for /dev/vdb1')
rescue
vdb1 = false
begin
vdb = true
ssh_exec!(ssh, 'test -e /dev/vdb', 'Checking for /dev/vdb')
rescue
vdb = false
end
end
end
log.debug 'Found the following:'
log.debug "- vdb1 = #{vdb1}"
log.debug "- vdb = #{vdb}"
# confirm it is not already mounted
# ubuntu: we remount from /mnt to /data
# centos: vdb1 already mounted at /data
if vdb1
# TODO: check that vdb1 is mounted at /data, for now assume it is
log.debug 'Assuming /dev/vdb1 is mounted at /data or at /mnt, if this is not the case, file an issue'
elsif vdb
begin
data_mounted = false
ssh_exec!(ssh, 'if grep "vdb /data " /proc/mounts ; then echo "/dev/vdb is mounted"; else /bin/false ; fi', 'Checking in /proc/mounts whether /dev/vdb mounted already')
data_mounted = true
rescue
log.debug 'Disk /dev/vdb is not mounted to /data'
end
# If data_mounted = true, we're done
unless data_mounted
# disk isn't mounted at /data, could be mounted elsewhere (e.g. /mnt)
begin
# Are we mounted? # if we are, set unmount to true
unmount = false
ssh_exec!(ssh, 'if mount | grep "^/dev/vdb " ; then echo "Disk /dev/vdb is mounted" ; else /bin/false ; fi', 'Confirm /dev/vdb is mounted')
unmount = true
rescue
log.debug 'Disk /dev/vdb is not mounted'
end
if unmount
begin
ssh_exec!(ssh, "#{sudo} umount /dev/vdb", 'Unmounting /dev/vdb')
rescue
raise 'Failure unmounting data disk /dev/vdb'
end
end
# Disk is unmounted, format it
begin
ssh_exec!(ssh, "#{sudo} /sbin/mkfs.ext4 /dev/vdb", 'Formatting filesystem at /dev/vdb')
rescue
raise 'Failure formatting data disk /dev/vdb'
end
# Mount it
begin
ssh_exec!(ssh, "#{sudo} mkdir -p /data && #{sudo} mount -o _netdev /dev/vdb /data", 'Mounting /dev/vdb as /data')
rescue
raise 'Failed to mount /dev/vdb at /data'
end
ssh_exec!(ssh, "#{sudo} sed -i -e 's:/mnt:/data:' /etc/fstab", 'Updating /etc/fstab for /data')
end
end
end
# Return 0
@result['status'] = 0
rescue Fog::Errors::TimeoutError
log.error 'Timeout waiting for the server to be created'
@result['stderr'] = 'Timed out waiting for server to be created'
rescue Net::SSH::AuthenticationFailed => e
log.error("SSH Authentication failure for #{providerid}/#{bootstrap_ip}")
@result['stderr'] = "SSH Authentication failure for #{providerid}/#{bootstrap_ip}: #{e.inspect}"
rescue => e
log.error('Unexpected Error Occurred in FogProviderJoyent.confirm: ' + e.inspect)
@result['stderr'] = "Unexpected Error Occurred in FogProviderJoyent.confirm: #{e.inspect}"
else
log.debug "Confirm finished successfully: #{@result}"
ensure
@result['status'] = 1 if @result['status'].nil? || (@result['status'].is_a?(Hash) && @result['status'].empty?)
end
end
def delete(inputmap)
providerid = inputmap['providerid']
fields = inputmap['fields']
begin
# Our fields are fog symbols
fields.each do |k, v|
instance_variable_set('@' + k, v)
end
# Delete server
log.debug 'Invoking server delete'
begin
fail ArgumentError if providerid.nil? || providerid.empty?
server = connection.servers.get(providerid)
server.destroy
rescue ArgumentError
log.debug "Invalid provider id #{providerid} specified on delete... skipping"
rescue NoMethodError, Fog::Compute::Joyent::Errors::NotFound
log.warn "Could not locate server '#{providerid}'... skipping"
else
sleep 30
end
# Return 0
@result['status'] = 0
rescue Fog::Compute::Joyent::Errors::Conflict => e
msg = 'Unable to delete a VM that has not been allocated to a server yet'
log.error(msg)
@result['stderr'] = msg
rescue => e
log.error('Unexpected Error Occurred in FogProviderJoyent.delete: ' + e.inspect)
@result['stderr'] = "Unexpected Error Occurred in FogProviderJoyent.delete: #{e.inspect}"
else
log.debug "Delete finished sucessfully: #{@result}"
ensure
@result['status'] = 1 if @result['status'].nil? || (@result['status'].is_a?(Hash) && @result['status'].empty?)
end
end
# Shared definitions (borrowed from knife-joyent gem, Apache 2.0 license)
def connection
# Create connection
# rubocop:disable UselessAssignment
@connection ||= begin
connection = Fog::Compute.new(
provider: 'Joyent',
joyent_username: @api_user,
joyent_password: @api_password,
joyent_keyname: @ssh_keypair,
joyent_keyfile: File.join(self.class.ssh_key_dir, @ssh_key_resource),
joyent_url: @joyent_api_url,
joyent_version: @joyent_version
)
end
# rubocop:enable UselessAssignment
end
def ip_address(server)
server_ips = server.ips.select { |ip| ip && !(loopback?(ip) || linklocal?(ip)) }
if server_ips.count === 1
server_ips.first
else
server_ips.find { |ip| !private?(ip) }
end
end
end
|
module DcrugDna
class Decoder
def initialize(base_pair_sequence)
@base_pair_sequence = base_pair_sequence
end
def decode
sequence_as_ordinals.map { |decimal| decimal.chr }.join
end
private
attr_reader :base_pair_sequence
def base_pairs_as_quaternary
base_pair_sequence.chars.each_slice(2).map(&:join).map do |pair|
DcrugDna::BASE_PAIRS.index(pair).to_s
end
end
def sequence_as_ordinals
base_pairs_as_quaternary.each_slice(4).map(&:join).map do |base_four|
base_four.to_i(4).to_i
end
end
end
end
|
require 'spec_helper'
describe UsersHelper do
describe "gravatar_for" do
before do
@user = User.new(name: "Mr. Bennett", email: "mail@mail.com")
@gravatar_base_url = "https://secure.gravatar.com/avatar/"
@gravatar_id = Digest::MD5::hexdigest(@user.email.downcase)
end
it "should include the gravatar's default size" do
gravatar_for(@user).should =~ /s=80/
end
it "should include the gravatar's custom size" do
gravatar_for(@user, {size: 40}).should =~ /s=40/
end
it "should output an <img> tag" do
gravatar_for(@user).should =~ /^<img/
end
it "should have the secure gravatar url included" do
gravatar_for(@user).should =~ /src=\"#{@gravatar_base_url}#{@gravatar_id}/
end
it "should have an alt attribute with the user's name" do
gravatar_for(@user).should =~ /alt=\"#{@user.name} img\"/
end
it "should have a 'gravatar' selector class" do
gravatar_for(@user).should =~ /class="gravatar"/
end
end
end
|
class Job < ApplicationRecord
validates :title, :level_of_interest, :city, presence: true
belongs_to :company
belongs_to :category, optional: true
has_many :comments
def self.company_jobs_index
Company.find(:company_id).jobs
end
def self.sort(params)
if params == 'location'
order(:city)
elsif params == 'interest'
order(:level_of_interest).reverse
end
end
def self.level_count
group(:level_of_interest).order('level_of_interest DESC').count
end
def self.by_city(params)
where(city: params)
end
end
|
module SyntaxHighlighting
# Represents a tmLanguage file.
#
class Language
# - parameter contents: Hash
#
def initialize(contents, parent_repository = nil)
@name = contents["name"]
@scope_name = contents["scope_name"]
@repository = Repository.new(
{ "$self" => self }.merge(contents["repository"] || {}),
parent_repository
)
contents["patterns"].each do |pattern_contents|
patterns << Pattern.find_or_initialize(pattern_contents, repository)
end
repository.freeze
patterns.freeze
end
# The name of the language.
#
attr_reader :name
# This is used as a reference when patterns need to reference another
# language. E.g. in markdown, if you put a code block, the code inside can
# be syntax highlighted to the type of code inside that block.
#
attr_reader :scope_name
# Hash that stores reusable patterns that can be "included" in patterns.
#
# For example in the tmLanguage:
# ```
# "escaped_char": {
# "match": "\\\\(?:[0-7]{1,3}|x[\\da-fA-F]{1,2}|.)",
# "name": "constant.character.escape.ruby"
# },
# ```
#
# Is repesented here as `{ name => pattern }`
#
attr_reader :repository
# See `Pattern`.
#
def patterns
@patterns ||= []
end
def begin
nil
end
def match
nil
end
end
end
|
module Backend
class UsersController < BackendController
before_filter :find_user, only: [:show, :edit, :update, :destroy, :impersonate]
def index
@users = User.all
respond_to do |format|
format.html
format.csv { send_data @users.to_csv }
end
end
def show
end
def new
@user = User.new
end
def create
@user = User.create(user_params)
if @user.save
redirect_to backend_users_path
else
flash.now[:error] = 'Could not create user'
render action: 'new'
end
end
def destroy
@user.destroy
redirect_to backend_users_path
end
def edit
end
def update
@user.update!(user_params)
redirect_to backend_users_path
end
private
def find_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(User.permitted_params)
end
end
end
|
# coding: utf-8
class Lexer
# 最初に、我々の言語でのspecial keywordsを定数で定義します。
# First we define the special keywords of our language in a constant.
# 後ほど、これはtokenizingの過程で、
# It will be used later on in the tokenizing process to disambiguate
# keywordと識別子(メソッド名、ローカル変数、その他)と区別するために使われます。
# an identifier (method name, local variable, etc.) from a keyword.
KEYWORDS = ["def", "class", "if", "true", "false", "nil"]
def tokenize(code)
code.chomp!
tokens = []
# ここでは、プログラムが現在どれほど深いインデントを字句解析しているかを知るために、
# We need to know how deep we are in the indentation
# 現在字句解析しているインデントレベルを保持し、またそのレベルをスタックに保持します。
# so we keep track of the current indentation level we are in, and previous ones in the stack
# そうすることにより、インデントレベルが下がった時(デデントした時)、我々が正しいレベルに居るかどうかを確認できます。
# so that when we dedent, we can check if we're on the correct level.
current_indent = 0
indent_stack = []
# 以下がとても単純なScannerの実装方法になります。
# Here is how to implement a very simple scanner.
# 解析するべき文字を見つけるまで、一文字ずつ文字を読み進めていきます。
# Advance one character at the time until you find something to parse.
# 以下のwhile文内では正規表現を用いて、現在の解析位置(変数iに格納されます)からコードの最後までプログラムを字句解析していきます。
# We'll use regular expressions to scan from the current position (i) up to the end of the code.
i = 0
while i < code.size
chunk = code[i..-1]
# 以下の各if/elsif節では、解析位置(変数i)のコードのまとまりを正規表現を使って検査していきます。
# Each of the following [if/elsif]s will test the current code chunk with a regular expression.
# ここで、ifをメソッド名ではなくキーワード(プログラム最初に宣言したKEYWORDS定数)として認識させる為には
# 最初のif/else節で補足する必要があり、今後も各if/else節の順番は重要になってきます。
# The order is important as we want to match [if] as a keyword, and not a method name, we'll need to apply it first.
# まず最初に、メソッド名や変数名(以下、識別子)を字句解析します。
# First, we'll scan for names: method names and variable names, which we'll call identifiers.
# 同じく、定数KEYWORDSに保持されている特別な意味を持つ単語(if、defやtrueなど)についてもここで字句解析します。
# Also scanning for special reserved keywords such as [if], [def] and [true].
if identifier = chunk[/\A([a-z]\w*)/, 1]
if KEYWORDS.include?(identifier)
tokens << [identifier.upcase.to_sym, identifier]
else
tokens << [:IDENTIFIER, identifier]
end
i += identifier.size
# 次に、先頭が大文字から始まる定数の走査に入ります。
# Now scanning for constants, names starting with a capital letter.
# これが意味するのは、我々の言語Awesomeではクラス名は定数であるということです。
# Which means, class names are constants in our language.
elsif constant = chunk[/\A([A-Z]\w*)/, 1]
tokens << [:CONSTANT, constant]
i += constant.size
# 次にNumberのマッチングに入ります。ここで、この言語では整数型のみを扱うことにします。
# Next, matching numbers. Our language will only support integers.
# しかし、浮動小数点型を新しく扱うにしても
# But to add support for floats,
# 単純に整数型と似た規則と正規表現を通例に従って適用する必要があるだけです。
# you'd simply need to add a similar rule and adapt the regular expression accordingly.
elsif number = chunk[/\A([0-9]+)/, 1]
tokens << [:NUMBER, number.to_i]
i += number.size
# もちろん、Stringのマッチングも同様です。ダブルクォートで囲まれた文字全てが対象になります。
# Of course, matching strings too. Anything between ["] and ["].
elsif string = chunk[/\A"([^"]*)"/, 1]
tokens << [:STRING, string]
i += string.size + 2
# さて、ここからが重要なインデントマジックについてです!ここで我々は三つのケースを取り扱う必要があります。
# And here's the indentation magic! We have to take care of 3 cases:
# if true: # 1) The block is created.
# line 1
# line 2 # 2) New line inside a block, at the same level.
# continue # 3) Dedent.
# このelsif節では最初のケースを取り扱います。空白文字の数がインデントレベルを決定します。
# This [elsif] takes care of the first case. The number of spaces will determine the indent level.
elsif indent = chunk[/\A\:\n( +)/m, 1]
if indent.size <= current_indent
raise "Bad indent level, got #{indent.size} indents, " + "expected > #{current_indent}"
end
current_indent = indent.size
indent_stack.push(current_indent)
tokens << [:INDENT, indent.size]
i += indent.size + 2
# 次のelsif節では以下のCase2と3を取り扱います。
# The next [elsif] takes care of the two last cases:
# Case 2: もしインデントレベル(空白文字の数)がcurrent_indentと同じだった場合、同じブロックに留まります。
# Case 2: We stay in the same block if the indent level (number of spaces) is the same as [current_indent].
# Case 3: インデントレベルがcurrent_indentよりも低かった場合、現在のブロックを:DEDENTにより閉じます。
# Case 3: Close the current block, if indent level is lower than [current_indent].
elsif indent = chunk[/\A\n( *)/m, 1]
if indent.size == current_indent
tokens << [:NEWLINE, "\n"]
elsif indent.size < current_indent
while indent.size < current_indent
indent_stack.pop
current_indent = indent_stack.last || 0
tokens << [:DEDENT, indent.size]
end
tokens << [:NEWLINE, "\n"]
else
raise "Missing ':'"
end
i += indent.size + 1
# Long operators(記述される事が多くよく利用される演算子?)、
# いわゆる ||だとか、&&、== などは以下のelsif節のブロックで捕捉されます。
# Long operators such as ||, &&, ==, etc. will be matched by the following block.
# 1文字のLong operatorsはこれより下のelse節で全て捕捉されます。
# One character long operators are matched by the catch all [else] at the bottom.
elsif operator = chunk[/\A(\|\||&&|==|!=|<=|>=)/, 1]
tokens << [operator, operator]
i += operator.size
# この言語、Awesomeでは空白は無視されます。改行文字とは対照的に、空白文字はここでは特別な意味を持たないのです。
# We're ignoring spaces. Contrary to line breaks, spaces are meaningless in our language.
# 理由として、我々が空白文字用のトークンを作成しないというからというが挙げられます。
# That's why we don't create tokens for them.
# 空白文字は、あるトークンとまた別のトークンを分割するためだけに使われます。
# They are only used to separate other tokens.
elsif chunk.match(/\A /)
i += 1
# 最後に、全ての一文字の記号(主に演算子)を補足します。
# Finally, catch all single characters, mainly operators.
# ここで、今までのif-else節で補足されていない全ての一文字の記号はトークンとして扱います。
# We treat all other single characters as a token. Eg.: ( ) , . ! + - <.
else
value = chunk[0,1]
tokens << [value, value]
i += 1
end
end
# ここでは全ての開いたブロックを閉じます。
# Close all open blocks.
# もしデデント無しにコードが終わっていた場合、ここでインデントとデデントの数を調節します。
# If the code ends without dedenting, this will take care of balancing the [INDENT]...[DEDENT]s.
while indent = indent_stack.pop
tokens << [:DEDENT, indent_stack.first || 0]
end
tokens
end
end
|
class User < ActiveRecord::Base
@@count = 0
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :id, :email, :username, :password, :password_confirmation, :remember_me, :username
has_many :post_comments
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
if auth.info.email == nil
user.email = 'undefined'+User.count.to_s+'@email.com'
else
user.email = auth.info.email
end
if auth.info.nickname != nil
user.username = auth.info.nickname
elsif auth.info.name != nil
user.username = auth.info.name
end
user.password = Devise.friendly_token[0,20]
end
end
def self.count
@@count += 1
return @@count
end
end
|
class ProductOrder
include ActiveModel::Model
attr_accessor :authenticity_token, :token, :postal_code, :prefecture_id, :city, :address, :building_name, :phone_number, :user_id, :product_id
# バリデーション
validates :token, presence: true
POSTAL_CODE_REGEX = /\A\d{3}[-]\d{4}\z/.freeze
validates :postal_code, presence: true, format: { with: POSTAL_CODE_REGEX, message: 'は「-」を含む7桁で入力してください' }
validates :prefecture_id, numericality: { other_than: 1, message: 'を選択してください' }
validates :city, :address, presence: true
PHONE_NUMBER_REGEX = /\A\d{10,11}\z/.freeze
validates :phone_number, presence: true, format: { with: PHONE_NUMBER_REGEX, message: 'は半角数字の11桁以内で入力してください' }
def save
order = Order.create(user_id: user_id, product_id: product_id)
SendingAddress.create(postal_code: postal_code, prefecture_id: prefecture_id, city: city, address: address, \
building_name: building_name, phone_number: phone_number, order_id: order.id)
end
end
|
require 'nokogiri'
require 'date'
require 'ostruct'
require 'delegate'
require 'uri'
# encoding: utf-8
class ITunesLibrary < DelegateClass( OpenStruct )
VERSION="0.0.1"
def initialize itunes_file
@db={}
File.open( itunes_file, 'r' ) {|io|
@parser=Nokogiri::XML::Reader io
loop do
node=@parser.read
break unless node
next if whitespace? node
# The iTunes XML is basically just a deeply nested dict.
if start_of_dict? node
@db=read_dict( node )
end
end
}
# flatten out the track list (keyed by Track ID), since the track_id is
# an internal key anyway.
@db[:tracks]=@db[:tracks].values.map {|h|
# Change from a file:// URI to a local path. Probably broken if you
# have stuff on shared disks, the internet etc etc
h[:location]=uri_parser.unescape( URI.parse( h[:location] ).path )
OpenStruct.new h
}
super OpenStruct.new( @db )
end
def inspect
"iTunes Library: #{self.tracks.size} tracks."
end
private
def uri_parser
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
end
# A bit ugly, but it makes the rest of the code nicer.
def start_of_element? node
node.node_type==Nokogiri::XML::Reader::TYPE_ELEMENT
end
def end_of_element? node
node.node_type==Nokogiri::XML::Reader::TYPE_END_ELEMENT
end
def start_of_dict? node
node.node_type==Nokogiri::XML::Reader::TYPE_ELEMENT and node.name=='dict'
end
def end_of_dict? node
node.node_type==Nokogiri::XML::Reader::TYPE_END_ELEMENT and node.name=='dict'
end
def start_of_array? node
node.node_type==Nokogiri::XML::Reader::TYPE_ELEMENT and node.name=='array'
end
def end_of_array? node
node.node_type==Nokogiri::XML::Reader::TYPE_END_ELEMENT and node.name=='array'
end
def whitespace? node
node.node_type==Nokogiri::XML::Reader::TYPE_SIGNIFICANT_WHITESPACE ||
node.node_type==Nokogiri::XML::Reader::TYPE_WHITESPACE
end
def snakey_symbolize str
str.downcase.split(' ').join('_').to_sym
end
def read_element node
contents=[]
type=''
# Get the element contents, if any, which may be split across
# multiple text nodes, for some reason.
loop do
if start_of_dict? node
return read_dict node
elsif start_of_array? node
return read_array node
elsif start_of_element? node
type=node.name
break if type=='true' || type=='false' # no end of element
until end_of_element? node
node=@parser.read
contents << node.value
end
break
else
# Skip stuff we don't know about, whitespace etc
node=@parser.read
end
end
# Use nice types
case type
when 'integer'
Integer( contents.join )
when *['string', 'key', 'data']
contents.join
when 'date'
DateTime.parse contents.join
when 'true'
true
when 'false'
false
else
raise "Unknown content type #{type}"
end
end
def read_array node
ary=[]
loop do
node=@parser.read
break if end_of_array? node
next if whitespace? node
ary << read_element( node )
end
ary
end
def read_dict node
dict={}
loop do
node=@parser.read
break if end_of_dict? node
next if whitespace? node
k,v=[ read_element( node ), read_element( node ) ]
dict[snakey_symbolize(k)]=v
end
dict
end
end
|
require 'rails_helper'
RSpec.describe User, :type => :model do
it { should have_many(:plays) }
it { should have_many(:histories) }
it { should have_many(:words) }
it { should validate_presence_of(:email) }
describe "#premium?" do
it "should return true if the user is premium" do
user = Fabricate(:premium_user)
expect(User.first.premium?).to eq(true)
end
it "should return false if the user is basic" do
user = Fabricate(:user)
expect(User.first.premium?).to eq(false)
end
end
end
|
class SongsController < ApplicationController
def index
@songs = Song.all
end
def new
@song = Song.new
end
def create
@song = Song.create(song_params)
if @song.save #If saving the song was successful
redirect_to @song #Go to the show view of the song
else
render "new" #Go to the new view for the song
end
end
def show
@song = Song.find(params[:id])
end
def song_params
params.require(:song).permit(:name, :genre)
end
end
|
# frozen_string_literal: true
# rubocop:todo all
class UsingHash < Hash
class UsingHashKeyError < KeyError
end
def use(key)
wrap(self[key]).tap do
delete(key)
end
end
def use!(key)
begin
value = fetch(key)
rescue KeyError => e
raise UsingHashKeyError, e.to_s
end
wrap(value).tap do
delete(key)
end
end
private
def wrap(v)
case v
when Hash
self.class[v]
when Array
v.map do |subv|
wrap(subv)
end
else
v
end
end
end
|
class FixBlankRanks < ActiveRecord::Migration
def change
change_column_default :songs, :rank, 0
end
end
|
class Feedback < ActiveRecord::Base
belongs_to :user
scope :latest, -> { order(created_at: :desc) }
end
|
# == Schema Information
#
# Table name: traffics
#
# id :integer not null, primary key
# user_id :integer
# bind_id :integer
# start_at :datetime
# period :string(255)
# remote_ip :string(255)
# incoming_bytes :integer default(0)
# outgoing_bytes :integer default(0)
# total_transfer_bytes :integer default(0)
# calculate_transfer_remaining :boolean default(FALSE)
# upcode :string(255)
# lock_version :integer default(0)
# client_id :integer
#
class Traffic < ApplicationRecord
enumerize :period, in: [:minutely, :hourly, :daily, :immediate], scope: true
belongs_to :user
belongs_to :bind
validates :upcode, uniqueness: { scope: :client_id }, allow_blank: true
before_save :build_total_transfer_bytes
after_save :cascade_calculate_transfer, if: :require_calculate_transfer?
def build_total_transfer_bytes
self.total_transfer_bytes = self.incoming_bytes + self.outgoing_bytes
end
def require_calculate_transfer?
self.period == :immediate
end
def cascade_calculate_transfer
if self.incoming_bytes_changed? || self.outgoing_bytes_changed?
transfer_bytes = self.total_transfer_bytes - self.total_transfer_bytes_was
self.user.consume(transfer_bytes) if transfer_bytes != 0
self.cascade_calculate_traffic_report
end
end
def cascade_calculate_traffic_report
access_at = self.start_at.change(:sec => 0, :usec => 0)
traffic = Traffic.where(period: 'minutely', user_id: self.user_id,
start_at: access_at, remote_ip: self.remote_ip).first_or_create
traffic.incoming_bytes += self.incoming_bytes - self.incoming_bytes_was
traffic.outgoing_bytes += self.outgoing_bytes - self.outgoing_bytes_was
traffic.save!
rescue ActiveRecord::StaleObjectError
retry
end
def self.sum_transfer_bytes(groups = [])
select_columns = [
"SUM(total_transfer_bytes) AS total_transfer_bytes",
"SUM(incoming_bytes) AS incoming_bytes",
"SUM(outgoing_bytes) AS outgoing_bytes"
]
select_columns += groups
group(groups).select(select_columns.join(", "))
end
def self.generate_hourly_records!(time_at)
start_at = time_at.beginning_of_hour
self.generate_period_records!(:hourly, start_at, start_at + 1.hour)
end
def self.generate_daily_records!(time_at)
start_at = time_at.beginning_of_day
self.generate_period_records!(:daily, start_at, start_at + 1.day)
end
def self.generate_period_records!(period, start_at, end_at)
scope = Traffic.where(period: period.to_s).where(start_at: start_at)
scope.destroy_all
Traffic.with_period('minutely').where(start_at: start_at.dup...end_at.dup)
.sum_transfer_bytes([ :user_id, :remote_ip ]).each do |grouped_traffic|
tr = scope.new(grouped_traffic.attributes)
tr.save!
end
end
end
|
class AddTimestampsToApiResponses < ActiveRecord::Migration[5.1]
def change
add_timestamps :api_responses, null: false, default: DateTime.current
change_column_default :api_responses, :created_at, nil
change_column_default :api_responses, :updated_at, nil
end
end
|
#!/usr/bin/env ruby
#this will work unless the system has more than one ext4 part
require 'sensu-plugin/check/cli'
class DiskSpace < Sensu::Plugin::Check::CLI
option :warn,
short: '-w WARN',
proc: proc {|a| a.to_f},
default: 80
option :crit,
short: '-c CRIT',
proc: proc {|a| a.to_f},
default: 90
option :sys,
short: '-s SYS',
proc: proc {|a| a.to_s},
default: 'ext4'
def run
io = IO.popen("df -t "+config[:sys]+" | awk 'FNR == 2 {print $5}'")
diskuse = io.read()
diskuse = diskuse.tr('%','')
diskuse = diskuse.to_i
critical(diskuse.to_s+'%') if diskuse > config[:crit]
warning(diskuse.to_s+'%') if diskuse > config[:warn]
ok(diskuse.to_s+'%')
end
end |
require 'spec_helper'
describe Author do
context "when the password matches the password confirmation" do
it "is valid" do
subject.password = "Pee-Wee Herman"
subject.password_confirmation = "Pee-Wee Herman"
expect(subject).to be_valid
end
end
context "when the password does not match the password confirmation" do
it "is invalid"
it "has errors"
end
end
|
class Product < ApplicationRecord
belongs_to :user
validates :product_name, presence: true, length: { minimum: 1 }
def self.search(term, per_page, current_page)
if term
Product.offset((current_page-1) * per_page).limit(per_page).where("category LIKE ?", "%#{term}%")
else
# @products = Product.all
Product.offset((current_page-1) * per_page).limit(per_page)
end
end
end
|
class CreatePlaces < ActiveRecord::Migration
def change
create_table :places do |t|
t.references :province, :null => false
t.string :name, :null => false, :limit => 50
t.string :key, :null => false, :limit => 30
t.integer :videos_count, :default => 0
t.integer :audios_count, :default => 0
t.integer :articles_count, :default => 0
t.integer :infos_count, :default => 0
t.string :keywords, :limit => 100
t.string :description, :limit => 1000
t.string :map, :null => false
t.integer :map_size, :default => 0
t.string :map_content_type
t.integer :order, :default => 0
t.timestamps
end
add_index :places, :name, unique: true
add_index :places, :key, unique: true
end
end
|
begin
require 'syslog_protocol'
rescue LoadError
raise 'Gem syslog_protocol is required for remote logging using the Syslog protol. Please add the gem "syslog_protocol" to your Gemfile.'
end
module SemanticLogger
module Formatters
class Syslog < Default
attr_accessor :level_map, :options, :facility
# Default mapping of ruby log levels to syslog log levels
#
# ::Syslog::LOG_EMERG - "System is unusable"
# ::Syslog::LOG_ALERT - "Action needs to be taken immediately"
# ::Syslog::LOG_CRIT - "A critical condition has occurred"
# ::Syslog::LOG_ERR - "An error occurred"
# ::Syslog::LOG_WARNING - "Warning of a possible problem"
# ::Syslog::LOG_NOTICE - "A normal but significant condition occurred"
# ::Syslog::LOG_INFO - "Informational message"
# ::Syslog::LOG_DEBUG - "Debugging information"
DEFAULT_LEVEL_MAP = {
fatal: ::Syslog::LOG_CRIT,
error: ::Syslog::LOG_ERR,
warn: ::Syslog::LOG_WARNING,
info: ::Syslog::LOG_NOTICE,
debug: ::Syslog::LOG_INFO,
trace: ::Syslog::LOG_DEBUG
}.freeze
# Create a Syslog Log Formatter
#
# Parameters:
# options: [Integer]
# Default: ::Syslog::LOG_PID | ::Syslog::LOG_CONS
# Any of the following (options can be logically OR'd together)
# ::Syslog::LOG_CONS
# ::Syslog::LOG_NDELAY
# ::Syslog::LOG_NOWAIT
# ::Syslog::LOG_ODELAY
# ::Syslog::LOG_PERROR
# ::Syslog::LOG_PID
#
# facility: [Integer]
# Default: ::Syslog::LOG_USER
# Type of program (can be logically OR'd together)
# ::Syslog::LOG_AUTH
# ::Syslog::LOG_AUTHPRIV
# ::Syslog::LOG_CONSOLE
# ::Syslog::LOG_CRON
# ::Syslog::LOG_DAEMON
# ::Syslog::LOG_FTP
# ::Syslog::LOG_KERN
# ::Syslog::LOG_LRP
# ::Syslog::LOG_MAIL
# ::Syslog::LOG_NEWS
# ::Syslog::LOG_NTP
# ::Syslog::LOG_SECURITY
# ::Syslog::LOG_SYSLOG
# ::Syslog::LOG_USER
# ::Syslog::LOG_UUCP
# ::Syslog::LOG_LOCAL0
# ::Syslog::LOG_LOCAL1
# ::Syslog::LOG_LOCAL2
# ::Syslog::LOG_LOCAL3
# ::Syslog::LOG_LOCAL4
# ::Syslog::LOG_LOCAL5
# ::Syslog::LOG_LOCAL6
# ::Syslog::LOG_LOCAL7
#
# level_map: [Hash]
# Supply a custom map of SemanticLogger levels to syslog levels.
# For example, passing in { warn: ::Syslog::LOG_NOTICE }
# would result in a log mapping that matches the default level map,
# except for :warn, which ends up with a LOG_NOTICE level instead of a
# LOG_WARNING one.
# Without overriding any parameters, the level map will be
# LEVEL_MAP = {
# fatal: ::Syslog::LOG_CRIT,
# error: ::Syslog::LOG_ERR,
# warn: ::Syslog::LOG_WARNING,
# info: ::Syslog::LOG_NOTICE,
# debug: ::Syslog::LOG_INFO,
# trace: ::Syslog::LOG_DEBUG
# }
def initialize(options = {})
options = options.dup
@options = options.delete(:options) || (::Syslog::LOG_PID | ::Syslog::LOG_CONS)
@facility = options.delete(:facility) || ::Syslog::LOG_USER
@level_map = DEFAULT_LEVEL_MAP.dup
if level_map = options.delete(:level_map)
@level_map.update(level_map)
end
# Time is already part of Syslog packet
options[:time_format] = nil unless options.has_key?(:time_format)
super(options)
end
def call(log, logger)
message = super(log, logger)
create_syslog_packet(log, message)
end
# Create Syslog Packet
def create_syslog_packet(log, message)
packet = SyslogProtocol::Packet.new
packet.hostname = host
packet.facility = facility
packet.tag = application.gsub(' ', '')
packet.content = message
packet.time = log.time
packet.severity = level_map[log.level]
packet.to_s
end
end
end
end
|
module RSence
module Plugins
# Include this module in your subclass of {Plugin__ Plugin} to enable sub-plugin bundles in another plugin bundle.
#
# The plugins loaded using this system are isolated from system-wide plugins.
#
# To address them from this plugin, use +@plugin_plugins+ instead of +@plugins+ to access them.
#
# Install your sub-plugins into a directory named +plugins+ inside your plugin bundle.
module PluginPlugins
# Makes @plugin_plugins accessible
attr :plugin_plugins
# Extended {#init}, delegates calls to the sub-plugins.
def init
super
@plugin_plugins = RSence::PluginManager.new({
:plugin_paths => [ bundle_path('plugins') ],
:autoreload => true,
:name_prefix => name_with_manager_s.to_sym,
:parent_manager => @plugins,
:resolved_deps => [ :system, @name, name_with_manager_s.to_sym ]
})
end
# Extended {#open}, delegates calls to the sub-plugins.
def open
super
@plugin_plugins.delegate(:open)
end
# Extended {#close}, delegates calls to the sub-plugins.
def close
super
@plugin_plugins.delegate(:close)
@plugin_plugins.shutdown
end
# Extended {#flush}, delegates calls to the sub-plugins.
def flush
super
@plugin_plugins.delegate(:flush)
end
# Extended {#idle}, delegates calls to the sub-plugins.
def idle( msg )
super
@plugin_plugins.delegate(:idle,msg)
end
# Extended {#init_ses}, delegates calls to the sub-plugins.
def init_ses( msg )
super
@plugin_plugins.delegate(:init_ses,msg)
end
# Extended {#restore_ses}, delegates calls to the sub-plugins.
def restore_ses( msg )
super
@plugin_plugins.delegate(:restore_ses,msg)
end
# Extended {#cloned_target}, delegates calls to the sub-plugins.
def cloned_target( msg, source_session )
super
@plugin_plugins.delegate(:cloned_target,msg,source_session)
end
# Extended {#cloned_source}, delegates calls to the sub-plugins.
def cloned_source( msg, target_session )
super
@plugin_plugins.delegate(:cloned_source,msg,target_session)
end
end
end
end
|
require 'rails_helper'
describe BusinessService do
context "retrieves businesses by keyword" do
it ".get_businesses_by_keyword" do
business = BusinessService.new("39.7541", "105.0002")
expect(business.get_businesses_by_keyword("food")).to have_key("businesses")
end
end
end |
class CreateConversation < ActiveRecord::Migration
def change
create_table :conversations do |t|
t.integer :user_id
t.integer :empresa_request_id
t.boolean :unread_user, :default=>false
t.boolean :unread_empresa, :default=>false
t.timestamps
end
add_index :conversations, :user_id
add_index :conversations, :empresa_request_id
end
end
|
require 'gmail'
class SantaMailer
def initialize(assignments, host_username, host_password)
@assignments = assignments
@gmail = Gmail.connect(host_username, host_password)
end
def send
@assignments.each do |gifter, giftee|
mail_to(gifter, giftee)
end
end
def mail_to(gifter, giftee)
@gmail.deliver do
to gifter[:email]
subject '🎁 Secret Santa 2k18 🎁'
text_part do
body "You are buying a gift for: \n\n🎄 #{ giftee[:name].upcase } 🎄"
end
end
end
end
class SecretSantaAssigner
attr_reader :assignments
def initialize(list)
@giftees = list.dup
@gifters = list.dup
@assignments = {}
end
def allocate_santas
@gifters.each do |name|
secret_santa = name
secret_santa = @giftees.sample until valid_allocation?(secret_santa, name)
@assignments[name] = secret_santa
@giftees.delete(secret_santa)
end
end
def shuffle
@giftees.shuffle!
end
private
def valid_allocation?(assignee, person)
person[:exclusions] ? assignee != person && !(person[:exclusions].include?(assignee[:name])) : assignee != person
end
end
|
class ApplicationController < ActionController::Base
def after_sign_in_path_for(resource)
case resource
when Admin
subjects_path #pathは設定したい遷移先へのpathを指定してください
when Customer
root_path #ここもpathはご自由に変更してください
end
end
end
|
puts "Basic classes, constructor, scope and instatiation"
class Person
@@people_count = 0
def initialize(name, age, profession)
@name = name
@age = age.to_s
@profession = profession
@@people_count += 1
puts "Person " << @@people_count.to_s << ": My name is " << @name << ", age " << @age << ". I work as a " << @profession
end
end
Person.new('Kevin', 56, 'Developer')
Person.new('Paul', 61, 'Lecturer')
Person.new('Tatiana', 43, 'Housewife')
puts "\nInheritance"
class Vehicle
@@type = 'Vehicle'
def initialize
puts "New vehicle created"
end
end
class Car < Vehicle
def initialize
@type = 'Car'
puts "New car created"
end
end
class Van < Vehicle
def initialize
@type = 'Van'
puts "New van created"
end
end
puts "\nsuper class method keyword"
class Truck < Vehicle
def initialize
puts "Instead of new truck created"
super
end
end
x = Vehicle.new()
y = Car.new()
z = Van.new()
a = Truck.new()
puts "\nClass review"
class Message
@@messages_sent = 0
def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
puts "Message: " << @from << " to " << @to
end
end
class Email < Message
def initialize(subject)
@subject = subject
puts "Email: " << @subject
end
end
class Email2 < Message
def initialize(me, you)
super
end
end
my_message = Message.new("me", "you")
my_email = Email.new("subject")
my_email2 = Email2.new("me", "you")
|
class ResultsController < ApplicationController
def create
@result = Result.find_or_initialize_by(user_id: result_params[:user_id], monster_id: result_params[:monster_id])
@result.update_attributes({
status: result_params[:status],user_id: result_params[:user_id], monster_id: result_params[:monster_id]
})
redirect_to :root
end
private
def result_params
params[:result].permit(:status,:user_id,:monster_id)
end
end
|
require 'rails_helper'
describe ProjectsController do
describe "POST #create" do
context "with valid attributes" do
it "creates a new project" do
expect {
post :create, project: FactoryGirl.attributes_for(:project)
}.to change(Project, :count).by(1)
end
it "responds with: 201 Created" do
post :create, project: FactoryGirl.attributes_for(:project)
expect(response).to have_http_status(201)
end
end
context "with invalid attributes" do
it "does not create a new project" do
expect {
post :create, project: FactoryGirl.attributes_for(:invalid_project)
}.to_not change(Project, :count)
end
it "responds with: 422 Unprocessable Entity" do
post :create, project: FactoryGirl.attributes_for(:invalid_project)
expect(response).to have_http_status(422)
end
it "response contains an error message" do
post :create, project: FactoryGirl.attributes_for(:invalid_project)
expect(JSON.parse(response.body)['errors']).not_to be_blank
end
end
end
describe "GET #show" do
context "for existing project" do
let(:project) { FactoryGirl.create(:project) }
it "responds with json" do
get :show, id: project
expect(response.header['Content-Type']).to include('application/json')
end
it "responds with: 200 OK" do
get :show, id: project
expect(response).to have_http_status(200)
end
end
context "for non-existing project" do
it "responds with: 404 Not Found" do
get :show, id: 0
expect(response).to have_http_status(404)
end
end
end
describe "GET #index" do
before do
3.times do |i|
FactoryGirl.create(:project)
end
end
it "responds with json" do
get :index
expect(response.header['Content-Type']).to include('application/json')
end
it "outputs all the projects" do
get :index
expect(JSON.parse(response.body).count).to eq(3)
end
it "responds with: 200 OK" do
get :index
expect(response).to have_http_status(200)
end
end
describe "PUT #update" do
context "with valid attributes" do
let(:project) { FactoryGirl.create(:project) }
it "updates the project with the new values" do
put :update, id: project, project: FactoryGirl.attributes_for(:project, name: 'Sample Project Updated')
project.reload
expect(project.name).to eq('Sample Project Updated')
end
it "responds with: 200 OK" do
put :update, id: project, project: FactoryGirl.attributes_for(:project, name: 'Sample Project Updated')
expect(response).to have_http_status(200)
end
end
context "with invalid attributes" do
let(:project) { FactoryGirl.create(:project) }
it "does not update the project" do
put :update, id: project, project: FactoryGirl.attributes_for(:project, name: nil)
name = project.name
project.reload
expect(project.name).to eq(name)
end
it "responds with: 422 Unprocessable Entity" do
put :update, id: project, project: FactoryGirl.attributes_for(:project, name: nil)
expect(response).to have_http_status(422)
end
it "response contains an error message" do
put :update, id: project, project: FactoryGirl.attributes_for(:project, name: nil)
expect(JSON.parse(response.body)['errors']).not_to be_blank
end
end
context "for non-existing project" do
it "responds with: 404 Not Found" do
put :update, id: 0
expect(response).to have_http_status(404)
end
end
end
describe "DELETE #destroy" do
context "for existing project" do
before do
@project = FactoryGirl.create(:project)
end
it "deletes the requested project" do
expect { delete :destroy, id: @project }.to change(Project, :count).by(-1)
end
it "responds with: 204 No Content" do
delete :destroy, id: @project
expect(response).to have_http_status(204)
end
end
context "for non-existing project" do
it "responds with: 404 Not Found" do
delete :destroy, id: 0
expect(response).to have_http_status(404)
end
end
end
end
|
class ThemesController < ApplicationController
before_action :set_theme, only: [:show]
def index
@themes = Theme.all
end
def show
@figurines = ScraperService.new(@theme.name).call
TestJob.perform_later
end
def new
@themes = Theme.new
end
def create
@theme = Theme.new(theme_params)
if @theme.save
redirect_to theme_path(@theme)
else
render 'new'
end
end
private
def set_theme
@theme = Theme.find(params[:id])
end
def theme_params
params.require(:theme).permit(:name)
end
end |
# GSPlan - Team commitment planning
#
# Copyright (C) 2008 Jan Schrage <jan@jschrage.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
class EmployeesController < ApplicationController
layout "ActScaffold"
active_scaffold :employee do |config|
config.label = "Employees"
config.columns = [:pernr, :name, :is_reviewer]
list.sorting = {:name => 'ASC'}
columns[:pernr].label = "ID"
columns[:name].label = "Name"
columns[:is_reviewer].label = "Reviewer?"
end
end
|
class NotificationMailer < ActionMailer::Base
include Sidekiq::Mailer
default from: 'notifications@' << Rails.application.secrets.domain_name
def new_episode_added episode_id, user_email
@episode = Episode.find episode_id
mail(to: user_email, subject: 'MovieMan notification')
end
end
|
class ConversationsQuery < Types::BaseResolver
description "Gets all conversations for the current user"
type Outputs::ConversationType.connection_type, null: false
policy ApplicationPolicy, :logged_in?
def authorized_resolve
Conversation.for_user(current_user).order_by_most_recent_message
end
end
|
require 'rails_helper'
describe CourseApi::Purchase do
let(:user) { create(:user) }
let(:auth_token) { user.auth_token }
let(:headers) do
{
'Content-Type' => 'application/json',
'Authorization' => auth_token
}
end
let(:course) { create(:course) }
let(:order) { create(:order, user: user, course: course) }
describe 'post api/v1/courses/:id/purchase' do
before { post("/api/v1/courses/#{course.id}/purchase", headers: headers) }
subject { JSON.parse(response.body) }
context 'purchase course success' do
it { expect(response.status).to eq(201) }
it { expect(subject.keys).to contain_exactly('amount', 'amount_currency', 'created_at', 'expired_at', 'paid_at', 'state') }
end
context 'purchase course fail' do
context 'when purchase the duplicate course' do
before do
order.pay!
post("/api/v1/courses/#{course.id}/purchase", headers: headers)
end
it { expect(response.status).to eq(400) }
it { expect(subject['error']).to eq('Course is duplicate purchase.') }
end
context 'when purchase the course not found' do
before { post("/api/v1/courses/#{Faker::Number.number(digits: 5)}/purchase", headers: headers) }
it { expect(response.status).to eq(404) }
it { expect(subject['error']).to eq('404 RecordNotFound') }
end
end
end
end |
Rails.application.routes.draw do
root to: 'static_pages#home', as: 'home'
get 'about(/:id)', to: 'static_pages#about', as: 'about'
end
|
module Interpreter
class Processor
module TokenProcessors
# QoL note: returns the rounded log if it gives the original argument when
# raising the same base
def process_logarithm(_token)
(base, argument) = resolve_parameters_from_stack!
validate_type [Numeric], base
validate_type [Numeric], argument
Util::Logger.debug(Util::Options::DEBUG_2) { Util::I18n.t('interpreter.log', base, argument).lpink }
should_suppress_error = !next_token_if(Token::BANG).nil?
begin
raise Errors::LogOfUndefinedBase, base if [0, 1].include? base
raise Errors::LogOfZero if argument.zero?
log = Math.log argument, base
log = log.round if base**log.round == argument
@sore = log
rescue
raise unless should_suppress_error
@sore = nil
end
end
end
end
end
|
class Download < ActiveRecord::Base
def uploaded_file=(file_field)
self.name = base_part_of(file_field.original_filename)
self.content_type = file_field.content_type.chomp
self.data = file_field.read
end
def base_part_of(file_name)
File.basename(file_name).gsub(/[^\w._-]/, '')
end
end
|
# include into mail-sending scenarios
module MailHelper
extend ActiveSupport::Concern
included do
after(:each) do
ActionMailer::Base.deliveries.each do |mail|
if mail.body.to_s[/translation missing: (.*)"/]
fail "There are missing translations: #{Regexp.last_match(1)}"
end
if begin
mail.body.parts.first.to_s[/translation missing: (.*)"/]
rescue
false
end
fail "There are missing translations: #{Regexp.last_match(1)}"
end
end
end
let(:mail) { ActionMailer::Base.deliveries.last }
let(:mails) { ActionMailer::Base.deliveries }
let(:multi_part_body) { mail.body.parts.first.to_s }
end
end
|
class CreateBootcamps < ActiveRecord::Migration
def change
create_table :bootcamps do |t|
t.string :name
t.string :location
t.date :starts_at
t.date :ends_at
t.integer :level
t.integer :community_price
t.integer :normal_price
t.integer :supporter_price
t.timestamps
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe PropertiesController, type: :controller do
let(:current_user) { create(:user) }
let(:session) { { user_id: current_user.id } }
let(:landlord) { create(:landlord) }
let(:tenant) { create(:tenant) }
let(:params) { {} }
describe 'PUT #update' do
subject { put :update, params: params, session: session }
let!(:property) { create(:property, landlord_email: landlord.email) }
let(:params) { { id: property.id } }
context 'when valid property param attributes' do
let(:valid_property_attributes) do
{
property_name: 'somepropertyname',
property_address: 'somepropertyaddress',
landlord_first_name: landlord.first_name,
landlord_last_name: landlord.last_name,
landlord_email: landlord.email,
tenancy_start_date: "02/02/2020".to_date,
tenancy_monthly_rent: 1500,
tenancy_security_deposit: 3000,
tenant_email: "sometenantemail@topfloor.ie"
}
end
let(:params) { { id: property.id, property: valid_property_attributes } }
it 'assigns @property' do
tenant.reload
subject
expect(assigns(:property)).to be_a Property
end
it 'updates the Property' do
tenant.reload
subject
property.reload
expect(property.property_name).to eq valid_property_attributes[:property_name]
expect(property.property_address).to eq valid_property_attributes[:property_address]
expect(property.landlord_first_name).to eq valid_property_attributes[:landlord_first_name]
expect(property.landlord_last_name).to eq valid_property_attributes[:landlord_last_name]
expect(property.landlord_email).to eq valid_property_attributes[:landlord_email]
expect(property.tenancy_start_date).to eq valid_property_attributes[:tenancy_start_date]
expect(property.tenancy_monthly_rent).to eq valid_property_attributes[:tenancy_monthly_rent]
expect(property.tenancy_security_deposit).to eq valid_property_attributes[:tenancy_security_deposit]
end
it 'responds with 302 Found' do
subject
expect(response).to have_http_status(:found)
end
it 'redirects to properties#show' do
subject
expect(response).to redirect_to Property.last
end
it 'assigns flash success' do
subject
expect(flash[:success]).to eq 'Property was successfully updated.'
end
end
context 'when invalid property param attributes' do
let(:invalid_property_attributes) do
{
property_name: '',
property_address: '',
landlord_first_name: '',
landlord_last_name: '',
landlord_email: ''
}
end
let(:params) { { id: property.id, property: invalid_property_attributes } }
it 'does not update the Property' do
expect { subject }.to_not(change { property.reload.attributes })
end
it 'responds with unprocessable_entity' do
subject
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'when incomplete tenancy attributes passed' do
let(:invalid_tenancy_attributes) do
{
tenant_id: tenant.email,
tenancy_monthly_rent: '',
tenancy_start_date: '',
tenancy_security_deposit: ''
}
end
let(:params) { { id: property.id, property: invalid_tenancy_attributes } }
it 'does not update the Property' do
expect { subject }.to_not(change { property.reload.attributes })
end
it 'responds with unprocessable_entity' do
subject
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'when user is not logged in' do
subject { put :update, params: params, session: {} }
it 'returns http forbidden status' do
subject
expect(response).to have_http_status(:forbidden)
end
it 'renders error page' do
subject
expect(response).to render_template('errors/not_authorized')
end
end
context 'when valid multiple landlords param attributes' do
let(:landlord1) {create(:landlord)}
let(:landlord2) {create(:landlord)}
let(:valid_property_attributes) do
{
property_name: 'somepropertyname',
property_address: 'somepropertyaddress',
landlord_first_name: landlord.first_name,
landlord_last_name: landlord.last_name,
landlord_email: landlord.email,
multiple_landlords: true,
other_landlords_emails: landlord1.email.to_s + ',' + landlord2.email.to_s
}
end
let(:params) { { id: property.id, property: valid_property_attributes } }
it 'assigns @property' do
subject
expect(assigns(:property)).to be_a Property
end
it 'update a Property' do
subject
property.reload
expect(property.property_name).to eq valid_property_attributes[:property_name]
expect(property.property_address).to eq valid_property_attributes[:property_address]
expect(property.landlord_first_name).to eq valid_property_attributes[:landlord_first_name]
expect(property.landlord_last_name).to eq valid_property_attributes[:landlord_last_name]
expect(property.landlord_email).to eq valid_property_attributes[:landlord_email]
expect(property.other_landlords_emails).to eq valid_property_attributes[:other_landlords_emails]
expect(property.multiple_landlords).to eq valid_property_attributes[:multiple_landlords]
end
it 'responds with 302 Found' do
subject
expect(response).to have_http_status(:found)
end
it 'redirects to properties#show' do
subject
expect(response).to redirect_to Property.last
end
it 'assigns flash success' do
subject
expect(flash[:success]).to eq 'Property was successfully updated.'
end
end
end
end
|
describe "Login com Cadastro", :Login3 do
before(:each) do
visit "/access"
end
after(:each) do
sleep 2
end
it "logando" do
within("#login") do #Dentro do elemento pai "#login" pesquise:
find("input[name=username]").set "stark" #Elemento filho username
find("input[name=password]").set "jarvis!" #Elemento filho password
click_button "Entrar"
end
expect(find("#flash")).to have_content "Olá, Tony Stark. Você acessou a área logada!" #Esperado que o texto do #flash contém " Olá, Tony..."
end
it "Criando conta" do
within("#signup") do #Dentro do elemento pai "#signup" pesquise:
find("input[name=username]").set "stark" #Elemento filho username
find("input[name=password]").set "jarvis!" #Elemento filho password
click_link "Criar Conta"
end
expect(page).to have_content "Dados enviados. Aguarde aprovação do seu cadastro!" #Esperado que o texto do #flash contém "Dados enviados..."
end
end
|
require 'spec_helper'
require 'mspire/isotope'
describe Mspire::Isotope do
specify 'Mspire::Isotope[] accesses isotopes by element' do
carbon12 = Mspire::Isotope[:C][0] # the lightest carbon isotope
carbon12.element.should == :C
carbon12.mass_number.should == 12
carbon12 = Mspire::Isotope[:C].find(&:mono) # the most abundant (i.e., monoisotopic isotope)
carbon12.element.should == :C
carbon12.mass_number.should == 12
carbon12.mono.should be_true
end
it 'can set the element_hash to change convenience method access' do
Mspire::Isotope[:C][0].relative_abundance.should == 0.9891
Mspire::Isotope.element_hash = Mspire::Isotope::NIST::BY_ELEMENT
Mspire::Isotope[:C][0].relative_abundance.should == 0.9893
end
specify 'Mspire::Isotope::ISOTOPES has all the common isotopes and (uses Neese by default)' do
# frozen
Mspire::Isotope::ISOTOPES.size.should == 288
hydrogen_isotopes = Mspire::Isotope::ISOTOPES.select {|iso| iso.element == :H }
hydrogen_isotopes.size.should == 2
{atomic_number: 1, element: :H, mass_number: 1, atomic_mass: 1.00782503207, relative_abundance: 0.999844, average_mass: 1.00794, mono: true}.each do |k,v|
hydrogen_isotopes.first.send(k).should == v
end
{atomic_number: 1, element: :H, mass_number: 2, atomic_mass: 2.0141017778, relative_abundance: 0.000156, average_mass: 1.00794, mono: false}.each do |k,v|
hydrogen_isotopes.last.send(k).should == v
end
u = Mspire::Isotope::ISOTOPES.last
{atomic_number: 92, element: :U, mass_number: 238, atomic_mass: 238.0507882, relative_abundance: 0.992742, average_mass: 238.02891, mono: true}.each do |k,v|
u.send(k).should == v
end
end
specify 'Mspire::Isotope::BY_ELEMENT has all common isotopes by element (uses Neese by default)' do
[{atomic_number: 6, element: :C, mass_number: 12, atomic_mass: 12.0, relative_abundance: 0.9891, average_mass: 12.0107, mono: true}, {atomic_number: 6, element: :C, mass_number: 13, atomic_mass: 13.0033548378, relative_abundance: 0.0109, average_mass: 12.0107, mono: false}].zip(Mspire::Isotope::BY_ELEMENT[:C]) do |hash, iso|
hash.each do |k,v|
iso.send(k).should == v
end
end
Mspire::Isotope::BY_ELEMENT[:H].size.should == 2
end
end
|
require 'spec_helper'
describe User do
it 'should create one with a valid password and email' do
user = User.create!(name: 'example', email: 'example@domain.com', password: 'example1', password_confirmation: 'example1')
user.id.should be_present
end
it 'should not allow a user creating without a valid password confirmation' do
lambda do
User.create!(name: 'example', email: 'example@domain.com', password: 'example1', password_confirmation: 'example2')
end.should raise_error
end
end
|
Rails.application.routes.draw do
devise_for :admins
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users, path: ''
resources :users, only: [:new, :create]
authenticated :user do
root 'users#dashboard', as: :dashboard
end
get 'invitations/accept', as: :invitation, to: 'invitations#accept'
authenticate :user do
resources :users, only: [:show, :edit, :update] do
member do
patch :change_password
post :destroy
end
end
resources :courses, except: [:edit] do
resources :lesson_categories, except: [:new, :edit]
member do
get :add_user
post :check_password
get :settings, as: :settings
post :update_attending
post :send_invitation
get 'remove_user/:user_id', action: :remove_user,
as: :remove_user
get 'toggle_flag/:lesson_category_id', action: :toggle_flag,
as: :toggle_flag
get :remove_self
end
resources :exams, except: [:show]
resources :lessons do
resources :pictures, only: [:create, :destroy]
end
resources :material_categories, except: [:index, :edit] do
resources :materials, only: [:create, :destroy]
end
end
# resource for path names; actual exams resource in courses resource
resources :exams, only: [] do
resources :question_categories, only: [:create, :destroy, :update], path: 'q_cs/' do
resources :questions, only: [:create, :update, :destroy]
end
end
resources :questions, only: [] do
resources :answers, only: [:create, :update, :destroy]
end
scope '/exam' do
get '/start/:id' => 'user_exams#start', as: :start_user_exam
get '/new/:id' => 'user_exams#new', as: :new_user_exam
get '/exit' => 'user_exams#exit', as: :exit_user_exam
get '/question' => 'user_exams#question', as: :question_user_exam
get '/:id/summary' => 'user_exams#show', as: :user_exam
post '/answer' => 'user_exams#answer', as: :answer_user_exam
get '/:id/edit' => 'user_exams#edit', as: :edit_user_exam
get '/:id/edit/:user_answer_id/correct' => 'user_exams#correct_answer', as: :correct_user_answer
end
get 'question_markdown/:id' => 'questions#get_markdown'
end
unauthenticated :user do
root 'static_pages#home'
end
get '/help' => 'static_pages#help', as: :help
scope '/help' do
get '/privacy' => 'static_pages#privacy', as: :privacy
get '/rules' => 'static_pages#rules', as: :rules
end
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
class MonsterReward < ActiveRecord::Base
attr_accessible :rank, :action, :drop_rate, :item_id, :monster_id
belongs_to :monster, inverse_of: :monster_rewards
belongs_to :item, inverse_of: :monster_rewards
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: photoposts
#
# id :bigint not null, primary key
# aasm_state :string
# ban_reason :string
# comments_count :integer default(0)
# content :text
# picture :string
# rating_count :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_photoposts_on_user_id (user_id)
# index_photoposts_on_user_id_and_created_at (user_id,created_at)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
class PhotopostSerializer < ActiveModel::Serializer
attributes :id, :content, :picture, :comments_count, :rating_count, :liked_by_current_user, :comments
belongs_to :user
def comments
comments = []
if instance_options[:template] == 'index'
object.comments.last(3)
else
object.comments.all
end.each do |comment|
comments << { id: comment.id, content: comment.content, user: { id: comment.user.id,
first_name: comment.user.first_name,
last_name: comment.user.last_name,
image: comment.user.image } }
end
comments
end
def liked_by_current_user
object.rating.pluck(:user_id).include?(instance_options[:current_user])
end
end
|
class Task < ApplicationRecord
belongs_to :card
validates :name, presence: true
enum status: [:todo, :doing, :paused, :pedding, :done]
end
|
class AddLinksToEvents < ActiveRecord::Migration[6.1]
def change
add_column :events, :calendar_link, :string
add_column :events, :meeting_link, :string
end
end
|
# Copyright (c) 2007, The RubyCocoa Project.
# Copyright (c) 2005-2006, Jonathan Paisley.
# All Rights Reserved.
#
# RubyCocoa is free software, covered under either the Ruby's license or the
# LGPL. See the COPYRIGHT file for more information.
# Takes a built RubyCocoa app bundle (as produced by the
# Xcode/ProjectBuilder template) and copies it into a new
# app bundle that has all dependencies resolved.
#
# usage:
# ruby standaloneify.rb -d mystandaloneprog.app mybuiltprog.app
#
# This creates a new application that should have dependencies resolved.
#
# The script attempts to identify dependencies by running the program
# without OSX.NSApplicationMain, then grabbing the list of loaded
# ruby scripts and extensions. This means that only the libraries that
# you 'require' are bundled.
#
# NOTES:
#
# Your ruby installation MUST NOT be the standard Panther install -
# the script depends on ruby libraries being in non-standard paths to
# work.
#
# I've only tested it with a DarwinPorts install of ruby 1.8.2.
#
# Extension modules should be copied over correctly.
#
# Ruby gems that are used are copied over in their entirety (thanks to some
# ideas borrowed from rubyscript2exe)
#
# install_name_tool is used to rewrite dyld load paths - this may not work
# depending on how your libraries have been compiled. I've not had any
# issues with it yet though.
#
# Use ENV['RUBYCOCOA_STANDALONEIFYING?'] in your application to check if it's being standaloneified.
# FIXME: Using evaluation is "evil", should use RubyNode instead. Eloy Duran.
module Standaloneify
MAGIC_ARGUMENT = '--standaloneify'
def self.find_file_in_load_path(filename)
return filename if filename[0] == ?/
paths = $LOAD_PATH.select do |p|
path = File.join(p,filename)
return path if File.exist?(path)
end
return nil
end
end
if __FILE__ == $0 and ARGV[0] == Standaloneify::MAGIC_ARGUMENT then
# Got magic argument
ARGV.shift
module Standaloneify
LOADED_FILES = []
def self.notify_loaded(filename)
LOADED_FILES << filename unless LOADED_FILES.include?(filename)
end
end
module Kernel
alias :pre_standaloneify_load :load
def load(*args)
if self.is_a?(OSX::OCObjWrapper) then
return self.method_missing(:load,*args)
end
filename = args[0]
result = pre_standaloneify_load(*args)
Standaloneify.notify_loaded(filename) if filename and result
return result
end
end
module Standaloneify
def self.find_files(loaded_features,loaded_files)
loaded_features.delete("rubycocoa.bundle")
files_and_paths = (loaded_features + loaded_files).map do |file|
[file,find_file_in_load_path(file)]
end
files_and_paths.reject! { |f,p| p.nil? }
if defined?(Gem) then
resources_d = OSX::NSBundle.mainBundle.resourcePath.fileSystemRepresentation
gems_home_d = File.join(resources_d,"RubyGems")
gems_gem_d = File.join(gems_home_d,"gems")
gems_spec_d = File.join(gems_home_d,"specifications")
FileUtils.mkdir_p(gems_spec_d)
FileUtils.mkdir_p(gems_gem_d)
Gem::Specification.list.each do |gem|
next unless gem.loaded?
$stderr.puts "Found gem #{gem.name}"
FileUtils.cp_r(gem.full_gem_path,gems_gem_d)
FileUtils.cp(File.join(gem.installation_path,"specifications",gem.full_name + ".gemspec"),gems_spec_d)
# Remove any files that come from the GEM
files_and_paths.reject! { |f,p| p.index(gem.full_gem_path) == 0 }
end
# Add basis RubyGems dependencies that are not detected since
# require is overwritten and doesn't modify $LOADED_FEATURES.
%w{fileutils.rb etc.bundle}.each { |f|
files_and_paths << [f, find_file_in_load_path(f)]
}
end
return files_and_paths
end
end
require 'osx/cocoa'
module OSX
def self.NSApplicationMain(*args)
# Prevent application main loop from starting
end
end
$LOADED_FEATURES << "rubycocoa.bundle"
$0 = ARGV[0]
require ARGV[0]
loaded_features = $LOADED_FEATURES.uniq.dup
loaded_files = Standaloneify::LOADED_FILES.dup
require 'fileutils'
result = Standaloneify.find_files(loaded_features, loaded_files)
File.open(ENV["STANDALONEIFY_DUMP_FILE"],"w") {|fp| fp.write(result.inspect) }
exit 0
end
module Standaloneify
RB_MAIN_PREFIX = <<-EOT.gsub(/^ */,'')
################################################################################
# #{File.basename(__FILE__)} patch
################################################################################
# Remove all entries that aren't in the application bundle
COCOA_APP_RESOURCES_DIR = File.dirname(__FILE__)
$LOAD_PATH.reject! { |d| d.index(File.dirname(COCOA_APP_RESOURCES_DIR))!=0 }
$LOAD_PATH << File.join(COCOA_APP_RESOURCES_DIR,"ThirdParty")
$LOAD_PATH << File.join(File.dirname(COCOA_APP_RESOURCES_DIR),"lib")
$LOADED_FEATURES << "rubycocoa.bundle"
ENV['GEM_HOME'] = ENV['GEM_PATH'] = File.join(COCOA_APP_RESOURCES_DIR,"RubyGems")
################################################################################
EOT
def self.patch_main_rb(resources_d)
rb_main = File.join(resources_d,"rb_main.rb")
main_script = RB_MAIN_PREFIX + File.read(rb_main)
File.open(rb_main,"w") do |fp|
fp.write(main_script)
end
end
def self.get_dependencies(macos_d,resources_d)
# Set an environment variable that can be checked inside the application.
# This is useful because standaloneify uses evaluation, so it might be possible
# that the application does something which leads to problems while standaloneifying.
ENV['RUBYCOCOA_STANDALONEIFYING?'] = 'true'
dump_file = File.join(resources_d,"__require_dump")
# Run the main Mac program
mainprog = Dir[File.join(macos_d,"*")][0]
ENV['STANDALONEIFY_DUMP_FILE'] = dump_file
system(mainprog,__FILE__,MAGIC_ARGUMENT)
begin
result = eval(File.read(dump_file))
rescue
$stderr.puts "Couldn't read dependency list"
exit 1
end
File.unlink(dump_file)
result
end
class LibraryFixer
def initialize
@done = {}
end
def self.needs_to_be_bundled(path)
case path
when %r:^/usr/lib/:
return false
when %r:^/lib/:
return false
when %r:^/Library/Frameworks:
$stderr.puts "WARNING: don't know how to deal with frameworks (%s)" % path.inspect
return false
when %r:^/System/Library/Frameworks:
return false
when %r:^@executable_path:
$stderr.puts "WARNING: can't handle library with existing @executable_path reference (%s)" % path.inspect
return false
end
return true
end
## For the given library, copy into the lib dir (if copy_self),
## iterate through dependent libraries and copy them if necessary,
## updating the name in self
def fixup_library(relative_path,full_path,dest_root,copy_self=true)
prefix = "@executable_path/../lib"
lines = %x[otool -L '#{full_path}'].split("\n")
paths = lines.map { |x| x.split[0] }
paths.shift # argument name
return if @done[full_path]
if copy_self then
@done[full_path] = true
new_path = File.join(dest_root,relative_path)
internal_path = File.join(prefix,relative_path)
FileUtils.mkdir_p(File.dirname(new_path))
FileUtils.cp(full_path,new_path)
File.chmod(0700,new_path)
full_path = new_path
system("install_name_tool","-id",internal_path,new_path)
end
paths.each do |path|
next if File.basename(path) == File.basename(full_path)
if self.class.needs_to_be_bundled(path) then
puts "Fixing %s in %s" % [path.inspect,full_path.inspect]
fixup_library(File.basename(path),path,dest_root)
lib_name = File.basename(path)
new_path = File.join(dest_root,lib_name)
internal_path = File.join(prefix,lib_name)
system("install_name_tool","-change",path,internal_path,full_path)
end
end
end
end
def self.make_standalone_application(source,dest,extra_libs)
FileUtils.cp_r(source,dest)
dest_d = Pathname.new(dest).realpath.to_s
# Calculate various paths in new app bundle
contents_d = File.join(dest_d,"Contents")
frameworks_d = File.join(contents_d,"Frameworks")
resources_d = File.join(contents_d,"Resources")
lib_d = File.join(contents_d,"lib")
macos_d = File.join(contents_d,"MacOS")
# Calculate paths to the to-be copied RubyCocoa framework
ruby_cocoa_d = File.join(frameworks_d,"RubyCocoa.framework")
ruby_cocoa_inc = File.join(ruby_cocoa_d,"Resources","ruby")
ruby_cocoa_lib = File.join(ruby_cocoa_d,"RubyCocoa")
# First check if the developer might already have added the RubyCocoa framework (in a copy phase)
unless File.exist? ruby_cocoa_d
# Create Frameworks dir and copy RubyCocoa in there
FileUtils.mkdir_p(frameworks_d)
FileUtils.mkdir_p(lib_d)
rc_path = [
"/System/Library/Frameworks/RubyCocoa.framework",
"/Library/Frameworks/RubyCocoa.framework"
].find { |p| File.exist?(p) }
raise "Cannot locate RubyCocoa.framework" unless rc_path
# FileUtils.cp_r(rc_path,frameworks_d)
# Do not use FileUtils.cp_r because it tries to follow symlinks.
unless system("cp -R \"#{rc_path}\" \"#{frameworks_d}\"")
raise "cannot copy #{rc_path} to #{frameworks_d}"
end
end
# Copy in and update library references for RubyCocoa
fixer = LibraryFixer.new
fixer.fixup_library(File.basename(ruby_cocoa_lib),ruby_cocoa_lib,lib_d,false)
third_party_d = File.join(resources_d,"ThirdParty")
FileUtils.mkdir_p(third_party_d)
# Calculate bundles and Ruby modules needed
dependencies = get_dependencies(macos_d,resources_d)
patch_main_rb(resources_d)
extra_libs.each do |lib|
dependencies << [lib,find_file_in_load_path(lib)]
end
dependencies.each do |feature,path|
case feature
when /\.rb$/
next if feature[0] == ?/
if File.exist?(File.join(ruby_cocoa_inc,feature)) then
puts "Skipping RubyCocoa file " + feature.inspect
next
end
if path[0..(resources_d.length - 1)] == resources_d
puts "Skipping existing Resource file " + feature.inspect
next
end
dir = File.join(third_party_d,File.dirname(feature))
FileUtils.mkdir_p(dir)
puts "Copying " + feature.inspect
FileUtils.cp(path,File.join(dir,File.basename(feature)))
when /\/rubycocoa.bundle$/
next
when /\.bundle$/
puts "Copying bundle " + feature.inspect
base = File.basename(path)
if path then
if feature[0] == ?/ then
relative_path = File.basename(feature)
else
relative_path = feature
end
fixer.fixup_library(relative_path,path,lib_d)
else
puts "WARNING: Bundle #{extra} not found"
end
else
$stderr.puts "WARNING: unknown feature %s loaded" % feature.inspect
end
end
end
end
if $0 == __FILE__ then
require 'ostruct'
require 'optparse'
require 'pathname'
require 'fileutils'
config = OpenStruct.new
config.force = false
config.extra_libs = []
config.dest = nil
ARGV.options do |opts|
opts.banner = "usage: #{File.basename(__FILE__)} -d DEST [options] APPLICATION\n\nUse ENV['RUBYCOCOA_STANDALONEIFYING?'] in your application to check if it's being standaloneified.\n"
opts.on("-f","--force","Delete target app if it exists already") { |config.force| }
opts.on("-d DEST","--dest","Place result at DEST (required)") {|config.dest|}
opts.on("-l LIBRARY","--lib","Extra library to bundle") { |lib| config.extra_libs << lib }
opts.parse!
end
if not config.dest or ARGV.length!=1 then
$stderr.puts ARGV.options
exit 1
end
source_app_d = ARGV.shift
if config.dest !~ /\.app$/ then
$stderr.puts "Target must have '.app' extension"
exit 1
end
if File.exist?(config.dest) then
if config.force then
FileUtils.rm_rf(config.dest)
else
$stderr.puts "Target exists already (#{config.dest.inspect})"
exit 1
end
end
Standaloneify.make_standalone_application(source_app_d,config.dest,config.extra_libs)
end
|
class Api::V1::StoresController < ApplicationController
def index
if params[:count]
stores = Store.all.limit(params[:count].to_i).select(:id, :name)
else
stores = Store.all.select(:id, :name)
end
render json: {
message: "success",
data: stores
}
end
def search
keyword = params[:keyword]
unless keyword
return render status: 400, json: {message: "The keyword is not entered."}
end
stores = Store.where("name LIKE ?", "%#{keyword}%").select(:id, :name)
if stores && stores.size > 0
render json: { data: stores }
else
render json: { message: "No data" }
end
end
end
|
# This file contains all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
root = Page.root
# About Page
about = Article.create title: 'About',
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/skating.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/skating.jpg",
intro: "<p>We are delighted to welcome you to this great adventure</p>",
content: "<p>We are delighted to welcome you to this great adventure - an Anglican church in new partnership with St Peter’s Brighton since November 2013. We are building a fun community in the heart of Whitehawk, with a vision to play our part in the re-evangelisation of the nations and the transformation of society. Feel free to join us at one of our two Sunday services.</p>
<p>If you would like to explore the meaning of life in an informal environment, we would love to invite you to join the next Alpha course.</p>
<p>We have Teams which are great places to connect and to see the vision of St Cuthman’s alive in Brighton. During the week we get together in Hubs - fortnightly gatherings of anything between 10-20 people, for food, friends, teaching, worship and prayer - the ideal way to feel like you belong.</p>
<p>For anything else, please check out the Facebook page, and don't hesitate to contact us.</p>",
parent_page_id: root.id
# Services
sunday = Article.create title: "Sunday services",
parent_page_id: about.page.id,
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/bench.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/bench.jpg",
intro:"<p>Services take place every Sunday at 9:00 and 11:00</p>",
content:"<p>Services take place every Sunday at 9:00 and 11:00</p>
<p>9am-Holy Communion</p>
<p>The Eleven-Informal service with café (including groups for children)</p>
<p>We’d love you to join us for the café at 11am before our service starts at 11.30. It’s a great opportunity to meet new friends, catch up with old friends and hear about what’s happening at St Cuthman’s.</p>
<p>Our Sunday services are about making friends, worshipping God freely, hearing a short life impacting talk (hopefully!)and praying for any needs people may have.</p>"
Widget.create page: about.page,
slot:'bottom_left',
resource_type: Article.to_s,
resource_id: sunday.id,
sort:2
alpha = Article.create title: "Alpha",
parent_page_id: about.page.id,
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/alpha.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/alpha.jpg",
intro:"<p>If you would like to explore the meaning of life in an informal environment, we would love to invite you to join the next Alpha course.</p>",
content:"<p>If you would like to explore the meaning of life in an informal environment, we would love to invite you to join the next Alpha course.</p>
<p>The Alpha course, is an opportunity for anyone to explore the Christian faith. It’s relaxed, low key and friendly. Alpha is for everyone; no question is out of bounds and you are free to discuss as much or as little as you wish</p>
<p>Each week we have dinner together, listen to a short talk and then have a discussion in a small group. The next Alpha course is starting on Wednesday 5th February 2014 and will be running every Wednesday from 7-9pm for 7 weeks. Come along to the first session and see what you think.</p>"
kids = Article.create title: "Kids church",
parent_page_id: about.page.id,
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/kids.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/kids.jpg",
intro:"<p>Our vision is that Sunday mornings at the Eleven will be the best hour of every child’s week! We want children to know the truths about God and his kingdom, to encounter Jesus and be transformed! We hope the kids will love their groups and make great friendships.</p>",
content:"<p>Our vision is that Sunday mornings at the Eleven will be the best hour of every child’s week! We want children to know the truths about God and his kingdom, to encounter Jesus and be transformed! We hope the kids will love their groups and make great friendships.</p>
<p>Our children’s groups are currently divided into two:</p>
<p>0 – 7’s We have a room full of toys, story time/craft session, lunchtime snack and a very capable team to look after all the children’s needs. Parents of younger children are welcome to stay, or go into the main service and we’ll text you if your little one needs you!</p>
<p>8 - 11’s Games, discussion, craft, Bible sound-bite</p>"
Widget.create page: about.page,
slot:'bottom_middle',
resource_type: Article.to_s,
resource_id: kids.id,
sort:2
hubs = Article.create title: "Hubs",
parent_page_id: about.page.id,
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/hubs.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/hubs.jpg",
intro:"<p>We see St Cuthman’s Church as more than a Sunday service. We want to live life together and help one another whilst serving our community. Hubs are our fortnightly gatherings of friends, fun, worship, discussion, prayer and are one of the best ways to meet people and feel connected.</p>",
content:"<p>We see St Cuthman’s Church as more than a Sunday service. We want to live life together and help one another whilst serving our community. Hubs are our fortnightly gatherings of friends, fun, worship, discussion, prayer and are one of the best ways to meet people and feel connected.</p>
<p>To join a Hub or just find out more please visit the welcome desk on a Sunday or email richandcathstcuthmans@gmail.com</p>"
safehaven = Article.create title: "Safehaven Women",
parent_page_id: about.page.id,
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/safehaven.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/safehaven.jpg",
intro:"<p>Coming Soon!</p><p>Every Monday 12-2pm during term time. Safehaven Women offers a cosy, comfortable space to relax in, with homemade meals, tea and coffee, hairdressing, manicures and pedicures, facials, craft sessions and a clothing bank. </p>",
content:"<p>Coming Soon!</p><p>Every Monday 12-2pm during term time. Safehaven Women offers a cosy, comfortable space to relax in, with homemade meals, tea and coffee, hairdressing, manicures and pedicures, facials, craft sessions and a clothing bank. </p>
<p>This is a safe place for vulnerable women to come together and hang out, to chat and to be listened to over a cup of tea and a piece of cake.</p>"
# News
news = Article.create title: "News",
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/table.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/table.jpg",
parent_page_id: root.id,
intro:"<p>Upcoming news and events at St Cuthmans.</p>",
content:"<p>Upcoming news and events at St Cuthmans.</p>
<h2>The Tabletop Sale</h2>
<p>We have a Table Top and Jumble sale on the last Saturday of everything month (except December). We have lots of new and used items to sell. We hope you'll find some useful bargains. A light lunch and refreshments are available.</p>
<p>The next sale will be on 22nd February 2014 10:30-12pm.</p>
<p>You can hire a table and sell your own items for £5. Please contact Jan for information on how you can help with the set up and selling.!</p>"
Widget.create page: news.page,
slot:'bottom_left',
resource_type: Article.to_s,
resource_id: safehaven.id,
sort:2
Widget.create page: news.page,
slot:'bottom_middle',
resource_type: Article.to_s,
resource_id: alpha.id,
sort:2
# Media
Article.create title: "Media",
parent_page_id: root.id,
image_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/media.jpg",
banner_upload_url:"http://st-cuthmans.s3.amazonaws.com/seed/media.jpg",
intro:"<p>Media coming soon</p>",
content:"<p>Media page coming soon.</p>"
Widget.create page: root,
slot:'left',
resource_type: Article.to_s,
resource_id: alpha.id,
sort:2
Widget.create page: root,
slot:'middle',
resource_type: Article.to_s,
resource_id: sunday.id,
sort:2
Widget.create page: root,
slot:'right',
resource_type: Article.to_s,
resource_id: kids.id,
sort:2
map = Map.create lat:50.828385,
lng: -0.105103,
zoom: 10,
address: "St Cuthman's Church<br/>Whitehawk Way<br/>Whitehawk<br/>BN2 5HE",
tel:"01273 555555"
Widget.create page: about.page,
slot:'bottom_right',
resource_type: Map.to_s,
resource_id: map.id,
sort:2
|
require "spec_helper"
describe ExternalRoutes do
context "routes drawing from config/routes" do
it 'routes external/success/index to external::success#index' do
expect(get: "external/success/index").to route_to(
controller: "external/success",
action: "index"
)
end
end
context "routes drawing from config/routes without namespace" do
it 'routes success/index to success#index' do
expect(get: "success/index").to route_to(
controller: "success",
action: "index"
)
end
end
end |
module Radiator
module Utils
def hexlify(s)
a = []
if s.respond_to? :each_byte
s.each_byte { |b| a << sprintf('%02X', b) }
else
s.each { |b| a << sprintf('%02X', b) }
end
a.join.downcase
end
def unhexlify(s)
s.split.pack('H*')
end
def varint(n)
data = []
while n >= 0x80
data += [(n & 0x7f) | 0x80]
n >>= 7
end
data += [n]
data.pack('C*')
end
def pakStr(s)
s = s.dup.force_encoding('BINARY')
bytes = []
bytes << varint(s.size)
bytes << s
bytes.join
end
def pakArr(a)
varint(a.size) + a.map do |v|
case v
when Symbol then pakStr(v.to_s)
when String then pakStr(v)
when Integer then paks(v)
when TrueClass then pakC(1)
when FalseClass then pakC(0)
when Array then pakArr(v)
when Hash then pakHash(v)
when NilClass then next
else
raise OperationError, "Unsupported type: #{v.class}"
end
end.join
end
def pakHash(h)
varint(h.size) + h.map do |k, v|
pakStr(k.to_s) + case v
when Symbol then pakStr(v.to_s)
when String then pakStr(v)
when Integer then paks(v)
when TrueClass then pakC(1)
when FalseClass then pakC(0)
when Array then pakArr(v)
when Hash then pakHash(v)
when NilClass then next
else
raise OperationError, "Unsupported type: #{v.class}"
end
end.join
end
def pakC(i)
[i].pack('C')
end
def pakc(i)
[i].pack('c')
end
def paks(i)
[i].pack('s')
end
def pakS(i)
[i].pack('S')
end
def pakI(i)
[i].pack('I')
end
def pakL!(i)
[i].pack('L!')
end
end
end
|
require 'fileutils'
Dir[File.join(File.dirname(__FILE__), "actions", "*.rb")].each do |action|
require action
end
class Thor
module Actions
attr_accessor :behavior
# On inclusion, add some options to base.
#
def self.included(base) #:nodoc:
return unless base.respond_to?(:class_option)
base.class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime,
:desc => "Run but do not make any changes"
base.class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime,
:desc => "Overwrite files that already exist"
base.class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime,
:desc => "Skip files that already exist"
base.class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime,
:desc => "Supress status output"
end
# Extends initializer to add more configuration options.
#
# ==== Configuration
# behavior<Symbol>:: The actions default behavior. Can be :invoke or :revoke.
# It also accepts :force, :skip and :pretend to set the behavior
# and the respective option.
#
# root<String>:: The root directory needed for some actions. It's also known
# as destination root.
#
def initialize(args=[], options={}, config={})
self.behavior = case config[:behavior]
when :force
options.merge!(:force => true, 'force' => true)
:invoke
when :skip
options.merge!(:skip => true, 'skip' => true)
:invoke
when :pretend
options.merge!(:pretend => true, 'pretend' => true)
:invoke
when :revoke
:revoke
else
:invoke
end
super
self.root = config[:root]
# For last, invoke source root to allow the result to be cached. This is
# needed because source root depends on the file location (__FILE__) which
# returns the wrong value if invoked after FileUtils#cd.
#
self.source_root if self.class.respond_to?(:source_root)
end
# Wraps an action object and call it accordingly to the thor class behavior.
#
def action(instance)
if behavior == :revoke
instance.revoke!
else
instance.invoke!
end
end
# Returns the root for this thor class (also aliased as destination root).
#
def root
@root_stack.last
end
alias :destination_root :root
# Sets the root for this thor class. Relatives path are added to the
# directory where the script was invoked and expanded.
#
def root=(root)
@root_stack ||= []
@root_stack[0] = File.expand_path(root || '')
end
# Gets the current root relative to the absolute root.
#
# inside "foo" do
# relative_root #=> "foo"
# end
#
def relative_root(remove_dot=true)
relative_to_absolute_root(root, remove_dot)
end
# Returns the given path relative to the absolute root (ie, root where
# the script started).
#
def relative_to_absolute_root(path, remove_dot=true)
path = path.gsub(@root_stack[0], '.')
remove_dot ? (path[2..-1] || '') : path
end
# Get the source root in the class. Raises an error if a source root is
# not specified in the thor class.
#
def source_root
self.class.source_root
rescue NoMethodError => e
raise NoMethodError, "You have to specify the class method source_root in your thor class."
end
# Do something in the root or on a provided subfolder. If a relative path
# is given it's referenced from the current root. The full path is yielded
# to the block you provide. The path is set back to the previous path when
# the method exits.
#
# ==== Parameters
# dir<String>:: the directory to move to.
#
def inside(dir='', &block)
@root_stack.push File.expand_path(dir, root)
FileUtils.mkdir_p(root) unless File.exist?(root)
FileUtils.cd(root) { block.arity == 1 ? yield(root) : yield }
@root_stack.pop
end
# Goes to the root and execute the given block.
#
def in_root
inside(@root_stack.first) { yield }
end
# Changes the mode of the given file or directory.
#
# ==== Parameters
# mode<Integer>:: the file mode
# path<String>:: the name of the file to change mode
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Example
#
# chmod "script/*", 0755
#
def chmod(path, mode, log_status=true)
path = File.expand_path(path, root)
say_status :chmod, relative_to_absolute_root(path), log_status
FileUtils.chmod_R(mode, path) unless options[:pretend]
end
# Executes a command.
#
# ==== Parameters
# command<String>:: the command to be executed.
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Example
#
# inside('vendor') do
# run('ln -s ~/edge rails')
# end
#
def run(command, log_status=true)
say_status :run, "#{command} from #{relative_to_absolute_root(root, false)}", log_status
`#{command}` unless options[:pretend]
end
# Executes a ruby script (taking into account WIN32 platform quirks).
#
# ==== Parameters
# command<String>:: the command to be executed.
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
def run_ruby_script(command, log_status=true)
run("ruby #{command}", log_status)
end
# Run a thor command. A hash of options can be given and it's converted to
# switches.
#
# ==== Parameters
# task<String>:: the task to be invoked
# args<Array>:: arguments to the task
# options<Hash>:: a hash with options used on invocation
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Examples
#
# thor :install, "http://gist.github.com/103208"
# #=> thor install http://gist.github.com/103208
#
# thor :list, :all => true, :substring => 'rails'
# #=> thor list --all --substring=rails
#
def thor(task, *args)
log_status = args.last.is_a?(Symbol) || [true, false].include?(args.last) ? args.pop : true
options = args.last.is_a?(Hash) ? args.pop : {}
in_root do
args.unshift "thor #{task}"
args.push Thor::Options.to_switches(options)
run args.join(' ').strip, log_status
end
end
# Removes a file at the given location.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Example
#
# remove_file 'README'
# remove_file 'app/controllers/application_controller.rb'
#
def remove_file(path, log_status=true)
path = File.expand_path(path, root)
say_status :remove, relative_to_absolute_root(path), log_status
::FileUtils.rm_rf(path) if !options[:pretend] && File.exists?(path)
end
# Run a regular expression replacement on a file.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# flag<Regexp|String>:: the regexp or string to be replaced
# replacement<String>:: the replacement, can be also given as a block
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Example
#
# gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
#
# gsub_file 'README', /rake/, :green do |match|
# match << " no more. Use thor!"
# end
#
def gsub_file(path, flag, *args, &block)
log_status = args.last.is_a?(Symbol) || [ true, false ].include?(args.last) ? args.pop : true
path = File.expand_path(path, root)
say_status :gsub, relative_to_absolute_root(path), log_status
unless options[:pretend]
content = File.read(path)
content.gsub!(flag, *args, &block)
File.open(path, 'wb') { |file| file.write(content) }
end
end
# Append text to a file.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# data<String>:: the data to append to the file, can be also given as a block.
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Example
#
# append_file 'config/environments/test.rb', 'config.gem "rspec"'
#
def append_file(path, data=nil, log_status=true, &block)
path = File.expand_path(path, root)
say_status :append, relative_to_absolute_root(path), log_status
File.open(path, 'ab') { |file| file.write(data || block.call) } unless options[:pretend]
end
# Prepend text to a file.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# data<String>:: the data to prepend to the file, can be also given as a block.
# log_status<Boolean>:: if false, does not log the status. True by default.
# If a symbol is given, uses it as the output color.
#
# ==== Example
#
# prepend_file 'config/environments/test.rb', 'config.gem "rspec"'
#
def prepend_file(path, data=nil, log_status=true, &block)
path = File.expand_path(path, root)
say_status :prepend, relative_to_absolute_root(path), log_status
unless options[:pretend]
content = data || block.call
content << File.read(path)
File.open(path, 'wb') { |file| file.write(content) }
end
end
protected
# Update dump_config to dump also behavior and root.
#
def _dump_config #:nodoc:
super.merge!(:behavior => self.behavior, :root => @root_stack[0])
end
end
end
|
class AddUrlHtmlToYtVideo < ActiveRecord::Migration
def change
add_column :yt_videos, :url_html, :text
end
end
|
module TrackerApi
module Resources
class ReviewType
include Shared::Base
attribute :id, Integer
attribute :project_id, Integer
attribute :name, String
attribute :hidden, Boolean
attribute :created_at, DateTime
attribute :updated_at, DateTime
attribute :kind, String
end
end
end |
class DecksController < ApplicationController
before_action :set_deck, only: [:show, :edit, :update, :destroy]
#added this
before_action :authenticate_user!, only: [:create, :index ]
# GET /decks
# GET /decks.json
def index
# @decks = Deck.all
@decks = Deck.all
render json: @decks, root: false
end
# GET /decks/1
# GET /decks/1.json
def show
render json: @deck, root: false
end
# GET /decks/new
def new
@deck = Deck.new
@deck.cards.build
end
# GET /decks/1/edit
def edit
@deck.cards.build
end
# POST /decks
# POST /decks.json
def create
# the params sent by backbone are not valid for nested attributes with rails
# therefore, we need to re-create the params object that will be used to create the deck
@deck = current_user.decks.new(nested_deck_params)
respond_to do |format|
if @deck.save
format.json { render json: @deck, root: false, status: :created, location: @deck }
else
format.json { render json: @deck.errors, root: false, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /decks/1
# PATCH/PUT /decks/1.json
def update
respond_to do |format|
if @deck.update(nested_deck_params)
format.json { render json: @deck, root: false, status: :ok, location: @deck }
else
format.json { render json: @deck.errors, root: false, status: :unprocessable_entity }
end
end
end
# DELETE /decks/1
# DELETE /decks/1.json
def destroy
@deck.destroy
respond_to do |format|
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_deck
@deck = Deck.find(params[:id])
end
def deck_params
params.require(:deck).permit(:title, :score, cards_attributes: [:id, :character] )
# params.require(:deck).permit(:title, :score, cards_attributes: [:id, :character, :sound, :translation, :_destroy])
end
#Create an ActionController::Parameters Object which is different from a Regular Hash containing the params from :deck with card attributes
def nested_deck_params
hash_params = ActionController::Parameters.new({
deck: params[:deck].merge({cards_attributes: params[:cards_attributes]})
})
#filters parameters
hash_params.require(:deck).permit(:user_id, :title, :score, cards_attributes: [:id, :character, :sound, :translation] )
end
end
|
#encoding: utf-8
class Web::Admin::PartnerProductItemsController < Web::Admin::ApplicationController
before_filter :set_partner_product, except: [:edit, :destroy]
def new
@ppi = @pp.partner_product_items.build
end
def create
@ppi = @pp.partner_product_items.build(params[:partner_product_item])
if @ppi.save
redirect_to admin_partner_product_partner_product_items_path, notice: 'Товар партнера успешно создан'
else
render 'new'
end
end
def index
@ppis = @pp.partner_product_items.active.asc_by_order_at
set_pp_type_in_session_for_back_in_browser(@pp.partner_product_type)
end
def edit
@ppi = PartnerProductItem.find(params[:id])
@pp = @ppi.partner_product
end
def update
@ppi = @pp.partner_product_items.find(params[:id])
if @ppi.update_attributes(params[:partner_product_item])
redirect_to admin_partner_product_partner_product_items_path(@pp.id)
else
render 'edit'
end
end
def destroy
ppi = PartnerProductItem.find(params[:id])
ppi.mark_as_deleted!
redirect_to admin_partner_product_partner_product_items_path(ppi.partner_product_id),
notice: 'Товар отправлен в архив.'
end
def deleted
@ppis = @pp.partner_product_items.deleted.by_deleted_at
set_pp_type_in_session_for_back_in_browser(@pp.partner_product_type)
end
def restore
ppi = @pp.partner_product_items.find(params[:id])
ppi.restore!
redirect_to admin_partner_product_partner_product_items_path(@pp),
notice: 'Товар восстановлен из архива'
end
private
def set_partner_product
@pp = PartnerProduct.find(params[:partner_product_id])
end
end
|
require "spec_helper"
require "sentry/integrable"
RSpec.describe Sentry::Integrable do
module Sentry
module FakeIntegration
extend Sentry::Integrable
register_integration name: "fake_integration", version: "0.1.0"
end
end
it "registers correct meta" do
meta = Sentry.integrations["fake_integration"]
expect(meta).to eq({ name: "sentry.ruby.fake_integration", version: "0.1.0" })
end
context "when the SDK is initialized" do
let(:io) { StringIO.new }
let(:logger) { Logger.new(io) }
module Sentry
module AnotherIntegration; end
end
before do
perform_basic_setup do |config|
config.logger = logger
end
end
it "logs warning message about the incorrect loading order" do
Sentry::AnotherIntegration.extend Sentry::Integrable
Sentry::AnotherIntegration.register_integration name: "another_integration", version: "0.1.0"
expect(io.string).to match(/Integration 'another_integration' is loaded after the SDK is initialized/)
end
end
describe "helpers generation" do
before do
perform_basic_setup
end
let(:exception) { ZeroDivisionError.new("1/0") }
let(:message) { "test message" }
it "generates Sentry::FakeIntegration.capture_exception" do
hint = nil
Sentry.configuration.before_send = lambda do |event, h|
hint = h
event
end
Sentry::FakeIntegration.capture_exception(exception, hint: { additional_hint: "foo" })
expect(hint).to eq({ additional_hint: "foo", integration: "fake_integration", exception: exception })
end
it "generates Sentry::FakeIntegration.capture_exception" do
hint = nil
Sentry.configuration.before_send = lambda do |event, h|
hint = h
event
end
Sentry::FakeIntegration.capture_message(message, hint: { additional_hint: "foo" })
expect(hint).to eq({ additional_hint: "foo", integration: "fake_integration", message: message })
end
it "sets correct meta when the event is captured by integration helpers" do
event = Sentry::FakeIntegration.capture_message(message)
expect(event.sdk).to eq({ name: "sentry.ruby.fake_integration", version: "0.1.0" })
end
it "doesn't change the events captured by original helpers" do
event = Sentry.capture_message(message)
expect(event.sdk).to eq(Sentry.sdk_meta)
end
end
end
|
module Mahjong
class Wind
WINDS = %i(east south west north)
delegate :hash, :to_s, :to_sym, to: :@sym
class << self
def all
WINDS.map {|w| new(w) }
end
end
def initialize(sym)
@sym = sym
end
def next
self.class.new(WINDS.zip(WINDS.rotate).to_h[@sym])
end
def prev
self.class.new(WINDS.zip(WINDS.rotate(-1)).to_h[@sym])
end
def eql?(other)
hash == other.hash
end
def ==(other)
eql?(other)
end
def as_json(*)
to_s
end
def <=>(other)
WINDS.index(to_sym) <=> WINDS.index(other.to_sym)
end
WINDS.each do |w|
define_method("#{w}?") { @sym == w }
end
end
end
|
class Admin::CSV::FacilityValidator
def self.validate(*args)
new(*args).validate
end
def initialize(facilities)
@facilities = facilities
@errors = []
end
attr_reader :errors
def validate
at_least_one_facility
duplicate_rows
facilities
self
end
def at_least_one_facility
@errors << "Uploaded file doesn't contain any valid facilities" if @facilities.blank?
end
def duplicate_rows
facilities_slice = @facilities.map { |facility| facility.slice(:organization_name, :facility_group_name, :name) }
@errors << "Uploaded file has duplicate facilities" if facilities_slice.count != facilities_slice.uniq.count
end
def facilities
row_errors = []
@facilities.each.with_index(2) do |facility, row_num|
import_facility = Facility.new(facility_params(facility))
row_errors << [row_num, import_facility.errors.full_messages.to_sentence] if import_facility.invalid?
end
group_row_errors(row_errors).each { |error| @errors << error } if row_errors.present?
end
private
def facility_params(facility)
return facility unless facility[:enable_teleconsultation]
facility[:teleconsultation_phone_numbers] = [{isd_code: facility[:teleconsultation_isd_code],
phone_number: facility[:teleconsultation_phone_number]}]
facility
end
def group_row_errors(row_errors)
unique_errors = row_errors.map { |row, message| message }.uniq
unique_errors.map do |error|
rows = row_errors.select { |row, message| row if error == message }.map { |row, message| row }
"Row(s) #{rows.join(", ")}: #{error}"
end
end
end
|
require 'formula'
#Builds Boost with clang and c++11
class Boost160 < Formula
homepage 'http://boost.org'
url 'http://sourceforge.net/projects/boost/files/boost/1.60.0/boost_1_60_0.tar.gz'
sha256 '21ef30e7940bc09a0b77a6e59a8eee95f01a766aa03cdfa02f8e167491716ee4'
def install
system "./bootstrap.sh", "--libdir=#{prefix}/lib/", "--includedir=#{prefix}/include/", "--with-python=#{HOMEBREW_PREFIX}/bin/python"
system "./b2", "toolset=clang", "cxxflags=-std=c++0x -stdlib=libc++", "linkflags=-stdlib=libc++", "--without-mpi", "--without-signals", "variant=release", "threading=multi", "install"
end
end
|
# -*- coding: utf-8 -*-
require "lucie/debug"
module SSH::Path
include Lucie::Debug
PUBLIC_KEY_NAME = "id_rsa.pub"
PRIVATE_KEY_NAME = "id_rsa"
#
# Returns <tt>[ssh home]/id_rsa.pub
#
#--
# [FIXME] dryrun かどうかでの場合分け。authorized_keys では
# @ssh_home を見てるのでどっちかにすべき。
#++
def public_key
base_dir = dry_run ? user_ssh_home : ssh_home
File.join base_dir, PUBLIC_KEY_NAME
end
#
# Returns <tt>[ssh home]/id_rsa</tt>
#
def private_key
File.join ssh_home, PRIVATE_KEY_NAME
end
#
# Returns the <tt>.ssh/</tt> directory used for installation.
#
# If both <tt>[lucie]/.ssh/{id_rsa,id_rsa.pub}</tt> exist, this
# returns <tt>[lucie]/.ssh/</tt>
#
# If both <tt>~/.ssh/{id_rsa,id_rsa.pub}</tt> exist, returns
# <tt>~/.ssh/</tt>
#
# If not found, raises an exception.
#
def ssh_home
if lucie_ssh_key_pair_exist?
lucie_ssh_home
elsif user_ssh_key_pair_exist?
user_ssh_home
else
raise "No ssh keypair found in #{ lucie_ssh_home } nor #{ user_ssh_home }!"
end
end
#
# Returns <tt>[ssh home]/authorized_keys</tt>
#
#--
# [FIXME] @ssh_home での切り替えは implicit すぎ
#++
def authorized_keys
File.join @ssh_home || user_ssh_home, "authorized_keys"
end
############################################################################
private
############################################################################
def home
@debug_options && @debug_options[ :home ] || ENV[ "LUCIE_USER" ] && File.expand_path( "~" + ENV[ "LUCIE_USER" ] ) || File.expand_path( "~" )
end
def user_ssh_home
File.join home, ".ssh"
end
def user_public_key
File.join user_ssh_home, PUBLIC_KEY_NAME
end
def user_private_key
File.join user_ssh_home, PRIVATE_KEY_NAME
end
def lucie_ssh_home
File.join home, ".lucie"
end
def lucie_public_key
File.join lucie_ssh_home, PUBLIC_KEY_NAME
end
def lucie_private_key
File.join lucie_ssh_home, PRIVATE_KEY_NAME
end
def lucie_ssh_key_pair_exist?
FileTest.exist?( lucie_public_key ) and FileTest.exist?( lucie_private_key )
end
def user_ssh_key_pair_exist?
FileTest.exist?( user_public_key ) and FileTest.exist?( user_private_key )
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
|
class DelayedJob < ApplicationRecord
has_one :feed_for_email, class_name: 'Feed', foreign_key: :delayed_job_email_id, dependent: :nullify
has_one :feed_for_webpush, class_name: 'Feed', foreign_key: :delayed_job_webpush_id, dependent: :nullify
end
|
class CreateProducersOwnerIdIndex < ActiveRecord::Migration
def up
add_index(:producers, :owner_id, { name: "producers_owner_id_index" })
end
def down
remove_index(:producers, name: "producers_owner_id_index")
end
end
|
class AddDetailFieldsToRightsDeclaration < ActiveRecord::Migration
def change
add_column :rights_declarations, :copyright_jurisdiction, :string
add_column :rights_declarations, :copyright_statement, :string
add_column :rights_declarations, :access_restrictions, :string
end
end
|
require 'test/unit'
require 'html5_tokenizer'
class TestTokenizer < Test::Unit::TestCase
def tokens(tokenizer)
tokens = []
tokenizer.run { |t| tokens << t }
tokens
end
def tokenize(html)
tokenizer = Html5Tokenizer::Tokenizer.new()
tokenizer.insert(html)
tokenizer.eof()
tokens(tokenizer)
end
def assert_tokens(expecteds, actuals)
assert_equal expecteds.count, actuals.count
actuals.zip(expecteds).each do |actual, expected|
expected.each { |k,v| assert_equal v, actual.send(k), "Test token #{actual}" }
end
end
def test_run_text
token = tokenize('foobar').first
assert_equal :character, token.type
assert_equal 'foobar', token.value
end
def test_run_html
actuals = tokenize('<!doctype html><html><body><a><img src="http://test.com/img"/> An Image </a><!--End-->')
expecteds = [
{ :type => :doctype, :name => 'html', :public_missing => true, :public_id => '', :system_missing => true, :system_id => '', :force_quirks => false },
{ :type => :start_tag, :name => 'html', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :start_tag, :name => 'body', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :start_tag, :name => 'a', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :start_tag, :name => 'img', :ns => :ns_html, :attributes => {'src' => 'http://test.com/img'}, :self_closing => true },
{ :type => :character, :value => ' An Image ' },
{ :type => :end_tag, :name => 'a', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :comment, :value => 'End' },
{ :type => :eof }
]
assert_tokens(expecteds, actuals)
end
def test_public_doctype
actuals = tokenize('<!DOCTYPE foo PUBLIC "public_location">')
expecteds = [{ :type => :doctype, :name => 'foo',
:public_missing => false, :public_id => 'public_location',
:system_missing => true, :system_id => '',
:force_quirks => false },
{ :type => :eof }]
assert_tokens(expecteds, actuals)
end
def test_system_doctype
actuals = tokenize('<!DOCTYPE foo SYSTEM "system_location">')
expecteds = [{ :type => :doctype, :name => 'foo',
:public_missing => true, :public_id => '',
:system_missing => false, :system_id => 'system_location',
:force_quirks => false },
{ :type => :eof }]
assert_tokens(expecteds, actuals)
end
def test_quirk_doctype
actuals = tokenize('<!DOCTYPE>')
expecteds = [{ :type => :doctype, :name => '',
:public_missing => true, :public_id => '',
:system_missing => true, :system_id => '',
:force_quirks => true },
{ :type => :eof }]
assert_tokens(expecteds, actuals)
end
def test_tag_ns
actuals = tokenize(%q{<a:a/><b a=a b="b" c='c'></a/></b>})
expecteds = [
{ :type => :start_tag, :name => 'a:a', :ns => :ns_html, :attributes => {}, :self_closing => true },
{ :type => :start_tag, :name => 'b', :ns => :ns_html, :attributes => {'a'=>'a','b'=>'b','c'=>'c'}, :self_closing => false },
{ :type => :end_tag, :name => 'a', :ns => :ns_html, :attributes => {}, :self_closing => true },
{ :type => :end_tag, :name => 'b', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :eof },
]
assert_tokens(expecteds, actuals);
end
def test_reentrant_tokenize
tokenizer = Html5Tokenizer::Tokenizer.new()
tokenizer.insert('<!--<a b="c">-->')
tokenizer.run do |token|
assert_equal :comment, token.type
assert_equal '<a b="c">', token.value
inner_token = tokenize(token.value).first
assert_equal :start_tag, inner_token.type
assert_equal 'a', inner_token.name
assert_equal ({'b'=>'c'}), inner_token.attributes
end
end
def test_insert_non_string
tokenizer = Html5Tokenizer::Tokenizer.new()
tokenizer.insert(nil)
tokenizer.insert(1)
tokenizer.insert(tokenizer)
tokenizer.eof()
tokenizer.run {|t| assert_equal :eof, t.type}
end
def test_cdata
actuals = tokenize(%q{<script><![CDATA[<foo></bar>]]></script>})
expecteds = [
{ :type => :start_tag, :name => 'script', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :character, :value => '<foo></bar>' },
{ :type => :end_tag, :name => 'script', :ns => :ns_html, :attributes => {}, :self_closing => false },
{ :type => :eof },
]
assert_tokens(expecteds, actuals);
end
end
|
class AddCodeToContent < ActiveRecord::Migration
def self.up
add_column :contents, :code, :string, :limit => 10
add_index :contents, :code, :unique => true
end
def self.down
remove_column :contents, :code
end
end
|
#!/usr/bin/env ruby
#
# Given an mxn matrix, design a function that will print out the contents of the matrix in spiral format.
# Spiral format means for a 5x5 matrix given below:
#
# [ 1 2 3 4 5 ]
# [ 6 7 8 9 0 ]
# [ 1 2 3 4 5 ]
# [ 6 7 8 9 0 ]
# [ 1 2 3 4 5 ]
# path taken is:
#
# [ > > > > > ]
# [ > > > > v ]
# [ ^ ^ > v v ]
# [ ^ ^ < < v ]
# [ < < < < < ]
# where ">" is going right, "v" going down, "<" is going left, "^" is going up.
# The output is:
#
# 1 2 3 4 5 0 5 0 5 4 3 2 1 6 1 6 7 8 9 4 9 8 7 2 3
a =
[
[ 1, 2, 3, 4, 5 ],
[ 6, 7, 8, 9, 0 ],
[ 1, 2, 3, 4, 5 ],
[ 6, 7, 8, 9, 0 ],
[ 1, 2, 3, 4, 5 ]
]
m = a.length
n = a[0].length
b = []
m.times{b << Array.new(n,0)}
s = []
j,k = 0,0
dj,dk = 0,1
kmin,jmin = 0,0
kmax,jmax = n-1,m-1
while true do
break if b[j][k] == 1
s << a[j][k]
b[j][k] = 1
if k + dk > kmax
dk = 0
dj = 1
jmin += 1
elsif k + dk < kmin
dk = 0
dj = -1
jmax -= 1
elsif j + dj > jmax
dk = -1
dj = 0
kmax -= 1
elsif j + dj < jmin
dk = 1
dj = 0
kmin += 1
end
j += dj
k += dk
end
p s
|
#
# Mixin for the Merb::DataMapperSession which provides for authentication
#
module Authentication
class DuplicateStrategy < Exception; end
class MissingStrategy < Exception; end
class NotImplemented < Exception; end
@@login_strategies = StrategyContainer.new
def self.login_strategies
@@login_strategies
end
module Session
def self.included(base)
base.send(:include, InstanceMethods)
base.send(:extend, ClassMethods)
end
module ClassMethods
end # ClassMethods
module InstanceMethods
def _authentication_manager
@_authentication_manager ||= Authentication::Manager.new(self)
end
def authenticated?
_authentication_manager.authenticated?
end
def authenticate(controller)
_authentication_manager.authenticate(controller)
end
def user
_authentication_manager.user
end
def user=(the_user)
_authentication_manager.user = the_user
end
def abandon!
_authentication_manager.abandon!
end
end # InstanceMethods
end # Session
end |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'statics#landing'
get 'landing', to: 'statics#landing'
get 'home', to: 'statics#home'
get 'about', to: 'statics#about'
get 'contact', to: 'statics#contact'
get 'thankyou', to: 'statics#thankyou'
get 'admin_panel', to: 'statics#panel'
get 'summit', to: 'statics#summit'
get 'under_development', to: 'statics#under_development'
get 'all_events', to: 'events#all_events'
get 'all_members', to: 'members#all_members'
get 'all_econsiders', to: 'econsiders#all_econsiders'
get 'all_dialogues', to: 'dialogues#all_dialogues'
get 'ameuxadminsignup', to: 'users#new'
resources :users, except: [:new]
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
resources :events
resources :dialogues
resources :members
resources :econsiders
end |
=begin
input : string
output : is a boolean
steps :
1: define a method that outputs a string
2: compare str to itself reversed.
=end
def palindrome?(str)
str == reverse(str)
end
def reverse(str)
new_str = ''
count = str.size
loop do
break if count == 0
new_str << str[count - 1]
count -= 1
end
p new_str
end
p palindrome?('madam') # == true
p palindrome?('Madam') # == false # (case matters)
p palindrome?("madam i'm adam") # == false # (all characters matter)
p palindrome?('356653') # == true
|
# -*- coding: utf-8 -*-
# "Vorwort" => VII
# "Inhaltsverzeichnis" => IX
PART = 0
CHAPTER = 1
SECTION = 2
EXKURS = 3
TOCLIST =
[
["EINLEITUNG", [1, PART]],
["I. Nationalökonomie und Praxeologie", [1, SECTION]],
["II. Das Problem einer Wissenschaft vom menschlichen Handeln", 3],
["III. Nationalökonomie und Zielwahl", 7],
["IV. Zusammenfassung", 9],
["ERSTER TEIL: DAS HANDELN", [11, PART]],
["1. Kapitel: Der handelnde Mensch", [11, CHAPTER]],
["I. Handeln und unbewusste Reaktion", [11, SECTION]],
["II. Die Vernunft im Handeln. Das Irrationale. Subjektivismus und Objektivität der Wissenschaft", 14],
["III. Der formale und apriorische Charakter der Lehre vom Handeln", 16],
["Exkurse: A. Über innere Erfahrung als vermeintliche Quelle praxeologischer Erkenntnis", [17, 3]],
["B. Über den tautologischen Charakter der praxeologischen Deduktion", 19],
["C. Theorie und Erfahrung", 20],
["D. Über Kausalität", 22],
["IV. Eigenes und fremdes Handeln", [23, 2]],
["Exkurs: Über den Instinkt", [29, 3]],
["V. Die allgemeinen Bedingungen des Handelns", [30, 2]],
["2. Kapitel: Die Wissenschaft vom menschlichen Handeln", [31, 1]],
["I. Der Ausgangspunkt der wissenschaftlichen Betrachtung des menschlichen Handelns: das Handeln der Einzelnen", [31, 2]],
["Exkurs: Ich und Wir", [34, 3]],
["II. Der Ausgangspunkt der wissenschaftlichen Betrachtung des menschlichen Handelns: die einzelne Handlung", [34, 2]],
["III. Einflüsse der Herkunft und der Umwelt auf das Handeln", 36],
["IV. Die Unwandelbarkeit der Struktur des Handelns", 37],
["V. Der logische Charakter der Praxeologie", 39],
["VI. Das praxeologische Problem", 40],
["VII. Theorie und Geschichte. Qualitative und quantitative Erkenntnis", 42],
["VIII. Begreifen und Verstehen", 51],
["IX. Praxeologischer Begriff und geisteswissenschaftlicher Typus", 56],
["X. Die Einheit der Wissenschaft", 60],
["XI. Praxeologischer Begriff und Wirklichkeit", 63],
["XII. Die Grenzen der praxeologischen Begriffsbildung", 64],
["3. Kapitel: Die Kategorien des Handelns", [65, 1]],
["I. Ende, Ziel, Zweck. Mittel und Wege. Knappheit der Mittel. Freie Güter und wirtschaftliche Güter. Die Güterordnungen", [65, 2]],
["Exkurse: A. Hedonismus, Eudämonismus, Utilitarismus", [68, 3]],
["B. Trieb und Triebsoziologie", 69],
["C. Bedürfnis und Bedürfnislehre", 71],
["II. Das Vorziehen und die Rangordnung der Zwecke und der Mittel", [72, 2]],
["Exkurs: Der nichthandelnde Mensch", [74, 3]],
["III. Das Handeln als Tausch. Wert und Preis. Kosten. Erfolg und Misserfolg. Gewinn und Verlust", [75, 2]],
["4. Kapitel: Zeit und Handeln", [76, CHAPTER]],
["I. Die Zeitlichkeit der Praxeologie", [76, SECTION]],
["II. Vergangenheit, Gegenwart, Zukunft", 77],
["Exkurs: Das Denken modo futuri exacti", [80, EXKURS]],
["III. Die Bewirtschaftung der Zeit", [80, SECTION]],
["IV. Das Problem der Gleichzeitigkeit und die Vorstellung vermeintlich irrationalen Handelns", 81],
["5. Kapitel: Das Handeln in der Welt", [84, CHAPTER]],
["I. Das Handeln und die Quantität und Qualität der Mittel. Das Grenznutzengesetz", [84, SECTION]],
["II. Das Ertragsgesetz", 95],
["III. Die menschliche Arbeit als Mittel", 99],
["Exkurse: A. Mittelbarer und unmittelbarer Arbeitsgenuss", [108, EXKURS]],
["B. Die bahnbrechende Leistung", 109],
["IV. Die Produktion", [111, SECTION]],
["ZWEITER TEIL: DAS HANDELN IN DER GESELLSCHAFT", [115, PART]],
["1. Kapitel: Die menschliche Gesellschaft", [115, CHAPTER]],
["I. Gesellschaft als Vereinigung menschlichen Handelns", [115, SECTION]],
["II. Kritik der universalistischen und kollektivistischen Gesellschaftsauffassung", 116],
["III. Die Arbeitsteilung", 125],
["IV. Das Ricardo’sche Vergesellschaftungsgesetz", 126],
["Exkurs: Missverständnisse in Bezug auf das Vergesellschaftungsgesetz", [129, EXKURS]],
["V. Wirkungen der Arbeitsteilung", [133, SECTION]],
["VI. Der Einzelne in der Gesellschaft", 134],
["Exkurs: Die Fabel von der Gemeinschaft", [136, EXKURS]],
["VII. Gesellschaft als Tauschgesellschaft im weitesten Sinne", [139, SECTION]],
["VIII. Der Kampf- und Zerstörungstrieb", 141],
["2. Kapitel: Die Idee im Handeln", [145, CHAPTER]],
["I. Die menschliche Vernunft", [145, SECTION]],
["II. Weltanschauung und Ideologie", 147],
["Exkurse: A. Die marxistische Ideologienlehre", [155, EXKURS]],
["B. Die rassenbiologische Variante des Polylogismus", 157],
["III. Idee, Macht, Gewalt, Herrschaft", [166, SECTION]],
["Exkurse: A. Traditionsgebundenheit als Ideologie", [171, EXKURS]],
["B. Der bildliche Gebrauch des Ausdruckes «Herrschaft»", 171],
["IV. Praxeologischer Subjektivismus und pseudohistorischer Relativismus", [172, SECTION]],
["V. Kritik der rassenbiologischen Gesellschafts- und Staatstheorie", 175],
["VI. Kritik des Fortschrittsoptimismus", 178],
["3. Kapitel: Der Tausch in der Gesellschaft", [180, CHAPTER]],
["I. Innerer Tausch und zwischenmenschlicher (gesellschaftlicher) Tausch", [180, SECTION]],
["II. Tauschgesellschaft und herrschaftlicher Verband", 182],
["III. Das Problem des rechnenden Handelns", 185],
["DRITTER TEIL: RECHNEN IM HANDELN", [188, PART]],
["1. Kapitel: Wertung ohne Rechnen", [188, CHAPTER]],
["I. Die Reihung der Mittel", [188, SECTION]],
["II. Die Naturaltausch-Fiktion der elementaren Wert- und Preislehre", 189],
["Exkurs: Wertlehre und Sozialismus", [194, EXKURS]],
["III. Das Problem der Wirtschaftsrechnung", [195, SECTION]],
["IV. Wirtschaftsrechnung und Marktverkehr", 197],
["2. Kapitel: Die Geldrechnung, ihre Voraussetzungen und die Grenzen ihres Bereiches", [198, CHAPTER]],
["I. Die Geldansätze der Geldrechnung", [198, SECTION]],
["II. Der Umfang der Geldrechnung", 202],
["III. Die Wandelbarkeit der Geldpreise", 205],
["IV. Stabilisierung", 208],
["V. Die Herkunft der Stabilisierungsidee", 213],
["VI. Nebeneinanderbestehen mehrerer Geldarten", 217],
["3. Kapitel: Die Geldrechnung als gedankliches Werkzeug des Handelns", [218, CHAPTER]],
["I. Die Geldrechnung als Denkverfahren. Der Begriff des Wirtschaftlichen im engeren Sinne", [218, SECTION]],
["II. Geldrechnung und Praxeologie", 220],
["VIERTER TEIL: DIE MARKTWIRTSCHAFT", [224, PART]],
["1. Kapitel: Problemstellung und Verfahren der Katallaktik", [224, CHAPTER]],
["I. Die Abgrenzung des katallaktischen Problemkreises", [224, SECTION]],
["II. Die Methode der Gedankenbilder", 227],
["III. Das Gedankenbild der reinen Marktwirtschaft", 228],
["Exkurs: Die Maximalisierung der Gewinne", [231, EXKURS]],
["IV. Das Gedankenbild der einfachen Wirtschaft", [234, SECTION]],
["V. Die Gedankenbilder des einfachen und des endlichen Ruhezustandes und der gleichmässigen Wirtschaft", 235],
["VI. Das Gedankenbild der stationären Wirtschaft", 243],
["VII. Das Problem einer nationalökonomischen Dynamik", 244],
["VIII. Das Gedankenbild der funktionell gegliederten Marktwirtschaft", 245],
["Exkurs: Die Unternehmerfunktion in der stationären Wirtschaft", [249, EXKURS]],
["2. Kapitel: Die Steuerung des Handelns durch den Markt", [250, CHAPTER]],
["I. Das Wesen der Marktwirtschaft", [250, SECTION]],
["II. Kapitalrechnung und Kapital; Realkapital und Geldkapital", 253],
["III. Kapitalismus", 256],
["IV. Unternehmer und Verbraucher", 258],
["Exkurs: Die Ausgabenwirtschaft des Unternehmers", [260, EXKURS]],
["V. Der Wettbewerb", [261, SECTION]],
["VI. Gewinn und Verlust der Unternehmer", 265],
["VII. Die Auslese des Marktes", 271],
["VIII. Erzeuger und Verbraucher", 273],
["IX. Die Werbung", 277],
["X. Die Wirte und die Volkswirtschaft", 280],
["3. Kapitel: Die Preise", [283, CHAPTER]],
["I. Die Preisbildung auf dem Markte", [283, SECTION]],
["II. Wertung und Preisbildung", 289],
["III. Die Preise der Güter höherer Ordnung", 291],
["Exkurs: Eine Grenze der Preisbildung der Produktionsmittel", [300, EXKURS]],
["IV. Die Kostenrechnung", [301, SECTION]],
["V. Der Menger-Böhm’sche Weg zur Lösung des Zurechnungsproblems und die mathematische Katallaktik", 312],
["VI. Die Monopolpreise", 319],
["Exkurs: Die mathematische Behandlung der Monopolpreislehre", [335, EXKURS]],
["VII. Die Kundschaft", [337, SECTION]],
["VIII. Die Preisgestaltung beim Nachfragemonopol", 341],
["IX. Der Verbrauch unter dem Einfluss der Monopolpreise", 343],
["X. Die Diskriminationspreise", 346],
["XI. Der Zusammenhang der Preise", 350],
["XII. Die Preise und die Einkommensbildung", 352],
["XIII. Die Preise und die Ordnung der Produktion", 354],
["4. Kapitel: Der indirekte Tausch", [356, CHAPTER]],
["I. Tauschmittel und Geld", [356, SECTION]],
["II. Bemerkungen über einige Irrwege der Geldtheorie", 356],
["III. Geldvorrat und Geldbedarf; Nachfrage nach Geld und Angebot an Geld", 360],
["Exkurs: Die methodologische Bedeutung der Menger’schen Lehre vom Ursprung des Geldes", [365, EXKURS]],
["IV. Die Gestaltung der Kaufkraft des Geldes", [368, SECTION]],
["V. Das Hume-Mill’sche Problem und die Triebkraft des Geldes", 375],
["VI. Veränderungen der Kaufkraft von der Geldseite her und von der Warenseite her", 379],
["VII. Kaufkraftänderungen und Geldrechnung", 383],
["VIII. Das Geld im Kreditverkehr", 385],
["IX. Der Einfluss erwarteter Kaufkraftänderungen auf die Gestaltung der Kaufkraft", 385],
["X. Der spezifische Geldwert und der Gelddienst", 389],
["XI. Die Geldsurrogate: Geldzertifikate und Umlaufsmittel", 392],
["XII. Die Grenzen der Umlaufsmittelausgabe", 394],
["Exkurs: Bemerkungen zur Diskussion über Bankfreiheit", [404, EXKURS]],
["XIII. Die Grösse der Kassenbestände der einzelnen Wirte", [406, SECTION]],
["XIV. Die Zahlungsbilanzen", 409],
["XV. Die Paritäten", 412],
["XVI. Die Zinsfussarbitrage und die Diskontpolitik der Notenbanken", 417],
["XVII. Sekundäre Tauschmittel", 419],
["XVIII. Die inflationistische Geschichtsauffassung", 423],
["XIX. Die Goldwährung", 428],
["5. Kapitel: Das Handeln im Ablauf der Zeit", [434, CHAPTER]],
["I. Die verschiedene Schätzung gleichlanger Zeitabschnitte", [434, SECTION]],
["Exkurs: Bemerkungen zu Böhm-Bawerks Lehre von der Höherwertung gegenwärtiger Güter", [439, EXKURS]],
["II. Der praxeologische Beweis für die Höhenwertung zeitlich näherer Befriedigung", [443, SECTION]],
["III. Die Kapitalgüter", 449],
["IV. Produktionszeit, Wartezeit, Vorsorgezeit", 452],
["Exkurs: Erstreckung der Vorsorgezeit über die erwartete Lebensdauer hinaus", [458, EXKURS]],
["V. Die Lenkbarkeit der Kapitalgüter", [459, SECTION]],
["VI. Das Kapital als Träger einer Einwirkung der Vergangenheit auf Produktion und Verbrauch", 463],
["VII. Kapitalersatz, Kapitalneubildung, Kapitalaufzehrung", 467],
["VIII. Geld und Kapital; Sparen und Investieren", 471],
["6. Kapitel: Der Zins", [474, CHAPTER]],
["I. Die Zinserscheinung", [474, SECTION]],
["II. Der Urzins", 476],
["III. Die Höhe des Zinses", 484],
["IV. Der Urzins in der ungleichmässigen Wirtschaft", 485],
["V. Die Zinsrechnung", 487],
["7. Kapitel: Geldzins, Kreditausweitung und Konjunkturwechsel", [488, CHAPTER]],
["I. Die Probleme der Geldzinslehre", [488, SECTION]],
["II. Die Risikokomponente im Bruttozins", 489],
["III. Die Preisprämie im Bruttozins", 492],
["IV. Der Darlehensmarkt", 496],
["V. Die Veränderungen des Geldstands und die Gestaltung des Urzinses", 498],
["VI. Der Marktzins unter dem Einfluss von Veränderungen des Geldstands im Fall der Inflation und der Kreditausweitung", 500],
["VII. Der Marktzins unter dem Einfluss von Veränderungen des Geldstands im Fall der Restriktion", 514],
["VIII. Die Zirkulationskredittheorie des Konjunkturwechsels", 518],
["IX. Die Marktwirtschaft im Wechsel der Konjunktur", 521],
["Exkurse: A. Die Rolle der unbeschäftigten Produktionsmittel im Anfangstadium des Aufschwungs", [527, EXKURS]],
["B. Bemerkungen über Versuche, den Konjunkturwechsel nicht monetär zu erklären", 529],
["8. Kapitel: Arbeit und Lohn", [532, CHAPTER]],
["I. Innenarbeit und Aussenarbeit", [532, SECTION]],
["II. Arbeitsfreude und Arbeitsqual", 534],
["III. Der Arbeitslohn", 540],
["IV. Die Arbeitslosigkeit", 546],
["V. Die Lohnbildung: die Ansprüche der Käufer von Arbeit", 548],
["VI. Die Lohnbildung: die Ansprüche der Verkäufer von Arbeit", 550],
["VII. Das Arbeitsleid und das Angebot an Arbeit", 556],
["VIII. Das Unternehmerrisiko des Arbeiters", 563],
["IX. Der Arbeitsmarkt", 565],
["Exkurs: Die Arbeit der Tiere und der Sklaven", [568, EXKURS]],
["9. Kapitel: Die aussermenschlichen ursprünglichen Produktionsfaktoren", [574, CHAPTER]],
["I. Bemerkungen zur Rententheorie", [574, SECTION]],
["II. Die Unzerstörbarkeit der Bodenkräfte", 577],
["III. Der Überfluss an Boden", 580],
["IV. Der Boden als Standort", 582],
["V. Die Bodenpreise", 583],
["Exkurs: Der Mythus vom Boden", [584, EXKURS]],
["10. Kapitel: Die Daten der Marktlage", [585, CHAPTER]],
["I. Das Gegebene und das Datum", [585, SECTION]],
["II. Die Macht als Datum", 588],
["III. Die Gewalt als Datum", 590],
["IV. Der leibhaftige Mensch als Datum", 592],
["V. Die Reaktionszeit. Wirkungen in the long run und in the short run", 597],
["VI. Die Grenzen des Sondereigentums und das Problem der external costs and external economies", 599],
["Exkurse: A. Über das Eigentum an Rezepten", [604, EXKURS]],
["B. Privilegien", 605],
["11. Kapitel: Einklang und Widerstreit der Interessen", [605, CHAPTER]],
["I. Die Quelle der Gewinne auf dem Markte", [605, SECTION]],
["II. Die Geburtenregelung", 608],
["III. Die Harmonie der «richtig verstandenen» Interessen", 614],
["IV. Das Sondereigentum", 621],
["V. Die Konflikte der modernen Welt", 624],
["FÜNFTER TEIL: DIE VERKEHRSLOSE ARBEITSTEILIGE WIRTSCHAFT", [628, PART]],
["1. Kapitel: Das Gedankenbild einer verkehrslosen arbeitsteiligen Wirtschaft", [628, CHAPTER]],
["I. Die Herkunft des planwirtschaftlichen Gedankens", [628, SECTION]],
["II. Das praxeologische Wesen der Gemeinwirtschaft", 632],
["2. Kapitel: Die Unmöglichkeit sozialistischer Wirtschaftsrechnung", [634, CHAPTER]],
["I. Die Lösungsversuche", [634, SECTION]],
["II. Die Aufgabe", 636],
["III. Der künstliche Markt", 638],
["IV. Die Gleichungen der mathematischen Katallaktik", 641],
["SECHSTER TEIL: DIE GEHEMMTE MARKTWIRTSCHAFT", [646, PART]],
["1. Kapitel: Markt und Obrigkeit", [646, CHAPTER]],
["I. Eine dritte Lösung", [646, SECTION]],
["II. Der Eingriff", 647],
["III. «Gerechtigkeit» als Richtmass des Handelns", 649],
["IV. Die Obrigkeit", 654],
["V. Die Obrigkeit und die Zielwahl", 654],
["2. Kapitel: Die steuerpolitischen Eingriffe", [657, CHAPTER]],
["I. Die neutrale Steuer", [657, SECTION]],
["II. Die totale Steuer", 659],
["III. Finanzpolitische und sozialpolitische Ziele der Besteuerung", 660],
["IV. Die drei Abarten der steuerpolitischen Eingriffe", 662],
["3. Kapitel: Die produktionspolitischen Eingriffe", [663, CHAPTER]],
["I. Das Wesen des produktionspolitischen Eingriffs", [663, SECTION]],
["II. Erfolg und Kosten des Eingriffs", 664],
["III. Der Eingriff als Privileg", 665],
["IV. Der produktionspolitische Eingriff als Aufwand", 666],
["4. Kapitel: Die preispolitischen Eingriffe", [668, CHAPTER]],
["I. Die Alternative: Macht oder ökonomisches Gesetz", [668, SECTION]],
["II. Die Reaktion des Marktes auf preispolitische Eingriffe", 672],
["Exkurs: Einige Worte über die Ursachen des Unterganges des antiken Kultur", [677, EXKURS]],
["5. Kapitel: Die währungs- und bankpolitischen Eingriffe", [679, CHAPTER]],
["I. Interventionistische Währungspolitik", [679, SECTION]],
["II. Die Schuldenabbürdung", 682],
["III. Die Abwertung", 685],
["IV. Die Kreditausweitung", 692],
["V. Devisenbewirtschaftung und Clearingverträge", 697],
["6. Kapitel: Konfiskation und Redistribution", [700, CHAPTER]],
["I. Die ausgleichende Gerechtigkeit in der Landwirtschaft", [700, SECTION]],
["II. Die Konfiskation durch Besteuerung", 703],
["III. Die Beschränkung des nicht aus Arbeit stammenden Ertrags", 704],
["7. Kapitel: Ständestaat und Syndikalismus", [705, CHAPTER]],
["I. Die neue ständische Idee", [705, SECTION]],
["II. Die politische Verfassung des Ständestaats", 708],
["III. Die Wirtschaftsverfassung des Korporativismus", 711],
["IV. Syndikalismus", 715],
["8. Kapitel: Die Krise des Interventionismus", [717, CHAPTER]],
["I. Die Beweiskraft der Tatsachen", [717, SECTION]],
["II. Arbeitslosigkeit, das Schicksalproblem der Zeit", 720],
["9. Kapitel: Kriegswirtschaft", [723, CHAPTER]],
["I. Der Krieg und die Marktwirtschaft", [723, SECTION]],
["II. Heereskrieg und totaler Krieg", 725],
["III. Die totale Mobilmachung", 727],
["IV. Kriegswirtschaftliche Autarkie", 730],
["V. Das Problem des letzten Krieges", 737],
["SCHLUSSWORT", [740, CHAPTER]],
["I. Die Wissenschaft und das Leben", [740, SECTION]],
["II. Die Wissenschaft und die Politik", 743],
["III. Die Wissenschaft und die Zukunft", 750]
# ["Sachregister", 752]
]
|
class AddForeignKeyToMoussaillon < ActiveRecord::Migration[5.1]
def change
add_reference :moussaillons, :gossip, foreign_key: true
end
end
|
class OrdersController < ApplicationController
before_action :authenticate_user!, except: [:notify]
def preload
bead = Bead.find(params[:bead_id])
today = Date.today
orders = bead.orders.where("start_date >= ? OR end_date >= ?", today, today)
render json: orders
end
def preview
# start_date = Date.parse(params[:start_date])
# end_date = Date.parse(params[:end_date])
# output = {
# conflict: is_conflict(start_date, end_date)
# }
# render json: output
end
def create
@order = current_user.orders.create(order_params)
if @order
# send request to PayPal
values = {
business: 'blankslatoya@gmail.com',
cmd: '_xclick',
upload: 1,
notify_url: 'http://beadiebeadwaisted.herokuapp.com//notify',
amount: @order.total,
item_name: @order.bead.listing_name,
item_number: @order.id,
quantity: '1',
return: 'http://beadiebeadwaisted.herokuapp.com/past_orders' #'http://########.ngrok.io/past_orders'
}
redirect_to "https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
else
redirect_to @order.bead, alert: "Oops, something went wrong..."
end
end
protect_from_forgery except: [:notify]
def notify
print 'hello'
params.permit!
status = params[:payment_status]
order = Order.find(params[:item_number])
if status == "Completed"
order.update_attributes status: true
else
order.destroy
end
render nothing: true
end
protect_from_forgery except: [:past_orders]
def past_orders
@trips = current_user.orders.where("status = ?", true)
end
def your_orders
@beads = current_user.beads
end
private
def is_conflict
@bead = Bead.find(params[:bead_id])
# check = bead.orders.where("? < start_date AND end_date < ?", start_date, end_date)
check.size > 0 ? true : false
end
def order_params
params.require(:order).permit(:price, :total, :bead_id)
end
end |
#! /usr/bin/env ruby
#
# Copyright © 2014 Andrew DeMaria (muff1nman) <ademaria@mines.edu>
#
# All Rights Reserved.
require 'pathname'
require 'uri'
require 'optparse'
GIT_ENDING = ".git"
def base_name name
uri = URI.parse(name)
base = File.basename(uri.path)
base = base[0..-(GIT_ENDING.length+1)] if base.end_with? GIT_ENDING
raise "Invalid name" if base.nil? or base.empty?
base
end
def process_submodules dir, callbacks={}
Dir.chdir dir do
top_dir = Pathname.new(Dir.pwd)
submodules = `git submodule foreach --quiet 'pwd'`.lines.map do |line|
Pathname.new(line).relative_path_from(top_dir).to_s.chomp
end
callbacks[:before].call submodules, dir unless callbacks[:before].nil?
submodules.each do |submodule|
callbacks[:during].call submodule unless callbacks[:during].nil?
process_submodules submodule, callbacks
end
callbacks[:after].call submodules, dir unless callbacks[:after].nil?
end
end
def print_pushd submodules, dir
puts "pushd #{dir}" unless submodules.empty?
end
def print_popd submodules, dir
puts "popd" unless submodules.empty?
end
def print_for_submodule submodule
#puts "Processing submodule [#{submodule}]"
puts "git submodule init #{submodule}"
previous_url = `git config submodule.#{submodule}.url`
#puts "previous url: #{previous_url}"
puts "git config submodule.#{submodule}.url \"$srcdir/#{base_name previous_url}\""
puts "git submodule update #{submodule}"
end
def print_url submodule
puts `git config submodule.#{submodule}.url`
end
USAGE = "Usage: ./path_to_script [--change-remotes | --list-remotes]"
options = {}
OptionParser.new do |opts|
opts.banner = USAGE
opts.on("-c", "--change-remotes", "Print the commands required for a makepkg to setup the urls correctly") do |_|
abort("Only choose one task please") unless options[:action].nil?
options[:callbacks] = {
before: method(:print_pushd),
after: method(:print_popd),
during: method(:print_for_submodule)
}
end
opts.on("-l", "--list-remotes", "Print a listing of remotes for a makepkg") do |_|
abort("Only choose one task please") unless options[:action].nil?
options[:callbacks] = {
during: method(:print_url)
}
end
end.parse!
abort(USAGE) unless options[:callbacks]
process_submodules Dir.pwd, options[:callbacks]
|
require 'rails_helper'
describe 'User visits purchase index page' do
context 'as an admin' do
it 'allows admin to see all purchases' do
admin = User.create!(username: 'Admin', password: 'pass', role: 1)
program = Program.create(name: 'Denver Fire Department')
vendor = Vendor.create(name: 'Benny Blancos', state: 'CO')
vendor2 = Vendor.create(name: 'Pizza Hut', state: 'CO')
vendor3 = Vendor.create(name: 'Dominos', state: 'CO')
purchase = Purchase.create(transaction_date: '4/16/2017',
payment_date: '4/18/2018',
description: 'Calzones',
amount: 50.1)
purchase2 = Purchase.create(transaction_date: '6/16/2017',
payment_date: '6/18/2018',
description: 'Pizza with cheese',
amount: 50.1)
purchase3 = Purchase.create(transaction_date: '12/16/2017',
payment_date: '12/18/2018',
description: 'Pepperoni pizza',
amount: 50.1)
ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase)
ProgramVendorPurchase.create!(program: program, vendor: vendor2, purchase: purchase2)
ProgramVendorPurchase.create!(program: program, vendor: vendor3, purchase: purchase3)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
visit admin_purchases_path
expect(page).to have_content(purchase.vendors.first.name)
expect(page).to have_content(purchase2.vendors.first.name)
expect(page).to have_content(purchase3.vendors.first.name)
end
end
context 'as a default user' do
it 'does not allow default user to see admin purchases index' do
user = User.create(username: 'Megan', password: 'OliolioO')
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
visit admin_purchases_path
expect(page).to_not have_content('All transactions')
expect(page).to have_content('The page you were looking for doesn\'t exist')
end
end
end
|
require 'spec_helper'
require 'redis_cache'
require 'redis'
describe RedisCache do
let!(:redis){ Redis.new }
let!(:redic){ Redic.new }
before(:each){ described_class.stub(:redis){ redic } }
after(:all){ described_class.disable! }
let!(:var_name){ described_class.var_name 'SomeClass', 123 }
let!(:redis_key){ described_class.redis_key(var_name) }
it 'should be disabled' do
described_class.disable!
described_class.should_not be_enabled
end
it 'should be enabled' do
described_class.disable!
described_class.enable!
described_class.should be_enabled
end
describe '.redis_key' do
it 'should return string cached_%s filled with var_name' do
described_class.redis_key(123).should == "cached_123"
end
end
describe '.cache' do
before(:each){ described_class.enable! }
it 'should read YAML from redis' do
redis.set(redis_key, 123.to_yaml)
described_class.cache(var_name){ nil }.should == 123
end
context 'when cache is empty' do
before(:each){ redis.del(redis_key) }
it 'should execute block' do
expect{ described_class.cache(var_name){ raise 'Executed!'} }.to raise_error(RuntimeError, 'Executed!')
end
it 'should raise argument error when block returns nil' do
expect{ described_class.cache(var_name){ nil } }.to raise_error(ArgumentError)
end
it 'should write to redis YAML' do
described_class.cache(var_name){ 0 }
redis.get(redis_key).should == 0.to_yaml
end
it 'should keep key during during seconds which are set with second argument' do
described_class.cache(var_name, 0){ 'some value' }
sleep 0.5
described_class.read(var_name).should be_nil
end
end
context 'when cache disabled' do
before(:each){ described_class.disable! }
it 'should execute block and nothing more' do
redis.should_not_receive(:get)
redis.should_not_receive(:write)
described_class.cache('some_str'){ 123 }.should == 123
end
end
end
describe '.clear' do
it 'should delete redis key' do
described_class.enable!
described_class.cache(var_name){ {:some => 'hash' } }
redis.exists(redis_key).should be_true
described_class.clear(var_name)
redis.exists(redis_key).should be_false
end
end
describe '.redis=' do
# it 'should raise error' do
# expect{ described_class.redis = {:host => 'localhost'} }.to raise_error(ArgumentError, 'An instance of Redis expected!')
# end
it 'should accept Redis instance object' do
redis = Redis.new
described_class.redis = redis
end
end
describe '.read_cache' do
it 'should read YAML from redis' do
redis.set(redis_key, 252.to_yaml)
described_class.read_cache(var_name).should == 252
end
it 'should return false if cache disabled' do
described_class.disable!
redis.set(redis_key, 252.to_yaml)
described_class.read_cache(var_name).should be_false
described_class.enable!
end
end
describe '.read_keys' do
before(:each) do
described_class.cache('key_1'){ 1 }
described_class.cache('key_1_ext'){ 'key1ext' }
described_class.cache('key_2'){ 2 }
described_class.cache('key_2_ext'){ 'key2ext' }
end
it 'should read keys by given template' do
described_class.read_keys('key_*_ext').should == { 'cached_key_1_ext' => 'key1ext', 'cached_key_2_ext' => 'key2ext' }
end
it 'should read keys by given templates' do
described_class.cache('other'){ 'value' }
described_class.read_keys(['key_?', 'ot?er']).should == { 'cached_key_1' => 1, 'cached_key_2' => 2, 'cached_other' => 'value' }
end
end
describe '.flush_all' do
it 'should remove cached data' do
described_class.cache('var_1'){ 1 }
described_class.cache('var_n'){ 'n' }
described_class.flush_all
described_class.read_cache('var_1').should be_nil
described_class.read_cache('var_n').should be_nil
end
end
end
|
class CreateWorkerFamiliars < ActiveRecord::Migration
def change
create_table :worker_familiars do |t|
t.string :paternal_surname
t.string :maternal_surname
t.string :names
t.string :relationship
t.date :dateofbirth
t.string :dni
t.timestamps
end
end
end
|
Rails.application.routes.draw do
devise_for :users
root 'home#index'
get '/about', to: 'home#show'
get '/songs', to: 'home#index'
get '/songs/:id', to: 'home#index'
namespace :api do
namespace :v1 do
resources :songs, only: [:index, :show, :create, :update, :destroy] do
resources :blocks, only: [:index]
end
resources :blocks, only: [:create, :update, :destroy]
end
end
end
|
require_relative '../../lib/models/assembly.rb'
RSpec.describe Assembly do
describe 'instance methods' do
let(:assembly) { Assembly.new }
it 'should respond to id' do
expect(assembly).to respond_to :id
end
# When the class itself is in the `describe` method, RSpec's one-liner
# syntax can be used. See:
# https://relishapp.com/rspec/rspec-core/v/3-9/docs/subject/one-liner-syntax
it { is_expected.to respond_to :id }
it 'should respond to materials' do
expect(assembly).to respond_to :materials
end
it 'should respond to title' do
expect(assembly).to respond_to :title
end
it 'should respond to difficulty' do
expect(assembly).to respond_to :difficulty
end
end
describe 'difficulty' do
let(:assembly) { Assembly.new }
it 'should be able to be assigned' do
assembly.difficulty = 666
expect(assembly.difficulty).to eq 666
end
it 'should be an integer' do
assembly.difficulty = '555'
expect(assembly.difficulty).to eq 555
assembly.difficulty = 'ABC'
expect(assembly.difficulty).to eq 0
end
end
describe 'valid?' do
it 'is always valid' do
expect(Assembly.new).to be_valid
end
end
describe 'save' do
it 'should be inserted into the ASSEMBLIES array' do
assembly = Assembly.new
expect { assembly.save! }.to change(Assembly::ASSEMBLIES, :size).by(1)
end
it 'should raise an error for invalid assemblies' do
assembly = Assembly.new
expect(assembly).to receive(:valid?).and_return(false)
expect { assembly.save! }.to raise_error Assembly::RecordNotSaved
end
end
describe 'delete' do
it 'should have set id to nil' do
assembly = Assembly.new
assembly.save!
assembly.delete
expect(assembly.id).to be_nil
end
it 'should ignore unsaved assemblies' do
assembly = Assembly.new
expect(assembly.delete).to be_nil
end
end
describe '::find' do
it 'should find the assembly' do
expected_assembly = Assembly.new
expected_assembly.save!
assembly = Assembly.find expected_assembly.id
expect(assembly).to be expected_assembly
end
it 'should raise an error if assembly not found' do
expect{ Assembly.find(-1) }.to raise_error Assembly::RecordNotFound
end
end
end |
ActiveAdmin.register AccountProgram do
actions :all, except: [:update, :destroy, :edit, :create, :new]
index do
column :representative do |i|
i.representative.abbreviated_name
end
column :account
column 'Policy Number', :account do |i|
i.account.policy_number_entered
end
column :program_type
column :quote_tier
column :group_code
column :fees_amount
column :paid_amount
column :effective_start_date
column :effective_end_date
column :created_at
actions
end
filter :representative, as: :select, collection: Representative.options_for_select
filter :program_type, as: :select, collection: proc { AccountProgram.program_types.keys }
filter :account_policy_number_entered_eq, label: 'Policy Number'
filter :quoted_tier
filter :group_code
filter :fees_amount, as: :numeric
filter :paid_amount, as: :numeric
filter :effective_start_date, as: :date_range
filter :effective_end_date, as: :date_range
filter :created_at, as: :date_range
end
|
class BucketPolicy
attr_reader :user, :bucket
def initialize(user, bucket)
@user = user
@bucket = bucket
end
def new?
@user.is_local_creator?(Bucket) or
@user.is_global_creator?
end
def create?
new?
end
def edit?
@user.is_local_editor?(@bucket) or
@user.is_global_editor?
end
def update?
edit?
end
def delete?
@user.is_local_destroyer(@bucket) or
@user.is_global_destroyer?
end
def show?
@user.is_local_viewer?(@bucket) or
@user.is_global_viewer?
end
end
|
# == Schema Information
#
# Table name: question_attempts
#
# id :integer not null, primary key
# quiz_attempt_id :integer
# question_id :integer
# data :json
# created_at :datetime not null
# updated_at :datetime not null
# type :string
# score :decimal(, )
#
# Indexes
#
# index_question_attempts_on_question_id (question_id)
# index_question_attempts_on_quiz_attempt_id (quiz_attempt_id)
#
require 'rails_helper'
RSpec.describe Quizer::SingleAnswerQuestionAttempt, type: :model do
context 'associations' do
it { should belong_to(:quiz_attempt) }
it { should belong_to(:question) }
end
it "has a valid factory" do
question_attempt = build(:single_answer_question_attempt)
expect(question_attempt).to be_valid
end
describe "validations" do
it "validates data schema" do
question_attempt = build(:single_answer_question_attempt)
expect(question_attempt).to receive(:validate_data_schema)
question_attempt.save
end
end
it "calculates and assigns score before save" do
question_attempt = build(:single_answer_question_attempt)
expect(question_attempt).to receive(:calculate_score)
question_attempt.save
end
it "assigns a score before_save" do
question_attempt = build(:single_answer_question_attempt)
question_attempt.save
expect(question_attempt.reload.score).to_not be_nil
end
describe ".score" do
it "is 1 if the answer is correct" do
question_attempt = build(:single_answer_question_attempt)
question_attempt.answer = SHA1.encode(question_attempt.question.answer)
question_attempt.save
expect(question_attempt.score).to eq(1)
end
it "is 0 if the answer is incorrect" do
question_attempt = build(:single_answer_question_attempt)
question_attempt.answer = SHA1.encode(question_attempt.question.wrong_answers.first)
question_attempt.save
expect(question_attempt.score).to eq(0)
end
end
end
|
# == Schema Information
#
# Table name: comments
#
# id :integer not null, primary key
# commentable_id :integer
# commentable_type :string
# text :text
# response_to_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_comments_on_commentable_type_and_commentable_id (commentable_type,commentable_id)
# index_comments_on_user_id (user_id)
#
require 'rails_helper'
RSpec.describe CommentsController, type: :controller do
render_views
shared_examples "comment editor" do
before { get :edit, params: { id: comment.id }, xhr: true }
it { expect(response).to be_successful }
it { expect(response).to render_template :edit }
end
shared_examples "comment updater" do
it "updates the comment if the body is not empty" do
text = "otro texto"
patch :update, params: { id: comment.id, text: text }, xhr: true
expect(response).to be_successful
comment.reload
expect(comment.text).to eq(text)
end
it "doesn't update the comment if the body is empty" do
original_text = comment.text
patch :update, params: { id: comment.id, text: "" }, xhr: true
expect(response).to be_successful
comment.reload
expect(comment.text).to eq(original_text)
end
end
shared_examples "comment deleter" do
it "deletes the comment" do
expect {
delete :destroy, params: { id: comment.id }, xhr: true
}.to change(Comment, :count).by(-1)
end
end
let!(:user) { create(:user) }
let!(:other_user) { create(:user) }
let!(:admin ) { create(:admin_user) }
let!(:subject) { create(:subject) }
let!(:challenge) { create(:challenge, subject: subject) }
let!(:solution) { create(:solution, user: user, challenge: challenge, status: :completed, completed_at: 1.week.ago) }
let!(:comment) { create(:comment, user: user, commentable: challenge) }
describe "POST #create" do
context "when not signed in" do
it "redirects to login" do
post :create, params: { commentable_resource: "challenges", id: challenge.id, text: "hola mundo" }, xhr: true
expect(response).to redirect_to :login
end
end
context "when signed in" do
before { controller.sign_in(user) }
it "creates the comment if body is not empty" do
expect {
post :create, params: { commentable_resource: "challenges", id: challenge.id, text: "hola mundo" }, xhr: true
}.to change(Comment, :count).by(1)
end
it "doesn't create the comment if body is empty" do
expect {
post :create, params: { commentable_resource: "challenges", id: challenge.id, text: "" }, xhr: true
}.to_not change(Comment, :count)
end
end
end
describe "GET #edit" do
context "when not signed in" do
it "redirects to login" do
get :edit, params: { id: comment.id }
expect(response).to redirect_to :login
end
end
context "when user is admin" do
before { controller.sign_in(admin) }
it_behaves_like "comment editor"
end
context "when user is the owner of the comment" do
before { controller.sign_in(user) }
it_behaves_like "comment editor"
end
context "when user is not the owner of the comment" do
it "raises a routing error" do
controller.sign_in(other_user)
expect { get :edit, params: { id: comment.id }, xhr: true }.to raise_error(ActionController::RoutingError)
end
end
end
describe "PATCH #update" do
context "when not signed in" do
it "redirects to login" do
patch :update, params: { id: comment.id, text: "hola mundo" }, xhr: true
expect(response).to redirect_to :login
end
end
context "when user is admin" do
before { controller.sign_in(admin) }
it_behaves_like "comment updater"
end
context "when user is the owner of the comment" do
before { controller.sign_in(user) }
it_behaves_like "comment updater"
end
context "when user is not the owner of the comment" do
before { controller.sign_in(other_user) }
it "doesn't update the comment and raises a routing error" do
original_text = comment.text
expect {
patch :update, params: { id: comment.id, text: "nuevo texto" }, xhr: true
}.to raise_error(ActionController::RoutingError)
comment.reload
expect(comment.text).to eq(original_text)
end
end
end
describe "DELETE #destroy" do
context "when not signed in" do
it "redirects to login" do
delete :destroy, params: { id: comment.id }
expect(response).to redirect_to :login
end
end
context "when user is admin" do
before { controller.sign_in(admin) }
it_behaves_like "comment deleter"
end
context "when user is the owner of the comment" do
before { controller.sign_in(admin) }
it_behaves_like "comment deleter"
end
context "when user is not the owner of the comment" do
before { controller.sign_in(other_user) }
it "doesn't delete the comment and raises a routing error" do
original_text = comment.text
expect {
delete :destroy, params: { id: comment.id }, xhr: true
}.to raise_error(ActionController::RoutingError)
comment.reload
expect(comment.text).to eq(original_text)
end
end
end
describe "GET #response_to" do
end
end
|
class AddCrawledInfoToBlogs < ActiveRecord::Migration
def change
add_column :blogs, :crawl_started_at, :timestamp
add_column :blogs, :crawl_finished_at, :timestamp
add_column :blogs, :crawled_pages, :integer, :default => 0
end
end
|
require 'ProcessMemory'
require 'ProcessMemory/pe/header'
require 'ProcessMemory/pe/sections'
module PE
# メモリ上のPEフォーマットを扱う
class PEModule
# コンストラクタ
# @param mem [ProcessMemoryEx] 入力元
# @param base [Integer] base address
def initialize(mem, base = nil)
@mem = mem
@base_addr = base || mem.base_addr
@base_name = mem.modules[@base_addr]
# ヘッダ解析
@nt_header = @base_addr + ptr_i32(@base_addr + 0x3C)
@file_header = ptr_struct @nt_header + 4, PEFormat::FileHeader, PEFormat::SizeOfFileHeader
optiheader = @nt_header + 4 + PEFormat::SizeOfFileHeader
@optional_header = analyze_optiheader optiheader
@data_directories = analyze_datadirs optiheader + PEFormat::SizeOfOptionalHeader
@size = @optional_header.SizeOfImage
# セクション解析
sec_offset = optiheader + @file_header.SizeOfOptionalHeader
@sections = PE::ModuleSections.new @mem, @base_addr, sec_offset,
@file_header.NumberOfSections
end
attr_reader :base_name, :base_addr, :size
def address_of(addr)
@sections.find_section addr
end
# Get Int32 Value from addr
# @param addr [Integer] target address
# @return [Integer] read Value
def ptr_i32(addr)
@mem.ptr_fmt(addr, 4, 'V')
end
# 構造体を読み込む
# @param addr [Integer] 読み取りアドレス
# @param struct [Class] 構造体クラス
# @return [Fiddle::CStruct] 読み取った構造体
def ptr_struct(addr, struct, size = nil)
struct.new Fiddle::Pointer[@mem.ptr_buf(addr, size || struct.size)]
end
private
def analyze_optiheader(opti)
case @mem.ptr_fmt(opti, 2, 'v')
when 0x010B then ptr_struct(opti, PEFormat::OptionalHeaderx86, PEFormat::SizeOfOptionalHeader)
when 0x020B then ptr_struct(opti, PEFormat::OptionalHeaderx64, PEFormat::SizeOfOptionalHeader)
else
raise "err: unknown optinalmagic (0x#{magic.to_s 16})"
end
end
# @return [Hash] Analyzed DataDirectories
def analyze_datadirs(offset)
keys = %i[Export Import Resource Exception
Certificate BaseRelocation DebugInfo Architecture
GPtr TLS LoadCfg BoundImport
IAT DelayImport CLRHeader _Reserve]
@mem.ptr_fmt(offset, 8 * 16, 'V*').each_slice(2)
.with_index.with_object({}) do |(data, ix), memo|
memo[keys[ix]] = data
end
end
end # End Of class PELib
end
|
# input: array of string
# output: array of string without vowels
# capital letters are also included, case insensitive
# map method to transform array and delete any vowels
def remove_vowels(array)
array.map do |elements|
elements.delete('aeiouAEIOU')
end
end
|
# calculator
require 'yaml'
MESSAGES = YAML.load_file('calculator_messages.yml')
puts MESSAGES.inspect
def prompt(message)
puts "=> #{message}"
end
result = nil
number1 = nil
number2 = nil
name = nil
operation = nil
def integer?(input)
input.to_i.to_s == input
end
def float?(input)
Float(input) rescue false
end
def interpolated_message(message_name, value)
MESSAGES['es'][message_name].gsub("{var}", value)
end
def number2(operation)
word = case operation
when '1'
'Adding'
when '2'
'Substracting'
when '3'
'Multiplying'
when '4'
'Dividing'
end
word
end
def valid_number?(number)
number.nonzero?
end
loop do
prompt(MESSAGES['es']['welcome'])
name = gets.chomp.to_s
if name.empty?
prompt 'Make sure you use a valid name.'
else
break
end
end
loop do # mail loop
loop do
prompt(MESSAGES['es']['number_1'])
number1 = gets.chomp.to_i
if valid_number?(number1)
break
else
prompt(MESSAGES['es']['not_valid_number'])
end
end
loop do
prompt(MESSAGES['es']['number_2'])
number2 = gets.chomp.to_i
if valid_number?(number2)
break
else
prompt(MESSAGES['es']['not_valid_number'])
end
end
loop do
prompt(MESSAGES['es']['select_operation'])
operation = gets.chomp.to_s
if %w(1 2 3 4).include?(operation)
break
else
prompt(MESSAGES['es']['reminder'])
end
end
#prompt "#{number2(operation)} two numbers."
prompt(interpolated_message("operation", number2(operation)))
result = case operation
when '1'
number1 + number2
when '2'
number1 - number2
when '3'
number1 * number2
when '4'
number1 / number2
end
prompt(interpolated_message("result", result.to_s))
prompt(MESSAGES['es']['continue'])
awnser = gets.chomp.to_s
break unless awnser.downcase.start_with?('y') || awnser.downcase.start_with?('s')
end
prompt(interpolated_message("thanks", name))
|
class Image < ActiveRecord::Base
before_validation :fetch_flickr_details
def self.from_decade(decade_image)
i = Image.new(decade_image)
i.full_path_url = i.date.strftime("http://cdn.m.ac.nz/decade/images/%Y%m%d.jpg")
i.thumbnail_url = i.date.strftime("http://cdn.m.ac.nz/decade/images/small/%Y%m%d.jpg")
i.save
end
def fetch_flickr_details
if photo_id?
update_flickr_info(photo_id)
end
end
def permalink (full = false)
r = self.date.strftime("/%Y/%m/%d/")
r = DC_CONFIG[:BASE].gsub(/\/$/, "") + r if full
r
end
def prev
self.class.where('date < ?', self.date).order('date DESC').first
end
def next
self.class.where('date > ?', self.date).order('date ASC').first
end
private
class FlickrAPI
include HTTParty
base_uri 'www.flickr.com'
format :json
def self.photoInfo(photo_id, options = {})
options.merge! :photo_id => photo_id, :method => 'flickr.photos.getInfo', :format => 'json', :api_key => ENV['FLICKR_KEY'], :nojsoncallback => 1
res = get '/services/rest/', :query => options
res['stat'] == "ok" && res['photo']
end
end
def gen_flickr_url(photo, size)
"http://farm#{ photo['farm'] }.static.flickr.com/#{ photo['server']}/#{ photo['id'] }_#{ photo['secret'] }#{ size && ("_" + size) }.jpg"
end
def update_flickr_info(photo_id)
f = FlickrAPI.photoInfo(photo_id)
self.flickr_url = f['urls']['url'][0]['_content']
self.full_path_url = gen_flickr_url(f, 'b')
self.thumbnail_url = gen_flickr_url(f, 's')
self.caption = f['title']['_content'] if self.caption.blank?
self.description = f['description'] if self.caption.blank?
logger.info "FFS" + self.to_yaml
end
end
|
When /^I agree with the terms of use$/ do
check "user_terms"
end
When /^I click "(.*?)"$/ do |link|
click_on link
end
When /^I click "(.*?)" button$/ do |button|
click_button button
end
Then /^I should sign up successfully$/ do
page.should have_selector("li#sign-out-btn")
end
Then /^I should not sign up successfully$/ do
page.should have_selector("li#sign-in-btn")
end
Then /^I (should|should not) see message "(.*?)"$/ do |should_or_not, message|
page.send(should_or_not.gsub(" ", '_'), have_content(message))
end
Given /^I login$/ do
@user = FactoryGirl.create(:user, :password => 'secret')
visit('/users/sign_in')
fill_in "Email", :with => @user.email
fill_in "Password", :with => 'secret'
click_button 'Sign in'
end
When /^I login as "(.*?)"$/ do |role|
@user = FactoryGirl.create(:user, password: 'secret', role: role)
visit('/users/sign_in')
fill_in "Email", :with => @user.email
fill_in "Password", :with => 'secret'
click_button 'Sign in'
end
Given /^I login with email "(.*?)" and password "(.*?)"$/ do |email, password|
visit('/users/sign_in')
fill_in "Email", :with => email
fill_in "Password", :with => password
click_button 'Sign in'
end
Given /^I logout$/ do
page.find("#sign-out-btn a").click
end
Then /^I should see refinery page content$/ do
page.should have_content("Switch to your website")
page.should have_content("Quick Tasks")
end
Then /^I should be on home page$/ do
current_path.should == '/'
end
When /^I input (.*?) field with "(.*?)"$/ do |field, value|
fill_in "#{field.camelize}", :with => value
end
Then /^I should receive an email sent to "(.*?)" with subject "(.*?)"$/ do |email_address, email_subject|
ActionMailer::Base.deliveries.select{|email| email.to.include?(email_address) && email.subject == email_subject}.should_not be_blank
end
Then /^I follow link "(.*?)" in the email "(.*?)" sent to "(.*?)"$/ do |link_title, email_subject, email_address|
email = ActionMailer::Base.deliveries.select{|email| email.to.include?(email_address) && email.subject == email_subject}.last
email_body = "<root>#{email.body}</root>"
REXML::Document.new(email_body).get_elements("//a").each do |link|
if link.text == link_title
visit link.attribute("href").value
break
end
end
end
Given /^I signed up with email "(.*?)" and password "(.*?)"$/ do |email, password|
FactoryGirl.create(:user, email: email, password: password)
end
Then /^I should sign in successfully$/ do
within("#credential-container") do
page.should have_content("Hi,")
end
end
Then /^I should sign in successfully with email "(.*?)"$/ do |email|
within("#credential-container") do
page.should have_content("Hi, #{email}")
end
end
Given /^I input (.*?) field with "(.*?)" in "(.*?)" form$/ do |field, value, container|
within("##{container.downcase.parameterize}") do
fill_in "#{field.camelize}", :with => value
end
end
Given /^I have not confirmed the email "(.*?)"$/ do |email|
if user = User.find_by_email(email)
user.update_attribute(:confirmed_at, nil)
end
end
Given /^I have the following users with role$/ do |user_table|
user_table.hashes.each do |hash|
role = hash.delete('role')
user = FactoryGirl.create(:user, hash)
user.add_role(role)
end
end
When /^I (should|should not) see the following users$/ do |should_or_not, user_table|
user_table.hashes.each do |hash|
within("#body-container table#users") do
hash.each do |key, value|
page.send(should_or_not.gsub(" ", '_'), have_content(value))
end
end
end
end
Then /^I should have role "(.*?)"$/ do |role|
current_user_email = page.find("#credential-container #user-box a").text.split("Hi,").last.strip
current_user = User.where(email: current_user_email).first
current_user && current_user.has_role?(role)
end
When /^I select value "(.*?)" from "(.*?)"$/ do |value, select_box|
select(value, :from => select_box)
end
Then /^I (should|should not) see "(.*?)"$/ do |should_or_not, user|
page.send(should_or_not.gsub(" ", '_'), have_content(user))
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'Retryable writes errors tests' do
let(:options) { {} }
let(:client) do
authorized_client.with(options.merge(retry_writes: true))
end
let(:collection) do
client['retryable-writes-error-spec']
end
context 'when the storage engine does not support retryable writes but the server does' do
require_mmapv1
min_server_fcv '3.6'
require_topology :replica_set, :sharded
before do
collection.delete_many
end
context 'when a retryable write is attempted' do
it 'raises an actionable error message' do
expect {
collection.insert_one(a:1)
}.to raise_error(Mongo::Error::OperationFailure, /This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string or use the retry_writes: false Ruby client option/)
expect(collection.find.count).to eq(0)
end
end
end
context "when encountering a NoWritesPerformed error after an error with a RetryableWriteError label" do
require_topology :replica_set
require_retry_writes
min_server_version '4.4'
let(:failpoint1) do
{
configureFailPoint: "failCommand",
mode: { times: 1 },
data: {
writeConcernError: {
code: 91,
errorLabels: ["RetryableWriteError"],
},
failCommands: ["insert"],
}
}
end
let(:failpoint2) do
{
configureFailPoint: "failCommand",
mode: { times: 1 },
data: {
errorCode: 10107,
errorLabels: ["RetryableWriteError", "NoWritesPerformed"],
failCommands: ["insert"],
},
}
end
let(:subscriber) { Mrss::EventSubscriber.new }
before do
authorized_client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
authorized_client.use(:admin).command(failpoint1)
expect(authorized_collection.write_worker).to receive(:retry_write).once.and_wrap_original do |m, *args, **kwargs, &block|
expect(args.first.code).to eq(91)
authorized_client.use(:admin).command(failpoint2)
m.call(*args, **kwargs, &block)
end
end
after do
authorized_client.use(:admin).command({
configureFailPoint: "failCommand",
mode: "off",
})
end
it "returns the original error" do
expect do
authorized_collection.insert_one(x: 1)
end.to raise_error(Mongo::Error::OperationFailure, /\[91\]/)
end
end
context "PoolClearedError retryability test" do
require_topology :single, :replica_set, :sharded
require_no_multi_mongos
require_fail_command
require_retry_writes
let(:options) { { max_pool_size: 1 } }
let(:failpoint) do
{
configureFailPoint: "failCommand",
mode: { times: 1 },
data: {
failCommands: [ "insert" ],
errorCode: 91,
blockConnection: true,
blockTimeMS: 1000,
errorLabels: ["RetryableWriteError"]
}
}
end
let(:subscriber) { Mrss::EventSubscriber.new }
let(:threads) do
threads = []
threads << Thread.new do
expect(collection.insert_one(x: 2)).to be_successful
end
threads << Thread.new do
expect(collection.insert_one(x: 2)).to be_successful
end
threads
end
let(:insert_events) do
subscriber.started_events.select { |e| e.command_name == "insert" }
end
let(:cmap_events) do
subscriber.published_events
end
let(:event_types) do
[
Mongo::Monitoring::Event::Cmap::ConnectionCheckedOut,
Mongo::Monitoring::Event::Cmap::ConnectionCheckOutFailed,
Mongo::Monitoring::Event::Cmap::PoolCleared,
]
end
let(:check_out_results) do
cmap_events.select do |e|
event_types.include?(e.class)
end
end
before do
authorized_client.use(:admin).command(failpoint)
client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
client.subscribe(Mongo::Monitoring::CONNECTION_POOL, subscriber)
end
it "retries on PoolClearedError" do
# After the first insert fails, the pool is paused and retry is triggered.
# Now, a race is started between the second insert acquiring a connection,
# and the first retrying the read. Now, retry reads cause the cluster to
# be rescanned and the pool to be unpaused, allowing the second checkout
# to succeed (when it should fail). Therefore we want the second insert's
# check out to win the race. This gives the check out a little head start.
allow_any_instance_of(Mongo::Server::ConnectionPool).to receive(:ready).and_wrap_original do |m, *args, &block|
::Utils.wait_for_condition(5) do
# check_out_results should contain:
# - insert1 connection check out successful
# - pool cleared
# - insert2 connection check out failed
# We wait here for the third event to happen before we ready the pool.
cmap_events.select do |e|
event_types.include?(e.class)
end.length >= 3
end
m.call(*args, &block)
end
threads.map(&:join)
expect(check_out_results[0]).to be_a(Mongo::Monitoring::Event::Cmap::ConnectionCheckedOut)
expect(check_out_results[1]).to be_a(Mongo::Monitoring::Event::Cmap::PoolCleared)
expect(check_out_results[2]).to be_a(Mongo::Monitoring::Event::Cmap::ConnectionCheckOutFailed)
expect(insert_events.length).to eq(3)
end
after do
authorized_client.use(:admin).command({
configureFailPoint: "failCommand",
mode: "off",
})
end
end
context 'Retries in a sharded cluster' do
require_topology :sharded
min_server_version '4.2'
require_no_auth
let(:subscriber) { Mrss::EventSubscriber.new }
let(:insert_started_events) do
subscriber.started_events.select { |e| e.command_name == "insert" }
end
let(:insert_failed_events) do
subscriber.failed_events.select { |e| e.command_name == "insert" }
end
let(:insert_succeeded_events) do
subscriber.succeeded_events.select { |e| e.command_name == "insert" }
end
context 'when another mongos is available' do
let(:first_mongos) do
Mongo::Client.new(
[SpecConfig.instance.addresses.first],
direct_connection: true,
database: 'admin'
)
end
let(:second_mongos) do
Mongo::Client.new(
[SpecConfig.instance.addresses.last],
direct_connection: false,
database: 'admin'
)
end
let(:client) do
new_local_client(
[
SpecConfig.instance.addresses.first,
SpecConfig.instance.addresses.last,
],
SpecConfig.instance.test_options.merge(retry_writes: true)
)
end
let(:expected_servers) do
[
SpecConfig.instance.addresses.first.to_s,
SpecConfig.instance.addresses.last.to_s
].sort
end
before do
skip 'This test requires at least two mongos' if SpecConfig.instance.addresses.length < 2
first_mongos.database.command(
configureFailPoint: 'failCommand',
mode: { times: 1 },
data: {
failCommands: %w(insert),
closeConnection: false,
errorCode: 6,
errorLabels: ['RetryableWriteError']
}
)
second_mongos.database.command(
configureFailPoint: 'failCommand',
mode: { times: 1 },
data: {
failCommands: %w(insert),
closeConnection: false,
errorCode: 6,
errorLabels: ['RetryableWriteError']
}
)
end
after do
[first_mongos, second_mongos].each do |admin_client|
admin_client.database.command(
configureFailPoint: 'failCommand',
mode: 'off'
)
admin_client.close
end
client.close
end
it 'retries on different mongos' do
client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
expect { collection.insert_one(x: 1) }.to raise_error(Mongo::Error::OperationFailure)
expect(insert_started_events.map { |e| e.address.to_s }.sort).to eq(expected_servers)
expect(insert_failed_events.map { |e| e.address.to_s }.sort).to eq(expected_servers)
end
end
context 'when no other mongos is available' do
let(:mongos) do
Mongo::Client.new(
[SpecConfig.instance.addresses.first],
direct_connection: true,
database: 'admin'
)
end
let(:client) do
new_local_client(
[
SpecConfig.instance.addresses.first
],
SpecConfig.instance.test_options.merge(retry_writes: true)
)
end
before do
mongos.database.command(
configureFailPoint: 'failCommand',
mode: { times: 1 },
data: {
failCommands: %w(insert),
closeConnection: false,
errorCode: 6,
errorLabels: ['RetryableWriteError']
}
)
end
after do
mongos.database.command(
configureFailPoint: 'failCommand',
mode: 'off'
)
mongos.close
client.close
end
it 'retries on the same mongos' do
client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
expect { collection.insert_one(x: 1) }.not_to raise_error
expect(insert_started_events.map { |e| e.address.to_s }.sort).to eq([
SpecConfig.instance.addresses.first.to_s,
SpecConfig.instance.addresses.first.to_s
])
expect(insert_failed_events.map { |e| e.address.to_s }.sort).to eq([
SpecConfig.instance.addresses.first.to_s
])
expect(insert_succeeded_events.map { |e| e.address.to_s }.sort).to eq([
SpecConfig.instance.addresses.first.to_s
])
end
end
end
end
|
# frozen_string_literal: true
# Controller for date ranges associated to slides
class DateRangesController < ApplicationController
before_action :set_date_range, only: %i[show edit update destroy]
before_action :authenticate_user!
before_action :authorize
# GET /date_ranges
# GET /date_ranges.json
def index
@date_ranges = DateRange.all
end
# GET /date_ranges/1
# GET /date_ranges/1.json
def show; end
# GET /date_ranges/new
def new
@date_range = DateRange.new
end
# GET /date_ranges/1/edit
def edit; end
# POST /date_ranges
# POST /date_ranges.json
def create
@date_range = DateRange.new(date_range_params)
respond_to do |format|
if @date_range.save
format.html { redirect_to @date_range, notice: 'Date range was successfully created.' }
format.json { render :show, status: :created, location: @date_range }
else
format.html { render :new }
format.json { render json: @date_range.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /date_ranges/1
# PATCH/PUT /date_ranges/1.json
def update
respond_to do |format|
if @date_range.update(date_range_params)
format.html { redirect_to @date_range, notice: 'Date range was successfully updated.' }
format.json { render :show, status: :ok, location: @date_range }
else
format.html { render :edit }
format.json { render json: @date_range.errors, status: :unprocessable_entity }
end
end
end
# DELETE /date_ranges/1
# DELETE /date_ranges/1.json
def destroy
@date_range.destroy
respond_to do |format|
format.html { redirect_to date_ranges_url, notice: 'Date range was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_date_range
@date_range = DateRange.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def date_range_params
params.require(:date_range).permit(:start_date, :end_date, :slide_id)
end
def authorize
unless current_user&.admin?
flash[:alert] = 'You do not have sufficient permissions to view this page'
redirect_to root_path
end
end
end
|
# encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'solidus_sendwithus'
s.version = '2.2.0'
s.summary = 'SendWithUs integration'
s.license = 'BSD-3'
s.required_ruby_version = '>= 1.9.3'
s.author = 'Stembolt Technologies, Nebulab'
s.email = 'info@nebulab.it'
s.homepage = 'https://github.com/nebulab/solidus_sendwithus'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_paths = ["lib"]
solidus_version = [">= 1.0", "< 3"]
s.add_dependency 'solidus_core', solidus_version
s.add_dependency 'send_with_us', '~> 1.9'
s.add_development_dependency 'rspec-rails', '~> 3.1'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'test-unit'
end
|
class Politician <Person
attr_accessor :name, :party
def initialize (name, party)
@name = name
@party = party
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
User.destroy_all
Skill.destroy_all
List.destroy_all
skills = []
skills << Skill.create!({ name: "Tocar piano", description: "Seco para tocar el piano", price: 2000 })
skills << Skill.create!({ name: "Tocar guitarra", description: "Guitarrista de tomo y lomo", price: 5000 })
skills << Skill.create!({ name: "Programación", description: "Aprenderas mucho en este mundo", price: 7000 })
users = []
users << User.create!({
name: "Son Goku",
username: "Kakaroto",
birthdate: "20/04/1991",
photo: "https://www.elpopular.pe/sites/default/files/styles/img_620x465/public/imagen/2017/08/05/Noticia-186692-dragon-ball-super.jpg",
biography: "Un tipo Profesional, con ganas de intercambiar información.",
email: "goku@gmail.com",
password: "12345678",
password_confirmation: "12345678"
})
users << User.create!({
name: "Vegeta",
username: "Principe Saiyayin",
birthdate: "30/08/1990",
photo: "http://mouse.latercera.com/wp-content/uploads/2018/01/vegeta-4.jpg",
biography: "Un tipo Profesional, con ganas de intercambiar información.",
email: "vegeta@gmail.com",
password: "12345678",
password_confirmation: "12345678"
})
users << User.create!({
name: "Son Gohan",
username: "Gohan",
birthdate: "28/10/2000",
photo: "http://mouse.latercera.com/wp-content/uploads/2018/01/Gohan-900x506.jpg",
biography: "Un tipo Profesional, con ganas de intercambiar información.",
email: "gohan@gmail.com",
password: "12345678",
password_confirmation: "12345678"
})
lists = []
lists << List.create!({ user_id: users[1].id, skill_id: skills[0].id })
lists << List.create!({ user_id: users[0].id, skill_id: skills[2].id })
lists << List.create!({ user_id: users[2].id, skill_id: skills[1].id })
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.