text stringlengths 10 2.61M |
|---|
module Api
module V2
class WorkspaceResource < BaseResource
model_name 'Team'
attributes :name, :slug
paginator :none
filter :is_tipline_installed, apply: ->(records, value, _options) {
self.has_bot_installed(records, value, BotUser.smooch_user)
}
filter :is_similarity_feature_enabled, apply: ->(records, value, _options) {
self.has_bot_installed(records, value, BotUser.alegre_user)
}
def self.records(options = {})
self.workspaces(options)
end
def self.has_bot_installed(records, value, bot = nil)
return records if bot.nil?
is_false = !value || value[0].to_s == 'false' || value[0].to_s == '0'
if is_false
records.joins("LEFT OUTER JOIN team_users tu2 ON tu2.team_id = teams.id AND tu2.user_id = #{bot.id}").where('tu2.team_id' => nil)
else
records.joins("INNER JOIN team_users tu2 ON tu2.team_id = teams.id AND tu2.user_id = #{bot.id}")
end
end
end
end
end
|
# ****************************************************************************
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
# ****************************************************************************
require '../../util/assert.rb'
# only one arg, and it is vararg
def test_1_vararg
def m(*args)
args
end
assert_return([]) { m }
assert_return([1]) { m 1 }
assert_return([2, 3]) { m 2, 3 }
assert_return([[4]]) { m [4] }
assert_return([5, [6]]) { m 5, [6] }
assert_return([[]]) { m(m) }
# expanding array as arg
assert_return([]) { m *[] }
assert_return([1]) { m *[1,] }
assert_return([1, 2, 3]) { m 1, *[2, 3,] }
end
# two args, the last one is vararg
def test_1_normal_1_vararg
def m(arg1, *arg2)
[arg1, arg2]
end
assert_raise(ArgumentError) { m }
assert_return([1, []]) { m 1 }
assert_return([2, [3]]) { m 2, 3 }
assert_return([4, [5, 6]]) { m 4, 5, 6 }
assert_return([7, [[8, 9]]]) { m 7, [8, 9] }
assert_return([[10], [11]]) { m [10], 11 }
# expanding array as arg
assert_raise(ArgumentError) { m *[] }
assert_return([1, []]) { m *[1,] }
assert_return([1, [2, 3]]) { m *[1, 2, 3] }
assert_return([1, [2, 3]]) { m 1, *[2, 3] }
assert_return([1, [2, 3]]) { m 1, 2, *[3] }
end
test_1_vararg
test_1_normal_1_vararg |
require 'poundpay'
require 'poundpay/elements'
require 'fixtures/payments'
require 'fixtures/developers'
include Poundpay
describe Developer do
include DeveloperFixture
before (:all) do
Poundpay.configure(
"DV0383d447360511e0bbac00264a09ff3c",
"c31155b9f944d7aed204bdb2a253fef13b4fdcc6ae1540200449cc4526b2381a")
end
after (:all) do
Poundpay.clear_config!
end
describe "#me" do
it "should return the developer's information" do
Developer.should_receive(:find).with(Developer.user).and_return(Developer.new developer_attributes)
@developer = Developer.me
end
end
describe "#callback_url=" do
before (:all) do
@developer = Developer.new :callback_url => nil
end
it "should not allow invalid urls to be assigned" do
invalid_url = "http://71.212.135.207:3000:payments" # There's a colon after the port number instead of a backslash
expect { @developer.callback_url = invalid_url }.to raise_error(URI::InvalidURIError, /format/)
end
it "should allow a developer to set their url" do
valid_url = "http://71.212.135.207:3000/payments"
@developer.callback_url = valid_url
@developer.callback_url.should == valid_url
@developer.callback_url = nil
@developer.callback_url.should == nil
end
end
describe "#save" do
it "should not allow saving with an invalid callback_url" do
Developer.should_not_receive(:create)
developer = Developer.new :callback_url => 'i am invalid'
expect { developer.save }.to raise_error(URI::InvalidURIError)
end
end
end
describe Payment do
include PaymentFixture
before (:all) do
Poundpay.configure(
"DV0383d447360511e0bbac00264a09ff3c",
"c31155b9f944d7aed204bdb2a253fef13b4fdcc6ae1540200449cc4526b2381a")
end
after (:all) do
Poundpay.clear_config!
end
describe "#escrow" do
it "should not be able to escrow a STAGED payment" do
@staged_payment = Payment.new staged_payment_attributes
expect {@staged_payment.escrow}.to raise_error(PaymentEscrowException)
end
it "should escrow an AUTHORIZED payment" do
@authorized_payment = Payment.new authorized_payment_attributes
@authorized_payment.should_receive(:save).and_return(Payment.new escrowed_payment_attributes)
@authorized_payment.escrow
@authorized_payment.status.should == 'ESCROWED'
end
end
describe "#release" do
it "should not be able to release a STAGED payment" do
@staged_payment = Payment.new staged_payment_attributes
expect {@staged_payment.release}.to raise_error(PaymentReleaseException)
end
it "should release an ESCROWED payment" do
@escrowed_payment = Payment.new escrowed_payment_attributes
@escrowed_payment.should_receive(:save).and_return(Payment.new released_payment_attributes)
@escrowed_payment.release
@escrowed_payment.status.should == 'RELEASED'
end
end
describe "#cancel" do
it "should not be able to cancel a STAGED payment" do
@staged_payment = Payment.new staged_payment_attributes
expect {@staged_payment.cancel}.to raise_error(PaymentCancelException)
end
it "should release an ESCROWED payment" do
@escrowed_payment = Payment.new escrowed_payment_attributes
@escrowed_payment.should_receive(:save).and_return(Payment.new canceled_payment_attributes)
@escrowed_payment.cancel
@escrowed_payment.status.should == 'CANCELED'
end
end
end |
require_relative '../lib/game.rb'
RSpec.describe Game do
let(:grid) {[[1, 2, 3], [4, 5, 6], [7, 8, 9]]}
let(:result) { Game.new(grid)}
describe "# Result" do
it "grid and with pieces" do
expect(result.grid).to eql(grid)
end
end
describe "winning positions" do
let(:horizontal_position) { [[1, 2, 3], %w[X X X], [7, 8, 9]] }
let(:vertical_position) {[['X', 2, 3], ['X', 5, 6], ['X', 8, 9]]}
let(:diagonal_position) { [['X', 2, 3], [4, 'X', 6], [7, 8, 'X']] }
let(:result1) { Game.new(horizontal_position) }
let(:result2) { Game.new(vertical_position) }
let(:result3) { Game.new(diagonal_position) }
it 'Returns true when there is a matching horizontally' do
expect(result1.win_game).to eql(true)
end
it 'Returns true when there is a matching vertically' do
expect(result2.win_game).to eql(true)
end
it 'Returns true when there is a matching diagonally' do
expect(result3.win_game).to eql(true)
end
it 'Returns false when there is no matching any position to win' do
expect(result.win_game).to eql(false)
end
end
end |
class CategoriesController < ApplicationController
# GET /categories
# GET /categories.json
def index
Rails.logger.puts params[:image_id].inspect
if (params[:image_id])
@categories = Image.find(params[:image_id]).categories
else
@categories = Category.all
end
# Serve the categories as a json with all their names
@categories.map! do |c| c.name end
respond_to do |format|
format.json { render json: @categories}
end
end
# GET /categories/1
# GET /categories/1.json
def show
@category = Category.where(:name => params[:id])[0]
@images = @category.images
respond_to do |format|
format.html # show.html.erb
end
end
# GET /categories/new
# GET /categories/new.json
def new
@category = Category.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @category }
end
end
# GET /categories/1/edit
def edit
@category = Category.find(params[:id])
end
# POST /categories
# POST /categories.json
def create
@category = Category.find_or_create_by_name params[:name]
@image = Image.find(params[:image_id])
if @category.save
@image.categories << @category
end
end
# PUT /categories/1
# PUT /categories/1.json
def update
@category = Category.find(params[:id])
respond_to do |format|
if @category.update_attributes(params[:category])
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
# Delete category from an image
@category = Category.where(:name => params[:name])
@image = Image.find(params[:image_id])
@image.categories -= @category
# If the category has no more images, delete ir
if @category.first.images.size == 0
@category.first.delete
end
redirect_to @image
end
end
|
class CreateEasyRakeTaskInfo < ActiveRecord::Migration
def self.up
create_table :easy_rake_task_infos, :force => true do |t|
t.column :easy_rake_task_id, :integer, {:null => false}
t.column :status, :integer, {:null => false}
t.column :started_at, :datetime, {:null => false}
t.column :finished_at, :datetime, {:null => true}
t.column :note, :text, {:null => true}
end
create_table :easy_rake_tasks, :force => true do |t|
t.column :type, :string, {:null => false, :limit => 2048}
t.column :active, :boolean, {:null => false, :default => true}
t.column :settings, :text, {:null => true}
t.column :period, :string, {:null => false, :limit => 255}
t.column :interval, :integer, {:null => false}
t.column :next_run_at, :datetime, {:null => false}
end
end
def self.down
drop_table :easy_rake_tasks
drop_table :easy_rake_task_infos
end
end |
module Alchemy
class Page < ActiveRecord::Base
DEFAULT_ATTRIBUTES_FOR_COPY = {
:do_not_autogenerate => true,
:do_not_sweep => true,
:visible => false,
:public => false,
:locked => false,
:locked_by => nil
}
SKIPPED_ATTRIBUTES_ON_COPY = %w(id updated_at created_at creator_id updater_id lft rgt depth urlname cached_tag_list)
attr_accessible(
:do_not_autogenerate,
:do_not_sweep,
:language_code,
:language,
:language_id,
:language_root,
:layoutpage,
:locked,
:locked_by,
:meta_description,
:meta_keywords,
:name,
:page_layout,
:parent_id,
:public,
:restricted,
:robot_index,
:robot_follow,
:sitemap,
:tag_list,
:title,
:urlname,
:visible
)
acts_as_taggable
acts_as_nested_set(:dependent => :destroy)
stampable(:stamper_class_name => 'Alchemy::User')
has_many :folded_pages
has_many :legacy_urls, :class_name => 'Alchemy::LegacyPageUrl'
belongs_to :language
validates_presence_of :language, :on => :create, :unless => :root
validates_presence_of :page_layout, :unless => :systempage?
validates_presence_of :parent_id, :if => proc { Page.count > 1 }
attr_accessor :do_not_sweep
attr_accessor :do_not_validate_language
before_save :set_language_code, :unless => :systempage?
before_save :set_restrictions_to_child_pages, :if => :restricted_changed?, :unless => :systempage?
before_save :inherit_restricted_status, :if => proc { parent && parent.restricted? }, :unless => :systempage?
after_update :create_legacy_url, :if => :urlname_changed?, :unless => :redirects_to_external?
scope :language_roots, where(:language_root => true)
scope :layoutpages, where(:layoutpage => true)
scope :all_locked, where(:locked => true)
scope :all_locked_by, lambda { |user| where(:locked => true, :locked_by => user.id) }
scope :not_locked, where(:locked => false)
scope :visible, where(:visible => true)
scope :published, where(:public => true)
scope :not_restricted, where(:restricted => false)
scope :restricted, where(:restricted => true)
scope :public_language_roots, lambda {
where(:language_root => true, :language_code => Language.all_codes_for_published, :public => true)
}
scope :all_last_edited_from, lambda { |user| where(:updater_id => user.id).order('updated_at DESC').limit(5) }
# Returns all pages that have the given language_id
scope :with_language, lambda { |language_id| where(:language_id => language_id) }
scope :contentpages, where(:layoutpage => [false, nil]).where(Page.arel_table[:parent_id].not_eq(nil))
# Returns all pages that are not locked and public.
# Used for flushing all page caches at once.
scope :flushables, not_locked.published.contentpages
scope :searchables, not_restricted.published.contentpages
# Scope for only the pages from Alchemy::Site.current
scope :from_current_site, lambda { where(:alchemy_languages => {site_id: Site.current || Site.default}).joins(:language) }
# TODO: add this as default_scope
#default_scope { from_current_site }
# Concerns
include Naming
include Cells
include Elements
# Class methods
#
class << self
alias_method :rootpage, :root
# @return the language root page for given language id.
# @param language_id [Fixnum]
#
def language_root_for(language_id)
self.language_roots.find_by_language_id(language_id)
end
# Creates a copy of source
#
# Also copies all elements included in source.
#
# === Note:
# It prevents the element auto generator from running.
#
# @param source [Alchemy::Page]
# @param differences [Hash]
#
# @return [Alchemy::Page]
#
def copy(source, differences = {})
source.attributes.stringify_keys!
differences.stringify_keys!
attributes = source.attributes.merge(differences)
attributes.merge!(DEFAULT_ATTRIBUTES_FOR_COPY)
new_name = differences['name'].present? ? differences['name'] : "#{source.name} (#{I18n.t('Copy')})"
attributes.merge!('name' => new_name)
page = self.new(attributes.except(*SKIPPED_ATTRIBUTES_ON_COPY))
page.tag_list = source.tag_list
if page.save!
copy_cells(source, page)
copy_elements(source, page)
page
end
end
def layout_root_for(language_id)
where({:parent_id => Page.root.id, :layoutpage => true, :language_id => language_id}).limit(1).first
end
def find_or_create_layout_root_for(language_id)
layoutroot = layout_root_for(language_id)
return layoutroot if layoutroot
language = Language.find(language_id)
layoutroot = Page.new({
:name => "Layoutroot for #{language.name}",
:layoutpage => true,
:language => language,
:do_not_autogenerate => true
})
if layoutroot.save(:validate => false)
layoutroot.move_to_child_of(Page.root)
return layoutroot
else
raise "Layout root for #{language.name} could not be created"
end
end
def all_from_clipboard(clipboard)
return [] if clipboard.blank?
self.find_all_by_id(clipboard.collect { |i| i[:id] })
end
def all_from_clipboard_for_select(clipboard, language_id, layoutpage = false)
return [] if clipboard.blank?
clipboard_pages = self.all_from_clipboard(clipboard)
allowed_page_layouts = Alchemy::PageLayout.selectable_layouts(language_id, layoutpage)
allowed_page_layout_names = allowed_page_layouts.collect { |p| p['name'] }
clipboard_pages.select { |cp| allowed_page_layout_names.include?(cp.page_layout) }
end
def link_target_options
options = [[I18n.t(:default, scope: 'link_target_options'), '']]
link_target_options = Config.get(:link_target_options)
link_target_options.each do |option|
options << [I18n.t(option, scope: 'link_target_options', default: option.to_s.humanize), option]
end
options
end
end
# Instance methods
#
# Finds the previous page on the same structure level. Otherwise it returns nil.
# Options:
# => :restricted => boolean (standard: nil) - next restricted page (true), skip restricted pages (false), ignore restriction (nil)
# => :public => boolean (standard: true) - next public page (true), skip public pages (false)
def previous(options = {})
next_or_previous(:previous, {
:restricted => nil,
:public => true
}.merge(options))
end
alias_method :previous_page, :previous
# Finds the next page on the same structure level. Otherwise it returns nil.
# Options:
# => :restricted => boolean (standard: nil) - next restricted page (true), skip restricted pages (false), ignore restriction (nil)
# => :public => boolean (standard: true) - next public page (true), skip public pages (false)
def next(options = {})
next_or_previous(:next, {
:restricted => nil,
:public => true
}.merge(options))
end
alias_method :next_page, :next
def lock(user)
self.locked = true
self.locked_by = user.id
self.save(:validate => false)
end
def unlock
self.locked = false
self.locked_by = nil
self.do_not_sweep = true
self.save
end
# Returns the name of the creator of this page.
def creator
@page_creator ||= User.find_by_id(creator_id)
return I18n.t('unknown') if @page_creator.nil?
@page_creator.name
end
# Returns the name of the last updater of this page.
def updater
@page_updater = User.find_by_id(updater_id)
return I18n.t('unknown') if @page_updater.nil?
@page_updater.name
end
# Returns the name of the user currently editing this page.
def current_editor
@current_editor = User.find_by_id(locked_by)
return I18n.t('unknown') if @current_editor.nil?
@current_editor.name
end
def locker
User.find_by_id(self.locked_by)
end
def fold(user_id, status)
folded_page = folded_pages.find_or_create_by_user_id(user_id)
folded_page.folded = status
folded_page.save
end
def folded?(user_id)
folded_page = folded_pages.find_by_user_id(user_id)
return false if folded_page.nil?
folded_page.folded
end
# Returns a Hash describing the status of the Page.
#
def status
{
visible: visible?,
public: public?,
locked: locked?,
restricted: restricted?
}
end
# Returns the translated status for given status type.
#
# @param [Symbol] status_type
#
def status_title(status_type)
I18n.t(self.status[status_type].to_s, scope: "page_states.#{status_type}")
end
def has_controller?
!PageLayout.get(self.page_layout).nil? && !PageLayout.get(self.page_layout)["controller"].blank?
end
def controller_and_action
if self.has_controller?
{
controller: self.layout_description["controller"].gsub(/(^\b)/, "/#{$1}"),
action: self.layout_description["action"]
}
end
end
# Returns the self#page_layout description from config/alchemy/page_layouts.yml file.
def layout_description
return {} if self.systempage?
description = PageLayout.get(self.page_layout)
if description.nil?
raise PageLayoutDefinitionError, "Description could not be found for page layout named #{self.page_layout}. Please check page_layouts.yml file."
else
description
end
end
alias_method :definition, :layout_description
# Returns translated name of the pages page_layout value.
# Page layout names are defined inside the config/alchemy/page_layouts.yml file.
# Translate the name in your config/locales language yml file.
def layout_display_name
I18n.t(self.page_layout, :scope => :page_layout_names)
end
def changed_publicity?
self.public_was != self.public
end
def set_restrictions_to_child_pages
descendants.each do |child|
child.update_attributes(:restricted => self.restricted?)
end
end
def inherit_restricted_status
self.restricted = parent.restricted?
end
def contains_feed?
definition["feed"]
end
# Returns true or false if the pages layout_description for config/alchemy/page_layouts.yml contains redirects_to_external: true
def redirects_to_external?
definition["redirects_to_external"]
end
# Returns the first published child
def first_public_child
children.published.first
end
# Gets the language_root page for page
def get_language_root
self_and_ancestors.where(:language_root => true).first
end
def copy_children_to(new_parent)
self.children.each do |child|
next if child == new_parent
new_child = Page.copy(child, {
:language_id => new_parent.language_id,
:language_code => new_parent.language_code
})
new_child.move_to_child_of(new_parent)
child.copy_children_to(new_child) unless child.children.blank?
end
end
def locker_name
return I18n.t('unknown') if self.locker.nil?
self.locker.name
end
def rootpage?
!self.new_record? && self.parent_id.blank?
end
def systempage?
return true if Page.root.nil?
rootpage? || (self.parent_id == Page.root.id && !self.language_root?)
end
# Overwrites the cache_key method.
def cache_key(request = nil)
"alchemy/pages/#{id}"
end
def taggable?
definition['taggable'] == true
end
# Publishes the page
#
# Sets public true and saves the object.
def publish!
self.public = true
self.save
end
private
def next_or_previous(direction = :next, options = {})
pages = self.class.scoped
if direction == :previous
step_direction = ["#{self.class.table_name}.lft < ?", self.lft]
order_direction = "lft DESC"
else
step_direction = ["#{self.class.table_name}.lft > ?", self.lft]
order_direction = "lft"
end
pages = pages.where(:public => options[:public])
pages = pages.where(:parent_id => self.parent_id)
pages = pages.where(step_direction)
if !options[:restricted].nil?
pages = pages.where(:restricted => options[:restricted])
end
pages.order(order_direction).limit(1).first
end
def set_language_code
return false if self.language.blank?
self.language_code = self.language.code
end
# Stores the old urlname in a LegacyPageUrl
def create_legacy_url
legacy_urls.find_or_create_by_urlname(:urlname => urlname_was)
end
end
end
|
#
# This file was ported to ruby from Composer php source code file.
#
# Original Source: Composer\Json\JsonFormatter.php
# Ref SHA: ce085826711a6354024203c6530ee0b56fea9c13
#
# (c) Nils Adermann <naderman@naderman.de>
# Jordi Boggiano <j.boggiano@seld.be>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
module Composer
module Json
# * Formats json strings used for php < 5.4 because the json_encode doesn't
# * supports the flags JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
# * in these versions
#
# PHP Authors:
# Konstantin Kudryashiv <ever.zet@gmail.com>
# Jordi Boggiano <j.boggiano@seld.be>
#
# Ruby Authors:
# Ioannis Kappas <ikappas@devworks.gr>
class JsonFormatter
class << self
# This code is based on the function found at:
# http://recursive-design.com/blog/2008/03/11/format-json-with-php/
#
# Originally licensed under MIT by Dave Perrett <mail@recursive-design.com>
#
# @param json string
# @param unescape_unicode bool Whether to unescape unicode
# @param unescape_slashes bool Whether to unescape slashes
# @return string
def format(json, unescape_unicode, unescape_slashes)
result = ''
pos = 0
str_len = json.length
indent_str = ' '
new_line = "\n"
out_of_quotes = true
buffer = ''
no_escape = true
for i in 0..(str_len - 1)
# grab the next character in the string
char = json[i]
# are we inside a quoted string?
if char === '"' && no_escape
out_of_quotes = !out_of_quotes
end
if !out_of_quotes
buffer << char
no_escape = '\\' === char ? !no_escape : true
next
elsif !buffer.empty?
if unescape_slashes
buffer.gsub!('\\/', '/')
end
if unescape_unicode
buffer.gsub!(/\\u([\da-fA-F]{4})/) {|m| [$1].pack('H*').unpack('n*').pack('U*')}
end
result << buffer + char
buffer = ''
next
end
if char === ':'
# Add a space after the : character
char << ' '
elsif char === '}' || char === ']'
pos -= 1
prev_char = json[i - 1]
if prev_char != '{' && prev_char != '['
# If this character is the end of an element,
# output a new line and indent the next line
result << new_line
for j in 0..(pos - 1)
result << indent_str
end
else
# Collapse empty {} and []
result.rstrip!
end
end
result << char
# If the last character was the beginning of an element,
# output a new line and indent the next line
if char === ',' || char === '{' || char === '['
result << new_line
pos += 1 if char === '{' || char === '['
for j in 0..(pos - 1)
result << indent_str
end
end
end
result
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Manufacturer, type: :model do
subject { Manufacturer.new }
include_examples 'required attributes', %i[name]
include_examples 'optional attributes', %i[short]
it 'can be created' do
manufacturer = Manufacturer.new(name: 'Drake Interplanetary', short: 'Drake')
expect(manufacturer.save).to be_truthy
end
describe '#short' do
it 'returns :name if nil' do
manufacturer = Manufacturer.create(name: 'Drake Interplanetary')
expect(manufacturer.short).to eq('Drake Interplanetary')
end
it 'returns :name if blank' do
manufacturer = Manufacturer.create(name: 'Drake Interplanetary', short: '')
expect(manufacturer.short).to eq('Drake Interplanetary')
manufacturer.short = ' '
manufacturer.save
expect(manufacturer.short).to eq('Drake Interplanetary')
end
it 'returns :short if defined' do
manufacturer = Manufacturer.create(name: 'Drake Interplanetary', short: 'Drake')
expect(manufacturer.short).to eq('Drake')
end
end
end
|
class User < ApplicationRecord
has_secure_password validations: false # => removes password_confirmation check
# Relationships
has_many :bookings
# Enums
enum role: [ :guest, :family, :admin ]
# Validations
validates :first_name, :last_name, :phone_number, presence: true
validates :password, presence: true, on: :create
validates :email, presence: true, uniqueness: true, if: :email_changed?
before_create :format_text
private
def format_text
self.first_name = self.first_name.downcase
self.last_name = self.last_name.downcase
self.email = self.email.downcase
end
end
|
require 'spec_helper'
module DmtdVbmappData
describe Protocol do
AVAILABLE_LANGUAGES.each do |language|
context "Language: #{language}" do
it 'can be created' do
client = Client.new(date_of_birth: Date.today, gender: DmtdVbmappData::GENDER_FEMALE, language: language)
expect(Protocol.new(client: client)).to_not be nil
end
it 'can provide areas' do
vbmapp = Protocol.new(client: Client.new(date_of_birth: Date.today, gender: DmtdVbmappData::GENDER_FEMALE, language: language))
expect(vbmapp.areas).to_not be nil
expect(vbmapp.areas.is_a?(Array)).to eq(true)
vbmapp.areas.each do |chapter|
expect(chapter.is_a?(DmtdVbmappData::ProtocolArea)).to eq(true)
end
end
end
end
end
end |
class CreateAuditFieldValues < ActiveRecord::Migration
def change
create_table :audit_field_values, id: :uuid do |t|
t.uuid :audit_field_id, index: true
t.uuid :audit_structure_id, index: true
t.string :string_value
t.float :float_value
t.decimal :decimal_value
t.integer :integer_value
t.datetime :date_value
t.boolean :boolean_value
t.datetime :successful_upload_on
t.datetime :upload_attempt_on
t.timestamps
end
end
end
|
class Definition < ActiveRecord::Base
belongs_to :glossary
has_many :meanings
def meanings_or_new
meanings.empty? ? [Meaning.new] : meanings
end
end
|
class CreateServicePricingTiers < ActiveRecord::Migration
def change
create_table :service_pricing_tiers do |t|
t.integer :user_id
t.integer :service_pricing_scheme_id
t.float :upto
t.datetime :valid_from
t.datetime :valid_to
t.decimal :unit_price
t.timestamps
end
change_table :service_pricing_tiers do |t|
t.index :user_id
t.index :service_pricing_scheme_id
end
end
end
|
class UpdateChannelScraper
include Sidekiq::Worker
sidekiq_options retry: false
def perform(id)
@channel = Channel.find(id)
@channel.update
end
end
|
Rails.application.routes.draw do
root to: 'main#index'
resources :main, only: %i[ create ], path: '/'
end
|
class StringTooBig < StandardError
def initialize(msg="The size of the string is too large for SteggyHide to handle.")
super(msg)
end
end |
require 'httparty'
require 'cgi'
class C2DM
include HTTParty
default_timeout 30
attr_accessor :timeout, :auth_token
AUTH_URL = 'https://www.google.com/accounts/ClientLogin'
PUSH_URL = 'https://android.apis.google.com/c2dm/send'
class << self
attr_accessor :auth_token
def authenticate!(username, password, source = nil)
auth_options = {
'accountType' => 'HOSTED_OR_GOOGLE',
'service' => 'ac2dm',
'Email' => username,
'Passwd' => password,
'source' => source || 'MyCompany-MyAppName-1.0'
}
post_body = build_post_body(auth_options)
params = {
:body => post_body,
:headers => {
'Content-type' => 'application/x-www-form-urlencoded',
'Content-length' => post_body.length.to_s
}
}
response = self.post(AUTH_URL, params)
# check for authentication failures
raise response.parsed_response if response['Error=']
@auth_token = response.body.split("\n")[2].gsub('Auth=', '')
end
def send_notifications(notifications = [])
c2dm = C2DM.new(@auth_token)
notifications.collect do |notification|
{
:body => c2dm.send_notification(notification),
:registration_id => notification[:registration_id]
}
end
end
def build_post_body(options={})
post_body = []
# data attributes need a key in the form of "data.key"...
data_attributes = options.delete(:data)
data_attributes.each_pair do |k,v|
post_body << "data.#{k}=#{CGI::escape(v.to_s)}"
end if data_attributes
options.each_pair do |k,v|
post_body << "#{k}=#{CGI::escape(v.to_s)}"
end
post_body.join('&')
end
end
def initialize(auth_token = nil)
@auth_token = auth_token || self.class.auth_token
end
# {
# :registration_id => "...",
# :data => {
# :some_message => "Hi!",
# :another_message => 7
# }
# :collapse_key => "optional collapse_key string"
# }
def send_notification(options)
options[:collapse_key] ||= 'foo'
post_body = self.class.build_post_body(options)
params = {
:body => post_body,
:headers => {
'Authorization' => "GoogleLogin auth=#{@auth_token}",
'Content-type' => 'application/x-www-form-urlencoded',
'Content-length' => "#{post_body.length}"
}
}
self.class.post(PUSH_URL, params)
end
end
|
class UserConnectionTable < ActiveRecord::Migration
def change
create_table :user_connections, :id=>false do |t|
t.integer "followee_id", :null => false
t.integer "follower_id", :null => false
end
end
end
|
require 'spec_helper'
describe Smsapi::SMS do
describe "#deliver" do
let(:sms) { Smsapi::SMS.new('to', 'message', server, {}) }
let(:server) { instance_double(Smsapi::Server, sms: response) }
subject { sms.deliver }
context "success" do
let(:response) { ["OK:7777:0.7"] }
it { expect(subject).to be_success }
it { expect(subject).not_to be_error }
it { expect(subject.id).to eq('7777') }
it { expect(subject.points).to eq(0.7) }
it { expect(subject.error_code).to be_nil }
end
context "error" do
let(:response) { ["ERROR:6666"] }
it { expect(subject).not_to be_success }
it { expect(subject).to be_error }
it { expect(subject.id).to be_nil }
it { expect(subject.points).to be_nil }
it { expect(subject.error_code).to eq('6666') }
end
end
end
|
# frozen_string_literal: true
class EventMessage < ApplicationRecord
module MessageType
INFORMATION = 'INFORMATION'
INVITATION = 'INVITATION'
REMINDER = 'REMINDER'
SIGNUP_CONFIRMATION = 'SIGNUP_CONFIRMATION'
SIGNUP_REJECTION = 'SIGNUP_REJECTION'
end
module Templates
SIGNUP_CONFIRMATION_SUBJECT = 'Bekreftelse av påmelding til [EVENT_NAME]'
SIGNUP_CONFIRMATION = <<~TEXT
Hei [EVENT_INVITEE_NAME]!
Vi har mottatt din påmelding til [EVENT_NAME],
og kan bekrefte at du har fått plass.
Har du noen spørsmål, så ta kontakt med oss på leir@jujutsu.no eller på telefon xxx xx xxx.
Vi vil fortløpende oppdatere informasjon på [www.jujutsu.no]([EVENT_LINK]).
--
Med vennlig hilsen,
Romerike Jujutsu Klubb
https://www.jujutsu.no/
TEXT
SIGNUP_REJECTION_SUBJECT = 'Påmelding til [EVENT_NAME]'
SIGNUP_REJECTION = <<~TEXT
Hei [EVENT_INVITEE_NAME]!
Vi har mottatt din påmelding til [EVENT_NAME],
men må dessverre meddele at du ikke har fått plass pga. plassmangel.
Vi har din kontaktinfo og vil ta kontakt hvis det skulle bli ledig plass.
Har du noen spørsmål, så ta kontakt med oss på leir@jujutsu.no eller på telefon xxx xx xxx.
--
Med vennlig hilsen,
Romerike Jujutsu Klubb
https://www.jujutsu.no/
TEXT
end
belongs_to :event
has_many :event_invitee_messages, dependent: :restrict_with_exception
validates :body, :event_id, :message_type, :subject, presence: true
validates :message_type, uniqueness: {
scope: :event_id,
unless: ->(mt) { [MessageType::INFORMATION, MessageType::REMINDER].include? mt.message_type },
}
end
|
class User < ApplicationRecord
validates_presence_of :name
def full_name
[first_name, middle_initial_with period, last_name].compact.join(' ')
end
def middle_initial_with_period
"#{middle_initial}." unless middle_initial.blank?
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
version = File.read(File.expand_path('../VERSION', __FILE__)).strip
Gem::Specification.new do |spec|
spec.name = "omniauth-open-wechat-oauth2"
spec.version = version
spec.authors = ["Special Leung"]
spec.email = ["specialcyci@gmail.com"]
spec.summary = 'Omniauth strategy for open wechat(weixin), https://open.weixin.qq.com/'
spec.description = 'Using OAuth2 to authenticate wechat user in web application.'
spec.homepage = "https://github.com/mycolorway/omniauth-open-wechat-oauth2"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'omniauth', '~> 1.0'
spec.add_dependency 'omniauth-oauth2', '~> 1.0'
spec.add_development_dependency 'rspec', '~> 2.7'
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
end
|
require_relative '../test_helper'
class TaskManagerTest < ModelTest
def test_it_creates_a_task
TaskManager.create({ :title => "a title",
:description => "a description"})
task = TaskManager.find(1)
# task = TaskManager.database.where(id: 1)
assert_equal "a title", task.title
assert_equal "a description", task.description
assert_equal 1, task.id
end
def test_tasks_table_has_three_hashes
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
TaskManager.create({ :title => "school", :description => "write tests"})
TaskManager.create({ :title => "exercise", :description => "swim"})
assert_equal 3, TaskManager.tasks_table.count
end
def test_tasks_table_title_is_go_shopping
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
tasks = TaskManager.tasks_table
assert_equal "go shopping", tasks.first[:title]
end
def test_it_can_count_all_tasks
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
TaskManager.create({ :title => "school", :description => "write tests"})
TaskManager.create({ :title => "exercise", :description => "swim"})
tasks = TaskManager.tasks_table
all_tasks = TaskManager.all
assert_equal 3, all_tasks.count
end
def test_it_can_find_the_task_by_id
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
TaskManager.create({ :title => "school", :description => "write tests"})
TaskManager.create({ :title => "exercise", :description => "swim"})
task = TaskManager.find(3)
assert_equal "exercise", task.title
assert_equal "swim", task.description
assert_equal 3, task.id
end
def test_it_can_update_a_task
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
TaskManager.update(1, { :title => "shop till you drop", :description => "candy, milk, hot dogs"})
assert_equal "shop till you drop", TaskManager.find(1).title
assert_equal "candy, milk, hot dogs", TaskManager.find(1).description
end
def test_it_can_delete_a_task
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
task_id = TaskManager.all.last.id
TaskManager.delete(task_id)
assert_equal [], TaskManager.all
end
def test_it_can_delete_all_tasks
TaskManager.create({ :title => "go shopping", :description => "eggs, milk, butter"})
TaskManager.create({ :title => "school", :description => "write tests"})
TaskManager.delete_all
assert_equal 0, TaskManager.all.count
end
end |
class AddBattletagToAccounts < ActiveRecord::Migration[5.1]
def change
add_column :oauth_accounts, :battletag, :string
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts, dependent: :destroy # remove user's posts if account is deleted
validates :username, format: { with: /\A[a-zA-Z0-9]+\Z/ }
validates_uniqueness_of :username, :case_sensitive => false
validates_presence_of :username
validates_presence_of :name
attr_accessor :current_password # check current pasword only if user is trying to change new password in edit.html.erb
has_attached_file :avatar, :styles => { :medium => "300x300#", :thumb => "100x100#" }, :default_url => lambda { |av| "/images/:style/default_#{av.instance.default_image_number}.png" }
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
def default_image_number
id.to_s.last
end
acts_as_voter
end
|
class ChangeTypeForApplications < ActiveRecord::Migration[5.0]
def change
change_column_null(:applications, :university, true)
change_column_null(:applications, :travel_origin, true)
change_column_null(:applications, :major, true)
end
end
|
class CobrandHost < ActiveRecord::Base
belongs_to :cobrand
validates_presence_of :name, :google_maps_api_key
validates_uniqueness_of :name
end
|
# -*- coding: utf-8 -*-
require 'write_xlsx/package/xml_writer_simple'
require 'write_xlsx/utility'
module Writexlsx
module Package
class Comments
include Writexlsx::Utility
def initialize
@writer = Package::XMLWriterSimple.new
@author_ids = {}
end
def set_xml_writer(filename)
@writer.set_xml_writer(filename)
end
def assemble_xml_file(comments_data)
write_xml_declaration
write_comments
write_authors(comments_data)
write_comment_list(comments_data)
@writer.end_tag('comments')
@writer.crlf
@writer.close
end
private
def write_xml_declaration
@writer.xml_decl
end
#
# Write the <comments> element.
#
def write_comments
xmlns = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'
attributes = [ 'xmlns', xmlns]
@writer.start_tag('comments', attributes)
end
#
# Write the <authors> element.
#
def write_authors(comment_data)
author_count = 0
@writer.start_tag('authors')
comment_data.each do |comment|
author = comment[3] || ''
if author && !@author_ids[author]
# Store the author id.
@author_ids[author] = author_count
author_count += 1
# Write the author element.
write_author(author)
end
end
@writer.end_tag('authors')
end
#
# Write the <author> element.
#
def write_author(data)
@writer.data_element('author', data)
end
#
# Write the <commentList> element.
#
def write_comment_list(comment_data)
@writer.start_tag('commentList')
comment_data.each do |comment|
row = comment[0]
col = comment[1]
text = comment[2]
author = comment[3]
# Look up the author id.
author_id = nil
author_id = @author_ids[author] if author
# Write the comment element.
write_comment(row, col, text, author_id)
end
@writer.end_tag( 'commentList' )
end
#
# Write the <comment> element.
#
def write_comment(row, col, text, author_id)
ref = xl_rowcol_to_cell( row, col )
author_id ||= 0
attributes = ['ref', ref]
(attributes << 'authorId' << author_id ) if author_id
@writer.start_tag('comment', attributes)
write_text(text)
@writer.end_tag('comment')
end
#
# Write the <text> element.
#
def write_text(text)
@writer.start_tag('text')
# Write the text r element.
write_text_r(text)
@writer.end_tag('text')
end
#
# Write the <r> element.
#
def write_text_r(text)
@writer.start_tag('r')
# Write the rPr element.
write_r_pr
# Write the text r element.
write_text_t(text)
@writer.end_tag('r')
end
#
# Write the text <t> element.
#
def write_text_t(text)
attributes = []
(attributes << 'xml:space' << 'preserve') if text =~ /^\s/ || text =~ /\s$/
@writer.data_element('t', text, attributes)
end
#
# Write the <rPr> element.
#
def write_r_pr
@writer.start_tag('rPr')
# Write the sz element.
write_sz
# Write the color element.
write_color
# Write the rFont element.
write_r_font
# Write the family element.
write_family
@writer.end_tag('rPr')
end
#
# Write the <sz> element.
#
def write_sz
val = 8
attributes = ['val', val]
@writer.empty_tag('sz', attributes)
end
#
# Write the <color> element.
#
def write_color
indexed = 81
attributes = ['indexed', indexed]
@writer.empty_tag('color', attributes)
end
#
# Write the <rFont> element.
#
def write_r_font
val = 'Tahoma'
attributes = ['val', val]
@writer.empty_tag('rFont', attributes)
end
#
# Write the <family> element.
#
def write_family
val = 2
attributes = ['val', val]
@writer.empty_tag('family', attributes)
end
end
end
end
|
class LinksController < ApplicationController
before_filter :signed_in_user, only: [:edit, :destroy, :update]
before_filter :correct_user, only: [:edit, :destroy, :update]
def index
end
def create
if signed_in?
@link = current_user.links.build(params[:link])
else
@link = Link.new(params[:link])
end
if @link.save
flash[:success] = shortlink(@link.id)
else
flash[:error] = "Oops! Try again."
end
redirect_to root_url
end
def destroy
@link.destroy
redirect_to root_url
end
def update
@link = Link.find_by_id(params[:id])
if params[:link][:name] == ""
flash[:error] = "No changes have been made."
elsif @link.update_attributes(params[:link])
flash[:success] = "Link updated."
else
flash[:error] = "Error. Link could not be updated."
end
redirect_to root_url
end
def go
if params[:username] == "s"
link_id = unshorten(params[:name])
@link = Link.find_by_id(link_id)
else
@user = User.find_by_username(params[:username])
if !@user.nil?
@link = Link.find_by_user_id_and_name(@user.id, params[:name])
end
end
if !@link.nil?
redirect_to("#{request.protocol}#{@link.url}", :status => 301)
else
redirect_to error_path
end
end
private
def correct_user
@link = current_user.links.find_by_id(params[:id])
redirect_to root_url if @link.nil?
end
def shortlink(long_id)
"/s/" + shorten(@link.id)
end
def shorten(long_id)
long_id.to_s(36)
end
def unshorten(short_id)
short_id.to_i(36)
end
end
|
require 'test_helper'
class WelcomeControllerTest < ActionDispatch::IntegrationTest
test "json endpoint should translate" do
expected_response = {
"navbar": [{"link": {"url" => "www.example.com", "text" => "home"}}, {"link": {"url" => "www.example.com", "text" => "about"}}],
"title": {"text" => "Señor Sisig"},
"picture": {"url" => "www.example.com"},
"menu": {
"text": "Menu",
"column1": {
"text": "Food",
"menu_items": [
{"li": {"text": "Sisg Tacos"}},
{"li": {"text": "Sisg Burritos"}},
]
},
"column2": {
"text": "Drinks",
"menu_items": [
{"li": {"text": "Coke"}},
{"li": {"text": "Diet Coke"}},
]
}
}
}
get welcome_index_url, as: :json
assert_equal expected_response, JSON.parse(response.body)
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)
Item.create([
{ name: "Credit Card", description: "This is the description of item 1.", amount: -150 },
{ name: "Student Loan", description: "This is the description of item 2.", amount: -200 },
{ name: "Occupation", description: "This is the description of item 3.", amount: 1500 },
{ name: "Side Hustle", description: "This is the description of item 4.", amount: 1500 }
])
|
class Menu
attr_accessor :dish
def initialize
@dish = []
end
def set(*dish)
@dish << dish
end
def dish_count
@dish.count
end
end |
class OrdenproduccionsController < ApplicationController
before_action :set_ordenproduccion, only: [:show, :edit, :update, :destroy]
# GET /ordenproduccions
# GET /ordenproduccions.json
def index
@ordenproduccions = Ordenproduccion.all
end
# GET /ordenproduccions/1
# GET /ordenproduccions/1.json
def show
end
# GET /ordenproduccions/new
def new
@ordenproduccion = Ordenproduccion.new
end
# GET /ordenproduccions/1/edit
def edit
end
# POST /ordenproduccions
# POST /ordenproduccions.json
def create
@ordenproduccion = Ordenproduccion.new(ordenproduccion_params)
respond_to do |format|
if @ordenproduccion.save
format.html { redirect_to @ordenproduccion, notice: 'Ordenproduccion was successfully created.' }
format.json { render :show, status: :created, location: @ordenproduccion }
else
format.html { render :new }
format.json { render json: @ordenproduccion.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /ordenproduccions/1
# PATCH/PUT /ordenproduccions/1.json
def update
respond_to do |format|
if @ordenproduccion.update(ordenproduccion_params)
format.html { redirect_to @ordenproduccion, notice: 'Ordenproduccion was successfully updated.' }
format.json { render :show, status: :ok, location: @ordenproduccion }
else
format.html { render :edit }
format.json { render json: @ordenproduccion.errors, status: :unprocessable_entity }
end
end
end
# DELETE /ordenproduccions/1
# DELETE /ordenproduccions/1.json
def destroy
@ordenproduccion.destroy
respond_to do |format|
format.html { redirect_to ordenproduccions_url, notice: 'Ordenproduccion was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ordenproduccion
@ordenproduccion = Ordenproduccion.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def ordenproduccion_params
params.require(:ordenproduccion).permit(:fechaprogramacion, :ordennumero, :cliente_id, :descripcion, :referencia, :corte, :ancho, :tela_id, :largotrazo, :largotendido, :numeropaquetes, :cantidad, :promediounidad, :totalmetros, :corte, :tiqueteada, :prenda_id)
end
end
|
require "toastmasters/mappers/base_mapper"
module Toastmasters
module Mappers
class MeetingMapper < BaseMapper
attributes :id, :date, :note
end
end
end
|
class ShiftWorkCenterDecorator < ApplicationDecorator
delegate_all
def work_center_title
h.link_to object.work_center_title, h.edit_shift_work_center_path(object)
end
def relevance
h.check_box_tag 'shift_work_centrs[]', object.relevance , object.relevance,{ :disabled => "disabled"}
end
def shift_start
helpers.content_tag :span, class: 'time' do
if !object.shift_start.nil?
object.shift_start.strftime("%H:%M")
end
end
end
# Define presentation-specific methods here. Helpers are accessed through
# `helpers` (aka `h`). You can override attributes, for example:
#
# def created_at
# helpers.content_tag :span, class: 'time' do
# object.created_at.strftime("%a %m/%d/%y")
# end
# end
end
|
if not @error
json.success true
json.set! :result do
json.extract! @contact, :id, :user_id, :name, :email, :phone, :description, :status
end
else
json.success false
json.error @error
end
|
class AddReferenceOfCategoryToWorklist < ActiveRecord::Migration[6.0]
def change
add_reference :work_lists, :category, foreign_key: true
end
end
|
class Task < ActiveRecord::Base
validates_presence_of :title
validate :future_completed_date
private
def future_completed_date
if !completed.blank? && completed > Date.today
self.errors.add(:completed, "can't be in the future")
end
end
end
|
require 'test_helper'
class HelpersTest < ActionController::TestCase
tests ApplicationController
def setup
@warden = mock()
@controller.request.env['warden'] = @warden
end
test 'proxy to Warden manager' do
assert_equal @controller.warden, @warden
end
test 'proxy #login to Warden #authenticate' do
@warden.expects(:authenticate).with(:my_strategy, :scope => :user)
@controller.login(:my_strategy, :scope => :user)
end
test 'proxy #login? to Warden #authenticate?' do
@warden.expects(:authenticate?).with(:my_strategy, :scope => :user)
@controller.login?(:my_strategy, :scope => :user)
end
test 'proxy #login! to Warden #authenticate!' do
@warden.expects(:authenticate!).with(:my_strategy, :scope => :user)
@controller.login!(:my_strategy, :scope => :user)
end
test 'proxy #logout to Warden #logout' do
@warden.expects(:raw_session)
@warden.expects(:logout).with(:user)
@controller.logout(:user)
end
test 'proxy #logged_in? to Warden #authenticated?' do
@warden.expects(:authenticated?).with(:user)
@controller.logged_in?(:user)
end
test 'proxy #logged_user to Warden #user' do
@warden.expects(:user).with(:user)
@controller.logged_user(:user)
end
test 'proxy #set_user to Warden #set_user' do
user = mock('User')
@warden.expects(:set_user).with(user, :user)
@controller.set_user(user, :user)
end
end
|
# encoding: utf-8
class Base < CarrierWave::Uploader::Base
storage :file
def store_dir
Iqvoc.upload_path.join(model.class.to_s.downcase)
end
def filename
"#{secure_token}.#{file.extension}" if original_filename.present?
end
protected
# https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Create-random-and-unique-filenames-for-all-versioned-files
def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex)
end
end
|
class AddPrice < ActiveRecord::Migration[5.2]
def self.up
add_column :parking_slot_reservations, :price, :integer
add_column :parking_slot_reservations, :subtotal, :integer
end
def self.down
remove_column :parking_slot_reservations, :price
remove_column :parking_slot_reservations, :subtotal
end
end
|
class ApplicationController < ActionController::API
include ActionController::MimeResponds
include ActionController::Cookies
include ActionController::RequestForgeryProtection
include Response
include ErrorHandler
include Authorization
before_action :set_csrf_cookie
private
def set_csrf_cookie
cookies["CSRF-TOKEN"] = form_authenticity_token
end
def authenticate_user
unless current_user
render_error_from(message: "Invalid credentials",
code: "unauthorized",
status: :unauthorized)
end
end
end
|
FactoryBot.define do
factory :service_area_code do
name { [Faker::Address.state_abbr, Faker::Number.number(3)].join }
end
end
|
class Api::V1::StepsController < ApplicationController
before_action :authenticate_user
def show
step = Step.find(params[:id])
render json: step
end
def create
step = Step.new(step_params)
job = Job.find(params[:job_id])
step.job = job
if step.save
render json: StepSerializer.new(step).serializable_hash.to_json, status: 201
else
render json: { error: step.errors.messages }, status: 422
end
end
def destroy
step = Step.find(params[:id])
if step.destroy
head :no_content
else
render json: { error: step.errors.messages }, status: 422
end
end
def update
step = Step.find(params[:id])
if step.update(step_params)
render json: StepSerializer.new(step).serializable_hash.to_json, status: 200
else
render json: { error: step.errors.messages }, status: 422
end
end
private
def step_params
params.require(:step).permit(:date, :status, :job_id)
end
end
|
class NewsletterController < ApplicationController
def signup
@newsletter_signup = NewsletterSignup.new :email => params[:email]
respond_to do |format|
if @newsletter_signup.valid? and @newsletter_signup.save
Notifications.newsletter_signup(params[:email]).deliver
format.json { render :json => true }
format.html { redirect_to :root_url, :notice => 'You have been signed up!' }
else
format.json { render :json => { :message => @newsletter_signup.errors }, :status => 400 }
format.html { render :template => 'newsletter/index' }
end
end
end
def index
@newsletter_signup = NewsletterSignup.new
end
end
|
class CreateTreatments < ActiveRecord::Migration[5.0]
def change
create_table :treatments do |t|
t.integer :field_id
t.date :date
t.integer :si
t.float :dose
t.integer :remedy_id
t.string :goal
t.string :establishment
t.string :weather
t.string :operator
t.timestamps
end
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe RubyPx::Dataset do
let(:subject) { described_class.new 'spec/fixtures/ine-padron-2014.px' }
context "ine-padron-2014.px" do
describe '#headings' do
it 'should return the list of headings described in the file' do
expect(subject.headings).to eq(['edad (año a año)'])
end
end
describe '#stubs' do
it 'should return the list of stubs described in the file' do
expect(subject.stubs).to eq(%w[sexo municipios])
end
end
describe 'metadata methods' do
it 'should return the title' do
expect(subject.title).to eq('Población por sexo, municipios y edad (año a año).')
end
it 'should return the units' do
expect(subject.units).to eq('personas')
end
it 'should return the source' do
expect(subject.source).to eq('Instituto Nacional de Estadística')
end
it 'should return the contact' do
expect(subject.contact).to eq('INE E-mail:www.ine.es/infoine. Internet: www.ine.es. Tel: +34 91 583 91 00 Fax: +34 91 583 91 58')
end
it 'should return the last_updated' do
expect(subject.last_updated).to eq('05/10/99')
end
it 'should return the creation_date' do
expect(subject.creation_date).to eq('20141201')
end
end
describe '#dimension' do
it 'should return all the values of a dimension' do
expect(subject.dimension('edad (año a año)')).to include('Total')
expect(subject.dimension('edad (año a año)')).to include('100 y más')
end
it 'should return the number of values' do
expect(subject.dimension('edad (año a año)').length).to eq(102)
end
it 'should return an error if the dimension does not exist' do
expect do
subject.dimension('foo').values
end.to raise_error('Missing dimension foo')
end
end
describe '#dimensions' do
it 'should return an array with all the dimensions of the dataset' do
expect(subject.dimensions).to eq(['sexo', 'edad (año a año)', 'municipios'])
end
end
describe '#data' do
it 'should raise an error if a dimension value does not exist' do
expect do
subject.data('edad (año a año)' => 'Totalxxx', 'sexo' => 'Ambos sexos', 'municipios' => '28079-Madrid')
end.to raise_error('Invalid value Totalxxx for dimension edad (año a año)')
end
it 'should raise an error if a dimension does not exist' do
expect do
subject.data('foo' => 'Total', 'sexo' => 'Ambos sexos', 'municipios' => '28079-Madrid')
end.to raise_error('Missing dimension foo')
end
it 'should return data when all the dimensions are provided' do
expect(subject.data('edad (año a año)' => 'Total', 'sexo' => 'Ambos sexos', 'municipios' => '28079-Madrid')).to eq('3165235')
expect(subject.data('edad (año a año)' => 'Total', 'sexo' => 'Hombres', 'municipios' => '28079-Madrid')).to eq('1472990')
expect(subject.data('edad (año a año)' => 'Total', 'sexo' => 'Mujeres', 'municipios' => '28079-Madrid')).to eq('1692245')
end
it 'should return an array of data when all the dimensions are provided except 1' do
result = subject.data('edad (año a año)' => 'Total', 'sexo' => 'Ambos sexos')
expect(result.first).to eq('46771341')
expect(result[3899]).to eq('3165235')
expect(result.length).to eq(8118)
end
it 'should return an error if more than one dimension is expected in the result' do
expect do
subject.data('edad (año a año)' => 'Total')
end.to raise_error('Not implented yet, sorry')
end
end
end
end
|
require 'farandula/constants'
require 'farandula/flight_managers/flight_manager'
require 'farandula/utils/logger_utils'
require 'farandula/models/itinerary'
require 'farandula/models/air_leg'
require 'farandula/models/segment'
require 'farandula/models/seat'
require 'farandula/models/fares'
require 'farandula/models/price'
require 'farandula/utils/exceptions_helper'
require 'farandula/utils/logger_utils'
require 'rest-client'
require 'time'
require 'logger'
module Farandula
module FlightManagers
module Sabre
class SabreFlightManager < FlightManager
def initialize(creds)
@access_manager = AccessManager.new(creds[:client_id], creds[:client_secret] )
# maps
@airline_code_map = YAML.load_file(File.dirname(__FILE__) + '/../../assets/amadeus/' + "airlinesCode.yml")
@airline_cabin_map = YAML.load_file(File.dirname(__FILE__) + '/../../assets/sabre/' + "cabins.yml")
@logger = Logger.new File.new('farandula-ruby.log', File::WRONLY | File::APPEND | File::CREAT)
@logger.level = Logger::DEBUG
end
def get_avail(search_form)
build_itineraries( get_response( search_form ) )
end
private
def get_response( search_form )
headers = {
content_type: :json,
accept: :json,
Authorization: @access_manager.build_auth_token
}
url = 'https://api.test.sabre.com/v3.1.0/shop/flights?mode=live&enabletagging=true&limit=50&offset=1'
if search_form.offset
url = "https://api.test.sabre.com/v3.1.0/shop/flights?mode=live&enabletagging=true&limit=#{search_form.offset}&offset=1"
end
request = Sabre::Request.new
request_json = request.build_request_for!(search_form)
@logger.info ("Sabre Request: #{request_json}.\n")
printf "Sabre Request: #{request_json}\n."
RestClient.post(
url,
request_json,
headers
)
end
def build_credentials(client_id, client_secret)
encoded_id = Base64.strict_encode64(client_id)
encoded_secret = Base64.strict_encode64(client_secret)
encoded = Base64.strict_encode64("#{encoded_id}:#{encoded_secret}")
"Basic #{encoded}"
end
def build_itineraries( response )
@logger.info ("Sabre Response: #{ Farandula::Utils::LoggerUtils.get_pretty_json response}.\n")
parsed = JSON.parse( response )
root = parsed['OTA_AirLowFareSearchRS']['PricedItineraries']
root['PricedItinerary'].each.map do |itin|
legs = build_air_legs(itin )
air_itinerary_pricing_info = itin['AirItineraryPricingInfo']
if air_itinerary_pricing_info.size > 1
msg = 'We don\'t support multiple AirPricingInfo'
Farandula::Utils::ExceptionsHelper.handle_exceptions(
ActionUnsupported(msg), msg )
end
set_seats( air_itinerary_pricing_info, legs )
itineray_result = Farandula::Itinerary.new
itineray_result.air_legs = legs
itineray_result.fares = extract_fares_info( air_itinerary_pricing_info );
itineray_result
end
end
def build_air_legs( json_itinerary )
originDestinationOption = json_itinerary['AirItinerary']['OriginDestinationOptions']['OriginDestinationOption']
airlegs = []
originDestinationOption.each_with_index.map do|element, index|
segments = element['FlightSegment'].each_with_index.map {|segment, index_seg| build_segment(segment, index_seg)}
air_leg = Farandula::AirLeg.new
air_leg.id = index
air_leg.departure_airport_code = segments[0].departure_airport_code
air_leg.departure_date = segments[0].departure_date
air_leg.arrival_airport_code = segments[segments.size - 1].arrival_airport_code
air_leg.arrival_date = segments[segments.size - 1].arrival_date
air_leg.segments = segments
airlegs << air_leg
end
airlegs
end
def build_segment(json_segment, index)
equipment_data = json_segment['Equipment'][0]
operative_airline_data = json_segment['OperatingAirline']
marketing_airline_data = json_segment['MarketingAirline']
# departure
departure_airport_data = json_segment['DepartureAirport']
# arrival
arrival_airport_data = json_segment['ArrivalAirport']
# airleg data
segment = Farandula::Segment.new
segment.key = index
segment.operating_airline_code = operative_airline_data['Code']
segment.operating_airline_name = @airline_code_map[segment.operating_airline_code]
segment.operating_flight_number = operative_airline_data['FlightNumber']
segment.marketing_airline_code = marketing_airline_data['Code']
segment.marketing_airline_name = @airline_code_map[segment.marketing_airline_code]
segment.airplane_data = equipment_data['AirEquipType']
segment.departure_airport_code = departure_airport_data['LocationCode']
segment.departure_terminal = departure_airport_data['TerminalID']
segment.departure_date = format_date(Time.parse (json_segment['DepartureDateTime']) )
segment.arrival_airport_code = arrival_airport_data['LocationCode']
segment.arrival_terminal = arrival_airport_data['TerminalID']
segment.arrival_date = format_date( Time.parse (json_segment['ArrivalDateTime']) )
segment.duration = json_segment['ElapsedTime']
segment
end
def format_date(date)
date.strftime('%Y-%m-%dT%H:%M:%S.%L%z')
end
def extract_cabins_info ( itinerary )
itinerary.each_with_index.map do | it, index|
fare_info = it['FareInfos']['FareInfo']
fare_info.each.map do| fare |
fare['TPA_Extensions']
end
end
end
def set_seats( itineray , legs )
cabins_info = extract_cabins_info( itineray )
legs.each do | leg |
leg.segments.each_with_index do | segment , segment_index |
cabin_by_segment = cabins_info[0][segment_index]
num_of_seats = cabin_by_segment['SeatsRemaining']['Number']
cabin_value = cabin_by_segment['Cabin']['Cabin']
cabin_class_type = @airline_cabin_map[cabin_value]? @airline_cabin_map[cabin_value]: "Other"
seats = num_of_seats.times.map { Farandula::Seat.new( cabin_class_type, "") }
segment.seats_available = seats
end
end
end
def extract_fares_info( itinerary )
fares = Farandula::Fares.new
fares.base_price = Farandula::Price.new( itinerary[0]['ItinTotalFare']['BaseFare']['Amount'],
itinerary[0]['ItinTotalFare']['BaseFare']['CurrencyCode'] )
fares.taxes_price = Farandula::Price.new( itinerary[0]['ItinTotalFare']['Taxes']['Tax'][0]['Amount'],
itinerary[0]['ItinTotalFare']['Taxes']['Tax'][0]['CurrencyCode'] )
fares.total_price = Farandula::Price.new( itinerary[0]['ItinTotalFare']['TotalFare']['Amount'],
itinerary[0]['ItinTotalFare']['TotalFare']['CurrencyCode'] )
fares
end
#private ends
end #ends sabreflightmanager
end #ends Sabre
end #ends FlightManagers
end # ends Farandula |
module Rightboat
module ParamsReader
def read_str(str)
str.strip if str.present?
end
def read_downcase_str(str)
if (str = read_str(str))
str.downcase
end
end
def read_id(str)
case str
when Numeric then str
when String then str.to_i if str.strip =~ /\A\d+\z/
end
end
def read_page(num_str)
if num_str.present?
num_str.to_i.clamp(1..100_000)
end
end
def read_array(items)
if items.present?
case items
when Array then items
when String then items.split('-')
end
end
end
def read_ids(ids_str)
if (arr = read_array(ids_str))
arr.map { |id| read_id(id) }.compact.presence
end
end
def read_state_codes(codes_str)
if (arr = read_array(codes_str))
arr.grep(String).select { |id| Rightboat::USStates.states_map[id] }.presence
end
end
def read_currency(currency_str)
if currency_str.present?
Currency.cached_by_name(currency_str)
end
end
def read_boat_price(price_str)
if price_str.present?
price_str.to_i.clamp(Boat::PRICES_RANGE)
end
end
def read_boat_year(year)
if year.present?
year.to_i.clamp(Boat::YEARS_RANGE)
end
end
def read_length_unit(length_unit)
length_unit.presence_in(Boat::LENGTH_UNITS)
end
def read_boat_length(len, len_unit)
if len.present?
length_range = len_unit == 'm' ? Boat::M_LENGTHS_RANGE : Boat::FT_LENGTHS_RANGE
len.to_f.round(2).clamp(length_range)
end
end
def read_hash(hash, possible_keys)
if hash.present?
if hash.is_a?(ActionController::Parameters)
hash.permit(possible_keys).to_h
elsif hash.is_a?(Hash)
hash.slice(*possible_keys)
end
end
end
def read_tax_status_hash(hash)
read_hash(hash, %w(paid unpaid))
end
def read_new_used_hash(hash)
read_hash(hash, %w(new used))
end
def read_boat_type(str)
read_downcase_str(str).presence_in(BoatType::GENERAL_TYPES)
end
def read_country(slug)
Country.find_by(slug: slug) if slug.present?
end
def read_manufacturer(slug)
Manufacturer.find_by(slug: slug) if slug.present?
end
def read_search_order(target_order)
if target_order.present? && SearchParams::ORDER_TYPES.include?(target_order)
m = target_order.match(/\A(.*)_(asc|desc)\z/)
[m[1].to_sym, m[2].to_sym]
end
end
end
end
|
require 'formula'
class StyleCheck < Formula
homepage 'http://www.cs.umd.edu/~nspring/software/style-check-readme.html'
url 'http://www.cs.umd.edu/~nspring/software/style-check-0.14.tar.gz'
sha1 '7308ba19fb05a84e2a8cad935b8056feba63d83b'
def install
inreplace "style-check.rb", '/etc/style-check.d/', etc+'style-check.d/'
system "make", "PREFIX=#{prefix}",
"SYSCONFDIR=#{etc}/style-check.d",
"install"
end
end
|
class AddExceptionDateToPeriods < ActiveRecord::Migration
def change
add_column :periods, :exception_date, :text
end
end
|
require_relative "base_nmea"
module NMEAPlus
module Message
module NMEA
# VWR - Relative Wind Speed and Angle
class VWR < NMEAPlus::Message::NMEA::NMEAMessage
field_reader :wind_direction_degrees, 1, :_float
field_reader :wind_direction_bow, 2, :_string
field_reader :speed_knots, 3, :_float
field_reader :speed_ms, 5, :_float
field_reader :speed_kmh, 7, :_float
end
end
end
end
|
require 'spec_helper'
describe SemanticNavigation::TwitterBootstrap::Breadcrumb do
context :renders do
before :each do
class ViewObject
attr_accessor :output_buffer
include ActionView::Helpers::TagHelper
include SemanticNavigation::HelperMethods
include ActionView::Helpers::UrlHelper
end
@configuration = SemanticNavigation::Configuration
@configuration.register_renderer :bootstrap_breadcrumb, SemanticNavigation::TwitterBootstrap::Breadcrumb
@view_object = ViewObject.new
end
it 'empty ul tag for empty navigation' do
@configuration.run do
navigate :menu do
end
end
result = @view_object.navigation_for :menu, :as => :bootstrap_breadcrumb
result.should == "<ul class=\"breadcrumb\"></ul>"
end
it 'one level navigation breadcrumb' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1'
item :url2, 'url2', :name => 'url2'
end
end
@view_object.should_receive(:current_page?).and_return(false,true)
result = @view_object.navigation_for :menu, :as => :bootstrap_breadcrumb
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"url2",
"</li>",
"</ul>"].join
end
it 'one multilevel navigation breadcrumb' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1' do
item :suburl1, 'suburl1', :name => 'suburl1'
end
item :url2, 'url2', :name => 'url2' do
item :suburl2, 'suburl2', :name => 'suburl2'
end
end
end
@view_object.should_receive(:current_page?).and_return(true,false,false,false)
result = @view_object.navigation_for :menu, :as => :bootstrap_breadcrumb
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"<a href=\"url1\">",
"url1",
"</a>",
"<span class=\"divider\">/",
"</span>",
"</li>",
"<li>",
"suburl1",
"</li>",
"</ul>"].join
end
it 'last item as link if :last_as_link => true' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1' do
item :suburl1, 'suburl1', :name => 'suburl1'
end
item :url2, 'url2', :name => 'url2' do
item :suburl2, 'suburl2', :name => 'suburl2'
end
end
end
@view_object.should_receive(:current_page?).and_return(true,false,false,false)
result = @view_object.navigation_for :menu, :as => :bootstrap_breadcrumb, :last_as_link => true
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"<a href=\"url1\">",
"url1",
"</a>",
"<span class=\"divider\">/",
"</span>",
"</li>",
"<li>",
"<a href=\"suburl1\">",
"suburl1",
"</a>",
"</li>",
"</ul>"].join
end
it 'only root level' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1' do
item :suburl1, 'suburl1', :name => 'suburl1'
end
item :url2, 'url2', :name => 'url2' do
item :suburl2, 'suburl2', :name => 'suburl2'
end
end
end
@view_object.should_receive(:current_page?).and_return(true,false,false,false)
result = @view_object.navigation_for :menu, :level => 0, :as => :bootstrap_breadcrumb
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"url1",
"</li>",
"</ul>"].join
end
it 'second level' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1' do
item :suburl1, 'suburl1', :name => 'suburl1'
end
item :url2, 'url2', :name => 'url2' do
item :suburl2, 'suburl2', :name => 'suburl2'
end
end
end
@view_object.should_receive(:current_page?).and_return(true, false, false, false)
result = @view_object.navigation_for :menu, :level => 1, :as => :bootstrap_breadcrumb
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"suburl1",
"</li>",
"</ul>"].join
end
it 'the exact levels' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1' do
item :suburl1, 'suburl1', :name => 'suburl1' do
item :subsub1, 'subsub1', :name => 'subsub1'
end
end
item :url2, 'url2', :name => 'url2' do
item :suburl2, 'suburl2', :name => 'suburl2' do
item :subsub2, 'subsub2', :name => 'subsub2'
end
end
end
end
@view_object.should_receive(:current_page?).and_return(true, false, false, false, false, false)
result = @view_object.navigation_for :menu, :levels => 0..1, :as => :bootstrap_breadcrumb
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"<a href=\"url1\">",
"url1",
"</a>",
"<span class=\"divider\">/",
"</span>",
"</li>",
"<li>",
"suburl1",
"</li>",
"</ul>"].join
end
it 'navigation except some item' do
@configuration.run do
navigate :menu do
item :url1, 'url1', :name => 'url1' do
item :suburl1, 'suburl1', :name => 'suburl1'
end
item :url2, 'url2', :name => 'url2' do
item :suburl2, 'suburl2', :name => 'suburl2'
end
end
end
@view_object.should_receive(:current_page?).and_return(true, false, false, false)
result = @view_object.navigation_for :menu, :except_for => [:suburl1], :as => :bootstrap_breadcrumb
result.should == ["<ul class=\"breadcrumb\">",
"<li>",
"url1",
"</li>",
"</ul>"].join
end
end
end
|
class CreateAttributionSecurities < ActiveRecord::Migration
def change
create_table :attribution_securities do |t|
t.string :cusip
t.string :ticker
t.date :effective_on
t.timestamps null: false
end
end
end
|
#
# vmstat用
#
# *** vmstatコマンドの実行例 ***
# procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
# r b swpd free buff cache si so bi bo in cs us sy id wa st
# 0 0 0 233000 9596 121264 0 0 27 1 853 41 2 1 97 0 0
#
# vmstatの結果を格納するクラス
class VmInfo
def initialize()
init()
end
def init()
@memory_free = "" # 空きメモリ容量(KB)
@cpu_id = "" # アイドル時間(CPUが何も処理せずに待っていた時間)の割合
end
def memory_free
@memory_free
end
def memory_free=(value)
@memory_free = value
end
def cpu_id
@cpu_id
end
def cpu_id=(value)
@cpu_id = value
end
# serial経由でvmstatコマンドを発行し
# VmInfoの指定したデバイス情報を取得
def command(serial)
init()
serial.write "vmstat\n" # vmstatコマンド発行
begin
sleep 0.05
recv = serial.readline # コマンド名の読み飛ばし
sleep 0.05
recv = serial.readline # vmstatヘッダーの読み飛ばし
sleep 0.05
recv = serial.readline # vmstatヘッダーの読み飛ばし
sleep 0.05
recv = serial.readline # vmstatデータの取得
ary = recv.scanf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s")
if ary.length == 17
@memory_free = ary[3]
@cpu_id = ary[14]
end
rescue EOFError
end
printAll
end
def printAll
print "***** vmstat実行結果 *****\n"
print "[memory free] #{@memory_free}\n"
print "[cpu id] #{@cpu_id}\n"
print "\n"
end
end
|
class RegistrationsController < ApplicationController
before_filter :require_logout
def new
@registration = Registration.new
end
def create
@registration = Registration.new(params[:registration])
if @registration.submit
login @registration.user
flash[:success] = "Account created!"
redirect_to messages_url
else
flash.now[:error] = "There was a problem creating your account"
render :new
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
current_path = File.dirname(__FILE__)
hostname = "vagrant-base-trusty32"
aliases = ""
server_cpus = "1"
server_memory = "512"
server_ip = "192.168.33.10"
# set the http://proxy-address-and:port here if you need to, eg, http://proxy.example.org:3128
proxy_addr = ""
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty32"
config.vm.hostname = hostname
# config.vm.network "forwarded_port", guest: 80, host: 8080
# config.vm.network "private_network", ip: server_ip
# config.vm.network "public_network"
config.vm.provider "virtualbox" do |vb|
vb.name = hostname
vb.customize [
"modifyvm", :id,
"--cpus", server_cpus,
"--memory", server_memory,
"--natdnshostresolver1", "on",
"--natdnsproxy1", "on"
]
end
if Vagrant.has_plugin?("vagrant-proxyconf") and !proxy_addr.empty?
config.proxy.http = proxy_addr
config.proxy.https = proxy_addr
config.proxy.ftp = proxy_addr
config.proxy.no_proxy = "localhost,127.0.0.1,.example.com"
end
if Vagrant.has_plugin?("vagrant-hostmanager")
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.ignore_private_ip = false
config.hostmanager.include_offline = false
config.vm.define hostname do |node|
if !aliases.empty?
node.hostmanager.aliases = aliases
end
end
end
# if Vagrant.has_plugin?("vagrant-hostsupdater") and !aliases.empty?
# config.hostsupdater.aliases = ["alias.vagrant-base-trusty32", "alias2.vagrant-base-trusty32"]
# end
# !!do not change this, some scripts still depend on this path!!
config.vm.synced_folder "./", "/vagrant", :mount_options => ['dmode=775', 'fmode=664']
# example path for running websites
# config.vm.synced_folder "d:/www", "/var/www", :mount_options => ['dmode=775', 'fmode=664'], owner: "www-data", group: "www-data"
config.vm.provision :shell, :inline => "echo \"Europe/Berlin\" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata"
# !!will run all scripts in the scripts/ folder!!
#config.vm.provision :shell, path: "provision-scripts.sh"
# runs selected scripts, edit to your needs
#config.vm.provision :shell, path: "provision-custom.sh"
end
|
module Ecm::Tournaments
class Tournament < ActiveRecord::Base
# associations
belongs_to :ecm_tournaments_series, :class_name => Series,
:foreign_key => :ecm_tournaments_series_id
belongs_to :ecm_tournaments_type, :class_name => Type,
:foreign_key => :ecm_tournaments_type_id
has_many :ecm_tournaments_matches, :class_name => Match,
:foreign_key => :ecm_tournaments_tournament_id
has_many :ecm_tournaments_participants, :class_name => Participant,
:foreign_key => :ecm_tournaments_tournament_id
has_many :ecm_tournaments_teams, :class_name => Team,
:foreign_key => :ecm_tournaments_tournament_id
# attributes
attr_accessible :begins_at,
:description,
:ends_at
# validations
validates :begins_at, :presence => true
validates :ecm_tournaments_series, :presence => true
validates :ecm_tournaments_type, :presence => true
# # methods
# def create_and_randomize_teams
# shuffled_participants = ecm_tournaments_participants.shuffle
# team_count = shuffled_participants.count.to_f / 2
# team_count.ceil.times do
# ecm_tournaments_teams.create! do |team|
# team.ecm_tournaments_team_memberships << TeamMembership.new(:ecm_tournaments_participant => shuffled_participants.pop, :ecm_tournaments_team => team)
# team.ecm_tournaments_team_memberships << TeamMembership.new(:ecm_tournaments_participant => shuffled_participants.pop, :ecm_tournaments_team => team) if shuffled_participants.count > 0
# end
# end
# end
# def generate_matches
# match_generator = MatchGenerators::SingleKnockOut.new(self.ecm_tournaments_teams)
# self.ecm_tournaments_matches = match_generator.matches
# end
end
end
|
class RelinkPurchaseToPayment < ActiveRecord::Migration
def up
if (Purchase.new.attributes.has_key?(:order_id.to_s))
end
add_column :purchases, :payment_id, :integer
end
def down
remove_column :purchases, :payment_id
end
end
|
class CSVDiff
# Defines functionality for exporting a Diff report to Excel in XLSX format
# using the Axlsx library.
module Excel
private
# Generare a diff report in XLSX format.
def xl_output(output)
require 'axlsx'
# Create workbook
xl = xl_new
# Add a summary sheet and diff sheets for each diff
xl_summary_sheet(xl)
# Save workbook
path = "#{File.dirname(output)}/#{File.basename(output, File.extname(output))}.xlsx"
xl_save(xl, path)
end
# Create a new XL package object
def xl_new
@xl_styles = {}
xl = Axlsx::Package.new
xl.use_shared_strings = true
xl.workbook.styles do |s|
s.fonts[0].sz = 9
@xl_styles['Title'] = s.add_style(:b => true)
@xl_styles['Comma'] = s.add_style(:format_code => '#,##0')
@xl_styles['Right'] = s.add_style(:alignment => {:horizontal => :right})
@xl_styles['Add'] = s.add_style :fg_color => '00A000'
@xl_styles['Update'] = s.add_style :fg_color => '0000A0', :bg_color => 'F0F0FF'
@xl_styles['Move'] = s.add_style :fg_color => '4040FF'
@xl_styles['Delete'] = s.add_style :fg_color => 'FF0000', :strike => true
@xl_styles['Matched'] = s.add_style :fg_coler => 'A0A0A0'
end
xl
end
# Add summary sheet
def xl_summary_sheet(xl)
compare_from = @left
compare_to = @right
xl.workbook.add_worksheet(name: 'Summary') do |sheet|
sheet.add_row do |row|
row.add_cell 'From:', :style => @xl_styles['Title']
row.add_cell compare_from
end
sheet.add_row do |row|
row.add_cell 'To:', :style => @xl_styles['Title']
row.add_cell compare_to
end
sheet.add_row
sheet.add_row ['Sheet', 'Adds', 'Deletes', 'Updates', 'Moves'], :style => @xl_styles['Title']
sheet.column_info.each do |ci|
ci.width = 10
end
sheet.column_info.first.width = 20
@diffs.each do |file_diff|
sheet.add_row([file_diff.options[:sheet_name] ||
File.basename(file_diff.left.path, File.extname(file_diff.left.path)),
file_diff.summary['Add'], file_diff.summary['Delete'],
file_diff.summary['Update'], file_diff.summary['Move']])
xl_diff_sheet(xl, file_diff) if file_diff.diffs.size > 0
end
end
end
# Add diff sheet
def xl_diff_sheet(xl, file_diff)
sheet_name = file_diff.options[:sheet_name] ||
File.basename(file_diff.left.path, File.extname(file_diff.left.path))
out_fields = output_fields(file_diff)
freeze_cols = file_diff.options[:freeze_cols] ||
(out_fields.select{ |f| f.is_a?(Symbol) }.length + file_diff.left.key_fields.length)
xl.workbook.add_worksheet(name: sheet_name) do |sheet|
sheet.add_row(out_fields.map{ |f| f.is_a?(Symbol) ? titleize(f) : f },
:style => @xl_styles['Title'])
file_diff.diffs.sort_by{|k, v| v[:row] }.each do |key, diff|
sheet.add_row do |row|
chg = diff[:action]
out_fields.each_with_index do |field, i|
cell = nil
comment = nil
old = nil
style = case chg
when 'Add', 'Delete' then @xl_styles[chg]
else 0
end
d = diff[field]
if d.is_a?(Array)
old = d.first
new = d.last
if old.nil?
style = @xl_styles['Add']
else
style = @xl_styles[chg]
comment = old
end
elsif d
new = d
style = @xl_styles[chg] if i == 1
elsif file_diff.options[:include_matched]
style = @xl_styles['Matched']
d = file_diff.right[key] && file_diff.right[key][field]
end
case new
when String
if new =~ /^0+\d+(\.\d+)?/
# Don't let Excel auto-convert this to a number, as that
# will remove the leading zero(s)
cell = row.add_cell(new, :style => style, :type => :string)
else
cell = row.add_cell(new.encode('utf-8'), :style => style)
end
else
cell = row.add_cell(new, :style => style)
end
sheet.add_comment(:ref => cell.r, :author => 'Current', :visible => false,
:text => old.to_s.encode('utf-8')) if comment
end
end
end
sheet.column_info.each do |ci|
ci.width = 80 if ci.width > 80
end
xl_filter_and_freeze(sheet, freeze_cols)
end
end
# Freeze the top row and +freeze_cols+ of +sheet+.
def xl_filter_and_freeze(sheet, freeze_cols = 0)
sheet.auto_filter = "A1:#{Axlsx::cell_r(sheet.rows.first.cells.size - 1, sheet.rows.size - 1)}"
sheet.sheet_view do |sv|
sv.pane do |p|
p.state = :frozen
p.x_split = freeze_cols
p.y_split = 1
end
end
end
# Save +xl+ package to +path+
def xl_save(xl, path)
begin
xl.serialize(path)
path
rescue StandardError => ex
Console.puts ex.message, :red
raise "Unable to replace existing Excel file #{path} - is it already open in Excel?"
end
end
end
end
|
# Facebook Thread Message class
class FacebookMessage < ActiveRecord::Base
belongs_to :facebook_thread, :counter_cache => 'message_count'
belongs_to :facebook_account, :foreign_key => 'backup_source_id'
has_one :member, :through => :facebook_account
serialize :attachment
validates_presence_of :message_id, :author_id
acts_as_archivable :on => :created_at
acts_as_taggable_on :tags
acts_as_restricted :owner_method => :member
acts_as_commentable
acts_as_time_locked
include TimelineEvents
include CommonDateScopes
# thinking_sphinx
# TODO: Add backup source foreign key so that we can search with attribute
define_index do
indexes :body
has created_at, backup_source_id
end
serialize_with_options do
methods :url, :thumbnail_url, :subject
end
# Builds new object from Facebooker::MessageThread::Message object
# TODO: Convert it to a proxy object before passing
def self.build_from_proxy(backup_source_id, message)
self.new(:message_id => message.message_id.to_s,
:author_id => message.author_id,
:body => message.body,
:attachment => message.attachment,
:created_at => Time.at(message.created_time.to_i),
:backup_source_id => backup_source_id
)
end
def thumbnail_url
if has_media?
media.first['src']
end
end
def url
media.first['href'] if has_media?
end
def subject
facebook_thread.subject
end
protected
def parsed_attachment
end
def media
attachment.try(:media)
end
def has_media?
media && media.any?
end
end |
class Rsvp < ActiveRecord::Base
belongs_to :rsvpable, :polymorphic => true
belongs_to :user
validates_presence_of :first_name, :last_name, :email, :if => Proc.new{|r| r.user.nil?}
validates_numericality_of :attendee_count, :only_integer => true, :greater_than => 0, :allow_nil => true
validates_format_of :email, :with => EMAIL_ADDRESS_REGEX, :message => User::EMAIL_VALIDATION_MESSAGE
before_create :generate_display_id
after_create :register_with_et, :if => Proc.new{|r| r.user.nil?}
def cobrand
rsvpable.try(:article_instance).try(:cobrand)
end
def first_name
user.blank? ? self[:first_name] : (user.first_name || self[:first_name])
end
def last_name
user.blank? ? self[:last_name] : (user.last_name || self[:last_name])
end
def email
user.blank? ? self[:email] : (user.email || self[:email])
end
def cell_number
user.blank? ? self[:cell_number] : (user.phone_number || self[:cell_number])
end
protected
def generate_display_id
self.display_id = UUIDTools::UUID.timestamp_create.to_s
end
# no uer has been found. need to register with ET
def register_with_et
App.et["accounts"].each_pair do |account_name, account_config|
next unless account_config[:rsvp_guest_list]
ETSubscriberAdd.create!(
:account => account_name,
:target => self,
:properties => {
:list_id => account_config[:rsvp_guest_list],
:values => {
:email_address => self.email,
:cobrand => cobrand.short_name
}
}
)
end
end
end
|
class CreateMenuPages < ActiveRecord::Migration[5.1]
def change
create_table :menu_pages do |t|
t.integer :page_number
t.integer :full_height
t.integer :full_width
t.integer :image_id
t.string :uuid
t.references :menu
t.timestamps
end
end
end
|
module SurveyBuilder
module Questions
class Checkbox < Question
store_accessor :question_data, :helper_text, :options
def self.construct_question_data(raw_data)
return raw_data.permit(:options, :helper_text).to_json
end
def self.construct_answer_specs(raw_data)
return raw_data[:answer_specs]
end
def set_type
self.type = self.class.name
end
def validate_answer(answer)
question = parse_question_data
Rails.logger.info "#{question}"
answer = parse_answer_data(answer)
answer.each do |key, ans|
ans.each do |option|
unless (key.to_i >= 0 && key.to_i < question.count && JSON.parse(question[key.to_i]["options"]).find_index(option))
raise SurveyBuilder::InvalidAnswer
end
end
end
end
def parse_question_data
super
# The format for the json question_data is as follows:
# It will either be an array or an hash.
# If array, it is supposed to be a list of multiple radio choice questions. Each element of array will be a hash as below.
# If hash, it is a single question with radio choices.
# Each hash will be have the following format.
# {
# helper_text: ""
# options : ["A", "B", "C"]
# }
parsed_question = question_data
if Hash == parsed_question.class
parsed_question = [parsed_question]
end
parsed_question.each_with_index do |question, index|
question["index"] = index
end
parsed_question
end
def parse_answer_data(answer)
super(answer)
# The answer_data is supposed to be a hash with index being the key and response being the list of values selected
parsed_response = answer.answer_data
return parsed_response
end
def format_answer(response)
# response is supposed to be like this {"0"=>["A", "B", "C"], "1"=>["D", "E", "F", "G", "H"]}
resp = {}
response.each do |index, values|
resp[index.to_i] = values
end
puts "Resposne - #{resp}"
return resp
end
end
end
end |
# # encoding: utf-8
# Inspec test for recipe set_proxy::default
# The Inspec reference, with examples and extensive documentation, can be
# found at https://docs.chef.io/inspec_reference.html
unless os.windows?
describe user('root') do
it { should exist }
skip 'This is an example test, replace with your own test.'
end
end
describe port(80) do
it { should_not be_listening }
skip 'This is an example test, replace with your own test.'
end
describe os_env('http_proxy') do
its('content') { should eq "http://192.168.100.2" }
end
describe os_env('https_proxy') do
its('content') { should eq "https://192.168.100.2" }
end
|
#
# Copyright 2011 National Institute of Informatics.
#
#
# 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.
class NodeConfig < ActiveRecord::Base
validates_presence_of :node, :component, :state
validates_inclusion_of :state, :in => %w(init installed failed)
belongs_to :proposal
belongs_to :node
belongs_to :component
after_initialize :init
def init
self.state ||= "init"
end
end
|
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "johny #{n}" }
sequence(:email) { |n| "johny_#{n}@gmail.com" }
about "Let others speak for me."
first_name "John"
last_name "Markovich"
factory :user_with_stories do
ignore do
story_count 5
end
after(:create) do |user, evaluator|
create_list(:story, evaluator.story_count, user: user )
end
end
end
factory :story do
user
active true
url "https://www.google.me"
title "Titl"
description "Some description"
factory :innactive_stories do
active false
end
factory :stories_with_comments do
ignore do
comment_count 5
end
after(:create) do |story, evaluator|
create_list(:comment, evaluator.comment_count, story: story)
end
end
end
factory :comment do
story
user
comment "This is an amazing story!"
end
end |
class RsvpController < ApplicationController
def index
end
def new
@partial = nil
@code = params[:code]
if Guest.valid_and_redeemable?(@code)
@partial = render_to_string(template: 'shared/_rsvp', layout: false )
else
@partial = render_to_string(template: 'shared/_rsvp_used', layout: false)
end
respond_to do |format|
format.json { render json: { success: true, html: @partial } }
format.html { }
end
end
def create
@partial = nil
@guest_names = params[:guest_names]
@email_address = params[:email_addr]
@invitation_code = params[:invitation_code]
@number_attending = params[:number_attending]
@meal_order = params[:meal_order]
@attributes = {
guest_names: @guest_names,
email_address: @email_address,
meal_order: @meal_order,
number_attending: @number_attending,
rsvp: true
}
@guest = Guest.find_by_invitation_code(@invitation_code)
if (!@guest) || (@guest.rsvp)
@partial = render_to_string(template: 'shared/_rsvp_used', layout: false)
elsif @guest.update_attributes(@attributes)
RsvpMailer.guest_email(@guest_names, @email_address).deliver
RsvpMailer.notice_email(@guest_names, @invitation_code, @meal_order).deliver
@partial = render_to_string(template: 'shared/_rsvp_success', layout: false)
else
@partial = render_to_string(template: 'shared/_rsvp_error', layout: false)
end
respond_to do |format|
format.json { render json: { success: true, html: @partial } }
format.html { }
end
end
end
|
#!/usr/bin/env ruby
# This script uploads sourcemaps to Sentry so we can see symbol names for exceptions.
# It is based on this: https://github.com/expo/sentry-expo/blob/master/upload-sourcemaps.js
#
# We can't use the expo postPublish hook as suggested since we're self-hosting the app.
require "json"
path_to_credentials = ARGV.first
if path_to_credentials.nil?
puts "Usage: ./bin/sourcemap /path/to/sentry-credentials.json"
exit(1)
end
def read_json(path)
json = File.read(File.expand_path(path))
JSON.parse(json, symbolize_names: true)
end
credentials = read_json(path_to_credentials)
manifest = read_json("dist/android-index.json")
version = manifest.fetch(:revisionId)
env = [
"SENTRY_ORG=#{credentials.fetch(:organisation)}",
"SENTRY_PROJECT=#{credentials.fetch(:project)}",
"SENTRY_AUTH_TOKEN=#{credentials.fetch(:auth_token)}",
].join(" ")
success = system(<<~CMD)
(which sentry-cli || (curl -sL https://sentry.io/get-cli/ | bash)) && \
\
cp dist/android-*.js tmp/main.android.bundle && \
cp dist/android-*.map tmp/main.android.map && \
\
#{env} sentry-cli releases new #{version} && \
\
#{env} sentry-cli releases files #{version} upload-sourcemaps --rewrite \
tmp/main.android.*
CMD
exit(success ? 0 : 1)
|
require 'rails_helper'
describe 'titles/index.json.jbuilder' do
before(:each) do
@titles = assign(:titles, Kaminari.paginate_array(FactoryGirl.create_list(:title, 4)).page(1))
assign(:watching_ids, [@titles.first.id])
@options = assign(:options, page: 1)
end
it 'render json' do
render
json = MultiJson.decode response, symbolize_keys: true
expect(json[:pages]).to eq 1
expect(json[:options]).to eq page: 1
titles = json[:titles]
expect(titles.count).to eq 4
expect(titles.first[:id]).to eq @titles.first.id
expect(titles.first[:name]).to eq @titles.first.name
expect(titles.map { |t| t[:watch] }).to eq [true, false, false, false]
end
end
|
class Goal < ActiveRecord::Base
validates_presence_of :name
belongs_to :resolution
def self.completed_goals
where(completed: true)
end
def self.current_goals
where(completed: false)
end
end
|
require 'test_helper'
class Blade::RailsPluginTest < Minitest::Test
def setup
Blade.initialize!(interface: 'ci', plugins: { rails: {} }, load_paths: "test/javascripts/src")
@load_paths = Blade.config.load_paths
end
def test_that_it_has_a_version_number
refute_nil ::Blade::RailsPlugin::VERSION
end
def test_total_load_paths
assert 3, @load_paths.size
end
def test_concat_rails_assets
assert @load_paths.include?(Rails.application.assets.paths[0])
assert @load_paths.include?(Rails.application.assets.paths[1])
end
def test_keep_blade_config_file_paths
assert @load_paths.include?("test/javascripts/src")
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user, :logged_in?, :same_as_current_user?, :show_action?
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
!!current_user
end
def same_as_current_user?(user)
current_user.id == user.id
end
def require_user
unless logged_in?
flash[:error] = "Must be logged in to do that!"
redirect_back fallback_location: root_path
end
end
def show_action?
params[:action] == 'show'
end
def destroy_item(model, path, message = nil)
@obj = model.find_by(id: params[:id])
if @obj.blank?
flash[:alert] = "Cannot perform delete."
return redirect_to path
end
@obj.destroy
flash[:notice] = message || "The #{model.name.downcase} \"#{@obj.name}\" has been deleted."
redirect_to path
end
def update_item(obj, params, path)
if obj.update(params)
flash[:notice] = "Your #{obj.class.name.downcase} was successfully updated."
redirect_to path
else
render :edit
end
end
end
|
class AddColumnIpAddressToFondsTable < ActiveRecord::Migration
def self.up
add_column :fonds, :ip_address, :string
add_index :fonds, :ip_address
end
def self.down
remove_column :fonds, :ip_address
remove_index :fonds, :ip_address
end
end
|
class Admin < ActiveRecord::Base
attr_accessible :email, :password, :username
before_save :encrypt_psw
def encrypt_psw
self.password = Digest::SHA1.hexdigest(self.password)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate
#come back later
# before_action :authenticate, only: [:index]
helper_method :current_user
def current_user
return User.find(session[:user_id])
end
private
def authenticate
if !session[:is_signed_in]
redirect_to "/signin"
end
end
end
|
class LargestProductSeries
def initialize(data)
@data = data.to_s.chars
end
def series_of(chunk_size)
products = []
@data.each_cons(chunk_size) do |group|
products << group.map(&:to_i).reduce(:*)
end
products.max
end
end
|
class RemovePetFromProperties < ActiveRecord::Migration[6.1]
def change
remove_column :properties, :pet, :boolean
end
end
|
class Node
attr_reader :value, :children
def initialize(value)
@value = value
@children = []
end
def add_child(value)
n = Node.new(value)
@children << n
n
end
def dfs(value)
# if the given value is the same as this node - return self
# Otherwise call dfs on each child and see if they found it
# if the child found it, return the result
# otherwise move on to the next child
# If no child can find it, return nil
@returnMe = nil
if @value == value
@returnMe = self
return @returnMe
end
self.children.each do |x|
if x.value == value
@returnMe = x
return @returnMe
else
y = x.dfs(value)
unless y.nil?
return y
end
end
end
@returnMe
end
def bfs(value, queue = [])
if value == @value
return self
end
# if the given value is the same as this node return self
# Otherwise add all of this nodes children to the queue
# of nodes needed to be searched
returnMe = nil
queue += @children
if !queue.empty?
x = queue.shift
if x == value
returnMe = x
else
returnMe = x.bfs(value, queue)
end
end
returnMe
# While the queue is not empty
# grab the first element in the queue (and remove it)
# run bfs on that node with the proper argument and get the result
# if that node found what you're looking for, return the resulting node
# Otherwise, move on to the next node
#
# If the queue is empty and you haven't found it yet, return nil
end
end
@house = @door = Node.new("door")
@l_room = @house.add_child("living room")
@kitchen = @l_room.add_child("kitchen")
@tv = @l_room.add_child("TV")
@couch = @l_room.add_child("Couch")
@stairs = @l_room.add_child("Stairs")
@refrigerator = @kitchen.add_child("refrigerator")
@microwave = @kitchen.add_child("microwave")
@food = @kitchen.add_child("food")
@l_room2 = @stairs.add_child("2nd living room")
@bedroom1 = @l_room2.add_child("bedroom1")
@bedroom2 = @l_room2.add_child("bedroom2")
@bedroom3 = @l_room2.add_child("bedroom3")
|
class CreateExercises < ActiveRecord::Migration[6.0]
def change
create_table :exercises do |t|
t.string :name
t.datetime :date_performed
t.string :sets_reps_weights
t.integer :goal_id
t.integer :workout_id
t.timestamps
end
end
end
|
class Venda < ApplicationRecord
has_one :cliente
has_one :produto
validates :clienteId, presence: { message: 'é um campo obrigatório' }
validates :produtoId, presence: { message: 'é um campo obrigatório' }
validates :valorServico, length: {maximum: 6, message: 'excede o valor padrão de serviços'}
validates_numericality_of :valorServico, message: 'deve ser um número'
end
|
Rails.application.routes.draw do
resources :thumbnails
resources :portfolios
resources :tests
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_locale
def default_url_options
I18n.locale == I18n.default_locale ? { lang: nil } : { lang: I18n.locale }
end
def after_sign_in_path_for(resource)
flash[:notice] = "Привет, #{resource.first_name} #{resource.last_name}"
if resource.admin?
admin_tests_path
else
root_path
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :password) }
devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:first_name, :last_name, :email, :password, :current_password) }
end
private
def set_locale
I18n.locale = I18n.locale_available?(params[:lang]) ? params[:lang] : I18n.default_locale
end
end
|
class Order < ApplicationRecord
belongs_to :user
has_many :order_details, dependent: :destroy
enum status: {waiting: 0, delivering: 1, delivered: 2, cancel: 3}
before_save :update_total
scope :find_order_by_status, ->(status){where(status: status)}
def total
order_details.map{|od| od.valid? ? od.quantity * od.unit_price : 0}.sum
end
def reduce_quantity_product
@order_details = order_details
@order_details.each do |od|
@product = Product.find_by id: od.product_id
@product.update_attributes(quantity: (@product.quantity - od.quantity))
end
end
def restore_quantity_product
@order_details = order_details
@order_details.each do |od|
@product = Product.find_by id: od.product_id
@product.update_attributes(quantity: (@product.quantity + od.quantity))
end
end
private
def update_total
self[:total] = total
end
end
|
module EasyPatch
module VersionPatch
def self.included(base)
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
attr_accessor :css_shared
base.class_eval do
has_many :relations_from, :class_name => 'EasyVersionRelation', :foreign_key => 'version_from_id', :dependent => :delete_all
has_many :relations_to, :class_name => 'EasyVersionRelation', :foreign_key => 'version_to_id', :dependent => :delete_all
acts_as_easy_journalized :format_detail_reflection_columns => ['easy_version_category_id']
belongs_to :easy_version_category
before_validation :create_easy_version_relations
validate :validate_effective_date
validates :project_id, :presence => true
after_save :reschedule_following_versions
after_save :create_journal
attr_accessor :css_shared, :relation, :mass_operations_in_progress
safe_attributes 'relation', 'project_id', 'easy_version_category_id'
alias_method_chain :estimated_hours, :easy_extensions
def update_from_gantt_data(data)
gantt_date = self.class.parse_gantt_date(data['est'])
if gantt_date
self.effective_date = gantt_date
end
end
def update_issues_due_dates(xeffective_date_was)
if xeffective_date_was
self.fixed_issues.find(:all, :include => [:status], :conditions => ["#{IssueStatus.table_name}.is_closed = ? AND #{Issue.table_name}.due_date IS NOT NULL", false]).each do |i|
if i.due_date && self.effective_date && xeffective_date_was
journal = i.init_journal(User.current)
i.due_date = (i.due_date + (self.effective_date - xeffective_date_was).days)
i.save
end
end
else
self.fixed_issues.each do |i|
journal = i.init_journal(User.current)
i.due_date = self.effective_date
i.save
end
end
end
def self.update_version_from_gantt_data(data)
v = self.find(data['id'])
if v
v.update_from_gantt_data(data)
if v.save
nil
else
v
end
else
nil
end
end
def self.parse_gantt_date(date_string)
if date_string.match('\d{4},\d{1,2},\d{1,2}')
Date.strptime(date_string, '%Y,%m,%d')
end
end
def css_classes
css = 'version'
css << " #{self.status}"
css << " #{self.css_shared}" if self.css_shared
return css
end
def relations
@relations ||= (relations_from + relations_to).sort
end
def all_dependent_version(except=[])
except << self
dependencies = []
relations_from.each do |relation|
if relation.version_to && !except.include?(relation.version_to)
dependencies << relation.version_to
dependencies += relation.version_to.all_dependent_version(except)
end
end
dependencies
end
def create_easy_version_relations
if self.relation && self.relation['version_to_id']
[self.relation['version_to_id']].flatten.each do |version_id|
version = Version.where({ :id => version_id }).first
if self.relation['relation_type'] == 'precedes'
self.relations_from.build(:relation_type => 'precedes', :delay => self.relation['delay'], :version_to => version, :version_from => self)
else
self.relations_to.build(:relation_type => 'precedes', :delay => self.relation['delay'], :version_to => self, :version_from => version)
end
end
end
end
def soonest_start
@soonest_start ||= (
relations_to.collect{|relation| relation.successor_soonest_start} +
ancestors.collect(&:soonest_start)
).compact.max
end
def reschedule_after(date)
return if date.nil? || self.mass_operations_in_progress
if effective_date.nil? || effective_date < date
self.effective_date = date
save
reschedule_following_issues(date)
elsif effective_date > date
self.effective_date = date
reschedule_following_issues(date)
save
end
end
def reschedule_following_issues(date)
return if self.mass_operations_in_progress
self.fixed_issues.find(:all, :include => [:status], :conditions => ["#{IssueStatus.table_name}.is_closed = ? AND #{Issue.table_name}.due_date IS NOT NULL", false]).each do |issue|
journal = issue.init_journal(User.current)
issue.due_date = date
issue.save
end
end
def reschedule_following_versions
return if self.mass_operations_in_progress
self.relations_from.find(:all, :conditions => {:relation_type => EasyVersionRelation::TYPE_PRECEDES}).each do |rel|
if rel.delay
rel.set_version_to_dates
end
end
end
def validate_effective_date
if self.project && !self.effective_date.nil? && !self.project.easy_due_date.nil? && self.effective_date > self.project.easy_due_date
errors.add :effective_date, :before_project_end, :due_date => format_date(self.effective_date), :project_due_date => format_date(self.project.easy_due_date)
end
end
end
end
module InstanceMethods
def estimated_hours_with_easy_extensions
if EasySetting.value('issue_recalculate_attributes', self.project)
@estimated_hours ||= fixed_issues.leaves.sum(:estimated_hours).to_f
else
@estimated_hours ||= fixed_issues.sum(:estimated_hours).to_f
end
end
end
module ClassMethods
end
end
end
EasyExtensions::PatchManager.register_model_patch 'Version', 'EasyPatch::VersionPatch'
|
require "alphabet_calc/alphabet_digit"
module AlphabetCalc
class AlphabetNum
def initialize(input)
@digits = Array.new
if input.is_a?(Integer)
@digits.unshift AlphabetDigit.new(0) if input == 0
while input > 0 do
@digits.unshift AlphabetDigit.new( input % 26 )
input = input / 26
end
elsif input =~ /\A[a-z]+\z/
input.split('').each do |ch|
@digits.push AlphabetDigit.new(ch)
end
else
raise ArgumentError
end
end
def to_int
sum = 0
@digits.each do |digit|
sum = sum * 26
sum = sum + digit.to_int
end
return sum
end
def to_str
@digits.map{ |digit| digit.to_str }.join
end
end
end |
class TaskMailer < ApplicationMailer
default from: 'xargrigoris@gmail.com'
layout 'mailer'
def new_task(user, task)
@user = user
@task = task
mail(to: @user.email, subject: @task.name)
end
end
|
class GeocodeApi
# ApiKeys
ApiKeys = {
map_quest: 'Fmjtd%7Cluur206y2q%2Crw%3Do5-9ay2dy',
bing: 'Ao9yUqipvyK9Gyt1jZEiolDPDNQ4evUSSKlvUN7t0rx0iiD-u9uMNeHsojrRyNVY',
geonames: 'nomadop'
}
RegApis = [:google, :map_quest, :bing, :geonames, :multi]
def self.geocode address, api, opts = {}
raise 'No such api' unless RegApis.include?(api.to_sym)
geocoder = Geokit::Geocoders.const_get("#{api.to_s.camelize}Geocoder")
geocoder.key = GeocodeApi::ApiKeys[api.to_sym] if geocoder.respond_to?(:key)
geocoder.premium = false if geocoder.respond_to?(:premium)
args = [address]
if api.to_sym == :google
geocoder.api_key = GoogleApis.key
args << opts
end
geocoder.geocode(*args)
end
end |
# This migration comes from keppler_capsules (originally 20180802184153)
class CreateKepplerCapsulesCapsules < ActiveRecord::Migration[5.2]
def change
create_table :keppler_capsules_capsules do |t|
t.string :name
t.integer :position
t.datetime :deleted_at
t.timestamps
end
add_index :keppler_capsules_capsules, :deleted_at
end
end
|
FactoryGirl.define do
factory :room, aliases:[:test_chamber] do
name "Test Chamber"
description Forgery::LoremIpsum.paragraphs(3)
end
end |
$:.push File.expand_path("../lib", __FILE__)
require 'image_gps/version'
Gem::Specification.new do |s|
s.name = ImageGps::NAME
s.version = ImageGps::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Tom Kulmacz"]
s.email = ["tomek.kulmacz@gmail.com"]
s.homepage = "https://github.com/tkz79"
s.summary = %q{CL app to find JPEGs and extract their GPS coordinates}
s.description = %q{
image_gps.rb is a utility that finds all JPEGs inside of a folder recursively,
and extracts their EXIF GPS data if present. It will default to scanning the
pwd unless a directory is provided as an argument.
Results are written to a file in the pwd as the scan runs. CSV files will be
produced by default, use -html for HTML files instead. If the app is not
installed as a gem, HTML output requires configuration.
}
s.rubyforge_project = "db_backup"
s.files = %w(
bin/image_gps.rb
lib/image.rb
lib/scanner.rb
lib/image_gps/version.rb
lib/templates/csv.rb
lib/templates/html.rb
lib/templates/html/_header.html.erb
lib/templates/html/_row.html.erb
lib/templates/html/_footer.html.erb
)
s.executables = ['image_gps.rb']
s.add_development_dependency('aruba', '~> 0.14.6')
s.add_development_dependency('exifr', '~> 1.3', '>= 1.3.4')
s.add_development_dependency('rake', '~> 12.3', '>= 12.3.1')
s.add_development_dependency('rspec', '~> 3.7')
end
|
require 'spec_helper'
describe 'crashkernel fact' do
before :each do
Facter.clear
end
context 'kernel is linux' do
it 'returns crashkernel' do
allow(Facter::Core::Execution).to receive(:exec).with('uname -s').and_return('Linux')
allow(Facter).to receive(:value).with(:kdump_kernel_arguments).and_return(my_fixture_read('kernelargs-with-crash.txt'))
expect(Facter.fact(:crashkernel).value).to eq('131M@0M')
end
it 'returns false' do
allow(Facter::Core::Execution).to receive(:exec).with('uname -s').and_return('Linux')
allow(Facter).to receive(:value).with(:kdump_kernel_arguments).and_return(my_fixture_read('kernelargs-without-crash.txt'))
expect(Facter.fact(:crashkernel).value).to eq(false)
end
end
end
|
# == Schema Information
#
# Table name: scholarships
#
# id :integer not null, primary key
# name :string(255) default(""), not null
# status_id :integer default(1), not null
# end_date :datetime not null
# copy :text default("")
# terms :text default("")
# meta_description :text
# permalink :string(255) not null
# created_at :datetime not null
# updated_at :datetime not null
# submission_format :text default("")
# submission_prompt :text default("")
# thank_you :text default("")
# voting_start_date :datetime
# voting_end_date :datetime
# voting_title :string(255) default("Vote for the winner")
# voting_copy :text
# high_school_label :string(255)
# or_label_text :string(255)
# description_instructions :string(255)
# title_label :string(255)
# show_upload :boolean default(TRUE)
# show_video_url :boolean default(TRUE)
# show_or_label :boolean default(TRUE)
# show_title :boolean default(TRUE)
# require_authentication :boolean default(FALSE)
# logged_in_copy :text
#
require 'spec_helper'
describe Scholarship do
pending "add some examples to (or delete) #{__FILE__}"
end
|
module DungeonMaster
class Master
def self.provider_for(game, user, text)
if game.rounds.empty?
round = game.rounds.create :kind => 'password'
else
round = game.active_round
end
"::DungeonMaster::#{round.kind.capitalize}Provider".constantize.new(game, round, user, text)
end
attr :game, :round, :user, :text
def initialize(game, round, user, text)
@game = game
@round = round
@user = user
@text = text
end
def run
throw NotImplementedError
end
end
end |
require 'spec_helper'
describe 'sensu::repo::yum', :type => :class do
context 'ensure: present' do
let(:params) { { :ensure => 'present' } }
it { should contain_yumrepo('sensu').with(
'enabled' => 1,
'baseurl' => 'http://repos.sensuapp.org/yum/el/$releasever/$basearch/',
'gpgcheck' => 0,
'before' => 'Package[sensu]'
) }
end
context 'ensure: absent' do
let(:params) { { :ensure => 'absent' } }
it { should contain_yumrepo('sensu').with(
'enabled' => 'absent',
'before' => 'Package[sensu]'
) }
end
context 'ensure: foo' do
let(:params) { { :ensure => 'foo' } }
it { should contain_yumrepo('sensu').with(
'enabled' => 'absent',
'before' => 'Package[sensu]'
) }
end
end |
class SongSerializer < ActiveModel::Serializer
attributes :id, :title, :categories, :docs
has_many :docs
end
|
require 'rails_helper'
RSpec.feature "Users list" do
feature "as a registered admin" do
given! (:admin2) { create(:user, :admin, :registered, email: "margoulin@free.fr") }
given (:admin) { create(:user, :admin, :registered, lastname: "ADMIN") }
given! (:player) { create(:user, :player, :registered, lastname: "PLAYER") }
background :each do
log_in admin
visit users_path
end
scenario "should list the theater's band members" do
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
end
scenario "should show at least an administrator" do
expect(page.body).to have_text "Administrateur"
end
scenario "I should access everyone else's show page" do
expect(page.body).to have_link(text: player.full_name)
click_link(text: player.full_name)
expect(page.body).to have_selector("h2", text: player.full_name)
end
scenario "I should access my own edit page" do
click_link(text: admin.full_name)
expect(page.body).to have_selector(".container > h2.edit_user", text: admin.full_name)
expect(page.body).to have_selector("i.fa.fa-pencil")
next_url = "/users/#{ admin.id }/edit"
visit next_url
expect(page.body).to have_selector("h2", text: I18n.t('users.complementary'))
end
scenario "I should not be able to edit to somebody else's page" do
click_link(text: player.full_name)
expect(page.body).not_to have_selector("i.fa.fa-pencil")
end
end
feature "PROMOTE - status" do
given! (:admin) { create(:user, :admin, :registered) }
background :each do
log_in admin
end
scenario "with setup status, it proposes archived status" do
player = create(:user, :player, :invited)
visit user_path(player)
page.find('.users_promote').find("option[value='archived']").select_option
click_button(I18n.t('users.promote'))
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
expect(page.body).to have_text("RIP")
end
scenario "with invited status, it proposes archived status" do
player = create(:user, :player, :invited)
visit user_path(player)
page.find('.users_promote').find("option[value='archived']").select_option
click_button(I18n.t('users.promote'))
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
expect(page.body).to have_text("RIP")
end
scenario "with googled status, it proposes archived status" do
player = create(:user, :player, :googled)
visit user_path(player)
page.find('.users_promote').find("option[value='archived']").select_option
click_button(I18n.t('users.promote'))
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
expect(page.body).to have_text("RIP")
end
scenario "with registered status, it proposes archived status" do
player = create(:user, :player, :registered)
visit user_path(player)
page.find('.users_promote').find("option[value='archived']").select_option
click_button(I18n.t('users.promote'))
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
expect(page.body).to have_text("RIP")
end
scenario "with archived status, it proposes setup status" do
player = create(:user, :player, :archived)
visit user_path(player)
page.find('.users_promote').find("option[value='setup']").select_option
click_button(I18n.t('users.promote'))
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
expect(page.body).not_to have_text("RIP")
end
end
feature "PROMOTE - role" do
given! (:admin) { create(:user, :admin, :registered) }
background :each do
log_in admin
end
scenario "with setup status, it proposes archived status" do
player = create(:user, :player, :invited)
visit user_path(player)
page.find('.users_promote').find("option[value='admin']").select_option
click_button(I18n.t('users.promote'))
expect(page.body).to have_selector("h2", text: I18n.t('users.list'))
click_link(player.full_name)
expect(page.body).to have_text(I18n.t('enums.user.role.admin'))
end
end
feature "As visitor " do
scenario "getting INDEX it fails mouwhahahahaa" do
visit users_path
expect(page.body).not_to have_selector("h2", text: I18n.t('users.list'))
end
end
end
|
require "application_system_test_case"
class GalaxiesTest < ApplicationSystemTestCase
setup do
@galaxy = galaxies(:one)
end
test "visiting the index" do
visit galaxies_url
assert_selector "h1", text: "Galaxies"
end
test "creating a Galaxy" do
visit galaxies_url
click_on "New Galaxy"
fill_in "Name", with: @galaxy.name
click_on "Create Galaxy"
assert_text "Galaxy was successfully created"
click_on "Back"
end
test "updating a Galaxy" do
visit galaxies_url
click_on "Edit", match: :first
fill_in "Name", with: @galaxy.name
click_on "Update Galaxy"
assert_text "Galaxy was successfully updated"
click_on "Back"
end
test "destroying a Galaxy" do
visit galaxies_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Galaxy was successfully destroyed"
end
end
|
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module RSpec
module Matchers
class HasObjectFunction < MatchSupporter
def has_match?()
return false if @args.length == 0
#
# Note: If the method name is "test" then trying to invoke
# a method with name "test" on the given object will always
# fail whenever __send__ is used. There appears to be an
# actual method called test that belongs to a Ruby object.
#
method_name = obj_property(@expected)
ret_val = nil
invoked_method = false
# Try with arguments
begin
args = @args.clone; args.pop
ret_val = @object.__send__(method_name, *args)
invoked_method = true
rescue NoMethodError => nme
rescue ArgumentError => ae
end
# Try with no arguments
begin
if not invoked_method
ret_val = @object.__send__(method_name)
invoked_method = true
end
rescue NoMethodError => nme
rescue ArgumentError => ae
end
return false if not invoked_method
operator = @args[@args.length - 1]
if operator.kind_of? Lebowski::RSpec::Operators::Operator
@result = operator.evaluate(ret_val)
return true
end
@result = Lebowski::RSpec::Util.match?(@args[@args.length - 1], ret_val)
return true
end
private
def obj_property(sym)
["has_", "have_"].each do |prefix|
if sym.to_s =~ /^#{prefix}/
return sym.to_s.sub(prefix, "").to_sym
end
end
end
end
end
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.