text stringlengths 10 2.61M |
|---|
class RenameQueryTableToTable < ActiveRecord::Migration
def change
rename_table :query_tables, :tables
end
end
|
feature 'Peeps' do
scenario 'expect profile page to display all peeps' do
visit('/')
submit_peep
expect(page.current_path).to eq '/profile'
expect(page).to have_content 'My first test peep!'
end
scenario 'expect homepage to have display peeps when logged out' do
visit('/')
submit_peep
click_button 'Log out'
expect(page.current_path).to eq '/'
expect(page).to have_content 'My first test peep!'
end
scenario 'clicking on a peep displays the specific peep on profile page' do
visit('/')
submit_peep
expect(page.current_path).to eq '/profile'
expect(page).to have_content 'My first test peep!'
end
scenario 'clicking on a peep displays the specific peep on profile page' do
visit('/')
submit_peep
click_on 'My first test peep!'
expect(page.current_path).to eq '/peep/4'
expect(page).to have_content 'My first test peep!'
end
scenario 'clicking on a peep displays peeps author' do
visit('/')
submit_peep
click_on 'My first test peep!'
expect(page).to have_content 'Test'
end
end
|
#!/usr/bin/env ruby
#
# Created by nwind on 2008-1-4.
Name = File.basename(__FILE__)
def usage
"USAGE: #{Name} file_path
"
end
def px2em(file)
unless FileTest.exists?(file)
puts '#{ARGV[0]} doen\'t exist'
exit
end
styles = IO.read(file).gsub(/\s*-?\d*px/) do |px|
sprintf(" %.1fem", px[0..-3].to_f / 12)
end
outPutFile = File.open(file, 'r+')
outPutFile.puts styles
outPutFile.close
end
if ARGV.size == 1
px2em(ARGV[0])
else
puts usage
end
|
class MenusRole < ApplicationRecord
belongs_to :menu
belongs_to :role
end
|
require 'rails_helper'
RSpec.describe 'Cycle#create', :ledgers, type: :system do
before { log_in admin_attributes }
context 'when Term' do
it 'adds due date', js: true do
cycle_page = CyclePage.new type: :term
cycle_create id: 1, due_ons: [DueOn.new(month: 3, day: 25)]
expect(Cycle.first.due_ons.count).to eq 1
cycle_page.load id: 1
expect(cycle_page.title).to eq 'Letting - Edit Cycle'
cycle_page.button 'Add Due Date'
cycle_page.due_on order: 1, month: 9, day: 29
cycle_page.button 'Update Cycle'
expect(cycle_page).to be_success
expect(Cycle.first.due_ons.count).to eq 2
end
it 'removes due_date', js: true do
cycle_page = CyclePage.new type: :term
cycle_create id: 1, due_ons: [DueOn.new(month: 6, day: 24),
DueOn.new(month: 12, day: 25)]
expect(Cycle.first.due_ons.count).to eq 2
cycle_page.load id: 1
expect(cycle_page.title).to eq 'Letting - Edit Cycle'
cycle_page.button 'Delete Due Date'
cycle_page.button 'Update Cycle'
expect(cycle_page).to be_success
expect(Cycle.first.due_ons.count).to eq 1
end
end
end
|
require 'eventmachine'
require 'cairo'
module MiW
autoload :KeySym, "miw/keysym"
autoload :Layout, "miw/layout"
autoload :Menu, "miw/menu"
autoload :MenuBar, "miw/menu_bar"
autoload :MenuItem, "miw/menu_item"
autoload :MenuWindow, "miw/menu_window"
autoload :Model, "miw/model"
autoload :Pointe, "miw/point"
autoload :PopupMenu, "miw/popup_menu"
autoload :PopupMenuWindow, "miw/popup_menu_window"
autoload :Rectangle, "miw/rectangle"
autoload :ScrollBar, "miw/scroll_bar"
autoload :ScrollView, "miw/scroll_view"
autoload :SeparatorItem, "miw/separator_item"
autoload :Size, "miw/size"
autoload :SplitView, "miw/split_view"
autoload :StringView, "miw/string_view"
autoload :TableView, "miw/table_view"
autoload :TextView, "miw/text_view"
autoload :Theme, "miw/theme"
autoload :Util, "miw/util"
autoload :View, "miw/view"
autoload :ViewModel, "miw/view_model"
autoload :Window, "miw/window"
autoload :XCB, "miw/xcb"
MiW::PLATFORM = MiW::XCB
MOUSE_BUTTON_LEFT = 1
MOUSE_BUTTON_CENTER = 2
MOUSE_BUTTON_RIGHT = 3
MOUSE_WHEEL_UP = 4
MOUSE_WHEEL_DOWN = 5
MOUSE_STATE_SHIFT = 1
MOUSE_STATE_CTRL = 4
def self.run
if EM.reactor_running?
MiW::PLATFORM.setup_for_em
else
EM.run { MiW::PLATFORM.setup_for_em }
end
end
def self.get_mouse
PLATFORM.get_mouse
end
colors = Theme::Colors.new("default")
colors[:content_background] = "#111"
colors[:content_background_highlight] = "#9ff"
colors[:content_background_active] = "#4ff"
colors[:content_background_disabled] = "#eee"
colors[:content_forground] = "#bbb"
colors[:content_forground_highlight] = "#bbb"
colors[:content_forground_active] = "#bbb"
colors[:content_forground_disabled] = "#bbb"
colors[:control_background] = "#333"
colors[:control_background_highlight] = "#777"
colors[:control_background_active] = "#669"
colors[:control_background_disabled] = "#555"
colors[:control_forground] = "#888"
colors[:control_forground_highlight] = "#444"
colors[:control_forground_active] = "#bbb"
colors[:control_forground_disabled] = "#666"
colors[:control_border] = "#000"
colors[:control_border_highlight] = "#ccc"
colors[:control_border_active] = "#000"
colors[:control_border_disabled] = "#000"
colors[:control_inner_background] = "#111"
colors[:control_inner_background_highlight] = "#222"
colors[:control_inner_background_active] = "#111"
colors[:control_inner_background_disabled] = "#555"
colors[:control_inner_forground] = "#000"
colors[:control_inner_forground_highlight] = "#000"
colors[:control_inner_forground_active] = "#000"
colors[:control_inner_forground_disabled] = "#888"
colors[:control_inner_border] = "#000"
colors[:control_inner_border_highlight] = "#ccc"
colors[:control_inner_border_active] = "#000"
colors[:control_inner_border_disabled] = "#000"
DEFAULT_COLORS = colors
fonts = Theme::Fonts.new("default")
fonts[:monospace] = "monospace 11"
fonts[:document] = "sans-serif 11"
fonts[:ui] = "sans-serif 11"
DEFAULT_FONTS = fonts
# pseudo
def self.colors
DEFAULT_COLORS
end
def self.fonts
DEFAULT_FONTS
end
end
|
module Sales
class Sale < ApplicationRecord
self.table_name = "sales"
belongs_to :sales_person
belongs_to :company
end
end
|
class AddTopicIdToReasons < ActiveRecord::Migration[5.0]
def change
create_table :procedures do |p|
p.belongs_to :topic, null: false
p.belongs_to :patient, null: false
p.belongs_to :clinician
p.integer :visit_id
p.timestamps null: false
end
create_table :complications do |c|
c.belongs_to :topic, null: false
c.belongs_to :patient, null: false
c.integer :time_ago
c.string :time_ago_scale
c.datetime :absolute_start_date
c.integer :visit_id
c.timestamps null: false
end
create_table :diagnoses do |d|
d.belongs_to :topic, null: false
d.belongs_to :patient, null: false
d.integer :time_ago
d.string :time_ago_scale
d.datetime :absolute_start_date
d.integer :visit_id
d.timestamps null: false
end
change_table :medications do |m|
m.belongs_to :topic, null: false
m.integer :time_ago
m.string :time_ago_scale
m.datetime :absolute_start_date
end
end
end
|
json.topic do
json.extract! @topic, :name, :id
end
|
class ChangeUrlTypeToText < ActiveRecord::Migration
def up
change_column :hyperlinks, :url, :text, null: false
end
def down
change_column :hyperlinks, :url, :string, null: false
end
end
|
class Theme
class Template < File
class << self
def valid?(path)
@@template_types.keys.include?(extname(path))
end
def subdirs
%w(templates)
end
end
def text?
true
end
def valid?
self.class.valid?(localpath) && valid_path?
end
def valid_path?
!!(%r((#{self.class.subdirs.join('|')})/) =~ localpath) && super
end
def extname
ext = basename.to_s.split('.')
ext.shift
'.' + ext.join('.')
end
def subdir
Pathname.new type.pluralize
end
def type
'template'
end
end
end |
# хелпер
# по большей части используются просто обертки для бутстраповых элементов,
# которые используются повсеместно
module Admin::AdminHelper
delegate :url_helpers, to: 'Rails.application.routes'
def empty_list
content_tag :div, 'Пусто', class: 'well'
end
# все языки
def get_languages
Language.all
end
# вернуть все языки кроме текущей
def get_another_locale
get_languages.select do |l|
l != @locale
end
end
def get_alignments
{
'center center' => 'По центру',
'left center' => 'По левому краю',
'right center' => 'По правому краю',
'center top' => 'По центру и верхнему краю',
'left top' => 'По левому верхнему краю',
'right top' => 'По правому вехнему краю',
'center bottom' => 'По нижнему краю по центру',
'left bottom' => 'По левому нижнему краю',
'right bottom' => 'По правому нижнему краю'
}
end
def save_or_update item
if item.id then
'Сохранить'
else
'Добавить'
end
end
def link_list items
render partial: 'admin/parts/link_list', locals: {items: items}
end
def with_pic item, image, size=:admin
render partial: 'admin/parts/with_pic', locals: {item: item, image: image, size: size}
end
def image_field item, property, form, size=[], options={}
render partial: 'admin/parts/form_avatar', locals: {
image: item.send(property),
item: item,
property: property,
form: form,
field: form.file_field(property),
size: size,
options: options
}
end
def locale_icon locale
result = []
result << content_tag(:i, '', class: ('icon icon-' + (get_item.locale_exists(locale.slug) ? 'pencil' : 'plus')))
result << ' '
result << locale.name
result.join.html_safe
end
def get_path route, params, additional = false
url_helpers.send(route, params.symbolize_keys)
end
def icon(type, white = false)
content_tag :i, '', class: 'icon-' + type + (' icon-white' if white).to_s
end
def trash_icon(white = false)
icon "trash", white
end
def down_icon(white = false)
icon "arrow-down", white
end
def up_icon(white = false)
icon "arrow-up", white
end
def pencil_icon(white = false)
icon "pencil", white
end
def plus_icon(white = false)
icon "plus", white
end
def tabs items, options={}
render partial: 'admin/parts/tabs', locals: {items: items, options: options}
end
def get_item
eval '@' + get_item_name
end
def get_item_name dirty=false
name = controller_name
if !dirty and ['good_categories', 'post_categories'].include? name
name = 'categories'
end
name.singularize
end
def language_prompt
render partial: 'admin/parts/language_prompt', locals: {item: get_item}
end
def language_select(route=nil)
route ||= 'languaged_' + controller.class.name.split('::').first.downcase + '_' + get_item_name(true)
render partial: 'admin/parts/language_select', locals: {route: route + '_path', item: get_item}
end
def form_errors form
render partial: 'admin/parts/form_errors', locals: {object: form.object}
end
def language_input form
render partial: 'admin/parts/form_language_input', locals: {form: form}
end
def category_types
['goods', 'blogs']
end
def tab_pane name, options={}, &block
content = capture(&block)
render partial: 'admin/parts/tab_pane', locals: {content: content, name: name, options: options}
end
# название текущего роута
def current_route
Rails.application.routes.router.recognize(request) do |route, _|
return route.name
end
end
def tab_contents &block
content = capture(&block)
content_tag :div, content, class: 'tab-content'
end
end |
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
Gem::Specification.new 'require_pattern', '1.1.2' do |s|
s.summary = 'Requires files based on a pattern in a robust and optimistic manner.'
s.authors = ['Tom Wardrop']
s.email = 'tom@tomwardrop.com'
s.homepage = 'http://github.com/wardrop/RequirePattern'
s.license = 'MIT'
s.files = Dir.glob(`git ls-files`.split("\n") - %w[.gitignore])
s.test_files = Dir.glob('spec/spec.rb')
s.rdoc_options = %w[--line-numbers --inline-source --title Scorched --encoding=UTF-8]
s.required_ruby_version = '>= 1.9.3'
s.add_development_dependency 'maxitest'
s.add_development_dependency 'mocha'
end
|
#---
# Excerpted from "Rails 4 Test Prescriptions",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/nrtest2 for more book information.
#---
require 'rails_helper'
include Warden::Test::Helpers
describe "task display" do
fixtures :all
before(:each) do
projects(:bluebook).roles.create(user: users(:user))
users(:user).update_attributes(twitter_handle: "noelrap")
tasks(:one).update_attributes(user_id: users(:user).id,
completed_at: 1.hour.ago)
login_as users(:user)
end
it "shows a gravatar", :vcr do
visit project_path(projects(:bluebook))
url = "http://pbs.twimg.com/profile_images/40008602/head_shot_bigger.jpg"
within("#task_#{tasks(:one).id}") do
expect(page).to have_selector(".completed", text: users(:user).email)
expect(page).to have_selector("img[src='#{url}']")
end
end
end
|
# The controller for schedule related pages and actions, such as the schedule page
# as well as creating and editing categories
# TODO: Most requests should enforce user being signed in, as data can't be made anonymously
class SchedulesController < ApplicationController
# Only admins can access the beta scheduler
before_action :authorize_admin!, only: [:show_beta]
after_action :allow_iframe, only: :show
def show
if params[:uid] # user viewing another user's schedule
@user = User.find(params[:uid])
else # user viewing their own schedule
redirect_to(user_session_path, alert: "You have to be signed in to do that!") && return unless user_signed_in?
@user = current_user
@read_only = false
end
@embedded = true if params[:iframe]
end
def save
new_event_ids = {}
params[:events].each do |obj|
# If an event ID is passed, this event is already in the DB and exists
existing_event = obj["eventId"].present?
if existing_event
evnt = Event.find(obj["eventId"].to_i)
else
evnt = Event.new
evnt.user = current_user
evnt.group = Group.find(obj["groupId"]) if obj["groupId"].present?
end
evnt.name = obj["name"]
evnt.repeat = obj["repeatType"]
evnt.date = Time.find_zone("UTC").parse(obj["startDateTime"])
evnt.end_date = Time.find_zone("UTC").parse(obj["endDateTime"])
evnt.repeat_start = obj["repeatStart"].blank? ? nil : Date.parse(obj["repeatStart"])
evnt.repeat_end = obj["repeatEnd"].blank? ? nil : Date.parse(obj["repeatEnd"])
evnt.repeat_exceptions = obj["breaks"].map { |id| RepeatException.find(id) } if obj["breaks"]
evnt.description = obj["description"] || ""
evnt.location = obj["location"] || ""
evnt.category_id = obj["categoryId"].to_i
if existing_event
authorize! :edit, evnt
else
authorize! :create, evnt
end
evnt.save!
new_event_ids[obj["tempId"]] = evnt.id if obj["eventId"].blank? # if this is not an existing event
end
render json: new_event_ids
end
private
# Allow any site to embed this page in an <iframe>
def allow_iframe
response.headers["X-Frame-Options"] = "ALLOWALL"
end
end
|
class CreatePieces < ActiveRecord::Migration
def change
create_table :pieces do |t|
t.string :type
t.string :subtype
t.string :color
t.string :brand
t.string :size
t.date :date_purchased
t.decimal :price
t.string :source
t.attachment :picture
t.text :note
t.references :location
t.references :user
t.timestamps
end
end
end
|
# frozen_string_literal: true
class UserPolicy < ApplicationPolicy
ADMIN_ATTRIBUTES = %i[
email
password
password_confirmation
admin
first_name
last_name
company
phone
address_id
coordinator_id
status
profession
printer_ids
tag_ids
printers_attributes
address_attributes
product_assignments_attributes
].freeze
OWN_ATTRIBUTES = %i[
password
password_confirmation
first_name
last_name
company
phone
address_id
status
profession
printer_ids
printers_attributes
address_attributes
].freeze
def permitted_attributes
if user.admin?
ADMIN_ATTRIBUTES
elsif self?
OWN_ATTRIBUTES
else
[]
end
end
def index?
user.admin? || user.volunteer?
end
def show?
self? || user.admin? || user.volunteer?
end
def update?
self? || user.admin?
end
def edit?
update?
end
def self?
record.id == user.id
end
class Scope < Scope
def resolve
scope.all
end
end
end
|
require 'spec_helper'
describe 'sensu::server', :type => :class do
let(:title) { 'sensu::server' }
context 'defaults' do
let(:facts) { { :fqdn => 'testhost.domain.com' } }
it { should contain_sensu_redis_config('testhost.domain.com').with_ensure('absent') }
it { should contain_sensu_api_config('testhost.domain.com').with_ensure('absent') }
it { should contain_sensu_dashboard_config('testhost.domain.com').with_ensure('absent') }
end
context 'defaults (enabled)' do
let(:facts) { { :fqdn => 'testhost.domain.com', :ipaddress => '1.2.3.4' } }
let(:params) { { :enabled => 'true' } }
it { should contain_file('/etc/sensu/conf.d/checks').with_ensure('directory').with_require('Package[sensu]') }
it { should contain_file('/etc/sensu/conf.d/handlers').with_ensure('directory').with_require('Package[sensu]') }
it { should contain_sensu_redis_config('testhost.domain.com').with(
'host' => 'localhost',
'port' => '6379',
'ensure' => 'present'
) }
it { should contain_sensu_api_config('testhost.domain.com').with(
'host' => 'localhost',
'port' => '4567',
'ensure' => 'present'
) }
it { should contain_sensu_dashboard_config('testhost.domain.com').with(
'host' => '1.2.3.4',
'port' => '8080',
'user' => 'admin',
'password' => 'secret',
'ensure' => 'present'
) }
end # Defaults
context 'setting params (enabled)' do
let(:facts) { { :fqdn => 'testhost.domain.com', :ipaddress => '1.2.3.4' } }
let(:params) { {
:redis_host => 'redishost',
:redis_port => '2345',
:api_host => 'apihost',
:api_port => '3456',
:dashboard_host => 'dashhost',
:dashboard_port => '5678',
:dashboard_user => 'user',
:dashboard_password => 'mypass',
:enabled => 'true'
} }
it { should contain_sensu_redis_config('testhost.domain.com').with(
'host' => 'redishost',
'port' => '2345',
'ensure' => 'present'
) }
it { should contain_sensu_api_config('testhost.domain.com').with(
'host' => 'apihost',
'port' => '3456',
'ensure' => 'present'
) }
it { should contain_sensu_dashboard_config('testhost.domain.com').with(
'host' => 'dashhost',
'port' => '5678',
'user' => 'user',
'password' => 'mypass',
'ensure' => 'present'
) }
end # setting params
context 'purge_configs' do
let(:params) { { :purge_config => true, :enabled => true } }
it { should contain_file('/etc/sensu/conf.d/redis.json').with_ensure('present') }
it { should contain_file('/etc/sensu/conf.d/api.json').with_ensure('present') }
it { should contain_file('/etc/sensu/conf.d/dashboard.json').with_ensure('present') }
end
end
|
class CreateLunch < ActiveRecord::Migration
def change
create_table :lunches do |t|
t.string :price
t.references :lunchable, polymorphic: true
end
end
end
|
class MyTradeShipProfitObject
attr_accessor :view_context, :show_profit
def initialize(view_context, show_profit: )
self.view_context = view_context
self.show_profit = show_profit
end
def table_first_header
view_context.content_tag('th', colspan: (show_profit ? 3 : 2)) do
if !show_profit
view_context.link_to('show profit', '#', data: { 'option-column': 'show' })
end
end
end
def table_middle_header
if @show_profit
view_context.content_tag('th') { '利益' }
else
view_context.content_tag('th', data: { 'option-column': 'profit' }) { }
end
end
def table_body
if @show_profit
return view_context.content_tag('td') { yield }
else
return view_context.content_tag('td', data: { 'option-column': 'profit' }) { yield }
end
end
end
|
class Api::V1::BaseController < ApplicationController
before_action :doorkeeper_authorize!
protect_from_forgery with: :null_session
rescue_from CanCan::AccessDenied do |e|
head :forbidden
end
private
def current_user
current_resource_owner
end
def current_resource_owner
@current_resource_owner ||= User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end
end
|
FactoryGirl.define do
factory :role do
sequence(:name) { |i| "Role #{i + 1}" }
event_id { Event.first.id }
end
end
|
class CreateExport < ActiveRecord::Migration
def up
create_table :exports do |t|
t.references :user, index: true
t.string :export_type
t.string :prefix
t.boolean :active, default: true
t.datetime :started_at
t.datetime :finished_at
t.string :error_msg
t.timestamps
end
Export.create [
{user_id: 18, export_type: 'openmarine'},
{user_id: 276, export_type: 'openmarine'},
{user_id: 33, export_type: 'openmarine'},
{user_id: 52, export_type: 'openmarine'},
{user_id: 262, export_type: 'openmarine'},
]
end
end
|
class AddRecordactionToActionlogs < ActiveRecord::Migration
def change
add_column :actionlogs, :recordaction_id, :integer
add_index :actionlogs, :recordaction_id
end
end
|
class AddOrderIdToReservation < ActiveRecord::Migration[5.0]
def change
add_column :reservations, :order_id, :string, :default => "11111111"
end
end
|
#!/usr/bin/env ruby
require 'marc'
require 'ostruct'
abort "Usage: ruby yrb.rb <MARC_FILE>" unless ARGV.size == 1
MAX_EACH_FILE = 20
reader = MARC::Reader.new ARGV[0], extenal_encoding: "UTF-8"
accounts = {
'175009': 'US Approvals',
'175010': 'US Firms',
'175059': 'UK Approvals',
'175060': 'UK Firms',
'175050': 'Ebooks',
'175051': 'SAIS Ebooks',
'175052': 'AFL Ebooks'
}.map {|key, str| [key, OpenStruct.new(name: str, records: [])] }.to_h
total = 0
for record in reader
# Insert a title if it doesn't have one. It's needed later for sorting
record.append MARC::DataField.new('245', ' ', ' ', ['a', 'ZZZ No title']) if record['245'].nil? and record['245']['a'].nil?
# Insert 035
record.append(MARC::DataField.new('035', ' ', ' ')) if record['035'].nil?
if record['970'] and record['970']['l']
record['035'].append MARC::Subfield.new('a', "ybp#{record['970']['l']}")
else
puts "Can't find 970$l: ", record
end
record.append(MARC::DataField.new('505', ' ' , ' ', ['a', 'TITLE ON ORDER']))
# reorder the fields
record.fields.sort! { |a, b| a.tag <=> b.tag }
if record['970'] and record['970']['x']
account_id = record['970']['x'].to_sym
if accounts.has_key? account_id # record['970']['x'].to_s
accounts[account_id].records << record
else
puts 'Invalid account code in 970$x', record['970']['x']
end
else
puts "Can't find 970$x", record
end
total += 1
end
abort "Didn't read any record" if total == 0
puts "\nNumber of records read: "
accounts.values.each do | order |
printf "%-15s %s\n", order.name, order.records.size
end
puts "\nTotal number of records: #{total}"
output_dir = "data/#{Time.now.strftime("%Y-%m-%d")}"
Dir.mkdir output_dir unless File.directory? output_dir
total_written = 0
accounts.values.each do | order |
if order.records.any?
order.records.uniq! { |r| r['035']['a'] }
order.records.sort! { |a, b| a['245']['a'] <=> b['245']['a'] }
order.records.each_slice(MAX_EACH_FILE).with_index { |group, index|
writer = MARC::Writer.new "#{output_dir}/#{order.name.downcase.tr(' ', '_')}_#{index+1}.mrc"
group.each { |record| writer.write record }
writer.close
}
total_written += order.records.size
end
end
puts "\nNumber of records written: "
accounts.values.each do | order |
printf "%-15s %s\n", order.name, order.records.size if order.records.any?
end
puts "\nTotal number of records written: #{total_written}"
|
# 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)
Response.destroy_all # ALWAYS have in our seed file (generally)
AnswerChoice.destroy_all # this cleans our database so when we seed, we will only have these seeds
Question.destroy_all # clears out all of our other data
Poll.destroy_all # destroy things in reverse order
User.destroy_all
u1 = User.create!(username: 'KenTing')
u2 = User.create!(username: 'IsaacNam')
u3 = User.create!(username: 'DarthVader')
p1 = Poll.create!(title: 'Food', user_id: u1.id)
p2 = Poll.create!(title: 'Animal', user_id: u2.id)
p3 = Poll.create!(title: 'Game', user_id: u3.id)
p4 = Poll.create!(title: 'Movie', user_id: u1.id)
q1 = Question.create!(question: 'Favorite food?', poll_id: p1.id)
q2 = Question.create!(question: 'Favorite recipe?', poll_id: p1.id)
q3 = Question.create!(question: 'Cutest animal?', poll_id: p2.id)
q4 = Question.create!(question: 'Favorite game?', poll_id: p3.id)
q5 = Question.create!(question: 'Favorite movie?', poll_id: p4.id)
ac1 = AnswerChoice.create!(answer: "Sushi", question_id: q1.id)
ac2 = AnswerChoice.create!(answer: "Pizza", question_id: q1.id)
ac3 = AnswerChoice.create!(answer: "Pork Fried Rice", question_id: q2.id)
ac4 = AnswerChoice.create!(answer: "Shakshush", question_id: q2.id)
ac5 = AnswerChoice.create!(answer: "Dog", question_id: q3.id)
ac6 = AnswerChoice.create!(answer: "Cat", question_id: q3.id)
ac7 = AnswerChoice.create!(answer: "Final Fantasy", question_id: q4.id)
ac8 = AnswerChoice.create!(answer: "Smash Bros", question_id: q4.id)
ac9 = AnswerChoice.create!(answer: "Inception", question_id: q5.id)
ac10 = AnswerChoice.create!(answer: "Dark Knight", question_id: q5.id)
r1 = Response.create!(answer_id: ac1.id, user_id: u1.id)
r2 = Response.create!(answer_id: ac2.id, user_id: u2.id)
r3 = Response.create!(answer_id: ac7.id, user_id: u3.id)
r4 = Response.create!(answer_id: ac10.id, user_id: u1.id)
r5 = Response.create!(answer_id: ac3.id, user_id: u2.id)
|
class ProjectsController < ApplicationController
before_action :fetch_project, only: [:show, :update, :destroy]
before_action :handle_already_enabled, only: [:create]
before_action :authenticate_user!, raise: false
def new
@organization_names = [current_user.github_id].concat(github_service.organization_names)
end
def search
repo_full_name = search_params[:org].present? ? "#{search_params[:org]}/#{search_params[:repo_name]}" :
"#{github_service.client.user[:login]}/#{search_params[:repo_name]}"
@searched_repo = github_service.repo(repo_full_name)
fetch_gitemit_enabled_repos
render :partial => "projects/search_results"
end
def create
@project = Project.new(name: creation_params[:name], owner: creation_params[:org])
@project.actions = GithubAction::DEFAULT_ACTIONS
@project.enabled_by = current_user.github_id
begin
ActiveRecord::Base.transaction do
if @project.save
current_user.projects << @project
if gitemit_manage_success?
flash[:notice] = 'Gitemit has been enabled for this project'
redirect_to @project
end
else
render json: {errors: @project.errors.full_messages} and return
end
end
rescue => exception
flash[:error] = GithubExceptionParser.new(exception).process
redirect_to request.referrer
end
end
def show
@project_carrier = ProjectCarrier.new(@project, project_carrier_options)
end
def update
project_update_service = ProjectUpdateService.new(@project, params)
if project_update_service.update_project
flash[:notice] = 'Project Updated successfully'
else
flash[:error] = 'Failed to update project'
end
redirect_to @project
end
def destroy
if @project.destroy && gitemit_manage_success?
redirect_to new_project_path, notice: "#{@project.owner}/#{@project.name} deleted."
end
end
private
def fetch_project
@project = Project.where(id: params[:id]).first!
end
def gitemit_manage_success?
GitemitManager.manage(@project.repo_full_name, current_user.github_access_token, params[:action])
end
def fetch_branches_to_update
github_service.repo_branch_names(@project.repo_full_name) - ["master"]
end
def gitemit_team_service
@_gitemit_team_service ||= GitemitTeamService.new(github_service, Array.wrap(@searched_repo))
end
def fetch_gitemit_enabled_repos
gitemit_team_service.gitemit_enabled_repo_names
@locally_enabled_repos = gitemit_team_service.locally_enabled_repos
@remotely_enabled_repos = gitemit_team_service.remotely_enabled_repos
@repos_without_admin_access = gitemit_team_service.repos_without_admin_access
end
def handle_already_enabled
project = Project.where(name: params[:name], owner: params[:owner]).first
if project.present?
flash[:notice] = "Gitemit is already enabled by #{project.enabled_by}"
redirect_to root_path and return
end
end
def project_carrier_options
{
actions: GithubAction::AVAILABLE_ACTIONS,
branches: fetch_branches_to_update
}
end
def repo_full_name
if params[:org].present?
"#{params[:org]}/#{params[:repo_name]}"
else
username = github_service.client.user[:login]
"#{username}/#{params[:repo_name]}"
end
end
def search_params
params.require(:search).permit(:org, :repo_name)
end
def creation_params
params.require(:project).permit(:name, :org)
end
end
|
class ItemOptionAddon < ActiveRecord::Base
attr_accessible :item_option_id, :name, :price, :is_selected, :is_deleted
belongs_to :item_option
has_many :order_item_options
validates :name , length:{minimum: 1, message:"^Addon Name can't be blank"}
validates :price ,:presence =>true
default_scope :order => "id"
def display_price_with_float_format
self.price.to_f
end
end
|
require 'erb'
require File.expand_path(File.join(File.dirname(__FILE__), 'dependencies'))
class PardotListAddProspectV1
def initialize(input)
# Set the input document attribute
@input_document = REXML::Document.new(input)
# Store the info values in a Hash of info names to values.
@info_values = {}
REXML::XPath.each(@input_document,"/handler/infos/info") { |item|
@info_values[item.attributes['name']] = item.text
}
# Retrieve all of the handler parameters and store them in a hash attribute
# named @parameters.
@parameters = {}
REXML::XPath.match(@input_document, 'handler/parameters/parameter').each do |node|
@parameters[node.attribute('name').value] = node.text.to_s
end
@enable_debug_logging = @info_values['enable_debug_logging'] == 'Yes'
end
def execute()
api_key = get_api_key(@info_values['email'], @info_values['password'], @info_values['api_user_key'])
user_key = @info_values['api_user_key']
# Get the email address and ensure there are no leading/trailing whitespace
email_address = (@parameters['email'] || "").strip
# Initializing the parameter list with
params = {
'api_key' => api_key,
'user_key' => user_key
}
list_name = "list_" + @parameters["list_id"]
params[list_name] = "1"
if @enable_debug_logging
puts "Updating the prospect to subscribe it to the list with the API list name of #{@parameters['list_name']}"
puts "---------------------"
puts "PARAMS: #{params}"
puts "---------------------"
end
begin
result = RestClient.get "https://pi.pardot.com/api/prospect/version/3/do/update/email/#{ERB::Util.url_encode(email_address)}", {:params => params}
rescue RestClient::BadRequest => error
raise StandardError, error.inspect
end
puts result if @enable_debug_logging
doc = REXML::Document.new(result)
# Check if the prospect has been added to the list. If it has not been,
# throw an error
prospect_object = doc.elements["rsp"].elements["prospect"]
if prospect_object.elements["lists"] == nil
raise StandardError, "Unknown Error: The prospect #{email_address} was not added to the list with the id of #{@parameters['list_id']}"
else
list_added = false
REXML::XPath.match(doc, 'rsp/prospect/lists/list_subscription/list/id').each do |list_id|
if list_id.text == @parameters['list_id']
list_added = true
break
end
end
if list_added == false
raise StandardError, "Unknown Error: The prospect #{email_address} was not added to the list with the id of #{@parameters['list_id']}"
end
end
return "<results/>"
end
def get_api_key(email, password, api_user_key)
puts "Getting a current API key" if @enable_debug_logging
params = {
'email' => email,
'password' => password,
'user_key' => api_user_key
}
result = RestClient.post("https://pi.pardot.com/api/login/version/3",params)
doc = REXML::Document.new(result)
puts result
api_key = ""
REXML::XPath.match(doc, 'rsp/api_key').each do |node|
api_key = node.text.to_s
end
return api_key
end
# This is a template method that is used to escape results values (returned in
# execute) that would cause the XML to be invalid. This method is not
# necessary if values do not contain character that have special meaning in
# XML (&, ", <, and >), however it is a good practice to use it for all return
# variable results in case the value could include one of those characters in
# the future. This method can be copied and reused between handlers.
def escape(string)
# Globally replace characters based on the ESCAPE_CHARACTERS constant
string.to_s.gsub(/[&"><]/) { |special| ESCAPE_CHARACTERS[special] } if string
end
# This is a ruby constant that is used by the escape method
ESCAPE_CHARACTERS = {'&'=>'&', '>'=>'>', '<'=>'<', '"' => '"'}
end
|
%w{dovecot-common dovecot-imapd}.each do |p|
package p do
action :install
end
end
service "dovecot" do
supports :restart => true, :start => true, :stop => true
action :nothing
end
template "/etc/dovecot/passwd" do
source "passwd.erb"
mode "0640"
owner "root"
group "root"
variables ({
:domains => node[:dovecot][:domains]
})
end
template "/etc/dovecot/users" do
source "users.erb"
mode "0644"
owner "root"
group "root"
variables ({
:domains => node[:dovecot][:domains],
:mail_folder => node[:dovecot][:mail_folder]
})
end
template "/etc/dovecot/dovecot.conf" do
source "conf.erb"
mode "0644"
owner "root"
group "root"
variables ({
:base_dir => node[:dovecot][:base_dir],
:protocols => node[:dovecot][:protocols],
:disable_plaintext_auth => node[:dovecot][:disable_plaintext_auth],
:log_timestamp => node[:dovecot][:log_timestamp],
:ssl_disable => node[:dovecot][:ssl_disable],
:login_greeting => node[:dovecot][:login_greeting],
:mail_location => node[:dovecot][:mail_location],
:valid_chroot_dirs => node[:dovecot][:valid_chroot_dirs],
:auth_default => node[:dovecot][:auth_default]
})
notifies :restart, "service[dovecot]"
end
|
require 'SimpleCov'
SimpleCov.start
require_relative '../lib/invoice_item_repository'
RSpec.describe InvoiceItemRepository do
before :each do
@iir = InvoiceItemRepository.new('./spec/fixture_files/invoice_item_fixture.csv')
end
it 'exists' do
expect(@iir).to be_an_instance_of(InvoiceItemRepository)
end
it 'can create invoice item object' do
expect(@iir.all[0]).to be_an_instance_of(InvoiceItem)
end
it 'returns a list of invoice items' do
expect(@iir.all.length).to eq(15)
end
it 'can find invoice item by id' do
expect(@iir.find_by_id(2).item_id).to eq(1)
end
it 'can find all invoice items by item id' do
expect(@iir.find_all_by_item_id(5).length).to eq(2)
expect(@iir.find_all_by_item_id(1).length).to eq(4)
end
it 'can find all invoice items by invoice id' do
expect(@iir.find_all_by_invoice_id(1).length).to eq(1)
expect(@iir.find_all_by_invoice_id(2).length).to eq(3)
end
it 'can find revenue by invoice id' do
expect(@iir.find_revenue_by_invoice_id(3)).to eq(3032)
end
it 'can create a new invoice item object' do
new = @iir.create({
:item_id => 4,
:invoice_id => 4,
:quantity => 250,
:unit_price => 1875
})
expect(@iir.all.length).to eq(16)
expect(new.id).to eq(16)
end
it 'can update invoice item attributes by id' do
data = { :quantity => 5000 }
@iir.update(4, data)
expect(@iir.find_by_id(4).quantity).to eq(5000)
expect(@iir.find_by_id(4).unit_price_to_dollars).to eq(20.00)
expect(@iir.find_by_id(4).updated_at).to_not eq(@iir.find_by_id(4).created_at)
end
it 'can delete invoice item by id' do
@iir.delete(6)
expect(@iir.all.length).to eq(14)
end
end
|
class AdvanceSearch < ActiveRecord::Base
def transactions
@transactions||=find_transactions
end
# Start Date getter
def start_date_string
start_date.strftime("%m/%d/%Y") unless start_date.blank?
end
#setter
def start_date_string=(start_date_str)
self.start_date=Date.strptime(start_date_str,'%m/%d/%Y')
rescue ArgumentError
@start_date_invalid=true
end
# End Date
def end_date_string
end_date.strftime("%m/%d/%Y") unless end_date.blank?
end
def end_date_string=(end_date_str)
self.end_date=Date.strptime(end_date_str,'%m/%d/%Y')
rescue ArgumentError
@end_date_invalid=true
end
def validate
errors.add(:start_date, "is invalid") if @start_date_invalid
errors.add(:end_date,"is invalid") if @end_date_invalid
end
####
private
def find_transactions
Spending.where(conditions)
end
def keyword_conditions
["spendings.title LIKE ?", "%#{keyword}%"] unless keyword.blank?
end
def minimum_price_conditions
["spendings.price >= ?", minimum_price] unless minimum_price.blank?
end
def maximum_price_conditions
["spendings.price <= ?", maximum_price] unless maximum_price.blank?
end
def start_date_conditions
["spendings.transaction_date_d >= ?", start_date] unless start_date.blank?
end
def end_date_conditions
["spendings.transaction_date_d <= ?", end_date] unless end_date.blank?
end
def conditions
[conditions_clauses.join(' AND '), *conditions_options]
end
def conditions_clauses
conditions_parts.map { |condition| condition.first }
end
def conditions_options
conditions_parts.map { |condition| condition[1..-1] }.flatten
end
def conditions_parts
private_methods(false).grep(/_conditions$/).map { |m| send(m) }.compact
end
end
|
class User < ActiveRecord::Base
has_secure_password
has_many :airports
has_many :reviews, through: :airports
end
|
class Quote < ApplicationRecord
validates :author, presence: true
validates :content, presence: true
# scope for searching for author and content
# where - like ? allows for a little more flexible search query?
# need % for the string interpolation for for it to work with the api call?
scope :search_author, -> (author) { where("author like ?", "%#{author}%")}
scope :search_content, -> (content) { where("content like ?", "%#{content}%")}
end
|
# frozen_string_literal: true
require 'spec_helper'
class Example
include Capybara::DSL
include CapybaraErrorIntel::DSL
def has_selector_test?
has_selector?(:css, 'h1', text: 'test')
end
def has_text_test?
has_text?('test_text')
end
def has_title_test?
has_title?('test_title')
end
end
describe CapybaraErrorIntel::DSL do
describe '#has_selector?' do
it 'returns heuristic error message when element is not found' do
expect do
allow(Capybara).to receive(:current_session) { '<h1>Hello</h1>' }
expect(Example.new).to have_selector_test
end.to raise_error(
/expected to find visible css "h1" with text "test" but there were no matches. Also found "Hello", which matched the selector but not all filters./
)
end
it 'returns true when element is found' do
allow(Capybara).to receive(:current_session) { '<h1>test</h1>' }
expect(Example.new).to have_selector_test
end
end
describe '#has_text?' do
it 'returns heuristic error message when text is not found' do
subject = Example.new
allow(Capybara).to receive(:current_session) { '<h1>test</h1>' }
expect { subject.has_text_test? }.to raise_error(
RSpec::Expectations::ExpectationNotMetError,
'expected to find text "test_text" in "test"'
)
end
it 'returns true when text is found' do
subject = Example.new
allow(Capybara).to receive(:current_session) { '<h1>test_text</h1>' }
expect(subject).to have_text_test
end
end
describe '#has_title?' do
it 'returns heuristic error message when title does not match' do
subject = Example.new
allow(Capybara).to receive(:current_session) { '<head><title>test</title></head>' }
expect { subject.has_title_test? }.to raise_error(
RSpec::Expectations::ExpectationNotMetError,
'expected "test" to include "test_title"'
)
end
it 'returns true when title is found' do
subject = Example.new
allow(Capybara).to receive(:current_session) { '<head><title>test_title</title></head>' }
expect(subject).to have_title_test
end
end
end
|
require 'spec_helper'
describe JobSphere do
context 'fields' do
it { should have_db_column(:name).of_type(:string) }
end
context 'mass assignment' do
it { should_not allow_mass_assignment_of(:id) }
it { should allow_mass_assignment_of(:name) }
it { should_not allow_mass_assignment_of(:created_at) }
it { should_not allow_mass_assignment_of(:updated_at) }
end
before(:each) do
@job_sphere = FactoryGirl.build(:job_sphere)
end
context 'validations' do
let(:job_sphere) { FactoryGirl.build(:job_sphere, id: 1, name: 'Business') }
let(:job_sphere2) { FactoryGirl.build(:job_sphere, id: 1, name: 'Business') }
it 'should be valid' do
@job_sphere.should be_valid
end
it 'should not be valid without name' do
@job_sphere.name = nil
@job_sphere.should_not be_valid
end
it 'should not be valid without unique name' do
job_sphere.save!
job_sphere.should be_valid
job_sphere2.should_not be_valid
end
end
end |
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "Montblanc#{n}" }
sequence(:email) { |n| "iloveinks#{n}@gmail.com" }
password 'password'
admin false
end
factory :ink do
sequence(:color_name){ |n| "Baystate Blue #{n}" }
manufacturer "Noodler's"
description 'A pigmented ink that will totally destroy pens if given the chance'
line 'Awesome Ink'
end
factory :user_ink do
association :ink
association :user
color_family 'Blue'
is_cartridge false
is_bottled true
bottle_size 89
num_bottles 1
favorite true
will_sell false
end
end
|
require 'test_helper'
class PcrInspectionsControllerTest < ActionDispatch::IntegrationTest
setup do
@pcr_inspection = pcr_inspections(:one)
end
test "should get index" do
get pcr_inspections_url
assert_response :success
end
test "should get new" do
get new_pcr_inspection_url
assert_response :success
end
test "should create pcr_inspection" do
assert_difference('PcrInspection.count') do
post pcr_inspections_url, params: { pcr_inspection: { clinic_id: @pcr_inspection.clinic_id, remarks: @pcr_inspection.remarks, result: @pcr_inspection.result, subject_id: @pcr_inspection.subject_id } }
end
assert_redirected_to pcr_inspection_url(PcrInspection.last)
end
test "should show pcr_inspection" do
get pcr_inspection_url(@pcr_inspection)
assert_response :success
end
test "should get edit" do
get edit_pcr_inspection_url(@pcr_inspection)
assert_response :success
end
test "should update pcr_inspection" do
patch pcr_inspection_url(@pcr_inspection), params: { pcr_inspection: { clinic_id: @pcr_inspection.clinic_id, remarks: @pcr_inspection.remarks, result: @pcr_inspection.result, subject_id: @pcr_inspection.subject_id } }
assert_redirected_to pcr_inspection_url(@pcr_inspection)
end
test "should destroy pcr_inspection" do
assert_difference('PcrInspection.count', -1) do
delete pcr_inspection_url(@pcr_inspection)
end
assert_redirected_to pcr_inspections_url
end
end
|
class RemovePhotosCountFromPhotos < ActiveRecord::Migration[5.1]
def change
remove_column :photos, :photos_count, :decimal
end
end
|
class WithoutLayout::PostsBaseController < PostsBaseController
def render_json_to_page_changes
render 'posts/show.html.erb'
response.content_type = "application/json"
response.body = {
:body => response.body,
:title => @post.title,
:sharing_head => @sharing_head.to_hash
}.to_json
end
end
|
class Comment < ActiveRecord::Base
attr_accessible :content
belongs_to :commentable, :inverse_of => :comments, :polymorphic => true
belongs_to :user, :inverse_of => :comments
validates_presence_of :user, :user_id
validates_presence_of :commentable, :commentable_id, :commentable_type
validates_presence_of :content
end
|
require 'spec_helper'
# find all parameters that don't have default values and put in here
# ensure validation occurs
describe Puppet::Type.type(:certmonger_certificate) do
let(:valid_booleans) { [true, false, 'true', 'false'] }
context 'with empty name' do
let(:name) { '' }
it 'raises ArgumentError if name is empty' do
expect do
Puppet::Type.type(:certmonger_certificate).new(name: name,
ensure: :present)
end.to raise_error(Puppet::Error)
end
end
context 'with valid name' do
let(:name) do
'some_name'
end
let(:type_instance) do
#
Puppet::Type.type(:certmonger_certificate).new(name: name)
end
describe :name do
it 'has a name parameter' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:name)
).to eq(:param)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(name: name,
ensure: :present)
end.not_to raise_error
end
end
describe :force_resubmit do
it 'has a force_resubmit parameter' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:force_resubmit)
).to eq(:param)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
force_resubmit: 'some_bad_value'
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
valid_booleans.each do |value|
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
force_resubmit: value
)
end.not_to raise_error
end
end
end
describe :wait do
it 'has a wait parameter' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:wait)
).to eq(:param)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
wait: 'some_bad_value'
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
valid_booleans.each do |value|
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
wait: value
)
end.not_to raise_error
end
end
end
describe :ignore_ca_errors do
it 'has a ignore_ca_errors parameter' do
expect(
Puppet::Type.type(
:certmonger_certificate
).attrtype(:ignore_ca_errors)
).to eq(:param)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
ignore_ca_errors: 'some_bad_value'
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
valid_booleans.each do |value|
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
ignore_ca_errors: value
)
end.not_to raise_error
end
end
end
describe :cleanup_on_error do
it 'has a cleanup_on_error parameter' do
expect(
Puppet::Type.type(
:certmonger_certificate
).attrtype(:cleanup_on_error)
).to eq(:param)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
cleanup_on_error: 'some_bad_value'
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
valid_booleans.each do |value|
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
cleanup_on_error: value
)
end.not_to raise_error
end
end
end
describe :certfile do
it 'has a certfile property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:certfile)
).to eq(:property)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
certfile: ''
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
certfile: 'some_value'
)
end.not_to raise_error
end
end
describe :keyfile do
it 'has a keyfile property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:keyfile)
).to eq(:property)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
keyfile: ''
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
keyfile: 'some_value'
)
end.not_to raise_error
end
end
describe :ca do
it 'has a ca property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:ca)
).to eq(:property)
end
it 'raises ArgumentError if not valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name,
ensure: :present,
ca: ''
)
end.to raise_error(Puppet::Error)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, ca: 'some_value'
)
end.not_to raise_error
end
end
describe :hostname do
it 'has a hostname property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:hostname)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, hostname: 'some_value'
)
end.not_to raise_error
end
end
describe :principal do
it 'has a principal property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:principal)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, principal: 'some_value'
)
end.not_to raise_error
end
end
describe :dnsname do
it 'has a dnsname property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:dnsname)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, dnsname: 'some_value'
)
end.not_to raise_error
end
end
describe :status do
it 'has a status property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:status)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, status: 'some_value'
)
end.not_to raise_error
end
end
describe :keybackend do
it 'has a keybackend property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:keybackend)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, keybackend: 'some_value'
)
end.not_to raise_error
end
end
describe :certbackend do
it 'has a certbackend property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:certbackend)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, certbackend: 'some_value'
)
end.not_to raise_error
end
end
describe :presave_cmd do
it 'has a presave_cmd property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:presave_cmd)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, presave_cmd: 'some_value'
)
end.not_to raise_error
end
end
describe :postsave_cmd do
it 'has a postsave_cmd property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:postsave_cmd)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, postsave_cmd: 'some_value'
)
end.not_to raise_error
end
end
describe :key_size do
it 'has a key_size property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:key_size)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, key_size: 'some_value'
)
end.not_to raise_error
end
end
describe :ca_error do
it 'has a ca_error property' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:ca_error)
).to eq(:property)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, ca_error: 'some_value'
)
end.not_to raise_error
end
end
describe :profile do
it 'has a profile parameter' do
expect(
Puppet::Type.type(:certmonger_certificate).attrtype(:profile)
).to eq(:param)
end
it 'validates and pass if valid value' do
expect do
Puppet::Type.type(:certmonger_certificate).new(
name: name, ensure: :present, ca_error: 'some_value'
)
end.not_to raise_error
end
end
end
end
|
class VoteOption < ActiveRecord::Base
belongs_to :poll
validates :title, presence: true
has_many :votes, dependent: :destroy
end
|
require "rails_helper"
require "nokogiri"
RSpec.describe ApplicationInstance, type: :model do
describe "create application" do
before :each do
@site = create(:site)
@name = "An Example application"
@key = "example"
@application = create(:application, name: @name, key: @key)
end
it "uses the provided lti key" do
lti_key = "atomic-key"
@application_instance = create(:application_instance, lti_key: lti_key, site: @site, application: @application)
expect(@application_instance.key).to eq(lti_key)
expect(@application_instance.lti_key).to eq(lti_key)
domain = "#{@application.key}.#{Rails.application.secrets.application_root_domain}"
expect(@application_instance.domain).to eq(domain)
end
it "sets a default lti key" do
@application_instance = create(:application_instance, lti_key: nil, site: @site, application: @application)
expect(@application_instance.lti_key).to eq(@application_instance.key)
end
it "generates a key based on the site and application" do
@application_instance = create(:application_instance, lti_key: nil, site: @site, application: @application)
expect(@application_instance.key).to eq("#{@site.key}-#{@application.key}")
end
it "sets a default domain" do
@application_instance = create(
:application_instance,
lti_key: nil,
domain: nil,
site: @site,
application: @application,
)
application_instance_domain = "#{@application.key}.#{Rails.application.secrets.application_root_domain}"
expect(@application_instance.domain).to eq(application_instance_domain)
end
it "sets a default secret" do
@application_instance = create(:application_instance, site: @site, application: @application)
expect(@application_instance.lti_secret).to be_present
end
it "sets a default tenant to the lti_key" do
@application_instance = create(:application_instance, site: @site, application: @application)
expect(@application_instance.tenant).to eq(@application_instance.lti_key)
end
it "sets anonymous to the value from application" do
@application.anonymous = true
@application.save!
@application_instance = create(:application_instance, site: @site, application: @application)
expect(@application_instance.anonymous).to eq(true)
end
it "doesn't change the tenant" do
@application_instance = create(
:application_instance,
site: @site,
application: @application,
tenant: "bfcoder",
)
expect(@application_instance.tenant).to_not eq(@application_instance.lti_key)
expect(@application_instance.tenant).to eq("bfcoder")
end
it "sets a valid lti_key using the key" do
key = "a-test"
application = create(:application, key: key)
@application_instance = create(:application_instance, lti_key: nil, site: @site, application: application)
expect(@application_instance.lti_key).to eq("#{@site.key}-#{key}")
end
it "doesn't set lti_key if the lti_key is already set" do
lti_key = "the-lti-key"
@application_instance = create(
:application_instance,
site: @site,
lti_key: lti_key,
)
expect(@application_instance.lti_key).to eq(lti_key)
end
it "sets the config to the application default_config if blank" do
app = create(:application, default_config: { foo: :bar })
app_instance = create(:application_instance, application: app)
expect(app_instance.config).to eq app.default_config
end
it "keeps the config to as entered" do
app = create(:application, default_config: { foo: :bar })
app_instance = create(:application_instance, application: app, config: { foo: :baz })
expect(app_instance.config).to eq("foo" => "baz")
end
it "sets the lti_config to the application lti_config if blank" do
app = create(:application, lti_config: { foo: :bar })
app_instance = create(:application_instance, application: app)
expect(app_instance.lti_config).to eq app.lti_config
end
it "keeps the lti_config to as entered" do
app = create(:application, lti_config: { foo: :bar })
app_instance = create(:application_instance, application: app, lti_config: { foo: :baz })
expect(app_instance.lti_config).to eq("foo" => "baz")
end
it "is anonymous if the application is anonymous" do
app = create(:application, anonymous: true)
app_instance = create(:application_instance, application: app)
expect(app_instance.anonymous).to eq(app.anonymous)
end
it "requires a site" do
expect do
create(:application_instance, site: nil, lti_key: "test")
end.to raise_exception(ActiveRecord::RecordInvalid)
end
it "creates a schema upon creation" do
expect(Apartment::Tenant).to receive(:create)
@application_instance = create :application_instance
end
it "does not allow the name to be changed after creation" do
@application_instance = create(:application_instance)
@application_instance.lti_key = "new-lti-key"
expect(@application_instance.valid?).to be false
end
it "generates the lti xml config" do
lti_config = {
title: "LTI Starter App",
description: "The Atomic Jolt LTI Starter app",
privacy_level: "public",
icon: "oauth_icon.png",
}
app = create(:application, lti_config: lti_config)
application_instance = create(:application_instance, application: app)
xml = application_instance.lti_config_xml
doc = Nokogiri::XML(xml)
doc.xpath("//lticm:property").each do |lti_property|
if lti_property.attributes["name"].value == "privacy_level"
expect(lti_property.children.text).to eq("public")
elsif lti_property.attributes["name"].value == "domain"
expect(lti_property.children.text).to eq(application_instance.domain)
end
end
end
it "generates the lti xml config with privacy_level anonymous" do
lti_config = {
title: "LTI Starter App",
description: "The Atomic Jolt LTI Starter app",
privacy_level: "public",
icon: "oauth_icon.png",
}
app = create(:application, lti_config: lti_config)
application_instance = create(:application_instance, application: app, anonymous: true)
xml = application_instance.lti_config_xml
doc = Nokogiri::XML(xml)
doc.xpath("//lticm:property").each do |lti_property|
if lti_property.attributes["name"].value == "privacy_level"
expect(lti_property.children.text).to eq("anonymous")
elsif lti_property.attributes["name"].value == "domain"
expect(lti_property.children.text).to eq(application_instance.domain)
end
end
end
end
describe "match_application_instance" do
let(:client_id) { FactoryBot.generate(:client_id) }
let(:deployment_id) { FactoryBot.generate(:deployment_id) }
let(:iss) { "https://canvas.instructure.com" }
let(:lms_url) { FactoryBot.generate(:url) }
let!(:site) { FactoryBot.create(:site, url: lms_url) }
let!(:application) { FactoryBot.create(:application) }
let!(:lti_install) { FactoryBot.create(:lti_install, iss: iss, client_id: client_id, application: application) }
context "application instance already has an lti deployment" do
it "connects the lti deployment and returns the application instance" do
application_instance = FactoryBot.create(:application_instance, application: application)
other_deployment_id = "other"
application_instance.lti_deployments.create!(lti_install: lti_install, deployment_id: other_deployment_id)
ret = described_class.match_application_instance(lti_install, deployment_id)
expect(ret).to eq(application_instance)
end
end
context "application instance does not have an lti deployment" do
it "throws" do
expect {
application_instance = FactoryBot.create(:application_instance, application: application)
ret = described_class.match_application_instance(lti_install, deployment_id)
lti_deployment = application_instance.lti_deployments.first
}.to raise_error(ApplicationInstanceNotFoundError)
end
end
end
describe ".by_client_and_deployment" do
context "when there is a matching LtiInstall" do
let(:client_id) { FactoryBot.generate(:client_id) }
let(:deployment_id) { FactoryBot.generate(:deployment_id) }
let(:iss) { "https://canvas.instructure.com" }
let(:lms_url) { FactoryBot.generate(:url) }
let!(:site) { FactoryBot.create(:site, url: lms_url) }
let(:application) { FactoryBot.create(:application) }
let!(:lti_install) { FactoryBot.create(:lti_install, iss: iss, client_id: client_id, application: application) }
context "when there isn't a matching ApplicationInstance" do
before do
ai = FactoryBot.create(:application_instance, application: application, site: site)
dep = LtiDeployment.create(deployment_id: "foo", application_instance: ai, lti_install: lti_install)
end
it "does not create a new ApplicationInstance" do
expect do
described_class.by_client_and_deployment(client_id, deployment_id, iss)
end.to change(described_class, :count).by(0)
end
it "associates the ApplicationInstance with the correct site" do
application_instance = described_class.by_client_and_deployment(client_id, deployment_id, iss)
expect(application_instance.site).to eq(site)
end
it "creates an LtiDeployment" do
expect do
described_class.by_client_and_deployment(client_id, deployment_id, iss)
end.to change(LtiDeployment, :count).from(1).to(2)
end
it "associates the LtiDeployment with the correct ApplicationInstance" do
application_instance = described_class.by_client_and_deployment(client_id, deployment_id, iss)
lti_deployment = LtiDeployment.last
expect(lti_deployment.application_instance).to eq(application_instance)
end
it "associates the LtiDeployment with the correct LtiInstall" do
described_class.by_client_and_deployment(client_id, deployment_id, iss)
lti_deployment = LtiDeployment.last
expect(lti_deployment.lti_install).to eq(lti_install)
end
it "gives the LtiDeployment the correct deployment_id" do
described_class.by_client_and_deployment(client_id, deployment_id, iss)
lti_deployment = LtiDeployment.last
expect(lti_deployment.deployment_id).to eq(deployment_id)
end
end
end
end
describe "#token_url" do
let(:customer_canvas_url) { "https://customer.instructure.com" }
let(:site) { FactoryBot.create(:site, url: customer_canvas_url) }
let(:application_instance) { FactoryBot.create(:application_instance, site: site) }
let(:client_id) { FactoryBot.generate(:client_id) }
def create_lti_install(iss, token_url)
FactoryBot.create(
:lti_install,
application: application_instance.application,
iss: iss,
client_id: client_id,
token_url: token_url,
)
end
context "when the URL is not a Canvas URL" do
let(:iss) { "https://www.sakaii.com" }
let(:token_url) { "https://www.sakaii.com/login/oauth2/token" }
before do
create_lti_install(iss, token_url)
end
it "returns the token_url from the LtiInstall record" do
result = application_instance.token_url(iss, client_id)
expect(result).to eq(token_url)
end
end
context "when the URL is a Canvas URL" do
let(:iss) { "https://canvas.instructure.com" }
let(:token_url) { "https://canvas.instructure.com/login/oauth2/token" }
before do
create_lti_install(iss, token_url)
end
it "returns the customer specific token_url" do
result = application_instance.token_url(iss, client_id)
expect(result).to eq("#{customer_canvas_url}/login/oauth2/token")
end
end
context "when the URL is a Canvas Beta URL" do
let(:iss) { "https://canvas.instructure.com" }
let(:token_url) { "https://canvas.beta.instructure.com/login/oauth2/token" }
before do
create_lti_install(iss, token_url)
end
it "returns the customer specific token_url" do
result = application_instance.token_url(iss, client_id)
expect(result).to eq("#{customer_canvas_url}/login/oauth2/token")
end
end
end
end
|
class MemberPresenter < BasePresenter
presents :member
def profile_full_name_field
text_field_tag :profile_full_name, [], size: 35,
placeholder: "Start typing and profile names will appear...",
autofocus: true, class: 'text'
end
end |
TAX = {"北海道" => 0.0685, "東日本" => 0.08, "西日本" => 0.0625, "四国" => 0.04, "九州" => 0.0825}
DISCOUNT = {1000 => 0.03, 5000 => 0.05, 7000 => 0.07, 10000 => 0.10, 50000 => 0.15}
def discount_rate sum
if (sum < 1000)
return 0
elsif ( sum < 5000 )
return 0.03
elsif ( sum < 7000 )
return 0.05
elsif ( sum < 10000 )
return 0.07
elsif ( sum < 50000 )
return 0.1
else
return 0.15
end
end
price_str = ARGV[0]
num_str = ARGV[1]
area = ARGV[2]
price = price_str.to_i
num = num_str.to_i
sum = price * num
tax = TAX[area]
discount = discount_rate(sum)
amount = sum * ( 1 + tax)
puts "price:#{price}"
puts "num:#{num}"
puts "area:#{area}"
puts "sum:#{sum}"
puts "tax:#{tax}"
puts "amount:#{amount}"
puts "discount#{discount}"
def discount_rate sum
if (sum < 1000)
return 0
elsif ( sum < 5000 )
return 0.03
elsif ( sum < 7000 )
return 0.05
elsif ( sum < 10000 )
return 0.07
elsif ( sum < 50000 )
return 0.1
else
return 0.15
end
end
|
class Size < ActiveRecord::Base
attr_accessible :atlas_id, :level, :label, :default_radius
belongs_to :atlas
has_many :tags
def self.atlas(index)
where(:atlas_id => index)
end
end
|
require_relative 'test_helper'
class SeasonStatsTest < Minitest::Test
def setup
game_path = './data/games.csv'
team_path = './data/teams.csv'
game_teams_path = './data/game_teams.csv'
locations = {
games: game_path,
teams: team_path,
game_teams: game_teams_path
}
@stat_tracker = StatTracker.from_csv(locations)
@season_stats = SeasonStats.new(@stat_tracker)
end
def test_it_exists
assert_instance_of SeasonStats, @season_stats
end
def test_group_by_coach
assert_equal 34, @season_stats.group_by_coach("20122013").keys.count
end
def test_coach_wins
assert_equal 34, @season_stats.coach_wins("20122013").keys.count
end
def test_can_get_games_from_season
assert_equal 1612, @season_stats.games_from_season("20122013").count
end
def test_winningest_coach
assert_equal "Claude Julien", @season_stats.winningest_coach("20132014")
assert_equal "Alain Vigneault", @season_stats.winningest_coach("20142015")
end
def test_worst_coach
assert_equal "Peter Laviolette", @season_stats.worst_coach("20132014")
assert_includes ["Ted Nolan", "Craig MacTavish"], @season_stats.worst_coach("20142015")
end
def test_it_can_group_by_team_id
assert_equal 30, @season_stats.find_by_team_id("20132014").count
end
def test_it_can_calculate_goals_to_shots_ratio
assert_equal 30, @season_stats.goals_to_shots_ratio_per_season("20122013").count
end
def test_it_can_find_the_most_accurate_team_id
assert_equal 24, @season_stats.find_most_accurate_team("20132014")
end
def test_it_can_find_most_accurate_team_name
@season_stats.stubs(:find_most_accurate_team).returns(24)
assert_equal "Real Salt Lake", @season_stats.most_accurate_team("20132014")
@season_stats.stubs(:find_most_accurate_team).returns(20)
assert_equal "Toronto FC", @season_stats.most_accurate_team("20142015")
end
def test_it_can_find_the_least_accurate_team
assert_equal 9, @season_stats.find_least_accurate_team("20132014")
end
def test_it_can_find_least_accurate_team_name
@season_stats.stubs(:find_least_accurate_team).returns(9)
assert_equal "New York City FC", @season_stats.least_accurate_team("20132014")
@season_stats.stubs(:find_least_accurate_team).returns(53)
assert_equal "Columbus Crew SC", @season_stats.least_accurate_team("20142015")
end
def test_it_can_calculate_total_tackles
assert_equal 30, @season_stats.total_tackles("20132014").count
end
def test_it_can_find_the_team_with_most_tackles
assert_equal 26, @season_stats.find_team_with_most_tackles("20132014")
end
def test_can_find_team_name_with_most_tackles_in_season
@season_stats.stubs(:find_team_with_most_tackles).returns(26)
assert_equal 'FC Cincinnati', @season_stats.most_tackles("20132014")
@season_stats.stubs(:find_team_with_most_tackles).returns(26)
assert_equal 'Seattle Sounders FC', @season_stats.most_tackles("20142015")
end
def test_it_can_find_the_team_with_fewest_tackles
assert_equal 1, @season_stats.find_team_with_fewest_tackles("20132014")
end
def test_can_find_team_name_with_fewest_tackles_in_season
@season_stats.stubs(:find_team_with_fewest_tackles).returns(1)
assert_equal 'Atlanta United', @season_stats.fewest_tackles("20132014")
@season_stats.stubs(:find_team_with_fewest_tackles).returns(30)
assert_equal 'Orlando City SC', @season_stats.fewest_tackles("20142015")
end
end
|
class Exchange::Huobi < Exchange::Base
attr_reader :user, :currency
def initialize(user, currency)
@user = user
@currency = currency
end
def id
'huobi'
end
def balance
begin
result = client.contract_balance('USDT')
balance = result['data'].find {|i| i['valuation_asset'] == 'USDT'}
balance['balance'].to_d
rescue
0.to_d
end
end
def place_order(client_order_id:, volume:, direction:, offset:, lever_rate:)
result = client.contract_place_order(
order_id: client_order_id,
contract_code: contract_code,
price: nil,
volume: volume,
direction: direction,
offset: offset,
lever_rate: lever_rate,
order_price_type: order_price_type
)
Exchange::Huobi::PlaceOrderResponse.new(result)
end
def order_info(remote_order_id)
result = client.order_info(contract_code: contract_code, order_id: remote_order_id)
Exchange::Huobi::OrderInfoResponse.new(result)
end
def current_position
Exchange::Huobi::CurrentPositionResponse.new(client.current_position(contract_code))
end
def has_position?
current_position.data.length > 0
end
def continuous_fail_times
latest_profile_order = closed_orders.find {|o| profit?(o)}
closed_orders.index(latest_profile_order)
end
def has_history?
closed_orders.length > 0
end
def last_order_profit?
profit?(last_closed_order)
end
def current_price
result = client.price_limit(contract_code)
item = result['data'].find {|i| i['symbol'] == currency}
raise "price not found #{result}" unless item
item['high_limit'].to_d
end
def contract_size
client.contract_info(contract_code)['data'].last['contract_size'].to_d
end
def contract_code
"#{currency}-USDT"
end
def credentials_set?
user.huobi_access_key.present? && user.huobi_secret_key.present?
end
def closed_orders
# revere order
@closed_orders ||=
begin
result = client.history(contract_code)['data']['trades']
result.select {|t| t['offset'] == 'close'}.map {|t| Exchange::Huobi::OrderInfoResponse.new('data' => [t])}
end
end
private
def last_closed_order
# time revere order
closed_orders.first
end
def current_position_response
end
def client
@client ||= HuobiClient.new(user)
end
def order_price_type
'opponent'
end
def profit?(order)
order.real_profit > 0
end
end
|
class CreateLoyalties < ActiveRecord::Migration[5.1]
def change
create_table :loyalties do |t|
t.integer :loyalty_type
t.integer :loyalty_points_percentage
t.timestamps
end
end
end
|
# typed: strict
# frozen_string_literal: true
module Packwerk
class Result < T::Struct
prop :message, String
prop :status, T::Boolean
end
end
|
# frozen_string_literal: true
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: :registrations,
omniauth_callbacks: "users/omniauth_callbacks" }
root to: 'static_pages#landing_page'
get 'static_pages/about'
get 'static_pages/contact'
get 'static_pages/terms_and_conditions'
get 'static_pages/legal_information'
get 'static_pages/privacy_policy'
get 'full_simulations/send_email_counselour', as: :send_email_counselour
namespace :admin do
root to: 'users#index'
resources :users
resources :full_simulations, only: [:show]
resources :gas_simulations, only: [:show]
resources :box_simulations, only: [:show]
resources :bank_simulations, only: [:show]
resources :ele_simulations, only: [:show]
resources :mobil_simulations, only: [:show]
resources :gas_contracts
resources :mobil_contracts
resources :box_contracts
resources :bank_contracts
resources :ele_contracts
end
resources :users, only: %i[show edit update] do
root to: 'full_simulations#new'
resources :full_simulations, except: [:edit] do
resources :gas_simulations, only: [:show, :create]
resources :mobil_simulations, only: [:show, :create]
resources :box_simulations, only: [:show, :create]
resources :bank_simulations, only: [:show, :create]
resources :ele_simulations, only: [:show, :create]
end
end
end
|
require 'spec_helper'
describe WavelabsClientApi::Client::Api::Core::MediaApi do
let(:login_user) {UserSignUp.login_user}
let (:media_api_obj) { WavelabsClientApi::Client::Api::Core::MediaApi.new}
let (:media_api) { WavelabsClientApi::Client::Api::Core::MediaApi}
it "#check_connection?" do
expect(media_api.check_connection?).to be true
end
it "#Check Constants of Media API URIS" do
expect(media_api::MEDIA_URI).to eq '/api/media/v0/media'
end
it "#get_media with user details after login" do
l_req = login_user
res = media_api_obj.get_media(l_req[:member].id, "profile", l_req[:member].token.value)
expect(res[:status]).to eq 200
end
it "#update_media with user details after login" do
l_req = login_user
file_path = Dir.pwd + "/spec/support/temp_user.png"
res = media_api_obj.upload_media(file_path, "profile", l_req[:member].token.value, l_req[:member].id)
expect(res[:status]).to eq 200
end
it "#update_media with invalide file type after login" do
l_req = login_user
file_path = Dir.pwd + "/spec/support/temp_user.doc"
res = media_api_obj.upload_media(file_path, "profile", l_req[:member].token.value, l_req[:member].id)
expect(res[:status]).to eq 200
expect(res[:media].message).to eq "media.upload.error"
end
end
|
# frozen_string_literal: true
class AddTokenToUsers < ActiveRecord::Migration[5.2]
def change
change_table :users do |u|
u.string :api_key
end
end
end
|
class WordFormatter
def initialize(string)
@string = string
end
def camelify
@string.split.map(&:capitalize).join
end
def format_postcode
joined_str = @string.split.map(&:upcase).join
joined_str.chars.each_slice(3).map(&:join).join(' ')
end
end
|
require 'rails_helper'
Rails.application.load_seed
# Return Type: Record
describe "Query: Movie.find(1)" do
it "lists one Movie record with all columns" do
visit "/"
fill_in "Enter a Query", with: "Movie.find(1)"
click_on "Execute"
movie = Movie.find(1)
within "tbody" do
expect(page).to have_css "tr", count: 1
end
expect(page).to have_selector 'td', text: movie.id
expect(page).to have_selector 'td', text: movie.title
expect(page).to have_selector 'td', text: movie.duration
expect(page).to have_selector 'td', text: movie.description
expect(page).to have_selector 'td', text: movie.director_id
end
it "says 'Your Query returned a Record'" do
visit "/"
fill_in "Enter a Query", with: "Movie.find(1)"
click_on "Execute"
expect(page).to have_selector 'div', text: 'Record'
end
end
describe "Query: Director.find(1)" do
it "lists one Director record with all columns" do
visit "/"
fill_in "Enter a Query", with: "Director.find(1)"
click_on "Execute"
director = Director.find(1)
within "tbody" do
expect(page).to have_css "tr", count: 1
end
expect(page).to have_selector 'td', text: director.id
expect(page).to have_selector 'td', text: director.name
expect(page).to have_selector 'td', text: director.dob
expect(page).to have_selector 'td', text: director.bio
end
end
describe "Query: Actor.find(1)" do
it "lists one Actor record with all columns" do
visit "/"
fill_in "Enter a Query", with: "Actor.find(1)"
click_on "Execute"
actor = Actor.find(1)
within "tbody" do
expect(page).to have_css "tr", count: 1
end
expect(page).to have_selector 'td', text: actor.id
expect(page).to have_selector 'td', text: actor.name
expect(page).to have_selector 'td', text: actor.dob
expect(page).to have_selector 'td', text: actor.bio
end
end
describe "Query: Role.find(1)" do
it "lists one Role record with all columns" do
visit "/"
fill_in "Enter a Query", with: "Role.find(1)"
click_on "Execute"
role = Role.find(1)
within "tbody" do
expect(page).to have_css "tr", count: 1
end
expect(page).to have_selector 'td', text: role.id
expect(page).to have_selector 'td', text: role.movie_id
expect(page).to have_selector 'td', text: role.actor_id
expect(page).to have_selector 'td', text: role.character_name
end
end
# Return Type: Collection
describe "Query: Movie.all" do
it "lists all Movie records with all columns" do
visit "/"
fill_in "Enter a Query", with: "Movie.all"
click_on "Execute"
movies = Movie.all
within "tbody" do
expect(page).to have_css "tr", count: movies.count
end
end
end
describe "Query: Role.all" do
it "lists all Role records with all columns" do
visit "/"
fill_in "Enter a Query", with: "Role.all"
click_on "Execute"
roles = Role.all
within "tbody" do
expect(page).to have_css "tr", count: roles.count
end
expect(page).to have_content "Collection"
end
end
describe "Query: Director.all" do
it "lists all Director records with all columns" do
visit "/"
fill_in "Enter a Query", with: "Director.all"
click_on "Execute"
directors = Director.all
within "tbody" do
expect(page).to have_css "tr", count: directors.count
end
end
end
describe "Query: Actor.all" do
it "lists all Actor records with all columns" do
visit "/"
fill_in "Enter a Query", with: "Actor.all"
click_on "Execute"
actors = Actor.all
within "tbody" do
expect(page).to have_css "tr", count: actors.count
end
end
end
# Return Type: Column
describe "Query: Movie.first.title", type: :feature do
it "says 'Your Query returned a Column'" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'div', text: 'Column'
end
end
describe "Query: Movie.first.title", type: :feature do
it "says 'Your Query returned a Column'" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'div', text: 'Column'
end
end
# Return Type: Array
describe "Query: Movie.all.pluck(:title)", type: :feature do
it "says 'Your Query returned an Array'" do
visit "/"
fill_in "Enter a Query", with: "Movie.all.pluck(:title)"
click_on "Execute"
expect(page).to have_selector 'div', text: 'Array'
end
end
# Return Type: Error
describe "Query: m.title", type: :feature do
it "says 'Your Query returned an Error'" do
visit "/"
fill_in "Enter a Query", with: "m.title"
click_on "Execute"
expect(page).to have_selector 'div', text: 'Error'
end
end
describe "Query: Doesn't break on empty input", type: :feature do
it "redirects to level page'" do
visit "/"
fill_in "Enter a Query", with: ""
click_on "Execute"
expect(page.current_path).to eql "/levels/1"
end
end
feature "Query:", type: :feature do
scenario "Display Movie id" do
visit "/"
fill_in "Enter a Query", with: "Movie.first"
click_on "Execute"
expect(page).to have_selector 'td', text: "1"
end
scenario "Display Movie title" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'td', text: "The Shawshank Redemption"
end
scenario "Display Movie year" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'td', text: "The Shawshank Redemption"
end
scenario "Display Movie duration" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'td', text: "The Shawshank Redemption"
end
scenario "Display Movie description" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'td', text: "The Shawshank Redemption"
end
scenario "Display Movie director_id" do
end
scenario "Displays Movie title column value" do
visit "/"
fill_in "Enter a Query", with: "Movie.first.title"
click_on "Execute"
expect(page).to have_selector 'td', text: "The Shawshank Redemption"
end
scenario "Display Director id" do
visit "/"
fill_in "Enter a Query", with: "Director.first.id"
click_on "Execute"
expect(page).to have_selector 'td', text: "1"
end
scenario "Display Director name" do
visit "/"
fill_in "Enter a Query", with: "Director.first.name"
click_on "Execute"
expect(page).to have_selector 'td', text: "Frank Darabont"
end
scenario "Display Director dob" do
visit "/"
fill_in "Enter a Query", with: "Director.first.dob"
click_on "Execute"
expect(page).to have_selector 'td', text: Date.parse("January 28, 1959")
end
scenario "Display Director bio" do
visit "/"
fill_in "Enter a Query", with: "Director.first.bio"
click_on "Execute"
expect(page).to have_selector 'td', text: "Frank Darabont was born"
end
scenario "Allows mutliple queries in one line" do
visit "/levels/2"
fill_in "Enter a Query", with: "Director.find(Movie.find_by(title: \"The Shawshank Redemption\").director_id)"
click_on "Execute"
expect(page).to have_selector 'a', text: "Next Level"
end
pending "Display Actor id"
pending "Display Actor name"
pending "Display Actor dob"
pending "Display Actor bio"
pending "Display Role id"
pending "Display Role movie_id"
pending "Display Role actor_id"
pending "Display Role character_name"
pending "Returns collection result"
pending "Returns record result"
pending "Returns column result"
pending "Returns array result"
pending "Returns error result"
end
|
require "spec_helper"
class Search < ActiveRecord::Base; end
describe Scenic::SchemaDumper, :db do
it "dumps a create_view for a view in the database" do
view_definition = "SELECT 'needle'::text AS haystack"
Search.connection.create_view :searches, sql_definition: view_definition
stream = StringIO.new
ActiveRecord::SchemaDumper.dump(Search.connection, stream)
output = stream.string
expect(output).to include "create_view :searches"
expect(output).to include view_definition
Search.connection.drop_view :searches
silence_stream(STDOUT) { eval(output) }
expect(Search.first.haystack).to eq "needle"
end
end
|
require "slack-ruby-bot"
class Bot < SlackRubyBot::Bot
help do
title "DJ"
desc "Ask me to queue up music"
end
command "ping" do |client, data, match|
client.say(text: "pong", channel: data.channel)
end
end
require "commands"
|
require 'yaml'
require_relative 'src/evie.rb'
# Make sure that static files are served from
# public which seems to be off by default with Rack
run Rack::Directory.new("./public")
# https://github.com/hashicorp/vault-ruby
if ENV['VAULT_TOKEN'].nil?
raise ArgumentError, 'VAULT_TOKEN env is not defined.'
end
# http://www.rubydoc.info/github/rack/rack/Rack/Config
if ENV['EVIE_CONFIG'].nil?
raise ArgumentError, 'EVIE_CONFIG env is not defined.'
end
if not File.exist?(ENV['EVIE_CONFIG'])
raise ArgumentError, "#{ENV['EVIE_CONFIG']} doesn't exist or couldn't be opened."
end
if ENV['PROFILE_CONFIG'].nil?
raise ArgumentError, 'PROFILE_CONFIG env is not defined.'
end
if not File.exist?(ENV['PROFILE_CONFIG'])
raise ArgumentError, "#{ENV['PROFILE_CONFIG']} doesn't exist or couldn't be opened."
end
use Rack::Config do |env|
env['evie'] = YAML::load(File.open(ENV['EVIE_CONFIG']))
env['profile'] = YAML::load(File.open(ENV['PROFILE_CONFIG']))
end
# Application Routes
map('/provision') { run Evie::Controller::Provision }
map('/ipxe') { run Evie::Controller::Ipxe }
map('/evie') { run Evie::Controller::Config }
|
class ApplicationMailer < ActionMailer::Base
default from: "noreply@verifyonline.in"
layout 'mailer'
end
|
require "application_system_test_case"
class JobsTest < ApplicationSystemTestCase
setup do
@job = jobs(:one)
end
test "visiting the index" do
visit jobs_url
assert_selector "h1", text: "Jobs"
end
test "creating a Job" do
visit jobs_url
click_on "New Job"
fill_in "Command", with: @job.command
fill_in "Completed", with: @job.completed
fill_in "Dispatched", with: @job.dispatched
fill_in "Job Valid", with: @job.job_valid
fill_in "Output", with: @job.output
fill_in "Success", with: @job.success
fill_in "Worker", with: @job.worker_id
click_on "Create Job"
assert_text "Job was successfully created"
click_on "Back"
end
test "updating a Job" do
visit jobs_url
click_on "Edit", match: :first
fill_in "Command", with: @job.command
fill_in "Completed", with: @job.completed
fill_in "Dispatched", with: @job.dispatched
fill_in "Job Valid", with: @job.job_valid
fill_in "Output", with: @job.output
fill_in "Success", with: @job.success
fill_in "Worker", with: @job.worker_id
click_on "Update Job"
assert_text "Job was successfully updated"
click_on "Back"
end
test "destroying a Job" do
visit jobs_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Job was successfully destroyed"
end
end
|
class WinesController < ApplicationController
before_filter :current_user
def index
@wines = Wine.paginate(page: params[:page])
end
def show
@wine = Wine.find(params[:id])
@user = current_user
end
end
|
#!/usr/bin/env ruby
lib = File.expand_path File.join(__dir__, '../lib')
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'optparse'
require 'timelapser'
$stdout.sync = true
$stdin.sync = true
options = {
interval: 1.0,
save_to: '~/Pictures/timelapses'
}
OptionParser.new do |opts|
opts.banner = "Usage: timelapser [options]"
opts.on("--version", "Show Version") do
$stdout.puts Timelapser::VERSION
exit
end
opts.on("-h", "--help") do
$stdout.puts opts
exit
end
opts.on("-i INTERVAL", "--interval INTERVAL", "Set screenshot interval") do |interval|
options[:interval] = interval.to_f
end
opts.on("-s PATH", '--save-path PATH', 'Save to') do |path|
options[:save_to] = path.to_s
end
opts.on('-d', '--delete-screenshots', 'Remove screenshots after') do |d|
options[:delete_screenshots] = true
end
end.parse!
capturer = Capturer.new(**options)
capturer.start
puts "Press enter to stop"
gets
capturer.stop
|
class AddBenFieldsToUsers < ActiveRecord::Migration
def change
add_column :users, :empid, :integer
add_column :users, :emp_class, :string
add_column :users, :emp_home, :string
end
end
|
# frozen_string_literal: true
require_relative 'views'
module Statistics
class UniquePageViews < Views
attr_reader :page_views_by_ip
private
# @return [Hash] the resulting hash, e.g.
# { "url" => value }, where `value` is the unique views count
def analyze!
page_views = page_views_stats_klass.new(log).generate!
page_views.keys.each_with_object({}) do |url, stats|
stats[url] = views_count_for(url)
end
end
# @return [Hash] the resulting hash, e.g.
# { "ip" => [Array] }, where `Array` is a list of uniq visited urls
def uniq_page_views_by_ip
@page_views_by_ip ||=
log.lines.each_with_object({}) do |line, stats|
group_urls_by_ip!(stats, line)
end
page_views_by_ip.tap { |views| views.values.each(&:uniq!) }
end
def views_count_for(url)
uniq_page_views_by_ip.values.flatten.select do |visited_page|
visited_page == url
end.count
end
def group_urls_by_ip!(stats, line)
stats[log.extract_ip_from(line)] ||= []
stats[log.extract_ip_from(line)] << log.extract_url_from(line)
end
def page_views_stats_klass
PageViews
end
end
end
|
require 'rails_helper'
RSpec.describe Micropost, type: :model do
let(:mp) { build :micropost }
it '正常系' do
expect(mp.save).to be_truthy
end
it 'messageの存在性チェック' do
mp.message = ''
expect(mp.valid?).to be_falsy
end
it 'messageの長さチェック' do
mp.message = 'a' * 140
expect(mp.valid?).to be_truthy
mp.message = 'a' * 141
expect(mp.valid?).to be_falsy
end
it 'userの存在性チェック' do
mp.user = nil
expect(mp.valid?).to be_falsy
end
end
|
require 'rails_helper'
RSpec.describe Matchmaker do
describe "#choose" do
let(:matchmaker) { Matchmaker.new(players) }
let(:least_recently_played_player) do
FactoryGirl.create :player, name: "Least", active: true
end
subject { matchmaker.choose }
context "when there are no players" do
let(:players) { [] }
it { is_expected.to be_a Matchup }
it { is_expected.not_to be_valid }
end
context "when there are 2 players" do
let(:other_player) { FactoryGirl.create :player, active: true }
let(:players) { [least_recently_played_player, other_player] }
it { is_expected.to be_a Matchup }
it { is_expected.to be_valid }
end
context "when there are 3 or more players" do
let(:other_player) { FactoryGirl.create :player, name: "Other", active: true }
let(:another_player) { FactoryGirl.create :player, name: "Another", active: true }
let(:players) { [least_recently_played_player, other_player, another_player] }
it { is_expected.to be_a Matchup }
it { is_expected.to be_valid }
end
end
describe "explain" do
subject { matchmaker.explain }
let(:matchmaker) { Matchmaker.new(players) }
let(:players) { [bert, ernie] }
let(:ernie) { FactoryGirl.create :player, name: "Ernie", elo: 400, active: true }
let(:bert) { FactoryGirl.create :player, name: "Bert", elo: 1200, active: true }
it "returns an arbitrary representation of the result of the matchup ranking" do
expect(subject).to eq [{
players: %w(Bert Ernie),
result: 3.66,
breakdown: [
{
name: "Matchup matches since last played",
base_value: Float::INFINITY,
max: 2.0,
factor: 0.33,
value: 0.66
},
{
name: "Combined matches since players last played",
base_value: Float::INFINITY,
max: 2.0,
factor: 1.5,
value: 3.0
}
]
}]
end
end
describe "matchmaking algorithm" do
context "with 5 players playing 80 matches" do
let!(:players) { FactoryGirl.create_list(:player, 5, active: true) }
before do
create :default_table
80.times { Match.setup!.finalize! }
end
it "plays all matchups" do
Player.find_each do |player|
expect(player.matches.count).to be_within(2).of 32
end
end
end
end
end
|
require "spree/core"
module SpreePos
class Configuration < Spree::Preferences::Configuration
preference :pos_shipping, :string
preference :pos_printing, :string , :default => "/admin/invoice/number/receipt"
end
end |
class Money
USD = 'USD'.freeze
CHF = 'CHF'.freeze
attr_reader :amount, :code
def initialize(amount = 0, code)
@amount = amount
@code = code
end
def times(value)
self.class.new(amount * value, code)
end
def self.dolar(value)
Dolar.new(value, USD)
end
def self.franc(value)
Franc.new(value, CHF)
end
def to_s
"#{amount} #{code}"
end
def ==(money)
return if !money.is_a? self.class
money.amount == self.amount
end
end
class Franc < Money; end
class Dolar < Money; end
|
require 'rails_helper'
RSpec.describe Product, :type => :model do
before(:each) do
@product = FactoryGirl.build(:product)
end
describe 'title' do
it 'must be present' do
@product.title = ''
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
end
describe 'description' do
it 'must be present' do
@product.description = ''
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
end
describe 'price' do
it 'must be present' do
@product.price = ''
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
it 'must have a positive amount ($0.01 or greater)' do
@product.price = '0.00'
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
end
describe 'category type' do
it 'must be present' do
@product.category_type = ''
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
it 'must be included in CATETORY_TYPES' do
@product.category_type = 'rubber ducky'
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
end
describe 'brand' do
it 'must be present' do
@product.brand = ''
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
it 'must be included in BRAND_LIST' do
@product.brand = 'rubber ducky'
expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid)
expect(Product.count).to eq(0)
end
end
end |
module Geometry
class Rectangle < Struct.new(:x, :y, :width, :height)
def area
(self.width - self.x).abs*(self.height - self.y).abs rescue 0
end
def empty?
self.area == 0
end
def intersection_with(rect)
return Rectangle.new if rect.empty? || self.empty?
l1, r1= x, x
l2, r2= rect.x, rect.x
t1, b1= y, y
t2, b2= rect.y, rect.y
width < 0 ? l1+= width : r1+= width
rect.width < 0 ? l2+= rect.width : r2+= rect.width
return Rectangle.new if l2 == r2
return Rectangle.new if (l1 >= r2 || l2 >= r1)
height < 0 ? t1+= height : b1+= height
return Rectangle.new if t1 == b1
rect.height < 0 ? t2+= rect.height : b2+= rect.height
return Rectangle.new if t2 == b2
return Rectangle.new if (t1 >= b2 || t2 >= b1)
intersection= Rectangle.new
intersection.x= [l1, l2].max;
intersection.y= [t1, t2].max;
intersection.width= [r1, r2].min - intersection.x;
intersection.height= [b1, b2].min - intersection.y;
intersection
end
def intersect_with?(rect)
!self.intersection_with(rect).empty?
end
end
end |
class CasesController < ApplicationController
def new
@case = Case.new
@atlas = Atlas.find_by_id(params[:atlas_id])
@reports = Report.where(:atlas_id => @atlas.id)
end
def create
if params[:case]
@case = Case.new(params[:case])
@case.atlas_id = params[:atlas_id]
@case.save
@case.add_reports(params["case_report_ids"])
respond_to do |format|
if @case.save
format.html { redirect_to atlas_case_path(params[:atlas_id], @case.id), notice: 'Report was successfully updated.' }
format.json { render json: atlas_case_path(params[:atlas_id], @case.id), status: :created, location: @case }
else
format.html { render action: "new" }
format.json { render json: @case.errors, status: :unprocessable_entity }
end
end
else
@case = Case.new(params[:new_case])
@case.atlas_id = params[:atlas_id]
@case.save
respond_to do |format|
if @case.save
format.html { redirect_to atlas_case_path(params[:atlas_id], @case.id), notice: 'Report was successfully updated.' }
format.json { render json: atlas_case_path(params[:atlas_id], @case.id), status: :created, location: @case }
else
format.html { render action: "new" }
format.json { render json: @case.errors, status: :unprocessable_entity }
end
end
end
end
def index
@atlas = Atlas.find_by_id(params[:atlas_id])
@cases = @atlas.cases.includes(:reports)
@new_case = Case.new
end
def update
@case = Case.find_by_id(params[:id])
@atlas = Atlas.find_by_id(params[:atlas_id])
@case.add_reports(params["case_report_ids"])
@case.remove_reports(params["remove_case_report_ids"])
@case.merge_cases(params["case_ids"])
redirect_to atlas_case_path(@atlas, @case)
end
def show
@atlas = Atlas.find_by_id(params[:atlas_id])
@case = Case.find_by_id(params[:id])
@reports = @case.reports
@p_reports = @case.potential_reports
@p_cases = @case.potential_cases
end
def merge_reports
@atlas = Atlas.find_by_id(params[:atlas_id])
@case = Case.find_by_id(params[:id])
@case.add_reports(params["case_report_ids"])
redirect_to atlas_case_path(@atlas, @case)
end
end |
module CommentMutations
MUTATION_TARGET = 'comment'.freeze
PARENTS = ['project_media', 'source', 'project', 'task', 'version'].freeze
module SharedCreateAndUpdateFields
extend ActiveSupport::Concern
include Mutations::Inclusions::AnnotationBehaviors
included do
field :versionEdge, VersionType.edge_type, null: true
end
end
class Create < Mutations::CreateMutation
include SharedCreateAndUpdateFields
argument :text, GraphQL::Types::String, required: true
end
class Update < Mutations::UpdateMutation
include SharedCreateAndUpdateFields
argument :text, GraphQL::Types::String, required: false
end
class Destroy < Mutations::DestroyMutation; end
end
|
module EasyJournalHelper
def easy_journal_render_history(easy_journals, options={})
return if easy_journals.nil? || easy_journals.empty?
options ||= {}
options[:back_url] = url_for(params)
journals = ''
easy_journals.each do |journal|
details = ''
details << content_tag(:h4, content_tag('a', '', :name => "note-#{journal.indice}") + authoring(journal.created_on, journal.user, :label => :label_updated_time_by))
if journal.visible_details.any?
details << '<ul class="details">'
easy_journal_details_to_strings(journal.visible_details, false, :entity => options[:entity]).each do |string|
details << content_tag(:li, string)
end
details << '</ul>'
end
content = avatar(journal.user) + content_tag(:div, details.html_safe, :class => 'journal-details-container')
content << content_tag(:div, '', :class => 'clear')
content << render_notes(journal.journalized, journal, {:reply_links => options[:reply_links], :editable => options[:editable], :back_url => options[:back_url]}) unless journal.notes.blank?
journals << content_tag(:div, content, :id => "change-#{journal.id}", :class => journal.css_classes)
end
if options[:collapsible]
options[:default_button_state] = true if !options.key?(:default_button_state)
toggling_container("easy-journal-history#{options[:modul_uniq_id]}", User.current, {:heading => l(:label_history), :default_button_state => options[:default_button_state]}) do
content_tag(:div, journals.html_safe, :id => 'history-show-bubble', :class => 'bubble')
end
else
content_tag(:div, :id => 'history') do
content_tag(:fieldset) do
content_tag(:legend, l(:label_history)) + content_tag(:div, journals.html_safe, :id => 'history-show-bubble', :class => 'bubble easy-journal')
end
end
end
end
# if entity is passed as options[:entity], than db queries are saved( 150ms average )
def easy_journal_details_to_strings(details, no_html=false, options={})
options[:only_path] = (options[:only_path] == false ? false : true)
strings = []
values_by_field = {}
details.each do |detail|
if detail.property == 'cf'
field = detail.custom_field
if field && field.multiple?
values_by_field[field] ||= {:added => [], :deleted => []}
if detail.old_value
values_by_field[field][:deleted] << detail.old_value
end
if detail.value
values_by_field[field][:added] << detail.value
end
next
end
end
strings << show_easy_journal_detail(detail, no_html, options)
end
values_by_field.each do |field, changes|
detail = JournalDetail.new(:property => 'cf', :prop_key => field.id.to_s)
detail.instance_variable_set "@custom_field", field
if changes[:added].any?
detail.value = changes[:added]
strings << show_easy_journal_detail(detail, no_html, options)
elsif changes[:deleted].any?
detail.old_value = changes[:deleted]
strings << show_easy_journal_detail(detail, no_html, options)
end
end
strings
end
# DO NOT USE WITHOUT easy_journal_details_to_strings
# options:
# => :no_html = true/false (default je false)
# => :only_path = true/false (default je true)
def show_easy_journal_detail(detail, no_html=false, options={})
only_path = options.key?(:only_path) ? options[:only_path] : true
multiple = false
field = detail.prop_key.to_s.gsub(/\_id$/, "")
label = l(("field_" + field).to_sym)
unless detail.property == 'cf'
entity = options[:entity]
entity ||= detail.journal.journalized
date_columns = [
'due_date', 'start_date', 'effective_date'
] + entity.journalized_options[:format_detail_date_columns]
time_columns = entity.journalized_options[:format_detail_time_columns]
reflection_columns = [
'project_id', 'parent_id', 'status_id', 'tracker_id', 'assigned_to_id', 'priority_id', 'category_id', 'fixed_version_id', 'author_id', 'activity_id', 'issue_id', 'user_id'
] + entity.journalized_options[:format_detail_reflection_columns]
boolean_columns = [
'is_private'
] + entity.journalized_options[:format_detail_boolean_columns]
hours_columns = [
'estimated_hours'
] + entity.journalized_options[:format_detail_hours_columns]
format_entity_journal_detail_method = "format_#{entity.class.name.underscore}_attribute"
if detail.property == 'attr' && respond_to?(format_entity_journal_detail_method)
attribute = EasyQueryColumn.new(field)
# formating from EntityAttributeHelper
value = send(format_entity_journal_detail_method, entity.class, attribute, detail.value, {:entity => entity, :no_link => true, :no_progress_bar => true})
old_value = send(format_entity_journal_detail_method, entity.class, attribute, detail.old_value, {:entity => entity, :no_link => true, :no_progress_bar => true})
# set nil if EntityAttributeHelper not formated value
value = nil if value == detail.value
old_value = nil if old_value == detail.old_value
end
end
case detail.property
when 'attr'
case detail.prop_key
when *date_columns
value ||= begin; detail.value && format_date(detail.value.to_date) rescue nil end
old_value ||= begin; detail.old_value && format_date(detail.old_value.to_date) rescue nil end
when *time_columns
value ||= begin; detail.value && format_time(Time.parse(detail.value), false) rescue nil end
old_value ||= begin; detail.old_value && format_time(Time.parse(detail.old_value), false) rescue nil end
when *reflection_columns
value ||= easy_journal_name_by_reflection(entity, field, detail.value)
old_value ||= easy_journal_name_by_reflection(entity, field, detail.old_value)
when *boolean_columns
value ||= l(detail.value == "0" ? :general_text_No : :general_text_Yes) unless detail.value.blank?
old_value ||= l(detail.old_value == "0" ? :general_text_No : :general_text_Yes) unless detail.old_value.blank?
when *hours_columns
value ||= "%0.02f h" % detail.value.to_f unless detail.value.blank?
old_value ||= "%0.02f h" % detail.old_value.to_f unless detail.old_value.blank?
end
label = l(:field_parent_issue) if detail.prop_key == 'parent_id'
when 'cf'
#if they are preloaded(they should be) than this is quicker, but otherwise... :(
if options[:entity].respond_to?(:custom_field_values)
cv = options[:entity].custom_field_values.detect{|cfv| cfv.custom_field_id == detail.prop_key.to_i }
custom_field = cv.custom_field if cv
end
custom_field ||= custom_field = detail.custom_field
if custom_field
multiple = custom_field.multiple?
label = custom_field.translated_name
if detail.value
cv = CustomFieldValue.new
cv.custom_field = custom_field
cv.value = detail.value
value = format_custom_field_value(cv, :no_html => no_html)
end
if detail.old_value
cv = CustomFieldValue.new
cv.custom_field = custom_field
cv.value = detail.old_value
old_value = format_custom_field_value(cv, :no_html => no_html)
end
end
when 'attachment'
label = l(:label_attachment)
when 'relation'
if detail.value && !detail.old_value
rel_issue = Issue.visible.find_by_id(detail.value)
value = rel_issue.nil? ? "#{l(:label_issue)} ##{detail.value}" :
(no_html ? rel_issue : link_to_issue(rel_issue, :only_path => options[:only_path]))
elsif detail.old_value && !detail.value
rel_issue = Issue.visible.find_by_id(detail.old_value)
old_value = rel_issue.nil? ? "#{l(:label_issue)} ##{detail.old_value}" :
(no_html ? rel_issue : link_to_issue(rel_issue, :only_path => options[:only_path]))
end
label = l(detail.prop_key.to_sym)
end
call_hook(:helper_easy_journal_show_detail_after_setting, {:detail => detail, :label => label, :value => value, :old_value => old_value, :options => options })
# Set default format
label ||= detail.prop_key
value ||= detail.value
old_value ||= detail.old_value
unless no_html
label = content_tag(:strong, label)
if detail.old_value && detail.property != 'relation'
if !detail.value || detail.value.blank?
old_value = content_tag(:del, old_value)
else
old_value = content_tag(:i, old_value)
end
end
if detail.property == 'attachment'
# Link to the attachment if it has not been removed
if !value.blank? && (a = Attachment.where({:id => detail.prop_key, :filename => value}).first || Attachment::Version.where({:id => detail.prop_key, :filename => value}).first)
if a.is_a?(Attachment) && !a.versions.earliest.nil?
a = a.versions.earliest
end
value = link_to_attachment(a, :download => true, :only_path => only_path)
if only_path != false && a.is_text?
value += link_to('',
{:controller => 'attachments', :action => 'show',
:id => a, :filename => a.filename, :version => !a.is_a?(Attachment) || nil}, :title => l(:title_show_attachment), :class => 'icon icon-magnifier'
)
end
else
# if attachment has been deleted...
value = content_tag(:del, h(value)) if value
end
else
value = content_tag(:i, h(value), :class => 'new-value') if value
end
end
if detail.property == 'attr' && detail.prop_key == 'description'
s = l(:text_journal_changed_no_detail, :label => label)
unless no_html
diff_link = link_to('diff',
{:controller => 'journals', :action => 'diff', :id => detail.journal_id, :detail_id => detail.id, :only_path => only_path},
:title => l(:label_view_diff))
s << " (#{ diff_link })"
end
s.html_safe
elsif !detail.value.blank?
case detail.property
when 'attr', 'cf'
if detail.old_value.present?
l(:text_journal_changed, :label => label, :old => old_value, :new => value).html_safe
elsif multiple
l(:text_journal_added, :label => label, :value => value).html_safe
else
l(:text_journal_set_to, :label => label, :value => value).html_safe
end
when 'attachment', 'relation'
l(:text_journal_added, :label => label, :value => value).html_safe
end
else
l(:text_journal_deleted, :label => label, :old => old_value).html_safe
end
end
# Find the name of an associated record stored in the field attribute
def easy_journal_name_by_reflection(entity, field, id)
association = entity.class.reflect_on_association(field.to_sym)
if association
record = association.class_name.constantize.find_by_id(id)
if record
if record.respond_to?(:name)
return record.name
else
return record.to_s
end
end
end
end
end
IssuesHelper.send(:include, EasyJournalHelper)
|
class BidsController < ApplicationController
# Bids will go up in one dollar increments, note all amounts are in cents (integers)
INCREMENT = 100
def new
@bid = Bid.new
end
# The logic in this method needs to be pulled out and placed into the respective model
def create
# Set up the new bid
@bid = Bid.new
@bid.amount = (bid_params[:amount].to_f * 100).to_i # Convert to integer and handle input with or without cents
@time = Time.now
@bid.bid_time = @time
@bid.user_id = @current_user.id
@bid.auction_id = session[:auction_id]
# Fetch the auction and its associated bids
@auction = Auction.find(session[:auction_id])
@existing_bids = Bid.where(:auction_id => session[:auction_id])
# Add the auction to the bidder's watch list
@watcher = Watcher.new
@watcher.auction_id = session[:auction_id]
@watcher.user_id = @current_user.id
# Create a new bid history entry
@bid_history = BidHistory.new
if @auction.status == 'live'
if @auction.user_id == @current_user.id
flash.notice = 'You cannot bid on your own auction'
redirect_to auction_path(session[:auction_id]) and return
else
if @bid.amount
if @existing_bids.length == 0
if @bid.amount >= @auction.start_price
@auction.current_bid = @auction.start_price
@bid_history.amount = @auction.current_bid
@bid_history.bid_time = @time
@bid_history.username = @current_user.username
@bid_history.auction_id = session[:auction_id]
@bid_history.save
@auction.save
flash.notice = 'You are the first bidder'
else
flash.notice = 'Bid must be at least equal to the starting price'
render :new and return
end
else
@highest_bid = Utilities.get_highest_bid(@existing_bids)
if @highest_bid.user_id == @current_user.id
if @bid.amount > @highest_bid.amount
flash.notice = "You have increased your maximum bid to #{Utilities.convert_to_price(@bid.amount)}"
else
flash.notice = "The amount entered needs to be higher than your last maximum bid, please enter an amount greater than #{Utilities.convert_to_price(@highest_bid.amount)}"
render :new and return
end
else
if @bid.amount > @highest_bid.amount # There is a new high bidder
@auction.current_bid = @highest_bid.amount + INCREMENT
@bid_history.amount = @auction.current_bid
@bid_history.bid_time = @time
@bid_history.username = @current_user.username
@bid_history.auction_id = session[:auction_id]
@bid_history.save
@auction.save
flash.notice = "You are now the high bidder, your maximum bid is #{Utilities.convert_to_price(@bid.amount)}"
elsif @bid.amount <= @highest_bid.amount && @bid.amount > @auction.current_bid
# The bid should increase by the challenging bidder plus the increment
if @highest_bid.amount - @bid.amount < INCREMENT # Do not want to push the high bid over by less than the INCREMENT as this would increase the maximum bid without asking the high bidder to approve
@auction.current_bid = @highest_bid.amount
else
@auction.current_bid = @bid.amount + INCREMENT
end
@bid_history.amount = @auction.current_bid
@bid_history.bid_time = @time
@bid_history.username = @current_user.username
@bid_history.auction_id = session[:auction_id]
@bid_history.save
@auction.save
flash.notice = 'You were outbid, please enter a higher amount'
else
flash.notice = 'Bid too low, please enter a higher amount'
render :new and return
end
end
end
else
flash.notice = 'No amount entered, please try again'
render :new and return
end
if @bid.save
@watcher.save
redirect_to auction_path(session[:auction_id])
else
flash.notice = 'Bid not entered, please try again'
render :new and return
end
end
else
flash.notice = 'Sorry, bidding for this auction has ended'
redirect_to auction_path(session[:auction_id])
end
end
private
def bid_params
params.require(:bid).permit(:amount)
end
end
|
class ChangeYearBuiltToInteger < ActiveRecord::Migration[5.0]
def change
change_column :estates, :year_built, :integer
end
end
|
class Cell
def initialize(opts)
@live = opts[:state] == :live
end
def live?
@live
end
def next_state
false
end
end |
#encoding: utf-8
class Work < ActiveRecord::Base
belongs_to :schoolyear
belongs_to :student
attr_accessible :cycle, :student, :technique, :title, :student_id, :schoolyear_id
validates :title, :presence => true
validates :technique, :presence => true
validates :student, :presence => true
validates :schoolyear, :presence => true
end
|
require 'mongo_active_instrumentation/controller_runtime'
module MongoActiveInstrumentation
class Railtie < Rails::Railtie
initializer "mongo_active_instrumentation" do |app|
Mongo::Monitoring::Global.subscribe(
Mongo::Monitoring::COMMAND,
MongoActiveInstrumentation::LogSubscriber.new
)
# Disable the existing log subscriber
Mongo::Monitoring::CommandLogSubscriber.class_eval do
def started(event); end
def succeeded(event); end
def failed(event); end
end
ActiveSupport.on_load(:action_controller) do
include MongoActiveInstrumentation::ControllerRuntime
end
end
end
end
|
class Admin::SortController < Admin::AdminController
# POST /admin/sort
def sort
class_name = params[:class_name]
sortable = params[class_name.to_sym]
sortable.each_with_index do |id, index|
class_name.camelize.constantize.where(id: id).update_all(position: index+1)
end
render nothing: true
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:confirmable, :lockable, :trackable
#nameは必ず入力されていないとだめ
validates :name, presence: true
#profileは200文字以内
validates :profile, length: { maximum: 200 }
has_many :recruitiments, dependent: :destroy
end
|
class HousesController < ApplicationController
before_action :set_house, only: [:show, :update, :destroy]
def index
render json: House.all
end
def create
render json: House.create(house_params)
end
def show
render json: @house
end
def update
render json: @house.update(house_params)
end
def destroy
render json: @house.destroy
end
private
def set_house
@house = Book.find(params[:id])
end
def house_params
params.require(:house).permit(:title, :author, :description, :isbn)
end
end |
require 'spec_helper'
describe HomeController do
describe "GET 'index'" do
it "returns http success" do
get 'index'
response.should be_success
end
it "sets title and welcome message" do
get 'index'
response.should be_success
assigns(:title).should eq('Outlaws Softball')
assigns(:message).should eq('Welcome to the Outlaws Softball website!')
end
end
end
|
module Student
class SkillsUsersController < BaseController
before_action :set_skill, only: [:show, :destroy]
def index
@skills = current_user.skills_users
end
def new
@skill = current_user.skills_users.new
end
def create
@skill = current_user.skills_users.new(skill_params)
if @skill.save
redirect_to student_skills_users_path, notice: 'Skill was successfully created.'
else
render :new
end
end
def destroy
@skill.delete
redirect_to student_skills_users_path, notice: 'Skill was successfully destroyed.'
end
private
def set_skill
@skill = SkillsUser.find(params[:id])
end
def skill_params
puts params
params[:skills_user].permit(:skill_id)
end
end
end
|
require 'digest'
class Bot::Smooch < BotUser
class MessageDeliveryError < StandardError; end
class FinalMessageDeliveryError < MessageDeliveryError; end
class TurnioMessageDeliveryError < MessageDeliveryError; end
class SmoochMessageDeliveryError < MessageDeliveryError; end
class CapiMessageDeliveryError < MessageDeliveryError; end
class CapiUnhandledMessageWarning < MessageDeliveryError; end
MESSAGE_BOUNDARY = "\u2063"
SUPPORTED_INTEGRATION_NAMES = { 'whatsapp' => 'WhatsApp', 'messenger' => 'Facebook Messenger', 'twitter' => 'Twitter', 'telegram' => 'Telegram', 'viber' => 'Viber', 'line' => 'LINE' }
SUPPORTED_INTEGRATIONS = SUPPORTED_INTEGRATION_NAMES.keys
SUPPORTED_TRIGGER_MAPPING = { 'message:appUser' => :incoming, 'message:delivery:channel' => :outgoing }
check_settings
include SmoochMessages
include SmoochResources
include SmoochTos
include SmoochStatus
include SmoochResend
include SmoochTeamBotInstallation
include SmoochNewsletter
include SmoochSearch
include SmoochZendesk
include SmoochTurnio
include SmoochCapi
include SmoochStrings
include SmoochMenus
include SmoochFields
include SmoochLanguage
::ProjectMedia.class_eval do
attr_accessor :smooch_message
def report_image
self.get_dynamic_annotation('report_design')&.report_design_image_url
end
def get_deduplicated_smooch_annotations
uids = []
annotations = []
ProjectMedia.where(id: self.related_items_ids).each do |pm|
pm.get_annotations('smooch').find_each do |annotation|
data = JSON.parse(annotation.load.get_field_value('smooch_data'))
uid = data['authorId']
next if uids.include?(uid)
uids << uid
annotations << annotation
end
end
annotations
end
end
::Relationship.class_eval do
def suggestion_accepted?
self.relationship_type_before_last_save.to_json == Relationship.suggested_type.to_json && self.is_confirmed?
end
def self.inherit_status_and_send_report(rid)
relationship = Relationship.find_by_id(rid)
unless relationship.nil?
target = relationship.target
parent = relationship.source
if ::Bot::Smooch.team_has_smooch_bot_installed(target) && relationship.is_confirmed?
s = target.annotations.where(annotation_type: 'verification_status').last&.load
status = parent.last_verification_status
if !s.nil? && s.status != status
s.status = status
s.save!
end
::Bot::Smooch.send_report_from_parent_to_child(parent.id, target.id)
end
end
end
after_create do
self.class.delay_for(1.seconds, { queue: 'smooch_priority'}).inherit_status_and_send_report(self.id)
end
after_update do
self.class.delay_for(1.seconds, { queue: 'smooch_priority'}).inherit_status_and_send_report(self.id) if self.suggestion_accepted?
end
after_destroy do
if self.is_confirmed?
target = self.target
unless target.nil?
s = target.annotations.where(annotation_type: 'verification_status').last&.load
status = ::Workflow::Workflow.options(target, 'verification_status')[:default]
if !s.nil? && s.status != status
s.status = status
s.save!
end
end
end
end
end
::Dynamic.class_eval do
after_save do
if self.annotation_type == 'smooch_user'
id = self.get_field_value('smooch_user_id')
unless id.blank?
sm = CheckStateMachine.new(id)
case self.action
when 'deactivate'
sm.enter_human_mode
when 'reactivate'
sm.leave_human_mode
when 'refresh_timeout'
Bot::Smooch.refresh_smooch_slack_timeout(id, JSON.parse(self.action_data))
else
app_id = self.get_field_value('smooch_user_app_id')
message = self.action.to_s.match(/^send (.*)$/)
unless message.nil?
Bot::Smooch.get_installation(Bot::Smooch.installation_setting_id_keys, app_id)
payload = {
'_id': Digest::MD5.hexdigest([self.action.to_s, Time.now.to_f.to_s].join(':')),
authorId: id,
type: 'text',
text: message[1]
}.with_indifferent_access
Bot::Smooch.save_message_later(payload, app_id)
end
end
end
end
end
before_destroy :delete_smooch_cache_keys, if: proc { |d| d.annotation_type == 'smooch_user' }, prepend: true
scope :smooch_user, -> { where(annotation_type: 'smooch_user').joins(:fields).where('dynamic_annotation_fields.field_name' => 'smooch_user_data') }
private
def delete_smooch_cache_keys
uid = self.get_field_value('smooch_user_id')
unless uid.blank?
["smooch:bundle:#{uid}", "smooch:last_accepted_terms:#{uid}", "smooch:banned:#{uid}"].each { |key| Rails.cache.delete(key) }
sm = CheckStateMachine.new(uid)
sm.leave_human_mode if sm.state.value == 'human_mode'
end
end
end
SMOOCH_PAYLOAD_JSON_SCHEMA = {
type: 'object',
required: ['trigger', 'app', 'version', 'appUser'],
properties: {
trigger: {
type: 'string'
},
app: {
type: 'object',
required: ['_id'],
properties: {
'_id': {
type: 'string'
}
}
},
version: {
type: 'string'
},
messages: {
type: 'array',
items: {
type: 'object',
required: ['type'],
properties: {
type: {
type: 'string'
},
text: {
type: 'string'
},
mediaUrl: {
type: 'string'
},
role: {
type: 'string'
},
received: {
type: 'number'
},
name: {
type: ['string', nil]
},
authorId: {
type: 'string'
},
'_id': {
type: 'string'
},
source: {
type: 'object',
properties: {
type: {
type: 'string'
},
integrationId: {
type: 'string'
}
}
}
}
}
},
appUser: {
type: 'object',
properties: {
'_id': {
type: 'string'
},
'conversationStarted': {
type: 'boolean'
}
}
}
}
}
def self.team_has_smooch_bot_installed(pm)
bot = BotUser.smooch_user
tbi = TeamBotInstallation.where(team_id: pm.team_id, user_id: bot&.id.to_i).last
!tbi.nil? && tbi.settings.with_indifferent_access[:smooch_disabled].blank?
end
def self.installation_setting_id_keys
['smooch_app_id', 'turnio_secret', 'capi_whatsapp_business_account_id']
end
def self.get_installation(key = nil, value = nil, &block)
id = nil
if !key.blank? && !value.blank?
keys = [key].flatten.map(&:to_s).reject{ |k| k.blank? }
id = Rails.cache.fetch("smooch_bot_installation_id:#{keys.join(':')}:#{value}", expires_in: 24.hours) do
self.get_installation_id(keys, value, &block)
end
elsif block_given?
id = self.get_installation_id(key, value, &block)
end
smooch_bot_installation = TeamBotInstallation.where(id: id.to_i).last
settings = smooch_bot_installation&.settings.to_h
RequestStore.store[:smooch_bot_provider] = 'TURN' unless smooch_bot_installation&.get_turnio_secret&.to_s.blank?
RequestStore.store[:smooch_bot_provider] = 'CAPI' unless smooch_bot_installation&.get_capi_whatsapp_business_account_id&.to_s.blank?
RequestStore.store[:smooch_bot_settings] = settings.with_indifferent_access.merge({ team_id: smooch_bot_installation&.team_id.to_i, installation_id: smooch_bot_installation&.id })
smooch_bot_installation
end
def self.get_installation_id(keys = nil, value = nil)
bot = BotUser.smooch_user
return nil if bot.nil?
smooch_bot_installation = nil
TeamBotInstallation.where(user_id: bot.id).each do |installation|
key_that_has_value = nil
installation.settings.each do |k, v|
key_that_has_value = k.to_s if keys.to_a.include?(k.to_s) && v == value && !value.blank?
end
smooch_bot_installation = installation if (block_given? && yield(installation)) || !key_that_has_value.nil?
end
smooch_bot_installation&.id
end
def self.valid_request?(request)
self.valid_zendesk_request?(request) || self.valid_turnio_request?(request) || self.valid_capi_request?(request)
end
def self.should_ignore_request?(request)
self.should_ignore_capi_request?(request)
end
def self.config
RequestStore.store[:smooch_bot_settings]
end
def self.webhook(request)
# FIXME This should be packaged as an event "invoke_webhook" + data payload
Bot::Smooch.run(request.body.read)
end
def self.run(body)
begin
json = self.preprocess_message(body)
JSON::Validator.validate!(SMOOCH_PAYLOAD_JSON_SCHEMA, json)
return false if self.user_banned?(json)
case json['trigger']
when 'capi:verification'
'capi:verification'
when 'message:appUser'
json['messages'].each do |message|
self.parse_message(message, json['app']['_id'], json)
SmoochTiplineMessageWorker.perform_async(message, json)
end
true
when 'message:delivery:failure'
self.resend_message(json)
true
when 'conversation:start'
message = {
'_id': json['conversation']['_id'],
authorId: json['appUser']['_id'],
type: 'text',
text: 'start',
source: { type: json['source']['type'] }
}.with_indifferent_access
self.parse_message(message, json['app']['_id'], json)
true
when 'message:delivery:channel'
self.user_received_report(json)
self.user_received_search_result(json)
SmoochTiplineMessageWorker.perform_async(json['message'], json)
true
else
false
end
rescue StandardError => e
self.handle_exception(e)
false
end
end
def self.handle_exception(e)
raise(e) if Rails.env.development?
Rails.logger.error("[Smooch Bot] Exception: #{e.message}")
CheckSentry.notify(e, bot: 'Smooch')
raise(e) if e.is_a?(AASM::InvalidTransition) # Race condition: return 500 so Smooch can retry it later
end
def self.get_workflow(language = nil)
team = Team.find(self.config['team_id'])
default_language = team.default_language
language ||= default_language
workflow = nil
default_workflow = nil
self.config['smooch_workflows'].each do |w|
default_workflow = w if w['smooch_workflow_language'] == default_language
workflow = w if w['smooch_workflow_language'] == language
end
workflow || default_workflow
end
def self.start_flow(workflow, language, uid)
CheckStateMachine.new(uid).start
if self.should_ask_for_language_confirmation?(uid)
self.ask_for_language_confirmation(workflow, language, uid)
else
self.send_greeting(uid, workflow)
self.send_message_for_state(uid, workflow, 'main', language)
end
end
def self.parse_query_message(message, app_id, uid, workflow, language)
sm = CheckStateMachine.new(uid)
if self.process_menu_option(message, sm.state.value, app_id)
# Do nothing else - the action will be executed by "process_menu_option" method
elsif self.is_v2?
sm.go_to_ask_if_ready unless sm.state.value == 'ask_if_ready'
self.ask_if_ready_to_submit(uid, workflow, 'ask_if_ready', language)
else
self.delay_for(self.time_to_send_request, { queue: 'smooch', retry: false }).bundle_messages(message['authorId'], message['_id'], app_id)
end
end
def self.parse_message_based_on_state(message, app_id)
uid = message['authorId']
sm = CheckStateMachine.new(uid)
state = sm.state.value
language = self.get_user_language(uid, message, state)
workflow = self.get_workflow(language)
message['language'] = language
state = self.send_message_if_disabled_and_return_state(uid, workflow, state)
if self.clicked_on_template_button?(message)
self.template_button_click_callback(message, uid, language)
return true
end
case state
when 'waiting_for_message'
self.bundle_message(message)
has_main_menu = (workflow&.dig('smooch_state_main', 'smooch_menu_options').to_a.size > 0)
if has_main_menu
self.process_menu_option_or_send_greetings(message, state, app_id, workflow, language, uid)
else
self.clear_user_bundled_messages(uid)
sm.go_to_query
self.parse_message_based_on_state(message, app_id)
end
when 'main', 'secondary', 'subscription', 'search_result'
unless self.process_menu_option(message, state, app_id)
self.send_message_for_state(uid, workflow, state, language, self.get_custom_string(:option_not_available, language))
end
when 'search'
self.send_message_to_user(uid, self.get_message_for_state(workflow, state, language, uid))
when 'query', 'ask_if_ready'
self.parse_query_message(message, app_id, uid, workflow, language)
when 'add_more_details'
self.bundle_message(message)
self.go_to_state_and_ask_if_ready_to_submit(uid, language, workflow)
end
end
def self.process_menu_option_or_send_greetings(message, state, app_id, workflow, language, uid)
self.process_menu_option(message, state, app_id) || self.start_flow(workflow, language, uid)
end
def self.time_to_send_request
value = self.config['smooch_time_to_send_request'] || 15
value.to_i.seconds
end
def self.get_menu_options(state, workflow, uid)
if state == 'ask_if_ready'
[
{ 'smooch_menu_option_keyword' => '1', 'smooch_menu_option_value' => 'search_state' },
{ 'smooch_menu_option_keyword' => '2', 'smooch_menu_option_value' => 'add_more_details_state' },
{ 'smooch_menu_option_keyword' => '3', 'smooch_menu_option_value' => 'main_state' }
]
elsif state == 'search_result'
[
{ 'smooch_menu_option_keyword' => '1', 'smooch_menu_option_value' => 'search_result_is_relevant' },
{ 'smooch_menu_option_keyword' => '2', 'smooch_menu_option_value' => 'search_result_is_not_relevant' }
]
elsif state == 'subscription' && self.is_v2?
[
{ 'smooch_menu_option_keyword' => '1', 'smooch_menu_option_value' => 'subscription_confirmation' },
{ 'smooch_menu_option_keyword' => '2', 'smooch_menu_option_value' => 'main_state' }
]
elsif ['query', 'add_more_details'].include?(state) && self.is_v2?
destination = { 'query' => 'main_state', 'add_more_details' => 'ask_if_ready_state' }[state]
[{ 'smooch_menu_option_keyword' => '1', 'smooch_menu_option_value' => destination }]
# Custom menus
else
self.get_custom_menu_options(state, workflow, uid)
end
end
def self.get_custom_menu_options(state, workflow, uid)
options = workflow.dig("smooch_state_#{state}", 'smooch_menu_options').to_a.clone
if ['main', 'waiting_for_message'].include?(state) && self.is_v2?
if self.should_ask_for_language_confirmation?(uid)
options = []
i = 0
self.get_supported_languages.each do |l|
i = self.get_next_menu_item_number(i)
options << {
'smooch_menu_option_keyword' => i.to_s,
'smooch_menu_option_value' => l
}
end
else
allowed_types = ['query_state', 'subscription_state', 'custom_resource']
options = options.reject{ |o| !allowed_types.include?(o['smooch_menu_option_value']) }.concat(workflow.dig('smooch_state_secondary', 'smooch_menu_options').to_a.clone.select{ |o| allowed_types.include?(o['smooch_menu_option_value']) })
language_options = self.get_supported_languages.reject { |l| l == workflow['smooch_workflow_language'] }
if (language_options.size + options.size) >= 10
options << {
'smooch_menu_option_keyword' => 'choose_language',
'smooch_menu_option_value' => 'choose_language'
}
else
language_options.each do |l|
options << {
'smooch_menu_option_keyword' => l,
'smooch_menu_option_value' => l
}
end
end
all_options = []
keyword = 0
options.reject{ |o| o.blank? }.each do |o|
keyword = self.get_next_menu_item_number(keyword)
o2 = o.clone
o2['smooch_menu_option_keyword'] = keyword.to_s
all_options << o2
end
options = all_options
end
end
options.reject{ |o| o.blank? }
end
def self.process_menu_option_value_for_state(value, message, language, workflow, app_id)
uid = message['authorId']
sm = CheckStateMachine.new(uid)
self.bundle_message(message)
new_state = value.gsub(/_state$/, '')
self.delay_for(self.time_to_send_request, { queue: 'smooch', retry: false }).bundle_messages(uid, message['_id'], app_id) if new_state == 'query' && !self.is_v2?
sm.send("go_to_#{new_state}")
self.delay_for(1.seconds, { queue: 'smooch_priority', retry: false }).search(app_id, uid, language, message, self.config['team_id'].to_i, workflow) if new_state == 'search'
self.clear_user_bundled_messages(uid) if new_state == 'main'
new_state == 'main' && self.is_v2? ? self.send_message_to_user_with_main_menu_appended(uid, self.get_string('cancelled', language), workflow, language) : self.send_message_for_state(uid, workflow, new_state, language)
end
def self.process_menu_option_value(value, option, message, language, workflow, app_id)
uid = message['authorId']
sm = CheckStateMachine.new(uid)
if value =~ /_state$/
self.process_menu_option_value_for_state(value, message, language, workflow, app_id)
elsif value == 'resource'
pmid = option['smooch_menu_project_media_id'].to_i
pm = ProjectMedia.where(id: pmid, team_id: self.config['team_id'].to_i).last
sm.reset
self.bundle_message(message)
self.delay_for(1.seconds, { queue: 'smooch', retry: false }).bundle_messages(uid, message['_id'], app_id, 'menu_options_requests', pm)
self.send_report_to_user(uid, {}, pm, language)
elsif value == 'custom_resource'
sm.reset
resource = self.send_resource_to_user(uid, workflow, option, language)
self.bundle_message(message)
self.delay_for(1.seconds, { queue: 'smooch', retry: false }).bundle_messages(uid, message['_id'], app_id, 'resource_requests', resource)
elsif value == 'subscription_confirmation'
self.toggle_subscription(uid, language, self.config['team_id'], self.get_platform_from_message(message), workflow)
elsif value == 'search_result_is_not_relevant'
self.submit_search_query_for_verification(uid, app_id, workflow, language)
sm.reset
elsif value == 'search_result_is_relevant'
sm.reset
self.bundle_message(message)
results = self.get_saved_search_results_for_user(uid)
self.delay_for(1.seconds, { queue: 'smooch', retry: false }).bundle_messages(uid, message['_id'], app_id, 'relevant_search_result_requests', results, true, self.bundle_search_query(uid))
self.send_final_message_to_user(uid, self.get_custom_string('search_result_is_relevant', language), workflow, language)
elsif value =~ CheckCldr::LANGUAGE_FORMAT_REGEXP
Rails.cache.write("smooch:user_language:#{uid}", value)
Rails.cache.write("smooch:user_language:#{self.config['team_id']}:#{uid}:confirmed", value)
sm.send('go_to_main')
workflow = self.get_workflow(value)
self.bundle_message(message)
self.send_greeting(uid, workflow)
self.send_message_for_state(uid, workflow, 'main', value)
elsif value == 'choose_language'
self.reset_user_language(uid)
self.ask_for_language_confirmation(workflow, language, uid, false)
end
end
def self.process_menu_option(message, state, app_id)
uid = message['authorId']
sm = CheckStateMachine.new(uid)
language = self.get_user_language(uid, message, state)
workflow = self.get_workflow(language)
typed, new_state = self.get_typed_message(message, sm)
state = new_state if new_state
if self.should_send_tos?(state, typed)
sm.reset
platform = self.get_platform_from_message(message)
self.send_tos_to_user(workflow, uid, language, platform)
self.bundle_message(message)
return true
end
workflow ||= {}
options = self.get_menu_options(state, workflow, uid)
# Look for button clicks and exact matches to menu options first...
options.each do |option|
if option['smooch_menu_option_keyword'].split(',').map(&:downcase).map(&:strip).collect{ |k| k.gsub(/[^a-z0-9]+/, '') }.include?(typed.gsub(/[^a-z0-9]+/, ''))
self.process_menu_option_value(option['smooch_menu_option_value'], option, message, language, workflow, app_id)
return true
end
end
# ...if nothing is matched, try using the NLU feature
option = SmoochNlu.menu_option_from_message(typed, language, options) if state != 'query'
unless option.nil?
self.process_menu_option_value(option['smooch_menu_option_value'], option, message, language, workflow, app_id)
return true
end
self.bundle_message(message)
return false
end
def self.user_received_report(message)
self.get_installation(self.installation_setting_id_keys, message['app']['_id'])
original = Rails.cache.read('smooch:original:' + message['message']['_id'])
unless original.blank?
original = begin JSON.parse(original) rescue {} end
if original['fallback_template'] =~ /report/
pmids = ProjectMedia.find(original['project_media_id']).related_items_ids
DynamicAnnotation::Field.joins(:annotation).where(field_name: 'smooch_data', 'annotations.annotated_type' => 'ProjectMedia', 'annotations.annotated_id' => pmids).where("value_json ->> 'authorId' = ?", message['appUser']['_id']).each do |f|
a = f.annotation.load
a.set_fields = { smooch_report_received: Time.now.to_i }.to_json
a.save!
end
end
end
end
def self.smooch_api_get_messages(app_id, user_id, opts = {})
self.zendesk_api_get_messages(app_id, user_id, opts)
end
def self.api_get_user_data(uid, payload)
if RequestStore.store[:smooch_bot_provider] == 'TURN'
self.turnio_api_get_user_data(uid, payload)
elsif RequestStore.store[:smooch_bot_provider] == 'CAPI'
self.capi_api_get_user_data(uid, payload)
else
self.zendesk_api_get_user_data(uid)
end
end
def self.api_get_app_name(app_id)
if RequestStore.store[:smooch_bot_provider] == 'TURN'
self.turnio_api_get_app_name
elsif RequestStore.store[:smooch_bot_provider] == 'CAPI'
self.capi_api_get_app_name
else
self.zendesk_api_get_app_data(app_id).app.name
end
end
def self.save_user_information(app_id, uid, payload_json)
payload = JSON.parse(payload_json)
self.get_installation(self.installation_setting_id_keys, app_id) if self.config.blank?
# FIXME Shouldn't we make sure this is an annotation in the right project?
field = DynamicAnnotation::Field.where('field_name = ? AND dynamic_annotation_fields_value(field_name, value) = ?', 'smooch_user_id', uid.to_json).last
if field.nil?
user = self.api_get_user_data(uid, payload)
app_name = self.api_get_app_name(app_id)
identifier = self.get_identifier(user, uid)
data = {
id: uid,
raw: user,
identifier: identifier,
app_name: app_name
}
a = Dynamic.new
a.skip_check_ability = true
a.skip_notifications = true
a.disable_es_callbacks = Rails.env.to_s == 'test'
a.annotation_type = 'smooch_user'
a.annotated_type = 'Team'
a.annotated_id = self.config['team_id'].to_i
a.set_fields = { smooch_user_data: data.to_json, smooch_user_id: uid, smooch_user_app_id: app_id }.to_json
a.save!
query = { field_name: 'smooch_user_data', json: { app_name: app_name, identifier: identifier } }.to_json
cache_key = 'dynamic-annotation-field-' + Digest::MD5.hexdigest(query)
Rails.cache.write(cache_key, DynamicAnnotation::Field.where(annotation_id: a.id, field_name: 'smooch_user_data').last&.id)
# Cache SmoochUserSlackChannelUrl if smooch_user_slack_channel_url exist
cache_slack_key = "SmoochUserSlackChannelUrl:Team:#{a.team_id}:#{uid}"
if Rails.cache.read(cache_slack_key).blank?
slack_channel_url = a.get_field_value('smooch_user_slack_channel_url')
Rails.cache.write(cache_slack_key, slack_channel_url) unless slack_channel_url.blank?
end
end
end
def self.get_identifier(user, uid)
# This identifier is used on the Slack side in order to connect a Slack conversation to a Smooch user
identifier = case user.dig(:clients, 0, :platform)
when 'whatsapp'
user.dig(:clients, 0, :displayName)
when 'messenger'
user.dig(:clients, 0, :info, :avatarUrl)&.match(/psid=([0-9]+)/)&.to_a&.at(1)
when 'twitter'
user.dig(:clients, 0, :info, :avatarUrl)&.match(/profile_images\/([0-9]+)\//)&.to_a&.at(1)
when 'telegram'
# The message on Slack side doesn't contain a unique Telegram identifier
nil
when 'viber'
viber_match = user.dig(:clients, 0, 'raw', 'avatar')&.match(/dlid=([^&]+)/)
viber_match.nil? ? nil : viber_match[1][0..26]
when 'line'
user.dig(:clients, 0, 'raw', 'pictureUrl')&.match(/sprofile\.line-scdn\.net\/(.*)/)&.to_a&.at(1)
end
identifier ||= uid
Digest::MD5.hexdigest(identifier)
end
def self.send_error_message(message, is_supported)
m_type = is_supported[:m_type] || 'file'
max_size = "Uploaded#{m_type.camelize}".constantize.max_size_readable
error_message = is_supported[:type] == false ? self.get_string(:invalid_format, message['language']) : I18n.t(:smooch_bot_message_size_unsupported, **{ max_size: max_size, locale: message['language'].gsub(/[-_].*$/, '') })
self.send_message_to_user(message['authorId'], error_message)
end
def self.send_message_to_user(uid, text, extra = {}, force = false)
return if self.config['smooch_disabled'] && !force
if RequestStore.store[:smooch_bot_provider] == 'TURN'
self.turnio_send_message_to_user(uid, text, extra, force)
elsif RequestStore.store[:smooch_bot_provider] == 'CAPI'
self.capi_send_message_to_user(uid, text, extra, force)
else
self.zendesk_send_message_to_user(uid, text, extra, force)
end
end
def self.create_project_media_from_message(message)
pm =
if message['type'] == 'text'
self.save_text_message(message)
else
self.save_media_message(message)
end
# Update archived column
if pm.is_a?(ProjectMedia) && pm.archived == CheckArchivedFlags::FlagCodes::UNCONFIRMED && message['archived'] != CheckArchivedFlags::FlagCodes::UNCONFIRMED
pm = ProjectMedia.find(pm.id)
pm.skip_check_ability = true
pm.archived = CheckArchivedFlags::FlagCodes::NONE
pm.save!
end
pm
end
def self.extract_url(text)
begin
urls = Twitter::TwitterText::Extractor.extract_urls(text)
return nil if urls.blank?
urls_to_ignore = self.config.to_h['smooch_urls_to_ignore'].to_s.split(/\s+/)
url = urls.reject{ |u| urls_to_ignore.include?(u) }.first
return nil if url.blank?
url = 'https://' + url unless url =~ /^https?:\/\//
url = Addressable::URI.escape(url)
URI.parse(url)
m = Link.new url: url
m.validate_pender_result(false, true)
if m.pender_error
raise SecurityError if m.pender_error_code == PenderClient::ErrorCodes::UNSAFE
nil
else
m
end
rescue URI::InvalidURIError => e
CheckSentry.notify(e, bot: 'Smooch', extra: { method: 'extract_url' })
nil
end
end
def self.extract_claim(text)
claim = ''
text.split(MESSAGE_BOUNDARY).each do |part|
claim = part.chomp.strip if part.size > claim.size
end
claim
end
def self.add_hashtags(text, pm)
hashtags = Twitter::TwitterText::Extractor.extract_hashtags(text)
return nil if hashtags.blank?
# Only add team tags.
TagText.where("team_id = ? AND text IN (?)", pm.team_id, hashtags).each do |tag|
unless pm.annotations('tag').map(&:tag_text).include?(tag.text)
Tag.create!(tag: tag.id, annotator: pm.user, annotated: pm)
end
end
end
def self.ban_user(message)
unless message.nil?
uid = message['authorId']
Rails.logger.info("[Smooch Bot] Banned user #{uid}")
Rails.cache.write("smooch:banned:#{uid}", message.to_json)
end
end
def self.user_banned?(payload)
uid = payload.dig('appUser', '_id')
!uid.blank? && !Rails.cache.read("smooch:banned:#{uid}").nil?
end
# Don't save as a ProjectMedia if it contains only menu options
def self.is_a_valid_text_message?(text)
!text.split(/#{MESSAGE_BOUNDARY}|\s+/).reject{ |m| m =~ /^[0-9]*$/ }.empty?
end
def self.save_text_message(message)
text = message['text']
team = Team.where(id: config['team_id'].to_i).last
return team unless self.is_a_valid_text_message?(text)
begin
link = self.extract_url(text)
pm = nil
extra = {}
if link.nil?
claim = self.extract_claim(text)
extra = { quote: claim }
pm = ProjectMedia.joins(:media).where('lower(quote) = ?', claim.downcase).where('project_medias.team_id' => team.id).last
else
extra = { url: link.url }
pm = ProjectMedia.joins(:media).where('medias.url' => link.url, 'project_medias.team_id' => team.id).last
end
if pm.nil?
type = link.nil? ? 'Claim' : 'Link'
pm = self.create_project_media(message, type, extra)
end
self.add_hashtags(text, pm)
pm
rescue SecurityError
self.ban_user(message)
nil
end
end
def self.create_project_media(message, type, extra)
extra.merge!({ archived: message['archived'] })
channel_value = self.get_smooch_channel(message)
extra.merge!({ channel: {main: channel_value }}) unless channel_value.nil?
pm = ProjectMedia.create!({ media_type: type, smooch_message: message }.merge(extra))
pm.is_being_created = true
pm
end
def self.detect_media_type(message)
type = nil
begin
headers = {}
url = URI(message['mediaUrl'])
Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') do |http|
headers = http.head(url.path).to_hash
end
m_type = headers['content-type'].first
type = m_type.split(';').first
unless type.nil? || type == message['mediaType']
Rails.logger.warn "[Smooch Bot] saved file #{message['mediaUrl']} as #{type} instead of #{message['mediaType']}"
end
rescue
nil
end
type || message['mediaType']
end
def self.store_media(media_id, mime_type)
if RequestStore.store[:smooch_bot_provider] == 'TURN'
self.store_turnio_media(media_id, mime_type)
elsif RequestStore.store[:smooch_bot_provider] == 'CAPI'
self.store_capi_media(media_id, mime_type)
end
end
def self.convert_media_information(message)
if ['audio', 'video', 'image', 'file', 'voice'].include?(message['type'])
mime_type = message.dig(message['type'], 'mime_type').to_s.gsub(/;.*$/, '')
{
mediaUrl: self.store_media(message.dig(message['type'], 'id'), mime_type),
mediaType: mime_type
}
else
{}
end
end
def self.save_media_message(message)
message = self.adjust_media_type(message)
allowed_types = { 'image' => 'jpeg', 'video' => 'mp4', 'audio' => 'mp3' }
return unless allowed_types.keys.include?(message['type'])
URI(message['mediaUrl']).open do |f|
text = message['text']
data = f.read
hash = Digest::MD5.hexdigest(data)
filename = "#{hash}.#{allowed_types[message['type']]}"
filepath = File.join(Rails.root, 'tmp', filename)
media_type = "Uploaded#{message['type'].camelize}"
File.atomic_write(filepath) { |file| file.write(data) }
team_id = self.config['team_id'].to_i
pm = ProjectMedia.joins(:media).where('medias.type' => media_type, 'medias.file' => filename, 'project_medias.team_id' => team_id).last
if pm.nil?
pm = ProjectMedia.new(archived: message['archived'], media_type: media_type, smooch_message: message)
pm.is_being_created = true
# set channel
channel_value = self.get_smooch_channel(message)
pm.channel = { main: channel_value } unless channel_value.nil?
File.open(filepath) do |f2|
pm.file = f2
pm.save!
end
end
FileUtils.rm_f filepath
self.add_hashtags(text, pm)
pm
end
end
def self.send_report_to_users(pm, action)
parent = Relationship.confirmed_parent(pm)
report = parent.get_annotations('report_design').last&.load
return if report.nil?
last_published_at = report.get_field_value('last_published').to_i
parent.get_deduplicated_smooch_annotations.each do |annotation|
data = JSON.parse(annotation.load.get_field_value('smooch_data'))
self.get_installation(self.installation_setting_id_keys, data['app_id']) if self.config.blank?
self.send_correction_to_user(data, parent, annotation.created_at, last_published_at, action, report.get_field_value('published_count').to_i) unless self.config['smooch_disabled']
end
end
def self.send_correction_to_user(data, pm, subscribed_at, last_published_at, action, published_count = 0)
self.get_platform_from_message(data)
uid = data['authorId']
lang = data['language']
# User received a report before
if subscribed_at.to_i < last_published_at.to_i && published_count > 0
if ['publish', 'republish_and_resend'].include?(action)
self.send_report_to_user(uid, data, pm, lang, 'fact_check_report_updated', self.get_string(:report_updated, lang))
end
# First report
else
self.send_report_to_user(uid, data, pm, lang, 'fact_check_report')
end
end
def self.send_report_to_user(uid, data, pm, lang = 'en', fallback_template = nil, pre_message = nil)
parent = Relationship.confirmed_parent(pm)
report = parent.get_dynamic_annotation('report_design')
Rails.logger.info "[Smooch Bot] Sending report to user #{uid} for item with ID #{pm.id}..."
if report&.get_field_value('state') == 'published' && [CheckArchivedFlags::FlagCodes::NONE, CheckArchivedFlags::FlagCodes::UNCONFIRMED].include?(parent.archived) && report.should_send_report_in_this_language?(lang)
unless pre_message.blank?
self.send_message_to_user(uid, pre_message)
sleep 1
end
last_smooch_response = nil
if report.report_design_field_value('use_introduction')
introduction = report.report_design_introduction(data, lang)
smooch_intro_response = self.send_message_to_user(uid, introduction)
Rails.logger.info "[Smooch Bot] Sent report introduction to user #{uid} for item with ID #{pm.id}, response was: #{smooch_intro_response&.body}"
sleep 1
end
if report.report_design_field_value('use_text_message')
workflow = self.get_workflow(lang)
last_smooch_response = self.send_final_messages_to_user(uid, report.report_design_text(lang), workflow, lang)
Rails.logger.info "[Smooch Bot] Sent text report to user #{uid} for item with ID #{pm.id}, response was: #{last_smooch_response&.body}"
elsif report.report_design_field_value('use_visual_card')
last_smooch_response = self.send_message_to_user(uid, '', { 'type' => 'image', 'mediaUrl' => report.report_design_image_url })
Rails.logger.info "[Smooch Bot] Sent report visual card to user #{uid} for item with ID #{pm.id}, response was: #{last_smooch_response&.body}"
end
self.save_smooch_response(last_smooch_response, parent, data['received'], fallback_template, lang)
end
end
def self.safely_parse_response_body(response)
begin JSON.parse(response.body) rescue nil end
end
def self.get_id_from_send_response(response)
response_body = self.safely_parse_response_body(response)
(RequestStore.store[:smooch_bot_provider] == 'TURN' || RequestStore.store[:smooch_bot_provider] == 'CAPI') ? response_body&.dig('messages', 0, 'id') : response&.body&.message&.id
end
def self.save_smooch_response(response, pm, query_date, fallback_template = nil, lang = 'en', custom = {}, expire = nil)
return false if response.nil? || fallback_template.nil?
id = self.get_id_from_send_response(response)
unless id.blank?
key = 'smooch:original:' + id
value = { project_media_id: pm&.id, fallback_template: fallback_template, language: lang, query_date: (query_date || Time.now.to_i) }.merge(custom).to_json
Rails.cache.write(key, value, expires_in: expire)
end
end
def self.send_report_from_parent_to_child(parent_id, target_id)
parent = ProjectMedia.where(id: parent_id).last
child = ProjectMedia.where(id: target_id).last
return if parent.nil? || child.nil?
child.get_annotations('smooch').find_each do |annotation|
data = JSON.parse(annotation.load.get_field_value('smooch_data'))
self.get_platform_from_message(data)
self.get_installation(self.installation_setting_id_keys, data['app_id']) if self.config.blank?
self.send_report_to_user(data['authorId'], data, parent, data['language'], 'fact_check_report')
end
end
def self.replicate_status_to_children(pm_id, status, uid, tid)
pm = ProjectMedia.where(id: pm_id).last
return if pm.nil?
User.current = User.where(id: uid).last
Team.current = Team.where(id: tid).last
pm.source_relationships.confirmed.joins('INNER JOIN users ON users.id = relationships.user_id').where("users.type != 'BotUser' OR users.type IS NULL").find_each do |relationship|
target = relationship.target
s = target.annotations.where(annotation_type: 'verification_status').last&.load
next if s.nil? || s.status == status
s.status = status
s.save!
end
User.current = nil
Team.current = nil
end
def self.refresh_smooch_slack_timeout(uid, slack_data = {})
time = Time.now.to_i
data = Rails.cache.read("smooch:slack:last_human_message:#{uid}") || {}
data.merge!(slack_data.merge({ 'time' => time }))
Rails.cache.write("smooch:slack:last_human_message:#{uid}", data)
sm = CheckStateMachine.new(uid)
if sm.state.value != 'human_mode'
sm.enter_human_mode
text = 'The bot has been de-activated for this conversation. You can now communicate directly to the user in this channel. To reactivate the bot, type `/check bot activate`. <http://help.checkmedia.org/en/articles/3336466-one-on-one-conversation-with-users-on-check-message|Learn about more features of the Slack integration here.>'
Bot::Slack.delay_for(1.second, { queue: 'smooch' }).send_message_to_slack_conversation(text, slack_data['token'], slack_data['channel'])
end
self.delay_for(15.minutes, { queue: 'smooch' }).timeout_smooch_slack_human_conversation(uid, time)
end
def self.timeout_smooch_slack_human_conversation(uid, time)
data = Rails.cache.read("smooch:slack:last_human_message:#{uid}")
return if !data || data['time'].to_i > time
sm = CheckStateMachine.new(uid)
if sm.state.value == 'human_mode'
sm.leave_human_mode
text = 'Automated bot-message reactivated after 15 min of inactivity. <http://help.checkmedia.org/en/articles/3336466-talk-to-users-on-your-check-message-tip-line|Learn more here>.'
Bot::Slack.send_message_to_slack_conversation(text, data['token'], data['channel'])
end
end
def self.refresh_smooch_menu_timeout(message, app_id)
uid = message['authorId']
time = Time.now.to_f
Rails.cache.write("smooch:last_message_from_user:#{uid}", time)
self.delay_for(15.minutes, { queue: 'smooch' }).timeout_smooch_menu(time, message, app_id, RequestStore.store[:smooch_bot_provider])
end
def self.timeout_smooch_menu(time, message, app_id, provider)
self.get_installation(self.installation_setting_id_keys, app_id) if self.config.blank?
RequestStore.store[:smooch_bot_provider] = provider
return if self.config['smooch_disable_timeout']
uid = message['authorId']
language = self.get_user_language(uid)
stored_time = Rails.cache.read("smooch:last_message_from_user:#{uid}").to_i
return if stored_time > time
sm = CheckStateMachine.new(uid)
unless ['human_mode', 'waiting_for_message'].include?(sm.state.value)
uid = message['authorId']
annotated = nil
type = 'timeout_requests'
if sm.state.value == 'search_result'
annotated = self.get_saved_search_results_for_user(uid)
type = 'timeout_search_requests'
end
self.send_message_to_user_on_timeout(uid, language)
self.bundle_messages(uid, message['_id'], app_id, type, annotated, true)
sm.reset
end
end
def self.sanitize_installation(team_bot_installation, blast_secret_settings = false)
team_bot_installation.apply_default_settings
team_bot_installation.reset_smooch_authorization_token
if blast_secret_settings
[
'capi_whatsapp_business_account_id', 'capi_verify_token', 'capi_permanent_token', 'capi_phone_number_id', 'capi_phone_number', # CAPI
'smooch_app_id', 'smooch_secret_key_key_id', 'smooch_secret_key_secret', 'smooch_webhook_secret', # Smooch
'turnio_secret', 'turnio_token', 'turnio_host' # On-prem
].each do |key|
team_bot_installation.settings.delete(key)
end
end
team_bot_installation
end
end
|
# frozen_string_literal: true
require_relative 'lib/monkeylang/version'
Gem::Specification.new do |spec|
spec.name = 'monkeylang'
spec.version = MonkeyLang::VERSION
spec.authors = ['Farid Zakaria']
spec.email = ['farid.m.zakaria@gmail.com']
spec.summary = 'A Ruby implementation of the Monkey language.'
spec.description = 'A Ruby inspired implementation of the Monkey language.'
spec.homepage = 'https://github.com/fzakaria/monkeylang'
spec.license = 'MIT'
spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = 'https://github.com/fzakaria/monkeylang'
spec.metadata['changelog_uri'] = 'https://github.com/fzakaria/monkeylang/blob/master/CHANGELOG'
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = 'exe'
spec.executables = ['monkey']
spec.require_paths = ['lib']
spec.add_dependency 'activesupport'
spec.add_dependency 'slop'
spec.add_dependency 'sorbet-runtime'
spec.add_development_dependency 'guard'
spec.add_development_dependency 'guard-minitest'
spec.add_development_dependency 'guard-rubocop'
spec.add_development_dependency 'minitest', '~> 5.0'
spec.add_development_dependency 'rake', '~> 12.0'
spec.add_development_dependency 'rubocop'
spec.add_development_dependency 'sorbet'
end
|
# frozen_string_literal: true
module SitePrism
module ElementChecker
def all_there?
elements_to_check.all? { |element| present?(element) }
end
def elements_present
mapped_items.select { |item_name| present?(item_name) }
end
private
def elements_to_check
if self.class.expected_items
mapped_items.select do |el|
self.class.expected_items.include?(el)
end
else
mapped_items
end
end
def mapped_items
self.class.mapped_items.uniq
end
def present?(element)
send("has_#{element}?")
end
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :rememberable
has_many :posts
has_many :images
validates :email,
presence: true,
format: { with: /.+@.+\..+/i },
uniqueness: true
validates :password,
presence: true,
length: { minimum: 8 },
confirmation: true
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.
#
#
# ****************************************************************************
# status: complete
require '../../util/assert.rb'
# to check whether the caller can access public/protected/private methods.
# - class, instance methods? // class methods always public?
# - access the defined methods inside the class, derived class, and outside the class
class My_base
public
def My_base.pub_sm; -100; end
def pub_im; 100; end
protected
def My_base.prot_sm; -200; end
def prot_im; 200; end
private
def My_base.priv_sm; -300; end
def priv_im; 300; end
public
def instance_check_from_base
assert_equal(pub_im, 100)
assert_equal(prot_im, 200)
assert_equal(priv_im, 300)
# accessing via self
assert_equal(self.pub_im, 100)
assert_equal(self.prot_im, 200)
assert_raise(NoMethodError) { self.priv_im }
assert_equal(My_base.pub_sm, -100)
assert_equal(My_base.prot_sm, -200)
assert_equal(My_base.priv_sm, -300)
end
def My_base.static_check_from_base
assert_equal(pub_sm, -100)
assert_equal(prot_sm, -200)
assert_equal(priv_sm, -300)
assert_equal(self.pub_sm, -100)
assert_equal(self.prot_sm, -200)
assert_equal(self.priv_sm, -300)
assert_equal(My_base.pub_sm, -100)
assert_equal(My_base.prot_sm, -200)
assert_equal(My_base.priv_sm, -300)
end
def instance_check_as_arg_from_base arg
assert_equal(arg.pub_im, 100)
assert_equal(arg.prot_im, 200)
assert_raise(NoMethodError) { arg.priv_im }
end
def My_base.static_check_as_arg_from_base arg
assert_equal(arg.pub_im, 100)
assert_raise(NoMethodError) { arg.prot_im }
assert_raise(NoMethodError) { arg.priv_im }
end
end
x = My_base.new
# calling outside
assert_equal(My_base.pub_sm, -100)
assert_equal(My_base.prot_sm, -200)
assert_equal(My_base.priv_sm, -300)
assert_equal(x.pub_im, 100)
assert_raise(NoMethodError) { x.prot_im } # protected method `prot_im' called for #<My_base:0x769f878> (NoMethodError)
assert_raise(NoMethodError) { x.priv_im } # private method `priv_im' called for #<My:0x75e0450> (NoMethodError)
My_base.static_check_from_base
x.instance_check_from_base
My_base.static_check_as_arg_from_base x
x.instance_check_as_arg_from_base x
class My_derived < My_base
public
def instance_check_from_derived
assert_equal(pub_im, 100)
assert_equal(prot_im, 200)
assert_equal(priv_im, 300)
assert_equal(self.pub_im, 100)
assert_equal(self.prot_im, 200)
assert_raise(NoMethodError) { self.priv_im }
assert_equal(My_derived.pub_sm, -100)
assert_equal(My_derived.prot_sm, -200)
assert_equal(My_derived.priv_sm, -300)
end
def My_base.static_check_from_derived
assert_equal(pub_sm, -100)
assert_equal(prot_sm, -200)
assert_equal(priv_sm, -300)
assert_equal(self.pub_sm, -100)
assert_equal(self.prot_sm, -200)
assert_equal(self.priv_sm, -300)
assert_equal(My_derived.pub_sm, -100)
assert_equal(My_derived.prot_sm, -200)
assert_equal(My_derived.priv_sm, -300)
end
def instance_check_as_arg_from_derived arg
assert_equal(arg.pub_im, 100)
assert_equal(arg.prot_im, 200)
assert_raise(NoMethodError) { arg.priv_im }
end
def My_derived.static_check_as_arg_from_derived arg
assert_equal(arg.pub_im, 100)
assert_raise(NoMethodError) { arg.prot_im }
assert_raise(NoMethodError) { arg.priv_im }
end
end
y = My_derived.new
y.instance_check_from_derived
My_derived.static_check_from_derived
y.instance_check_as_arg_from_derived y
My_derived.static_check_as_arg_from_derived y
assert_equal(y.pub_im, 100)
assert_raise(NoMethodError) { y.prot_im }
assert_raise(NoMethodError) { y.priv_im }
|
# frozen_string_literal: true
require 'structures/doubly_linked_list'
module Structures
# +Structures::Queue+ represents a Queue
class Queue
def initialize
@list = Structures::DoublyLinkedList.new
end
def empty?
@list.empty?
end
def offer(item)
@list.add_last(item)
end
def poll
raise 'Empty Queue' if empty?
@list.remove_first
end
def peek
raise 'Empty Queue' if empty?
@list.peek_first
end
def search(item)
@list.index_of(item)
end
def size
@list.size
end
end
end
|
class CreateTaskListService
include Auth::JsonWebTokenHelper
def call(payload_json)
@payload = JSON.parse(payload_json)
@task_list = TaskList.new(create_task_params)
if @task_list.save
task_list_data
else
unprocessable_entity
end
end
private
def task_list_data
{
headers: { "status_code": 200 },
payload: {
data: TaskListSerializer.new(@task_list).attributes
}
}
end
def unprocessable_entity
{
headers: { "status_code": 422 },
payload: {
errors: [{
error_message: 'unprocessable entity :('
}]
}
}
end
def create_task_params
{
user_id: @payload['user_id'],
name: @payload['name'],
description: @payload['description'],
frequence_type: @payload['frequence_type']
}
end
end
|
class AddAvailabilityIdInMeetings < ActiveRecord::Migration[6.0]
def change
add_reference :availabilities, :availability, foreign_key: true
end
end
|
class ChallengesController < ApplicationController
def index
@contest = Contest.current
@challenges = @contest.challenges
end
end |
#!/usr/bin/env ruby
VERSION='1.1.0'
$:.unshift File.expand_path('../../lib', __FILE__)
require 'hashie'
require 'devops_api'
require 'pry'
require 'awesome_print'
class Api
include DevopsApi
end
begin
opts = Slop.parse(strict: true, help: true) do
banner "Domain Cutover List Hosted Zones, version #{VERSION}\n\nUsage: domain_cutover_list_hz [options]"
on 'p', 'profile', '[required] The name of the AWS credential profile to use.', argument: true
on 'v', 'version' do
puts 'domain cutover, version #{version}'
exit 0
end
end
opts = Hashie::Mash.new(opts.to_hash)
# Profile required test
raise 'AWS Profile name required!' unless opts.profile?
api = Api.new(opts.profile)
# list hosted zones
hz_list = api.get_hosted_zone_list
puts ''
puts 'Hosted Zones'
puts ''
ap hz_list
puts ''
rescue => e
puts ''
puts e.message
puts ''
end
|
class PhoneNumbersController < ApplicationController
def index
@phone_numbers = PhoneNumber.all
end
def edit
@phone_number = PhoneNumber.where(id: params['id']).first
end
def new
@phone_number = PhoneNumber.new
@person = Person.find_by_id(params[:person_id])
end
def create
@phone_number = PhoneNumber.new(phone_number_params)
@person = Person.find_by_id(phone_number_params[:phoneable_id])
if @phone_number.save
redirect_to @person
else
render 'new'
end
end
def destroy
@phone_number = PhoneNumber.where(id: params['id']).first
person = @phone_number.phoneable
flash.notice = "Deleting phone number #{@phone_number.number}"
@phone_number.destroy
redirect_to person
end
def phone_number_params
params.require(:phone_number).permit(:phoneable_type, :phoneable_id, :description, :number)
end
end
|
class CreateArticles < ActiveRecord::Migration[5.1]
def change
create_table :articles do |t|
t.integer :Articleno, null: false
t.string :Regno, foreign_key: true
t.text :abstract
t.string :Articletype
t.string :Language
t.text :article
t.string :Status
t.references :reg
t.timestamps
end
add_index :articles, :Articleno, unique: true
end
end
|
module Adornable
class Decorators
def self.log(method_receiver, method_name, arguments)
receiver_name, name_delimiter = if method_receiver.is_a?(Class)
[method_receiver.to_s, '::']
else
[method_receiver.class.to_s, '#']
end
full_name = "`#{receiver_name}#{name_delimiter}#{method_name}`"
arguments_desc = arguments.empty? ? "no arguments" : "arguments `#{arguments}`"
puts "Calling method #{full_name} with #{arguments_desc}"
yield
end
def self.memoize(method_receiver, method_name, arguments)
memo_var_name = :"@adornable_memoized_#{method_receiver.object_id}_#{method_name}"
existing = instance_variable_get(memo_var_name)
value = existing.nil? ? yield : existing
instance_variable_set(memo_var_name, value)
end
def self.memoize_for_arguments(method_receiver, method_name, arguments)
memo_var_name = :"@adornable_memoized_#{method_receiver.object_id}__#{method_name}__#{arguments}"
existing = instance_variable_get(memo_var_name)
value = existing.nil? ? yield : existing
instance_variable_set(memo_var_name, value)
end
end
end
|
require 'rails_helper'
require 'base64'
RSpec.describe Ng::V1::VehiclesController, type: :controller do
let(:user) { User.first }
let(:user_auth_data) { Base64.strict_encode64("#{user.email}:test@1234") }
let(:vehicle) { Vehicle.first }
let(:vehicle_2) { Vehicle.last }
describe 'GET #index' do
context 'with no authorization header' do
it 'responds successfully HTTP 401 status code' do
get :index
expect(response).to have_http_status(401)
end
end
context 'with invalid authorization header' do
before(:each) do
request.headers['Authorization'] = 'hello'
get :index
end
it 'responds successfully HTTP 401 status code' do
expect(response).to have_http_status(401)
end
end
context 'with valid authorization header' do
before(:each) do
request.headers['Authorization'] = "Basic #{user_auth_data}"
get :index
end
it 'responds successfully HTTP 200 status code' do
expect(response).to be_success
expect(response).to have_http_status(200)
expect(response.body).to eq(Vehicle.all.to_json)
end
end
end
describe 'PUT next_state' do
before(:each) do
request.headers['Authorization'] = "Basic #{user_auth_data}"
end
context 'next state available' do
before(:each) do
put :next_state, params: { id: vehicle.id }
end
it 'changes Designed to Assembled' do
expect(response).to be_success
expect(response).to have_http_status(200)
expect(JSON.parse(response.body)['vehicle']['state_name']).to eq('Assembled')
end
end
context 'next state not available' do
before(:each) do
vehicle_2.update(state_id: State.ordered.last.id)
put :next_state, params: { id: vehicle_2.id }
end
it 'returns 403' do
expect(response).to have_http_status(400)
end
end
end
end
|
class Word
def initialize(word)
@word = word
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.