text stringlengths 10 2.61M |
|---|
class Species < ActiveRecord::Base #sighting has one species and belongs to a region; a region has many sightings
validates :name, :presence => true #a species has many sightings; a sighting has one species
belongs_to :regions #todo whats the difference
has_many :sightings
end |
require 'spec_helper'
module Refinery
module Testimonials
describe Testimonial, type: :model do
let(:good_testimonial) { FactoryBot.create(:testimonial)}
let(:no_name_testimonial) { FactoryBot.create(:testimonial, name: "") }
let(:no_quote_testimonial) { FactoryBot.create(:testimonial, quote: "")}
describe 'validations' do
context "with all required attributes" do
it "has no errors" do
expect(good_testimonial.errors).to be_empty
end
it "has a name" do
expect(testimonial.name).to eq('Person Name')
end
it "has a quote" do
expect(testimonial.quote).to eq('Like your work')
end
end
context "without required attribute name" do
it 'fails validation' do
expect(no_name_testimonial).not_to be_valid
end
it "has errors" do
expect(no_name_testimonial.errors).not_to be_empty
end
end
context "without required attribute quote" do
it 'fails validation' do
expect(no_quote_testimonial).not_to be_valid
end
it "has errors" do
expect(no_name_testimonial.errors).not_to be_empty
end
end
end
end
end
end
|
#!/usr/bin/env ruby
require 'csv'
require 'rally_rest_api'
require 'ostruct'
require 'optparse'
require 'yaml'
require 'gruff'
options = OpenStruct.new
options.csvoutput = false
options.pdfouput = false
options.iteration = ""
options.user = nil
options.password = nil
opts = OptionParser.new
opts.banner = "Usage: taskpair [options] TASKID username , username ..."
opts.on('-U username','--user=username','Provides a Rally User') do |user|
options.user = user
end
opts.on('-P password','--password=password','Provides a Rally Password') do |pass|
options.password = pass
end
opts.on('-r','--remove','Removes rally users from the task') do |user|
options.action='remove'
end
opts.on('-a','--add','Adds rally users to the task') do |user|
options.action='add'
end
opts.on_tail( '-h', '--help', 'Displays this screen' ) do
puts opts
exit
end
opts.parse!(ARGV)
obj_name = ARGV.shift
if !obj_name then
puts opts
exit
end
begin
config = YAML.load_file("#{Dir.home}/.rallyutils")
rescue
if !options.user and !options.password then
puts opts
puts "\nERROR: #{Dir.home}/.rallyutils not found and no user/password provided"
exit
end
end
rally_user=options.user || config["user"]
rally_pass=options.password || config["password"]
#Queries iteratio
rally = RallyRestAPI.new(:username => rally_user, :password => rally_pass)
res = rally.find( :task ) { equal :formatted_i_d , obj_name }
task = res.first
pair = []
if task.pair then
pair = task.pair.split(',')
end
if options.action == 'add' then
ARGV.each do |user|
if !pair.include?(user) then
pair.push(user)
end
end
end
if options.action == 'remove' then
ARGV.each do |user|
if pair.include?(user) then
pair.delete(user)
end
end
end
if options.action then
task.update(:pair => pair.join(','))
else
puts pair
end
|
Rails.application.routes.draw do
resources :articles, only: [:index, :create, :show] do
resources :comments
end
root "articles#index"
end
|
module QuotientCube
module Tree
module Query
class Point < Base
def process(selected = {})
node_id = tree.nodes.root
tree.dimensions.each_with_index do |dimension, index|
value = conditions[dimension]
if value != nil and value != '*'
node_id = search(node_id, dimension, value, index)
end
break if node_id.nil?
Point.log("Found node #{node_id}:#{value} at #{dimension}") unless value.nil?
end
if node_id.nil?
return node_id
else
return search_measures(node_id, measures).merge(selected)
end
end
class << self
def log(title, msg = nil)
puts "[Point Query] #{title} => #{msg}" if QuotientCube::Tree::Query::Base.debugging?
end
end
end
end
end
end |
class ApplicationController < ActionController::API
include ActionController::MimeResponds
include ActionController::ImplicitRender
include ActionController::StrongParameters
before_action :cors_set_access_control_headers
###################
# ERROR RESPONSES #
###################
# Generic fallback - this has to be FIRST
rescue_from(Exception) do |exception|
logger.error "[500 ERROR]: #{exception.message}"
exception.backtrace.each { |line| logger.error line }
Rollbar.report_exception(exception, rollbar_request_data, rollbar_person_data) if defined?(Rollbar)
render json: {success: false, message: "Sorry - something went wrong."}, status: 500
end
# Postgres will error if calling find without a valid UUID string. Could
# try to validate UUID's using regex, but that didn't work perfectly on
# naieve implementation. Just let the database check the format, and 404 if
# it was invalid.
rescue_from ActiveRecord::StatementInvalid, with: :record_not_found
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
rescue_from ActionController::RoutingError, with: :record_not_found
rescue_from ActionController::ParameterMissing, with: :missing_parameters
rescue_from ActionController::UnpermittedParameters do |exception|
logger.warn "[ERROR]: Unpermitted parameters passed to the controller (#{current_user && current_user.email})"
invalid_parameters
end
rescue_from CustomExceptions::InvalidOauthCredentials, with: :invalid_parameters
rescue_from CustomExceptions::MissingParameters, with: :missing_parameters
rescue_from CustomExceptions::InvalidParameters, with: :invalid_parameters
rescue_from CustomExceptions::UserExistsFromOauth do |exception|
provider = exception.message
oauth_login_error "That e-mail is already attached to a different provider (try #{provider})."
end
rescue_from CustomExceptions::UserExistsWithPassword do |exception|
oauth_login_error "An account already exists for that email using password registration. Please sign in with your email/password, and then you can add that authentication provider from your profile page."
end
protected
def authenticate_user!
if user_signed_in?
true
else
access_denied
false
end
end
def current_user
@current_user ||= get_user
end
def user_signed_in?
current_user.present?
end
def get_user
email = request.headers['X-Auth-Email'] || request.headers['HTTP-X-Auth-Email'] || params[:auth_email]
auth_token = request.headers['X-Auth-Token'] || request.headers['HTTP-X-Auth-Token'] || params[:auth_token]
logger.debug( (email.present? && auth_token.present?) ? "[AUTH_INFO]: #{email} || #{auth_token}" : "[AUTH INFO]: NONE" ) if Rails.env.development?
User.authenticate_from_email_and_token(email, auth_token)
end
def access_denied(message = "Error with your login credentials")
render json: {success: false, message: message}, status: 401
end
def record_not_found
render json: {success: false, message: "404 - Record Not Found"}, status: 404
end
def missing_parameters
render json: {success: false, message: "422 - Missing parameters"}, status: 422
end
def invalid_parameters(message="422 - Invalid parameters")
render json: {success: false, message: message}, status: 422
end
def oauth_login_error(message)
render json: { success: false, message: message, sticky: 10000 }, status: 422
end
def cors_set_access_control_headers
origin_header = request.headers["HTTP_ORIGIN"]
if Rails.env.deveopment?
headers['Access-Control-Allow-Origin'] = '*'
elsif origin_header.present? && ( origin_header == ENV['ADMIN_APP'] || origin_header == ENV['FRONTEND'] )
headers['Access-Control-Allow-Origin'] = origin_header
else
headers['Access-Control-Allow-Origin'] = ENV['FRONTEND']
end
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Max-Age'] = "1728000"
headers['Access-Control-Allow-Methods'] = %w{
POST
PUT
PATCH
DELETE
GET
OPTIONS
}.join(', ')
headers['Access-Control-Allow-Headers'] = %w{
*
Origin
X-Requested-With
Content-Type
Accept
X-Auth-Email
X-Auth-Token
If-Modified-Since
If-None-Match
}.join(', ')
end
end
|
class MenuItem < ActiveRecord::Base
before_save :linkit
belongs_to :menu
#acts_as_nested_set
attr_accessor :page
attr_accessor :url
def published?
self.published == 1
end
private
def linkit
self.link = ( self.page == 0 ) ? self.url : self.page
end
end |
FactoryGirl.define do
factory :start_time do
day_of_week 1
time '2014-12-14 00:44:29'
track nil
is_repeated true
factory :start_time_with_date do
day_of_week nil
date 2.day.from_now
is_repeated false
end
factory :start_time_with_passed_date do
day_of_week nil
date 2.day.ago
is_repeated false
end
end
end
|
class ItemApisController < ApplicationController
# GET /item_apis
# GET /item_apis.xml
def index
@item_apis = ItemApi.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @item_apis }
end
end
# GET /item_apis/1
# GET /item_apis/1.xml
def show
@item_api = ItemApi.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @item_api }
end
end
# GET /item_apis/new
# GET /item_apis/new.xml
def new
@item_api = ItemApi.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @item_api }
end
end
# GET /item_apis/1/edit
def edit
@item_api = ItemApi.find(params[:id])
end
# POST /item_apis
# POST /item_apis.xml
def create
@item_api = ItemApi.new(params[:item_api])
respond_to do |format|
if @item_api.save
format.html { redirect_to(@item_api, :notice => 'Item api was successfully created.') }
format.xml { render :xml => @item_api, :status => :created, :location => @item_api }
else
format.html { render :action => "new" }
format.xml { render :xml => @item_api.errors, :status => :unprocessable_entity }
end
end
end
# PUT /item_apis/1
# PUT /item_apis/1.xml
def update
@item_api = ItemApi.find(params[:id])
respond_to do |format|
if @item_api.update_attributes(params[:item_api])
format.html { redirect_to(@item_api, :notice => 'Item api was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @item_api.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /item_apis/1
# DELETE /item_apis/1.xml
def destroy
@item_api = ItemApi.find(params[:id])
@item_api.destroy
respond_to do |format|
format.html { redirect_to(item_apis_url) }
format.xml { head :ok }
end
end
end
|
module API
module V1
class WordsController < ApplicationController
def index
words = Word.all
render json: words, status: 200
end
def show
word = Word.find(params[:id])
render json: word, status: 200
end
def create
word = Word.new(word_params)
if word.save
render json: word, status: 201, location: api_v1_word_url(word[:id])
else
render json: word.errors, status: 422
end
end
private
def word_params
params.require(:word).permit(:name)
end
end
end
end
|
class Api::Merchant::BaseController < ApplicationController
skip_before_filter :verify_authenticity_token
before_filter :authenticate_merchant!, :set_headers
respond_to :json
before_filter :set_headers
private
def set_headers
if request.headers["HTTP_ORIGIN"] #&& /^https?:\/\/(.*)\.some\.site\.com$/i.match(request.headers["HTTP_ORIGIN"])
headers['Access-Control-Allow-Origin'] = request.headers["HTTP_ORIGIN"]
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE'
headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match,Auth-User-Token'
headers['Access-Control-Max-Age'] = '86400'
headers['Access-Control-Allow-Credentials'] = 'true'
end
end
rescue_from Exception do |exception|
output = generate_exception_output(exception)
render :json => output
end
end
|
module ProductPriceRangeHelper
def product_price_range(product)
price = number_to_currency(product.min_price, strip_insignificant_zeros: true)
price = "#{price} - #{number_to_currency(product.max_price)}" unless product.min_price == product.max_price
price
end
end
|
Moli::Application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
root 'recipes#index'
get '/register', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
resources :recipes do
member do
post :vote
end
resources :comments, only: [:create] do
member do
post :vote
end
end
end
resources :categories, only: [:show, :new, :create]
resources :users, except: [:new, :destroy]
end
|
require 'spec_helper'
describe User do
before(:each) do
@attr = {
:name => "Example User",
:email => "user@example.com",
:password => "changeme",
:password_confirmation => "changeme"
}
end
it "creates a new instance given a valid attribute" do
User.create!(@attr)
end
it "requires an email address" do
no_email_user = User.new(@attr.merge(:email => ""))
expect(no_email_user).not_to be_valid
end
it "accepts valid email addresses" do
addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
addresses.each do |address|
valid_email_user = User.new(@attr.merge(:email => address))
expect(valid_email_user).to be_valid
end
end
it "rejects invalid email addresses" do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
addresses.each do |address|
invalid_email_user = User.new(@attr.merge(:email => address))
expect(invalid_email_user).not_to be_valid
end
end
it "rejects duplicate email addresses" do
User.create!(@attr)
user_with_duplicate_email = User.new(@attr)
expect(user_with_duplicate_email).not_to be_valid
end
it "rejects email addresses identical up to case" do
upcased_email = @attr[:email].upcase
User.create!(@attr.merge(:email => upcased_email))
user_with_duplicate_email = User.new(@attr)
expect(user_with_duplicate_email).not_to be_valid
end
describe "passwords" do
before(:each) do
@user = User.new(@attr)
end
it "has a password attribute" do
expect(@user).to respond_to(:password)
end
it "has a password confirmation attribute" do
expect(@user).to respond_to(:password_confirmation)
end
end
describe "password validations" do
it "requires a password" do
user = User.new(@attr.merge(:password => "", :password_confirmation => ""))
expect(user).not_to be_valid
end
it "requires a matching password confirmation" do
user = User.new(@attr.merge(:password_confirmation => "invalid"))
expect(user).not_to be_valid
end
it "rejects short passwords" do
short = "a" * 5
hash = @attr.merge(:password => short, :password_confirmation => short)
expect(User.new(hash)).not_to be_valid
end
end
describe "password encryption" do
before(:each) do
@user = User.create!(@attr)
end
it "has an encrypted password attribute" do
expect(@user).to respond_to(:encrypted_password)
end
it "sets the encrypted password attribute" do
expect(@user.encrypted_password).not_to be_blank
end
end
describe "skills" do
let(:user) { create(:user) }
let(:skill) { create(:skill, category: category) }
let(:category) { create(:category) }
it "finds skills that have been completed" do
expect(user.skills).to be_empty
create(:completion, user: user, skill: skill)
expect(user).to have(1).skills
expect(user.skills).to match([skill])
other_completion = create(:completion, user: user)
expect(user.reload).to have(2).skills
expect(user.skills).to include(skill)
end
it "finds skills by category" do
create(:completion, user: user, skill: skill)
other_completion = create(:completion, user: user)
# scope down on category
expect(user.skills.for_category(category)).to have(1).item
expect(user.skills.for_category(category)).not_to include(other_completion.skill)
end
it "checks completion of a skill" do
expect(user).not_to have_completed(skill)
create(:completion, user: user, skill: skill)
expect(user).to have_completed(skill)
end
end
end
|
class TasksController < ApplicationController
before_filter :signed_in_user, only: [:index, :create, :update, :edit, :destroy]
before_filter :correct_user, only: [:destroy, :edit, :update]
def index
@tasks = Task.where(:complete => false)
@tasks_complete = Task.where(:complete => true)
@user = current_user
end
def new
@task = Task.new
end
def create
@task = current_user.tasks.build(params[:task])
@task.priority = Task.maximum("priority") + 1
if @task.save
flash[:success] = "Task created!"
redirect_to '/tasks'
else
render 'tasks'
end
end
def edit
@task = Task.find(params[:id])
@users = User.all.map {|user| [user.name, user.id]}
end
def update
@task = Task.find(params[:id])
if @task.update_attributes(params[:task])
flash[:success] = "Profile Updated"
redirect_to '/tasks'
else
render 'edit'
end
end
def update_all
params['task'].keys.each do |id|
@task = Task.find(id.to_i)
@task.update_attributes(params['task'][id])
end
flash[:success] = "Profile Updated"
redirect_to '/tasks'
end
def destroy
@task.destroy
flash[:success] = "Task Deleted"
redirect_to '/tasks'
end
private
def correct_user
@task = current_user.tasks.find_by_id(params[:id])
redirect_to root_url if @task.nil? && !current_user.admin?
end
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
require 'open-uri'
# User.destroy_all
# url = 'https://source.unsplash.com/collection/829192/1920x1080'
# counter = 1
# 10.times do
# u = User.create!(
# email: Faker::Internet.email,
# password: 'password',
# user_name: Faker::Internet.user_name
# )
# game = Game.new(
# name: Faker::Pokemon.name,
# description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
# sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
# genre: Faker::Book.genre,
# location: Faker::GameOfThrones.city,
# platform: ["PS4", "XB1", "Steam(PC)"].sample,
# price: (1..6).to_a.sample,
# )
# game.remote_photo_url = url
# game.user = u
# game.save
# sleep(1)
# puts "created user number #{counter}"
# counter += 1
# end
User.destroy_all
ben = User.create!(
email: "ben.s-a@hotmail.com",
user_name: "Ben",
password: "123456"
)
User.create!(
email: "alex.s-a@hotmail.com",
user_name: "Alex",
password: "123456"
)
Game.create!(
name: 'GTA',
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
genre: 'Action-adventure',
location: 'London',
platform: 'XB1',
price: 5,
remote_photo_url: "https://cdn.images.dailystar.co.uk/dynamic/184/photos/553000/620x/GTA-5-online-630659.jpg",
user_id: 1
)
Game.create!(
name: 'Diablo 3',
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
genre: 'Role-Playing Game',
location: 'Machester',
platform: 'Steam(PC)',
price: 7,
remote_photo_url: "http://www.dlcompare.com:8042/upload/cache/game_tetiere/img/diablo-3-reaper-of-souls-img-4.jpg",
user_id: 1
)
Game.create!(
name: 'FIFA',
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
genre: 'Sport',
location: 'Birmingham',
platform: 'PS4',
price: 10,
remote_photo_url: "https://media.contentapi.ea.com/content/dam/ea/easports/fifa/ultimate-team/campaigns/2018/home-page-toty/fifa18-homepage-topterhero-bg-xs.jpg",
user_id: 1
)
Game.create!(
name: 'FIFA',
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
genre: 'Sport',
location: 'Leeds',
platform: 'PS4',
price: 8,
remote_photo_url: "https://media.contentapi.ea.com/content/dam/ea/easports/fifa/ultimate-team/campaigns/2018/home-page-toty/fifa18-homepage-topterhero-bg-xs.jpg",
user_id: 1
)
puts "seeding complete"
|
# frozen_string_literal: true
class StopSerializer < ActiveModel::Serializer
attributes :id, :x, :y
end
|
# -*- ruby -*-
#encoding: utf-8
require 'simplecov' if ENV['COVERAGE']
require 'rspec'
require 'loggability/spechelpers'
require 'arborist'
require 'arborist/mixins'
require 'arborist/webservice'
RSpec::Matchers.define( :match_criteria ) do |criteria|
match do |node|
criteria = Arborist::HashUtilities.stringify_keys( criteria )
node.matches?( criteria )
end
end
### Mock with RSpec
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
config.mock_with( :rspec ) do |mock|
mock.syntax = :expect
end
config.include( Loggability::SpecHelpers )
end
|
module Machsend
module RPC
class ClientToClient
def initialize(base, client)
@base, @client = base, client
end
def sync
@client.refresh
true
end
def assets
@base.assets
end
def download(guid)
@asset = @base.asset_by_guid(guid)
@asset.open
end
end
end
end |
class AddRangeFieldtoTemplateFields < ActiveRecord::Migration
def change
add_column :template_fields, :start_of_range, :integer
add_column :template_fields, :end_of_range, :integer
end
end
|
class Question
attr_reader :num1, :num2
attr_accessor :is_right
def initialize(current_player)
@num1 = 1 + rand(20)
@num2 = 1 + rand(20)
puts "#{current_player}: What does #{num1} plus #{num2} equal?"
print "> "
end
def ques
@num1 + @num2
end
def answer
users_input = $stdin.gets.chomp.to_i
if users_input == self.ques
puts "Good Work!!!"
@is_right = true
else
puts "Seriously? WRONG!!!"
@is_right = false
end
end
end
|
# frozen_string_literal: true
class Role < ::ApplicationRecord
def table_id = 'rol'
has_many :users
has_many :allowed_actions, dependent: :destroy
class << self
def admin = find_by!(name: 'admin')
def login = find_by!(name: 'login')
def default = find_by!(name: 'default')
end
end
|
class SubCategory < ActiveRecord::Base
has_many :product_categories
has_many :products, through: :product_categories
belongs_to :category, inverse_of: :sub_category
rails_admin do
navigation_label 'Cadastros'
list do
field :id
field :name
field :category
end
edit do
field :name
field :category
end
end
end
|
class CommentsController < ApplicationController
layout false
before_filter :authenticate_user!
def create
@comment = Comment.new(params[:comment])
unless [@comment.bid.bidder, @comment.bid.requestor].include?(current_user)
render json: {error: 'Unauthorized'}, status: :unauthorized
return
end
@comment.user = current_user
if @comment.save
CommentNotifier.delay.new_comment(@comment)
render partial: 'comment', locals: {comment: @comment}, status: :created
else
render json: @comment.errors, status: :unprocessable_entity
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url }
format.json { head :no_content }
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
50.times do |n|
name = Faker::Internet.user_name(2..10)
password = "Password"
User.create!(name: name, password: password, password_confirmation: password)
end
users = User.order(:created_at)
2.times do
content = Faker::Overwatch.quote
users.each do |user|
user.posts.create!(content: content)
end
end
users = User.all
user = users.first
following = users[2..50]
followers = users[3..40]
following.each do |followed|
user.follow(followed)
end
followers.each do |follower|
follower.follow(user)
end
|
class PropertyListingSerializer < ApplicationSerializer
include ActionView::Helpers::DateHelper
attributes :id, :bhk, :address, :property_type, :buildup_area, :bathrooms,
:furnish_type, :rent, :security_deposit, :created_at, :poster_id,
:image_url, :is_shortlisted, :is_created
has_many :shortlisted_users, embed: :ids, :include => true, :root => "users"
def created_at
time_ago_in_words object.created_at
end
def is_shortlisted
object.is_shortlisted_by_user(scope.id)
end
def is_created
object.poster_id == scope.id
end
end
|
class User < ApplicationRecord
include Searchable
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable,
:omniauthable, omniauth_providers: %i[facebook google_oauth2]
belongs_to :country, optional: true
has_many :blogs
has_many :likes
has_many :comments
has_many :bookmarks
has_many :bookmarked_blogs, through: :bookmarks, source: :blog
has_many :followers, as: :followable
has_many :taggings
has_many :tags, through: :taggings
validates :username, :email, uniqueness: true, allow_nil: true
after_create :set_username
before_save :reindex_blogs, if: proc {|user| user.name_changed? || user.username_changed?}
enum status: { active: 1, pending: 2 }
mount_uploader :avatar, ImageUploader
def as_indexed_json(options = {})
self.as_json(
only: [:username, :name, :blogs_count]
)
end
def following_users
Follower.where(user_id: id, followable_type: 'User')
end
def following_tags
Follower.where(user_id: id, followable_type: 'Tag')
end
def following_categories
Follower.where(user_id: id, followable_type: 'Category')
end
def liked_blog?(blog)
likes.where(blog: blog).exists?
end
def bookmarked?(blog)
bookmarks.where(blog: blog, active: true).exists?
end
def following?(resource)
send("following_#{resource.class.table_name}").where(followable_id: resource.id).exists?
end
def admin?
false #self.is_admin
end
def set_username
user_name = ''
loop do
user_name = (email.split("@").first.gsub(".","") + rand(999).to_s)
break user_name unless User.where(username: user_name).exists?
end
self.update_column(:username, user_name)
end
def top_tags
self.tags.select('tags.id,tags.name,tags.slug,count(taggings.tag_id) as count').group('tags.id,taggings.tag_id,tags.name,tags.slug').to_a.sort_by(&:count).reverse
end
def people_suggestion_on_category(already_following_users)
categories_follow = self.following_categories
users_suggestions = {}
if categories_follow.count > 1
# N+1 Query is here Danger !!!
categories_follow.each do |category_follow|
curr_category = category_follow.followable
users_suggestions["#{curr_category.name}"] = User.joins(:blogs).where(blogs: {category_id: curr_category.id}).distinct - already_following_users
end
elsif categories_follow.count == 1
curr_category = categories_follow.first.followable
users_suggestions["#{curr_category.name}"] = User.joins(:blogs).where(blogs: {category_id: curr_category.id}).distinct - already_following_users
else
curr_category = Category.first
users_suggestions["#{curr_category.name}"] = User.joins(:blogs).where(blogs: {category_id: curr_category.id}).distinct - already_following_users
end
users_suggestions.reject!{|k,v| v.count == 0}
end
def reindex_blogs
blogs.each do |blog|
blog.es_reindex
end
end
class << self
def new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
if data = session["devise.google_oauth2"] && session["devise.google_oauth2_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
def from_omniauth(auth)
user = where(provider: auth.provider, uid: auth.uid).first_or_initialize
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name
# user.avatar = auth.provider == 'facebook' ? auth.info.image + '&type=normal' : auth.info.image
user.status = User.statuses[:active] if user.pending?
user.skip_confirmation! if user.new_record?
user.save!
user
end
end
end
|
class Vote < ActiveRecord::Base
belongs_to :movie
belongs_to :user
enum rating: {disliked: -1, liked: 1, not_voted: 0}
scope :likes, ->() { liked }
scope :dislikes, ->() { disliked }
scope :user, ->(user) { where user: user}
scope :movie, ->(movie) { where movie: movie}
def liked
self.rating = :liked
end
def disliked
self.rating = :disliked
end
# Estos ya no se usan por el enum
# def liked!
# liked
# save
# end
# def disliked!
# disliked
# save
# end
#Estos 2 metodos son para tests
# def liked?
# amount == 1
# end
# def disliked?
# amount == -1
# end
end
|
class DownloadsController < ApplicationController
def index
@title = "Downloads"
version_file = (Pathname(__dir__) + "../../../data/bcb-version.txt")
@bcb_version = version_file.exist? ? version_file.read.strip : "unknown"
version_file = (Pathname(__dir__) + "../../../data/xmage-version.txt")
@xmage_version = version_file.exist? ? version_file.read.strip : "unknown"
end
end
|
# Controller for execution environments
class EnvironmentsController < ApplicationController
before_action :verify_login
before_action :set_environment, only: %i[show update destroy edit]
# GET /environments
def index
respond_to do |format|
format.html do
# Show all the user's environments
@environments = Environment.where(user: @user)
end
format.json do
# If one of them is marked default, just return that one.
# Otherwise return them all so the GUI can prompt to select one.
default = Environment.where(user: @user, default: true).first
@environments = default ? [default] : Environment.where(user: @user)
end
end
end
# GET /environments/:name
def show
head :no_content
end
# GET /environments/new
def new
@environment = Environment.new
@url = '/environments'
@type = 'POST'
respond_to do |format|
format.html {render 'modal', layout: false}
end
end
# GET /environments/:name/edit
def edit
@url = '/environments/' + @environment.name
@type = 'PATCH'
respond_to do |format|
format.html {render 'modal', layout: false}
end
end
# POST /environments
def create
@environment =
Environment.find_by(user: @user, name: params[:name].strip) ||
Environment.find_by(user: @user, url: params[:url].strip) ||
Environment.new(user: @user, default: false)
handle_create_or_update
end
# PATCH /environments/:name
def update
handle_create_or_update
end
# DELETE /environments/:name
def destroy
@environment.destroy
flash[:success] = "Environment has been deleted successfully."
head :no_content
end
private
# Common code for create and update
def handle_create_or_update
@environment.name = params[:name].strip if params[:name].present?
@environment.url = params[:url].strip if params[:url].present?
@environment.default = params[:default].to_bool
# The usersave paramter is how we tell the difference between a user saving
# the form versus the environment registration pligin triggering again.
if(@environment.new_record? || params[:usersave])
if params[:user_interface].present?
@environment.user_interface = params[:user_interface].strip
end
end
if @environment.save
if @environment.default
# Set all other environments to non-default
Environment
.where('user_id = ? AND id != ?', @user.id, @environment.id)
.find_each {|e| e.update(default: false)}
end
flash[:success] = "Environment has been successfully updated."
head :no_content
else
render json: @environment.errors, status: :unprocessable_entity
end
end
# Set the environment object to use
def set_environment
@environment = Environment.find_by!(user: @user, name: params[:id])
end
end
|
class Team < ApplicationRecord
belongs_to :game
has_many :players
end
|
# === COPYRIGHT:
# Copyright (c) Jason Adam Young
# === LICENSE:
# see LICENSE file
class BatterPlayingTime < ApplicationRecord
include CleanupTools
belongs_to :roster
def remaining_starts
self.allowed_starts - self.gs
end
def need_ab
need_ab = (self.qualifying_ab - self.ab)
(need_ab >= 0) ? (need_ab) : 0
end
end |
# When done, submit this entire file to the autograder.
# Part 1
def sum arr
arr.reduce(0, :+)
end
def max_2_sum arr
arr.empty? ? 0 : arr.sort.last(2).reduce(:+)
end
def sum_to_n? arr, n
arr.length < 2 ? false : (arr.combination(2).find{|x,y| x + y == n } ? true : false)
end
# Part 2
def hello(name)
"Hello, " + name
end
def starts_with_consonant? s
/^[bcdfghjklmnpqrstvwxyz]/i === s
end
def binary_multiple_of_4? s
s =~ /^[01]*1[01]*00$/ || s == "0"
end
# Part 3
class BookInStock
attr_accessor :isbn, :price
def initialize isbn, price
@isbn = isbn
@price = price
raise ArgumentError if(@isbn===""||@price<=0)
end
def price_as_string
format("$%.2f", @price)
end
end
|
class AgentsController < ApplicationController
before_action :set_agent, only: [:show, :edit, :update, :destroy]
def index
if params[:filter]
@agents = params[:filter][:on_assignment] ? Agent.on_assignment : Agent.not_on_assignment
else
@agents = Agent.all
end
end
def show
end
def new
@agent = Agent.new
end
def create
@agent = Agent.new(agent_params)
if @agent.save
redirect_to agents_url
else
render :new
end
end
def edit
end
def update
if @agent.update(agent_params)
redirect_to @agent
else
render :edit
end
end
def destroy
@agent.destroy
redirect_to agents_url
end
private
def agent_params
params.require(:agent).permit(:first_name, :last_name, :email)
end
def set_agent
@agent = Agent.find(params[:id])
end
end
|
class AddGoogleVerificationKeyToKuhsaftPages < ActiveRecord::Migration
def change
add_column :kuhsaft_pages, :google_verification_key, :string
end
end
|
# https://docs.hetzner.cloud/#resources-actions-get
module Fog
module Hetznercloud
class Compute
class SshKey < Fog::Model
identity :id
attribute :name
attribute :fingerprint
attribute :public_key
def destroy
requires :identity
service.delete_ssh_key(identity)
true
end
def public_key=(value)
attributes[:public_key] = if value =~ /^\.?\/[^\/]+/
File.read(value)
else
value
end
end
def save
if persisted?
update
else
create
end
end
private
def create
requires :name, :public_key
if (ssh_key = service.create_ssh_key(name, public_key).body['ssh_key'])
merge_attributes(ssh_key)
true
else
false
end
end
def update
requires :identity, :name
body = attributes.dup
body[:name] = name
if (ssh_key = service.update_ssh_key(identity, body).body['ssh_key'])
merge_attributes(ssh_key)
true
else
false
end
end
end
end
end
end
|
# frozen_string_literal: true
require 'uri'
RSpec.describe URI do
it 'parses the host' do
expect(URI.parse('http://foo.com/').host).to eq 'foo.com'
end
it 'parses the port' do
expect(URI.parse('http://example.com:9876').port).to eq 9876
end
it 'defaults the port for an http URI to 80' do
expect(URI.parse('http://example.com/').port).to eq 80
end
it 'defaults the port for an https URI to 443' do
expect(URI.parse('https://example.com/').port).to eq 443
end
it 'parses the scheme' do
expect(URI.parse('https://a.com/').scheme).to eq 'https'
end
it 'parses the path' do
expect(URI.parse('http://a.com/foo').path).to eq '/foo'
end
end
|
class Api::V1::HealthController < ApplicationController
def health
render json: {message: "API status ok"}, status: :ok
end
end
|
# This migration comes from authentify (originally 20120608223732)
class CreateUsers < ActiveRecord::Migration
def change
create_table :authentify_users do |t|
t.string :name
t.string :email
t.string :login
t.string :encrypted_password
t.string :salt
t.string :status, :default => 'active'
t.integer :last_updated_by_id
t.string :auth_token
t.string :password_reset_token
t.datetime :password_reset_sent_at
t.timestamps
t.string :brief_note
t.string :cell
t.boolean :allow_text_msg, :default => false
t.boolean :allow_email, :default => false
t.integer :customer_id
t.string :local
end
add_index :authentify_users, :name
add_index :authentify_users, :email
add_index :authentify_users, :status
add_index :authentify_users, :allow_text_msg
add_index :authentify_users, :allow_email
add_index :authentify_users, :customer_id
end
end
|
class Event < ActiveRecord::Base
validate :date_must_be_valid
validates :date, presence: true, format: {with: /....\-..\-../}
validates :title, presence: true, uniqueness: true
validates :organizer_name, presence: true
validates :organizer_email, format: {with: /.+@.+\..+/}
def date_must_be_valid
if date < Date.today
errors.add(:date, "cannot be in the past")
end
end
end
|
class CreateTeams < ActiveRecord::Migration[5.2]
def change
create_table :teams do |t|
t.string :name
t.string :description
t.string :twitter
t.string :instagram
t.string :github
t.timestamps
end
end
end
|
require 'rails_helper'
RSpec.describe AdminApplication do
describe 'show page' do
it 'can approve a Pet for adoption' do
shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9)
shelter_2 = Shelter.create(name: 'RGV animal shelter', city: 'Harlingen, TX', foster_program: false, rank: 5)
shelter_3 = Shelter.create(name: 'Fancy pets of Colorado', city: 'Denver, CO', foster_program: true, rank: 10)
pet_1 = shelter.pets.create!(adoptable: true, age: 7, breed: 'sphynx', name: 'Bare-y Manilow', shelter_id: shelter.id)
pet_2 = shelter_2.pets.create!(adoptable: true, age: 3, breed: 'domestic pig', name: 'Babe', shelter_id: shelter.id)
pet_3 = shelter.pets.create!(adoptable: true, age: 4, breed: 'chihuahua', name: 'Elle', shelter_id: shelter.id)
application_1 = Application.create!(name:'Julius Caesar',
street_address: '123 Copperfield Lane',
city: 'Atlanta', state: 'GA',
zip_code: '30301',
description: 'I love dogs',
application_status: 'Pending')
application_2 = Application.create!(name:'Miles Davis',
street_address: 'Main St',
city: 'Memphis', state: 'TN',
zip_code: '75239',
description: 'I love cats',
application_status: 'In Progress')
ApplicationPet.create!(pet: pet_1, application: application_1)
ApplicationPet.create!(pet: pet_2, application: application_1)
visit "admin/applications/#{application_1.id}"
expect(page).to have_link(pet_1.name)
expect(page).to have_link(pet_2.name)
expect(page).to have_button("Approve #{pet_1.name}")
expect(page).to have_button("Approve #{pet_2.name}")
click_button("Approve #{pet_1.name}")
expect(current_path).to eq("/admin/applications/#{application_1.id}")
end
end
end
|
class User
def initialize
@fname = "Johnny"
@lname = "Designer"
@email = "hello@domain.com"
@title = "Senior Director of Fun"
@experience = 3
@joined = "#{Time.now.month}/#{Time.now.day}/#{Time.now.year}"
@admin = false
@behance_username = "lexevan"
@project_covers = []
end
attr_reader :joined, :admin, :full_name
attr_accessor :fname, :lname, :email, :title, :experience, :behance_username, :project_covers
def full_name
"#{@fname} #{@lname}"
end
end |
class MeasurementController < ApplicationController
before_action :verify_token, only: %i[index create show destroy]
before_action :set_measurement, only: %i[show destroy]
def index
@measurements = current_user.measurements
render :all, formats: :json, status: :ok
end
def create
@measurement = current_user.measurements.new(m_params)
if @measurement.save
render :create, formats: :json, status: :created
else
@error = @measurement.errors
render :error, formats: :json, status: :unprocessable_entity
end
end
def show
render :show, formats: :json, status: :ok
end
def destroy
@measurement.destroy
render :destroy, formats: :json, status: :ok
end
def set_measurement
@measurement = Measurement.find(params[:id])
rescue StandardError => e
@error = e
render :not_found, formats: :json, status: :not_found
end
def m_params
params.require(:measurement).permit(:value, :things_to_measure_id)
end
end
|
class RemoveProviderIdFromLiveVideos < ActiveRecord::Migration
def change
remove_index :live_videos, :provider_id
remove_column :live_videos, :provider_id
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# gender_id :string(255)
# created_at :datetime
# updated_at :datetime
# modelling_agency :string(255)
# phone_number :string(255)
# country :string(255)
# town :string(255)
#
require "test_helper"
class UserTest < ActiveSupport::TestCase
test "should not save user without name" do
user = User.new email: "user@email.com", gender: genders(:male), modelling_agency: "my agency", phone_number: "+2546789876", country: "Kenya", town: "Migori"
assert !user.save, "Cannot save user without name"
assert assert user.errors[:name].first == "can't be blank"
end
test "should not save user without email" do
user = User.new name: "user1@email.com", gender: genders(:male), modelling_agency: "my agency", phone_number: "+2546789876", country: "Kenya", town: "Migori"
assert !user.save, "Cannot save user without email"
assert assert user.errors[:email].first == "can't be blank"
end
test "should not save user without gender" do
user = User.new name: users(:one).name, email: "user4@email.com", modelling_agency: "my agency", phone_number: "+2546789876", country: "Kenya", town: "Migori"
assert !user.save, "Cannot save user without gender"
assert assert user.errors[:gender].first == "can't be blank"
end
test "should not save user without modelling agency" do
user = User.new name: "name1", email: "user6@email.com", gender: genders(:male), phone_number: "+2546789876", country: "Kenya", town: "Migori"
assert !user.save, "Cannot save user without modelling agency"
assert assert user.errors[:modelling_agency].first == "can't be blank"
end
test "should not save user without phone number" do
user = User.new name: "name1", email: "user6@email.com", gender: genders(:male), modelling_agency: "my agency", country: "Kenya", town: "Migori"
assert !user.save, "Cannot save user without phone number"
assert assert user.errors[:phone_number].first == "can't be blank"
end
test "should not save user without country" do
user = User.new name: "name1", email: "user6@email.com", gender: genders(:male), modelling_agency: "my agency", town: "Migori"
assert !user.save, "Cannot save user without country"
assert assert user.errors[:country].first == "can't be blank"
end
test "should not save user without town" do
user = User.new name: "name1", email: "user6@email.com", gender: genders(:male), modelling_agency: "my agency", phone_number: "+2546789876", country: "Kenya"
assert !user.save, "Cannot save user without town"
assert assert user.errors[:town].first == "can't be blank"
end
test "should accept unique email for users" do
user1 = User.new name: "name1", email: "user6@email.com", gender: genders(:male), modelling_agency: "my agency", phone_number: "+2546789876", country: "Kenya", town: "Migori"
assert user1.save, "does not save user with correct params"
user2 = User.new name: "Mike Jones", email: "user6@email.com", gender: genders(:male), modelling_agency: "my agency", phone_number: "+2546789876", country: "Kenya", town: "Migori"
assert !user2.save, "Should not save with duplicate email"
assert user2.errors[:email].first == "has already been taken", "error on email should reject dups"
end
end |
require 'rails_helper'
RSpec.feature 'Editing price in admin area', settings: false do
given!(:price) { create(:effective_price) }
background do
sign_in_to_admin_area
end
scenario 'updates price' do
visit admin_prices_path
open_form
submit_form
expect(page).to have_text(t('admin.billing.prices.update.updated'))
end
def open_form
find('.edit-price-btn').click
end
def submit_form
click_link_or_button t('admin.billing.prices.form.update_btn')
end
end
|
# How can I show a files modification date with Jekyll?
# http://stackoverflow.com/a/18233371/16185
module Jekyll
module ModifiedDate
def file_date(path)
source_dir = @context.registers[:site].source # This doesn't look reliable
posts_dir = File.join(source_dir, '_posts')
post_path = File.join(posts_dir, File.basename(path))
File.mtime(post_path) || '?'
end
end
end
Liquid::Template.register_filter(Jekyll::ModifiedDate)
|
class NotificationMailer < ActionMailer::Base
default from: "from@example.com"
def notification_email(report)
@report = report
mail(to: @report.service.contact.pluck(:email), from: @report.user.email, cc: @report.user.email, subject: 'Systems Emergency: ' + @report.service.name)
end
end
|
require('spec_helper')
describe(Venue) do
it("ensures the presence of a name") do
venue = Venue.new({:name => ""})
expect(venue.save()).to(eq(false))
end
it("ensures the presence of a location") do
venue = Venue.new({:location => ""})
expect(venue.save()).to(eq(false))
end
it("properly capitalizes the name") do
venue = Venue.create({:name => "doug fir lounge", :location => "Portland"})
expect(venue.name()).to(eq("Doug Fir Lounge"))
end
it("properly capitalizes the location") do
venue = Venue.create({:name => "doug fir lounge", :location => "portland, or"})
expect(venue.location()).to(eq("Portland, OR"))
end
end
|
class ContactMailer < ActionMailer::Base
default from: "from@example.com"
def contact_email(contact)
@contact = contact
mail(to: rstevenson542@gmail.com, subject: "Website Contact Form")
end
end
|
class User < ApplicationRecord
has_many :comments
has_many :images, as: :image_type
has_and_belongs_to_many :achievements
end |
class User < ApplicationRecord
before_create :generate_friendly_id
has_many :albums, dependent: :destroy
has_many :posts, dependent: :destroy
validates :name, presence: true
validates :friendly_id,
uniqueness: { case_sensitive: false },
format: { with: /\A[A-Za-z][\w-]*\z/ },
length: { minimum: 3, maximum: 25 },
allow_nil: true,
ban_reserved: true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: %i[facebook twitter google_oauth2]
def self.from_omniauth(auth)
user = User.where(provider: auth.provider, uid: auth.uid).first
unless user
user = User.create(name: auth.extra.raw_info.name,
provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
token: auth.credentials.token,
friendly_id: auth.set_random_name,
password: Devise.friendly_token[0, 20])
end
return user
end
def to_param
friendly_id
end
def set_random_name
friendly_id = SecureRandom.hex(10)
while User.where(friendly_id: friendly_id).exists?
friendly_id = SecureRandom.hex(10)
end
return friendly_id
end
def generate_friendly_id
self.friendly_id = self.set_random_name
end
def update_without_current_password(params, *options)
params.delete(:current_password)
if params[:password].blank? && params[:password_confirmation].blank?
params.delete(:password)
params.delete(:password_confirmation)
end
result = update_attributes(params, *options)
clean_up_passwords
result
end
end
|
class EventsController < ApplicationController
before_action :set_event, only: [:show, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
# GET /events
def index
@events = Event.all
render json: @events
end
# GET /events/1
def show
@event.view_count += 1
@event.save
render json: @event
end
# POST /events
def create
@event = Event.new(event_params)
@event.user_id = current_user.id
if @event.save
render json: @event, status: :created, location: @event
else
render json: @event.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /events/1
def update
if current_user.id != @event.user_id
render json: { "error": "user doesn't match" }, status: :unauthorized
elsif @event.update(event_params)
render json: @event
else
render json: @event.errors, status: :unprocessable_entity
end
end
# DELETE /events/1
def destroy
if current_user.id != @event.user_id
render json: { "error": "user doesn't match" }, status: :unauthorized
else
@event.destroy
end
end
# POST /events/1/follow
def follow
event_id = params[:event_id]
new_follow = UsersEvent
.where(user_id: current_user.id, event_id: event_id)
.first_or_create
render json: new_follow, status: :created
end
# DELETE /events/1/follow
def unfollow
event_id = params[:event_id]
UsersEvent.where(user_id: current_user.id, event_id: event_id).destroy_all
render json: {}, status: :no_content
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event
@event = Event.find(params[:id] || params[:event_id])
end
# Only allow a trusted parameter "white list" through.
def event_params
params.fetch(:event, {})
.permit(
:event_type, :title, :organization, :location, :url,
:content, :begin_time, :end_time, :user_id, :cover_image
)
end
end
|
class Wiki < ApplicationRecord
belongs_to :user
validates :user, presence: true
has_many :collaborators, dependent: :destroy
has_many :users, through: :collaborators
validates :title,
presence: true
validates :body,
presence: true
end
|
require_relative 'acceptance_helper'
feature 'Make new search', %q{
As some user I want to be able to update username} do
given!(:user) { create(:user, name: 'SomeUser', email: 'some@email.test') }
given!(:other_user) { create(:user, name: 'SomeOtherUser', email: 'someother@email.test') }
given!(:one_commit) { create(:commit, user_id: user.id, date: "2015-11-15 19:48:47 UTC",
sha: 'someHash', message: 'SomeCommit') }
given!(:one_more_commit) { create(:commit, user_id: user.id, date: "2015-11-15 19:48:47 UTC", sha: 'oneMoresomeHash',
message: 'oneMoreSomeCommit') }
given!(:two_commit) { create(:commit, user_id: user.id, date: "2015-11-15 19:48:47 UTC", sha: 'someMoreHash',
message: 'SomeMoreCommit') }
scenario 'User is trying to search change username for commit', js: true do
visit commits_path
click_on "edit_link_#{user.id}_0"
fill_in 'user_name', with: 'NewName'
click_on 'Apply'
expect(page).to_not have_content 'SomeUser'
expect(page).to have_content 'NewName'
expect(page).to_not have_content 'SomeOtherUser'
end
end
|
module Pyrite
module Assertions
# Assert some text appears somewhere on the page
def assert_text(text, msg=nil)
assert browser.text?(text), msg || "Text '#{text}' not found on page"
end
# Assert some text does not appear somewhere on the page
def assert_no_text(text, msg=nil)
assert !browser.text?(text), msg || "Text '#{text}' not found on page"
end
# Assert an element appears on the page via jquery selector
def assert_element(selector, msg=nil)
assert browser.element?("jquery=#{selector}"),
msg || "Element '#{selector}' not found on page"
end
# Assert an element does not appear on the page via jquery selector
def assert_no_element(selector, msg=nil)
assert !browser.element?("jquery=#{selector}"),
msg || "Element '#{selector}' was found on page but shouldn't be"
end
end
end
|
class AddDraftPlayers < ActiveRecord::Migration[5.2]
def change
create_table "draft_players", id: :integer, force: :cascade do |t|
t.integer "season"
t.references :player
t.references :roster
t.string "firstname", default: "", null: false
t.string "lastname", default: "", null: false
t.string "position", limit: 3, default: "", null: false
t.integer "age", default: 0, null: false
t.string "type", default: "0"
t.integer "statline_id", default: 0
t.integer "team_id", default: 0, null: false
t.integer "original_team_id", default: 0, null: false
t.integer "draftstatus", default: 2, null: false
t.datetime "updated_at"
end
add_index "draft_players", ["draftstatus"], name: "draftplayers_draftstatus_ndx"
add_index "draft_players", ["lastname", "firstname"], name: "draftplayers_name_ndx"
add_index "draft_players", ["position"], name: "draftplayers_position_ndx"
add_index "draft_players", ["statline_id"], name: "draftplayers_statline_ndx"
add_index "draft_players", ["type"], name: "draftplayers_type_ndx"
end
end
|
class AnimalsController < ApplicationController
def index
@zoo = params[:zoo_id]
@zoo_animals = Zoo.find_by_id(@zoo)
@animals = @zoo_animals.animals
end
def new
@animal = Animal.new
@zoo = Zoo.find params[:zoo_id]
end
def create
@zoo = Zoo.find params[:zoo_id]
@animal = @zoo.animals.create(animal_params)
if @animal.save
flash[:success] = "Successfully Created!"
redirect_to zoo_animals_path
else
# show new page again with error messages.
@errors = @animal.errors.full_messages
render :new
end
end
def edit
@animal = Animal.find params[:id]
end
def update
@animal = Animal.find params[:id]
@animal.update_attributes(animal_params)
if @animal.save
flash[:success] = "Successfully Created!"
redirect_to zoo_animals_path(@animal.zoo_id)
else
# show new page again with error messages.
@errors = @animal.errors.full_messages
render :new
end
end
def show
@animal = Animal.find params[:id]
end
def destroy
@animal = Animal.find params[:id]
@zoo = @animal.zoo_id
@animal.destroy
redirect_to zoo_animals_path(@zoo)
end
private
def animal_params
animal_params = params.require(:animal).permit(:name, :species)
end
end
|
class Technician < ActiveRecord::Base
belongs_to :account, class_name: Account
belongs_to :group, class_name: Group
validate :is_technician_account
def is_technician_account
account = Account.find(account_id)
unless account.technician?
errors.add(:technician, 'cannot add non-technician to Technician Group')
end
end
end
|
# == Schema Information
#
# Table name: path_subscriptions
#
# id :integer not null, primary key
# path_id :integer
# user_id :integer
#
# Indexes
#
# index_path_subscriptions_on_path_id (path_id)
# index_path_subscriptions_on_user_id (user_id)
#
class PathSubscription < ApplicationRecord
belongs_to :user
belongs_to :path
end
|
module Archangel
class Post < ApplicationRecord
acts_as_paranoid
# Callbacks
before_validation :parameterize_slug
before_save :stringify_meta_keywords
before_save :build_path_before_save
after_destroy :column_reset
# Uploader
mount_uploader :feature, Archangel::FeatureUploader
# Validation
validates :author_id, presence: true
validates :content, presence: true, allow_blank: true
validates :path, uniqueness: true
validates :published_at, allow_blank: true, date: true
validates :slug, presence: true
validates :title, presence: true
# Associations
belongs_to :author, class_name: Archangel::User
has_many :categorizations, as: :categorizable
has_many :categories, through: :categorizations
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
# Nested attributes
accepts_nested_attributes_for :categories, reject_if: :all_blank,
allow_destroy: true
accepts_nested_attributes_for :tags, reject_if: :all_blank,
allow_destroy: true
# Default scope
default_scope { order(published_at: :desc) }
# Scope
scope :published, -> { where("published_at <= ?", Time.now) }
scope :unpublished, lambda {
where("published_at IS NULL OR published_at > ?", Time.now)
}
scope :in_year, lambda { |year|
unless year.nil?
where("cast(strftime('%Y', published_at) as int) = ?", year)
end
}
scope :in_month, lambda { |month|
unless month.nil?
where("cast(strftime('%m', published_at) as int) = ?", month)
end
}
scope :in_year_and_month, ->(year, month) { in_month(month).in_year(year) }
scope :with_category, lambda { |category|
joins(:categories).where("archangel_categories.slug = ?", category)
}
scope :with_tag, lambda { |tag|
joins(:tags).where("archangel_tags.slug = ?", tag)
}
protected
def parameterize_slug
self.slug = slug.to_s.downcase.parameterize
end
def stringify_meta_keywords
keywords = parse_keywords(meta_keywords)
self.meta_keywords = keywords.compact.reject(&:blank?).join(",")
end
def build_path_before_save
year = published_at.nil? ? nil : published_at.year
month = published_at.nil? ? nil : "%02d" % published_at.month
self.path = [year, month, slug].compact.join("/")
end
def column_reset
self.slug = "#{Time.current.to_i}_#{slug}"
self.save
end
def parse_keywords(keywords)
JSON.parse(keywords)
rescue
keywords.to_s.split(",")
end
end
end
|
class PeopleController < ApplicationController
before_action :set_person, only: [:show, :edit, :update]
# GET /people/1
# GET /people/1.json
def show
end
# GET /people/new
def new
@person = Person.new
end
# GET /people/1/edit
def edit
@symptoms = Symptom.all
end
# POST /people
# POST /people.json
def create
@person = Person.new(person_params)
@person.department = Department.first
@person.city = @person.department.cities.first
respond_to do |format|
if @person.save
format.html { redirect_to step2_path(@person), notice: 'Person was successfully created.' }
format.json { render :show, status: :created, location: @person }
else
format.html { render :new }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /people/1
# PATCH/PUT /people/1.json
def update
respond_to do |format|
if @person.update(person_params)
format.html { redirect_to result_path(@person), notice: 'Person was successfully updated.' }
format.json { render :show, status: :ok, location: @person }
else
format.html { render :edit }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_person
@person = Person.find(params[:id])
end
# Only allow a list of trusted parameters through.
def person_params
params.require(:person).permit(:age, :sex, :recent_trip, :contact_with_recent_trip, :latitude, :longitude,
symptoms_ids: [])
end
end
|
# Specification: health insurance contribution
class InsuranceHealthTag < PayrollTag
def initialize
super(PayTagGateway::REF_INSURANCE_HEALTH, PayConceptGateway::REFCON_INSURANCE_HEALTH)
end
def deduction_netto?
true
end
end |
require 'rubygems'
require 'zlib'
class MultipartSitemap
# to speed things up, this uses the permalink columns directly. If we ever
# change how to create the canonical links for categories, products, reviews
# or profile pages, this will need to be updated.
PRIORITIES = {
:home => 0.9,
:content => 0.7,
:profile => 0.5,
:product => 1.0,
:review => 1.0,
:landing_page => 0.7,
:forum => 0.5,
:topic => 0.5,
:idea_instance => 0.5,
:idea_category => 0.35,
:idea => 0.15,
:article_instance => 0.7,
:article_category => 0.8,
:article => 1.0
}
# Google has two limitations on sitemap files:
# 1. File size (10MB uncompressed)
# 2. Number of URLs (50k)
#
# This limit of 30k is to make sure we don't go over 10MB
MAX_URL_COUNT = 30000
FILE_NAME_BASE = 'sitemap'
GZIP = true
def self.w3c_date(date)
date.utc.strftime("%Y-%m-%dT%H:%M:%S+00:00")
end
# calls yield with an array of up to limit elements
def self.each_with_limit(limit)
all_results = []
each_url { |elem| all_results << elem }
while all_results.size > 0 do
yield all_results.slice!(0, limit)
end
end
def self.images(local_photos, cobrand = Cobrand.root, location = nil)
local_photos.compact.map do |local_photo|
image_params = {}
image_params[:loc] = "http://#{cobrand.host}#{local_photo.get_thumbnail_url}"
image_params[:caption] = local_photo.caption if local_photo.caption
image_params[:geo_location] = location if location
image_params
end
end
def self.geo_location_for_user(user)
[user.city, user.state].reject{|part| part.blank?}.join(", ")
end
# needs to return a 2 element array [url,priority]
def self.each_url(limit = 1000)
# the home page
yield ["http://#{Cobrand.root.host}/", PRIORITIES[:home]]
# the content pages
content_actions = ContentController.instance_methods(false)
content_actions.each do |action|
yield ["http://#{Cobrand.root.host}/content/#{action}", PRIORITIES[:content]]
end
maximum_opt = !!Rails.env[/^dev|(?:dev|int)$/] ? {:maximum => 300} : {}
yield batch_fetch(User, limit,
{ :joins => :user_stat,
:conditions => ["`account_status` = ? AND `user_stats`.`reviews_written` > ?", 'active', 0]
}.merge(maximum_opt)
) {|user| yield ["http://#{Cobrand.root.host}/aboutme/#{user.screen_name}", PRIORITIES[:profile], images([user.primary_photo], user.cobrand, geo_location_for_user(user))]}
yield batch_fetch(Product, limit,
{ :joins => :stat,
:conditions => ["`status` = ? AND `active_review_count` > ?", 'active', 0]
}.merge(maximum_opt)
) { |product| yield ["http://#{Cobrand.root.host}/#{product.permalink}-reviews", PRIORITIES[:product], images([product.primary_local_photo])]}
yield batch_fetch(Review, limit,
{ :joins => :product,
:conditions => { "reviews.status" => 'active' }
}.merge(maximum_opt)
) {|review| yield ["http://#{Cobrand.root.host}/#{review.product.permalink}-review-#{review.permalink}", PRIORITIES[:review], images(review.photos, review.cobrand || Cobrand.root)]}
yield batch_fetch(LandingPage, limit, { :conditions => { :status => 'active' } }.merge(maximum_opt)
) {|page| yield ["http://#{Cobrand.root.host}/#{page.permalink}", PRIORITIES[:landing_page]]}
yield batch_fetch(Forum, limit,
{ :conditions => { :cobrand_id => Cobrand.root.id, :owner_type => nil } }.merge(maximum_opt)
) {|forum| yield ["http://#{Cobrand.root.host}/discussion_boards/#{forum.permalink}/topics", PRIORITIES[:forum]]}
yield batch_fetch(Forum, limit,
{ :conditions => ["`cobrand_id` = ? AND `owner_type` IS NOT NULL", Cobrand.root.id] }.merge(maximum_opt)
) {|forum| yield ["http://#{Cobrand.root.host}/#{forum.owner.to_param}/topics", PRIORITIES[:forum]]}
yield batch_fetch(Topic, limit,
{ :joins => :forum,
:conditions => ["`forums`.`cobrand_id` = ? AND `forums`.`owner_type` IS NOT NULL", Cobrand.root.id]
}.merge(maximum_opt)
) {|topic| yield ["http://#{Cobrand.root.host}/#{topic.forum.owner.to_param}/topics/#{topic.permalink}/posts", PRIORITIES[:topic]]}
yield batch_fetch(IdeaInstance, limit,
{ :conditions => { :cobrand_id => Cobrand.root.id } }.merge(maximum_opt)
) {|instance| yield ["http://#{Cobrand.root.host}/#{instance.short_name}", PRIORITIES[:idea_instance]]}
yield batch_fetch(IdeaCategory, limit,
{ :joins => :idea_instance,
:conditions => { "idea_instances.cobrand_id" => Cobrand.root.id } }.merge(maximum_opt)
) {|category| yield ["http://#{Cobrand.root.host}/#{category.idea_instance.short_name}/c/#{category.permalink}", PRIORITIES[:idea_category]]}
yield batch_fetch(Idea, limit,
{ :joins => :idea_instance,
:conditions => { "idea_instances.cobrand_id" => Cobrand.root.id } }.merge(maximum_opt)
) {|idea| yield ["http://#{Cobrand.root.host}/#{idea.idea_instance.short_name}/#{idea.permalink}", PRIORITIES[:idea]]}
if App.articles_enabled?
yield batch_fetch(ArticleInstance, limit,
{ :conditions => { :cobrand_id => Cobrand.root.id } }.merge(maximum_opt)
) {|instance| yield ["http://#{Cobrand.root.host}/#{instance.short_name}", PRIORITIES[:article_instance]]}
yield batch_fetch(ArticleCategory, limit,
{ :joins => :article_instance, :conditions => { "article_instances.cobrand_id" => Cobrand.root.id } }.merge(maximum_opt)
) {|category| yield ["http://#{Cobrand.root.host}/#{category.article_instance.short_name}/#{category.permalink}", PRIORITIES[:article_category]]}
yield batch_fetch(Article, limit,
{ :joins => :article_instance, :conditions => { "article_instances.cobrand_id" => Cobrand.root.id } }.merge(maximum_opt)
) {|article| yield ["http://#{Cobrand.root.host}/#{article.article_instance.short_name}/#{article.permalink}", PRIORITIES[:article]]}
end
end # each_url
def self.batch_fetch(model, batch_size = nil, opts = {}, &block)
opts.merge!({ :hide_counter => true })
model.each(batch_size, opts, &block)
end
def self.build_xml(url_batch)
xml = Builder::XmlMarkup.new(:indent => 2)
xml.instruct!
xml.urlset "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9", "xmlns:image" => "http://www.google.com/schemas/sitemap-image/1.1" do
url_batch.each do |map_element|
next if map_element.blank? # skip element if we do not have a url or priority
# split the map element into the url and the priority
# TODO if we ever get super smart, add the true last modified date.
(url,priority,images) = map_element
xml.url do
xml.loc url
xml.lastmod w3c_date(Time.now)
xml.changefreq "daily"
xml.priority priority
images.each do |image|
xml.tag!("image:image") do
xml.tag!("image:loc", image[:loc])
xml.tag!("image:caption", image[:caption]) if image[:caption]
xml.tag!("image:geo_location", image[:geo_location]) unless image[:geo_location].blank?
end
end if images
end
end # each url in url_batch
end # xml urlset do
xml
end
def self.generate
# first, blow away all the old ones. not strictly necessary as we should
# never be shrinking in page count, and the only ones referenced in the
# sitemap index should be used by crawlers, but still.
# TODO -- blow away the old ones
map_list = []
each_with_limit(MAX_URL_COUNT) do |url_batch|
xml = build_xml(url_batch)
# TODO: write a gzip file if you can.
file_name = "#{SITEMAPS_DIR}/sitemap#{map_list.size + 1}.xml"
file_name << ".gz" if GZIP
if GZIP
Zlib::GzipWriter.open(file_name) do |gz|
gz.write(xml.target!)
gz.close
end
else
File.open(file_name, "w") { |f| f.write(xml.target!)}
end
map_list << File.basename(file_name)
end # loop over ALL the urls
# now generate the index
xml = Builder::XmlMarkup.new(:indent => 2)
xml.instruct!
xml.sitemapindex "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" do
map_list.each do |mapfile|
xml.sitemap do
xml.loc "http://#{Cobrand.root.host}/#{mapfile}"
xml.lastmod w3c_date(Time.now)
end # sitemap node
end # map list mode
end # xml.urlset do
File.open("#{SITEMAPS_DIR}/sitemap.xml", "w") { |f| f.write(xml.target!) }
end # def generate
end # class MultipartSiteMap
|
# A loyalty currency such as miles or points which a user can spend on flights
# (and other rewards)
#
# An specific user's balance in a specific currency (if they have one) is
# stored in the `balances` table.
#
# Attributes:
# - name:
# the currency's name. This will be seen by users; i.e. it's not just for
# our internal use
#
# - award_wallet_id:
# the name that AwardWallet use for this currency. At the the time of
# writing we haven't implemented any integration with AwardWallet yet, so
# data in this column is just being stored for future or use
#
# - shown_on_survey:
# whether or not the user is asked about this currency (and asked to tell
# us their balance in this currency if they have one) on the 'balances'
# page of the onboarding survey
#
# - alliance_name
# which Alliance the currency belongs to, if any. See
# app/models/alliance.rb
#
class Currency < ApplicationRecord
self.inheritance_column = :_no_sti
# Attributes
Type = Types::Strict::String.enum('airline', 'bank', 'hotel').freeze
# Validations
# Associations
def alliance
Alliance.new(name: alliance_name)
end
# Scopes
scope :alphabetical, -> { order(name: :asc) }
scope :survey, -> { where(shown_on_survey: true) }
end
|
module EmSpecHelper
# This is designed to work like EM.connect --
# it mixes the module into StubConnection below instead of EM::Connection.
# It does *not* run within an EM reactor.
# The block passed it should set any expectations, and
# then call the callbacks being tested.
# These will be called (synchronously of course) after post_init.
# For example, to test that close_connection is called in :receive_data:
# stub_connection(MyRealClient, params) do |conn|
# conn.expects(:close_connection)
# conn.receive_data "200 OK"
# end
#
# If you want to test expectations in post_init, you can pass a :stubs proc:
# stub_connection(MyRealClient, params,
# :stubs => Proc.new { |s| s.expects(:send_data).with("message") }
# ) do |conn|
# conn.receive_data "200 OK"
# end
#
# Or more simply as an array if you don't care about parameters or return values:
# stub_connection(MyRealClient, params,
# :stubs => [ :send_data ]
# ) do |conn|
# conn.receive_data "200 OK"
# end
#
# If you don't set any expectations, the EM::Connection methods will
# simply quietly fire and return nil.
#
def self.stub_connection(klass, *args, &blk)
Class.new(StubConnection){ include klass }.new(*args, &blk)
end
class StubConnection
def self.new(*args)
opts = args.last.is_a?(Hash) ? args.pop : {}
stubs = opts[:stubs]
allocate.instance_eval {
# set expectations here
case stubs
when Symbol
self.expects(stubs)
when Array # expect methods
stubs.each {|sym| self.expects(sym.to_sym)}
when Hash # expect methods => returns
stubs.each_pair {|sym, v| self.expects(sym.to_sym).returns(v)}
else # define more complicated stubs in a proc
stubs.call(self) if stubs.respond_to?(:call)
end
initialize(*args)
post_init
yield(self) if block_given?
self
}
end
def initialize(*args)
end
# stubbed methods => nil
def send_data(data); nil; end
def close_connection after_writing = false; nil; end
def close_connection_after_writing; nil; end
def proxy_incoming_to(conn,bufsize=0); nil; end
def stop_proxying; nil; end
def detach; nil; end
def get_sock_opt level, option; nil; end
def error?; nil; end
def start_tls args={}; nil; end
def get_peer_cert; nil; end
def send_datagram data, recipient_address, recipient_port; nil; end
def get_peername; nil; end
def get_sockname; nil; end
def get_pid; nil; end
def get_status; nil; end
def comm_inactivity_timeout; nil; end
def comm_inactivity_timeout= value; nil; end
def set_comm_inactivity_timeout value; nil; end
def pending_connect_timeout; nil; end
def pending_connect_timeout= value; nil; end
def set_pending_connect_timeout value; nil; end
def reconnect server, port; nil; end
def send_file_data filename; nil; end
def stream_file_data filename, args={}; nil; end
def notify_readable= mode; nil; end
def notify_readable?; nil; end
def notify_writable= mode; nil; end
def notify_writable?; nil; end
def pause; nil; end
def resume; nil; end
def paused?; nil; end
# no-op callbacks
def post_init; end
def receive_data data; end
def connection_completed; end
def ssl_handshake_completed; end
def ssl_verify_peer(cert); end
def unbind; end
def proxy_target_unbound; end
end
class << self
#
# These are designed to run a dummy server in a separate thread
# For testing within the EM reactor instead of stubbing it
#
def start_server_thread(klass, host, port)
Thread.new {
EM.run {
EM.start_server(host, port, klass)
}
}
end
def stop_server_thread(th)
th.wakeup
EM.stop
end
def stop_connect_thread(th); th.wakeup; end
def start_connect_thread(klass, host, port, data)
Thread.new {
EM.run {
EM.connect(host, port, klass, data)
#EM.next_tick { EM.stop }
}
}
end
end
module DummyServer
def initialize
$stdout.print "Connection initializing\n"; $stdout.flush
end
def post_init
$stdout.print "Connection initialized\n"; $stdout.flush
end
def receive_data data
$stdout.print "Data received\n"; $stdout.flush
close_connection
end
end
module DummyClient
def initialize(msg)
@msg = msg
end
def post_init
send_data @msg
close_connection_after_writing
end
end
end |
class Admin::InventoryController < ApplicationController
before_action :set_garments, :set_categorys
def index
authorize! :edit, Category
end
private
def set_garments
@garments = Garment.all
end
def set_categorys
@categories = Category.all
end
end
|
Capistrano::Configuration.instance(:must_exist).load do
desc "Setup configuration variables for deploying in a "\
"production environment"
task :staging do
# Population of roles requires setting up of environment
# variables for the different roles. The expected syntax
# is a simple csv.
#
role(:crawler) { "ec2-23-23-124-176.compute-1.amazonaws.com" }
set :environment, "staging"
set :branch, "master"
end
end
|
class UsersController < ApplicationController
before_action :authenticate, except: :show
before_action :user_self?, except: :show
def show
@user = User.find_by_id(params[:id])
@symptoms = Symptom.where(:user_id => @user.id).reverse_order
end
def destroy
@user = current_user
@user.destroy!
reset_session
redirect_to root_path, notice: '退会しました'
end
private
def user_params
params.require(:user).permit(:birth,:sex)
end
def user_self?
not_found unless current_user.id.to_s == params[:id]
end
end
|
module Amorail
# AmoCRM lead entity
class Unsorted < Amorail::Entity
attr_accessor :contacts, :leads, :pipeline_id, :form_id, :form_page
validates :form_id, :form_page, presence: true
def initialize(*args)
super
self.contacts ||= []
self.leads ||= []
end
protected
def create_params(method)
ret =
{
created_at: Time.now.to_i,
incoming_entities:
{
leads: [],
contacts: []
},
incoming_lead_info:
{
form_id: self.form_id,
form_page: self.form_page
}
}
ret[:pipeline_id] = self.pipeline_id if self.pipeline_id.present?
self.leads.each { |l| ret[:incoming_entities][:leads].push(l.params.except(:last_modified)) }
self.contacts.each { |c| ret[:incoming_entities][:contacts].push(c.params.except(:last_modified)) }
{ add: [ ret ] }
end
def commit_request(attrs)
client.safe_request(
:post,
"/api/v2/incoming_leads/form",
normalize_params(attrs)
)
end
def handle_response(response, method)
(response.status == 200) && (response.body['status']=='success')
end
end
end
|
# frozen_string_literal: true
class UserPresenter < ApplicationPresenter
def roles
Enums.user_roles
end
end
|
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
hash_nums = {}
(0...nums.length).each do |i|
another = target - nums[i]
return [hash_nums[another], i] if hash_nums.has_key?(another)
hash_nums[nums[i]] = i
end
end |
require 'spec_helper'
describe 'visit games#show' do
subject { page }
before :each do
create_and_sign_in_user
click_button('Play as X')
end
it { should have_selector('h1') }
it { should have_selector('div.gameboard') }
it { should have_selector('div.square', count: 9) }
it { should have_selector('a', text: 'Back') }
it { should have_selector('a', text: 'Delete') }
end
|
require "rails_helper"
RSpec.describe Tag, type: :model do
it "is invalid with missing attributes" do
tag = Tag.new(name: nil)
expect(tag).to_not be_valid
end
it "is valid with all attributes" do
tag = Tag.new(name: "Moon")
expect(tag).to be_valid
end
end
|
class CreateDemandResponses < ActiveRecord::Migration
def change
create_table :demand_responses do |t|
t.references :interval, index: true, foreign_key: true
t.timestamps null: false
end
end
end
|
class UserTwoFactorAuthenticationMutation < Mutations::BaseMutation
graphql_name "UserTwoFactorAuthentication"
argument :id, GraphQL::Types::Int, required: true
argument :password, GraphQL::Types::String, required: true
argument :qrcode, GraphQL::Types::String, required: false
argument :otp_required, GraphQL::Types::Boolean, required: false, camelize: false
field :success, GraphQL::Types::Boolean, null: true
field :user, UserType, null: true
def resolve(id:, password:, qrcode: nil, otp_required: nil)
user = User.where(id: id).last
if user.nil? || User.current.id != id
raise ActiveRecord::RecordNotFound
else
options = {
otp_required: otp_required,
password: password,
qrcode: qrcode
}
user.two_factor = (options)
{ success: true, user: user.reload }
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
def time_rand from = 0.0, to = Time.now
Time.at(from + rand * (to.to_f - from.to_f))
end
puts "Cleaning Database"
Client.destroy_all
User.destroy_all
user = User.new(email: 'teste@gmail.com', password: '123456')
user.save
thais = User.new(email: 'tsbpaiva@gmail.com', password: 'loviners', user_name: 'redhead')
thais.save
keywords = Client.new(user: thais, name: 'Keywords', bio: 'Awesome translation company')
keywords.save
locsmiths = Client.new(user: thais, name: 'Locsmiths', bio: 'European Translation Company')
locsmiths.save
destiny = Project.new(client: client, name: 'Lectures', description: "Just doing some lectures")
destiny.save
wow = Project.new(client: client, name: 'Lectures', description: "Just doing some lectures")
wow.save
tlou = Project.new(client: client, name: 'Lectures', description: "Just doing some lectures")
tlou.save
5.times do
Payment.create(
project: project,
value: rand(1..10000),
notes: 'Everything went well',
paid: [true, false].sample,
date_of_payment: time_rand
)
end
# defining random date
|
class Picture < ActiveRecord::Base
validates :title, :artist, :url, presence: true
validates :title, length: { in: 3..20 }
validates :url, uniqueness: true
end
|
#!/usr/bin/env ruby -rubygems -wKU
require 'rdiscount'
require 'time'
require 'index'
require 'erb'
require 'page'
INTRAY_DIR = "InTray"
OUTTRAY_DIR = "OutTray"
MAIN_STYLESHEET_FILENAME = "styles/main.css"
MAIN_DOCUMENT_TEMPLATE = "main_page_template.erb.txt"
INDEX_STYLESHEET = MAIN_STYLESHEET_FILENAME
CREATION_TIME_INDEX_TEMPLATE = "index_creation_time_page_template.erb.txt"
MODIFIED_TIME_INDEX_TEMPLATE = "index_modified_time_page_template.erb.txt"
CREATED_AT_INDEX_FILENAME = "archives.html"
LAST_MODIFIED_INDEX_FILENAME = "index.html"
def datestamp_filename(basefilename, creation_time, extension = nil)
common_part = "#{creation_time.strftime("%Y%m%d")}_#{basefilename}"
return common_part if extension == nil
"#{common_part}.#{extension}"
end
def embed_in_html_template(template_filename,
page, main_stylesheet_filename)
template = IO.read(template_filename)
template = ERB.new(template)
template.result(binding)
end
def should_ignore?(filename)
(filename == "." || filename == ".." || filename == ".DS_Store")
end
def process_in_tray
created_at_index = Index.new("Articles organized by Creation Time", INDEX_STYLESHEET, CREATION_TIME_INDEX_TEMPLATE, :latest_first)
last_modified_index = Index.new("Articles organized by Last Update Time", INDEX_STYLESHEET, MODIFIED_TIME_INDEX_TEMPLATE, :latest_first)
Dir.entries(INTRAY_DIR).each do |filename|
next if should_ignore?(filename)
page = Page.new(INTRAY_DIR, filename)
next if !File.file?(page.path_and_filename) # skip directories
# embed the converted content into a style/site template
html = embed_in_html_template(MAIN_DOCUMENT_TEMPLATE, page, MAIN_STYLESHEET_FILENAME)
# generate an appropriate output filename
page.output_filename = datestamp_filename(page.title, page.creation_time, "html")
# update the indices...
created_at_index.add_entry(page)
last_modified_index.add_entry(page)
# write the file to the OutTray
File.open(File.join(OUTTRAY_DIR, page.output_filename), "w") do |out|
out.puts html
end
end
created_at_index.generate_in_file(:creation_time, File.join(OUTTRAY_DIR, CREATED_AT_INDEX_FILENAME))
last_modified_index.generate_in_file(:last_modified_time, File.join(OUTTRAY_DIR, LAST_MODIFIED_INDEX_FILENAME))
end
process_in_tray
|
class CreateLtiDeployments < ActiveRecord::Migration[5.1]
def change
create_table :lti_deployments do |t|
t.bigint :application_instance_id
t.string :deployment_id
t.timestamps
end
add_index :lti_deployments, :application_instance_id
add_index :lti_deployments, :deployment_id
add_index :lti_deployments, [:deployment_id, :application_instance_id], unique: true, name: "index_lti_deployments_on_d_id_and_ai_id"
end
end
|
class AddPriorityToUsers < ActiveRecord::Migration
def change
add_column :users, :priority_level, :int
end
end
|
# Run me with `rails runner db/data/20230718131711_import_ukri_level_d_budgets.rb`
# Script to add budgets to activities when those budgets cannot be added via bulk upload (for example they are for a
# level not currently handled by bulk upload).
# Re-usable if you replace `file_name` with the path to your chosen csv.
# Note that the script expects column headers of the following form: "Activity RODA ID"; "Budget amount"; "Type";
# "Financial year" The order of the columns is not sensitive.
# This script bypasses the usual budget validation required by the Budget model. This is to allow us to upload these
# budgets without the need for a report attached to each.
# Details of budgets that cannot be successfully created are logged to the terminal at the end of the script run.
require "csv"
def get_financial_year(financial_year_range)
financial_year_range.split("-")[0]
end
def validate_budget(budget)
budget.valid?
report_error = budget.errors.messages[:report]
budget.errors.messages.count == 1 && report_error.count == 1
end
file_name = "ukri_level_d_budget_upload.csv"
puts "Loading csv data from #{file_name}"
file = File.open(file_name)
budget_data = CSV.parse(file.read, headers: true)
initial_budgets_count = Budget.count
puts "There are #{initial_budgets_count} existing budgets."
puts "There are #{budget_data.count} budgets to create."
puts "Creating budgets..."
logged_unsuccessful = {}
budget_data.each do |row|
roda_identifier = row["Activity RODA ID"]
parent_activity = Activity.find_by(roda_identifier: roda_identifier)
value = row["Budget amount"]
budget_type = row["Type"]
financial_year_range = row["Financial year"]
budget_attributes = {
parent_activity_id: parent_activity&.id,
currency: parent_activity&.default_currency,
value: value,
budget_type: Budget.budget_types.key(Integer(budget_type, exception: false)),
financial_year: get_financial_year(financial_year_range)
}
begin
budget = Budget.new
budget.assign_attributes(budget_attributes)
unless validate_budget(budget)
logged_unsuccessful[roda_identifier] = budget
next
end
budget.save(validate: false)
rescue
budget.valid?
logged_unsuccessful[roda_identifier] = budget
end
end
puts "Budget creation complete."
puts "There were #{initial_budgets_count} budgets in the database before the import"
puts "There are now #{Budget.count} budgets in the database"
puts "#{Budget.count - initial_budgets_count} budgets have been imported"
puts "#{budget_data.count} budgets were supplied in CSV"
if logged_unsuccessful.size > 0
puts "The following #{logged_unsuccessful.size} budgets could not be created and have not been saved to the database:"
logged_unsuccessful.each do |roda_identifier, budget|
puts "Budget for #{roda_identifier} in financial year #{budget.financial_year} was not created."
puts "Error(s):"
budget.errors.messages.each_key { |k| puts k }
end
end
|
#!/run/nodectl/nodectl script
# Compare datasets/snapshots between DB and on-disk states
#
# This script does not take any locks, so some mismatches may be due to changes
# being done while this script is running.
require 'nodectld/standalone'
include OsCtl::Lib::Utils::Log
include NodeCtld::Utils::System
class Dataset
attr_reader :name, :ident
def initialize(row, **opts)
@data = row
@name = File.join(*[
row['filesystem'],
row['full_name'],
(opts[:tree] || opts[:branch]) ? "tree.#{row['tree_index']}" : nil,
opts[:branch] && "branch-#{row['branch_name']}.#{row['branch_index']}"
].compact)
if opts[:snapshot]
@name = "#{@name}@#{row['snapshot_name']}"
end
@ident = make_ident(row, **opts)
end
def to_s
name
end
protected
def make_ident(row, **opts)
ret = []
ret << "id=#{row['dataset_id']}"
ret << "dip=#{row['dataset_in_pool_id']}"
ret << "tree=#{row['tree_id']}" if opts[:tree] || opts[:branch]
ret << "branch=#{row['branch_id']}" if opts[:branch]
ret << "snap=#{row['snapshot_id']}" if opts[:snapshot]
if opts[:snapshot]
ret << "sip=#{row['snapshot_in_pool_id']}" if row['snapshot_in_pool_id']
ret << "sipb=#{row['snapshot_in_pool_in_branch_id']}" if row['snapshot_in_pool_in_branch_id']
end
ret.join(' ')
end
end
pools = []
db_datasets = {}
ondisk_datasets = {}
db = NodeCtld::Db.new
db.prepared(
'SELECT filesystem FROM pools WHERE node_id = ?',
$CFG.get(:vpsadmin, :node_id),
).each do |row|
pools << row['filesystem']
end
# TODO: this is wrong for backups... we must capture snapshots *through* sipbs...
# this way it's like they're in all branches
db.prepared(
'SELECT
p.filesystem,
ds.id AS dataset_id, ds.full_name,
dips.id AS dataset_in_pool_id,
s.id AS snapshot_id, s.name AS snapshot_name,
sips.id AS snapshot_in_pool_id,
sipbs.id AS snapshot_in_pool_in_branch_id,
t.id AS tree_id, t.index AS tree_index,
b.id AS branch_id, b.name AS branch_name, b.index AS branch_index
FROM datasets ds
INNER JOIN dataset_in_pools dips ON ds.id = dips.dataset_id
INNER JOIN pools p ON p.id = dips.pool_id
LEFT JOIN snapshot_in_pools sips ON sips.dataset_in_pool_id = dips.id
LEFT JOIN snapshots s ON s.id = sips.snapshot_id
LEFT JOIN snapshot_in_pool_in_branches sipbs ON sipbs.snapshot_in_pool_id = sips.id
LEFT JOIN dataset_trees t ON t.dataset_in_pool_id = dips.id
LEFT JOIN branches b ON b.dataset_tree_id = t.id
WHERE
p.node_id = ?
AND
(sipbs.id IS NULL OR sipbs.branch_id = b.id)
AND
ds.confirmed = 1
AND
dips.confirmed = 1
AND
(sips.confirmed IS NULL or sips.confirmed = 1)
AND
(s.confirmed IS NULL or s.confirmed = 1)
AND
(sipbs.confirmed IS NULL or sipbs.confirmed = 1)
AND
(t.confirmed IS NULL or t.confirmed = 1)
AND
(b.confirmed IS NULL or b.confirmed = 1)
',
$CFG.get(:vpsadmin, :node_id),
).each do |row|
[
Dataset.new(row),
row['tree_index'] && Dataset.new(row, tree: true),
row['branch_index'] && Dataset.new(row, branch: true),
row['snapshot_name'] && Dataset.new(row, snapshot: true, branch: row['branch_index']),
].compact.each do |ds|
db_datasets[ds.name] = ds
end
end
zfs(:list, '-r -t all -o name -H', pools.join(' ')).output.strip.split[1..-1].each do |name|
ondisk_datasets[name.strip] = true
end
db_datasets.delete_if do |name, _|
ondisk_datasets.delete(name)
end
ondisk_datasets.delete_if do |name, _|
db_datasets.delete(name)
end
if db_datasets.any?
puts "Missing on-disk datasets:"
db_datasets.sort do |a, b|
a[1].name <=> b[1].name
end.each do |_, ds|
puts "#{ds} (#{ds.ident})"
end
puts
puts
puts
end
if ondisk_datasets.any?
puts "Unknown datasets:"
ondisk_datasets.sort do |a, b|
a[0] <=> b[0]
end.each do |name, _|
puts "#{name}"
end
puts
puts
puts
end
|
require 'test_helper'
class CommentsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
@comment = comments(:one)
@lecture = lectures(:one)
end
test "should get edit" do
sign_in users(:one)
get edit_lecture_comment_url(@lecture,@comment)
assert_response :success
end
test "should destroy comment" do
sign_in users(:one)
assert_difference('Comment.count', -1) do
delete lecture_comment_url(@comment,@lecture)
end
assert_redirected_to lecture_url(@lecture)
end
# test "the truth" do
# assert true
# end
end
|
class CreateProfiles < ActiveRecord::Migration
def self.up
create_table :profiles do |t|
t.integer :user_id
t.string :first_name
t.string :last_name
t.string :city
t.string :state
t.string :country
t.string :postal_code
t.string :job_title
t.string :website
t.string :gender, :default => :male
t.boolean :hidden, :default => false
t.string :status, :default => :active
t.timestamps
end
end
def self.down
drop_table :profiles
end
end
|
module TheCityAdmin
FactoryGirl.define do
factory :user_process_answer, :class => TheCityAdmin::UserProcessAnswer do
question_id 316
question "Do you like foo?"
answer "bar"
answered_at Date.today
required true
end
end
end
|
module ApplicationHelper
def formatted_price(price, currency = nil)
currency = (currency || current_currency)
if CoingateService::CRYPTO_CURRENCIES.include? currency
"#{price} #{currency}"
else
number_with_precision(price, precision: 2).to_s + ' ' + currency
end
end
def currency_icon(currency_iso)
content_tag(:i, '', class: "currency-icon-#{currency_iso}")
end
def currency_rate_info
"1 USD = #{session[:currency_rate]} #{current_currency}" if current_currency != 'USD'
end
def label_class_by_order_status(status)
case status
when 'paid' then 'label-success'
when 'canceled' then 'label-danger'
when 'pending' then 'label-warning'
when 'invalid' then 'label-danger'
else 'label-default'
end
end
def title(page_title)
content_for(:title) { "#{page_title} - " if page_title.present? }
end
end
|
class MapFacade
attr_reader :location
def initialize(location)
@location = location
end
def closest_electric_station
service = NrelService.new
nearest_station_data ||= service.fetch_electric_stations(@location)
Station.new(nearest_station_data)
end
end
|
class AddTwitterScreenNameToUsers < ActiveRecord::Migration
def self.up
add_column :photos, :migrated, :string
add_column :users, :twitter_screen_name, :string
add_column :users, :twitter_oauth_token, :string
add_column :users, :twitter_oauth_secret, :string
add_column :users, :twitter_avatar_url, :string
add_column :users, :facebook_access_token, :string
add_column :users, :facebook_user_id, :string
end #of self.up
def self.down
remove_column :photos, :migrated
remove_column :users, :twitter_screen_name
remove_column :users, :twitter_oauth_secret
remove_column :users, :twitter_screen_name
remove_column :users, :twitter_avatar_url
remove_column :users, :facebook_access_token
remove_column :users, :facebook_user_id
end
end
|
class Api::CourseLevelsController < Api::ApplicationController
def mass_update_order
level_ids = params[:ids]
levels = Course::Level.find(level_ids)
level_ids.map!(&:to_i);
levels.each do |level|
order = level_ids.index(level.id)
level.update_attribute :order_at, order
end
head :ok
end
end
|
#!/usr/bin/env ruby
## BrianWGray
## Carnegie Mellon University
## Initial Creation date: 10.05.2016
## = Description:
## == The script performs the following:
# 1. load fingerprint file
# 2. Apply the fingerprint file to a provided uri
# 3. Return data as filtered by the finger print.
#
# Examples:
# - "ruby debug_fp.rb xpath_webapps.xml http://baseurl/"
## TODO:
# 1. Write it?
# 2. Add appropriate exception handlers etc. A lot of them
require 'rubygems'
require 'net/http'
require 'openssl'
gem 'nokogiri'
require 'nokogiri'
require 'pp'
if ARGV.length < 2
# for now if no argument is passed evaluate the current cwd
puts "No file name or base url provided: Exiting..."
puts "If this isn't what you intended try #{__FILE__} xpath_webapps.xml http://baseurl/"
else
# accept fingerprint file name
fpXmlFile = ARGV[0] # => "xpath_webapps.xml"
url = URI.parse(ARGV[1])
# Broken out in this fasion to help me remember values
# fpUri = URI("#{url.scheme}://#{url.host}#{url.path}#{url.port}#{url.query}#{url.fragment}")
end
## provide path locations to rapid7 schema files
## default location to find the schema files - console:/opt/rapid7/nexpose/plugins/xsd/
xsdPath = "xsd/"
xmlXsdPath = "#{xsdPath}xml.xsd"
# Define Validation via Nokogiri
def validate(document_path, schema_path, root_element)
@document_path, @schema_path, @root_element = document_path, schema_path, root_element
begin
schema = Nokogiri::XML::Schema(File.open(@schema_path))
document = Nokogiri::XML(File.read(@document_path))
# schema.validate(document.xpath("//#{root_element}").to_s)
schema.validate(document)
rescue => error
puts error
end
end
# Apply XML Validations against the finger print file.
def fpCheck(fpXmlFile="./xpath_webapps.xml",xmlXsdPath)
@fpXmlFile = fpXmlFile
@xmlXsdPath = xmlXsdPath
if File.exists?(@fpXmlFile) # => @fpXmlFile = true
begin
validate(@fpXmlFile, @xmlXsdPath, 'container').each do |error|
puts error.message
end
end
else
puts "\n** The #{@fpXmlFile} file is missing and the finger print description may not be validated\n\n"
end
end
## Support HTTP Calls for fingerprint checks
# Make HTTP Connection and GET URI data to be evaluated
def getHttp(fpUri,fpVerb="GET",fpData="")
#@fpUserAgent = "CMU/2.2 CFNetwork/672.0.8 Darwin/14.0.0"
@fpUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:49.0) Gecko/20100101 Firefox/49.0"
http = Net::HTTP.new(fpUri.host, fpUri.port)
case fpUri.scheme.upcase
when "https".upcase
http.use_ssl = true
# For signature checks it doesn't matter if a valid certificate is present.
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if fpUri.scheme.upcase == "https".upcase
else
end
case fpVerb.upcase
when "Get".upcase
# For now forcing encoding to text as some devices being tested have broken compression implemented.
request = Net::HTTP::Get.new(fpUri,initheader = {'Accept-Encoding' => 'gzip, default, br', 'User-Agent' => @fpUserAgent}) if fpVerb.upcase == "Get".upcase
# request = Net::HTTP::Get.new(fpUri) if fpVerb.upcase == "Get".upcase # Default Header
puts "GET #{fpUri}"
when "Post".upcase
request = Net::HTTP::Post.new(fpUri.request_uri) if fpVerb.upcase == "Post".upcase
request.set_form_data(fpData) if fpVerb.upcase == "Post".upcase
else
requestFail = true
end
response = http.request(request) if !requestFail
return response
end
def parseConfigs(fpXmlFile="./xpath_webapps.xml")
if File.exists?(fpXmlFile)
begin
# Load fingerprint xml
@fpXml = Nokogiri::XML(File.open(fpXmlFile)) do |config|
config.options = Nokogiri::XML::ParseOptions::NONET # Disable Network Connections during parsing
end
end
else
puts "\n** The #{@fpXml} file is missing and the finger print configurations may not be imported\n\n"
exit(1)
end
return @fpXml
end
def parseBody(fpUri,fpVerb,fpData,fpXpath,fpRegex)
@fpUri = fpUri
@fpXpath = fpXpath
@fpRegex = fpRegex
@queryInfo = getHttp(@fpUri,fpVerb,)
@value = Nokogiri::HTML.parse(@queryInfo.body)
xpathReturn = @value.xpath("#{@fpXpath}")
regexReturn = xpathReturn.to_s.match("#{@fpRegex}")
#regexReturn = Array.new
#xpathReturn.each do |item|
# regexReturn << item.to_s.match("#{fpRegex}")
#end
puts "\r\nResults:\r\n"
puts "XPath Match: #{xpathReturn}"
puts "RegEx Match: #{regexReturn}"
puts "Group 1 (Version) : #{regexReturn[1]}" if !regexReturn.nil?
puts "Group 2 (SubVersion) : #{regexReturn[2]}" if !regexReturn.nil?
puts "\r\n"
returnValue = [regexReturn, xpathReturn]
return returnValue
end
def evaluateFingerPrints(fpXml,fpUrl)
@fpVerb = "GET" # Default Verb for requests
fpXml.xpath('//fingerprint').each do |fpInfo|
fpInfo.xpath('example').each do |exampleInfo|
puts "\r\n----------------------------- Finger Print: #{exampleInfo.attributes["product"].to_s} -----------------------------\r\n"
end
fpInfo.xpath('get').each do |getInfo|
# Check Path that will be provided from the signature file
@fpVerb = "GET"
@path = getInfo.attributes["path"].to_s
puts "\r\nRequest will #{@fpVerb} #{@path}\r\n"
fpInfo.xpath('test').each do |testInfo|
@fpXpath = testInfo.attributes["xpath"].to_s
@fpRegex = testInfo.attributes["regex"].to_s
puts "\r\nxpath: #{@fpXpath}"
puts "regex: #{@fpRegex}"
end
end
fpInfo.xpath('post').each do |postInfo|
@fpVerb = "POST"
@fpData = "" # What should be posted to the URI?
@path = postInfo.attributes["path"].to_s
puts "\r\n#{pathVerb} #{@path}\r\n"
end
@fpUri = URI("#{fpUrl.scheme}://#{fpUrl.host}:#{fpUrl.port}#{@path}")
# Parse a specified URI based on information from the fingerprint.
parsedReturn = parseBody(@fpUri,@fpVerb,@fpData,@fpXpath,@fpRegex)
#puts "\r\nResults:\r\n"
#puts "XPath Match: #{parsedReturn[1][0]}"
#puts "RegEx Match: #{parsedReturn[0][0]}"
#puts "Group 1 (Version) : #{parsedReturn[0][1]}"
#puts "\r\n"
end
end
# fpCheck(fpXmlFile,xmlXsdPath) # No XSD currently seems to exists to validate finger prints?
# Load fingerprint xml into fpXml
fpXml = parseConfigs(fpXmlFile)
evaluateFingerPrints(fpXml,url)
|
require_relative "pseudo_db/version"
require_relative "pseudo_db/database"
module PseudoDb
DEFAULTS = {
adapter: 'mysql',
user: nil,
password: nil,
host: 'localhost',
database: 'test',
dry_run: false,
custom_dictionary: nil
}
def anonymize(options = {})
options = DEFAULTS.merge(options)
sequel_connection = Sequel.connect(
:adapter => options[:adapter],
:user => options[:user],
:host => options[:host],
:database => options[:database],
:password => options[:password]
)
data_dictionary = DataDictionary.new(options[:custom_dictionary])
db_anonymizer = Database.new(sequel_connection, data_dictionary, options[:dry_run])
db_anonymizer.anonymize
end
end
|
require 'rails_helper'
describe MeasureSelection do
it { is_expected.to validate_presence_of(:measure_id) }
it { is_expected.to validate_presence_of(:audit_report_id) }
it { is_expected.to belong_to(:measure) }
it { is_expected.to belong_to(:audit_report) }
it { is_expected.to have_many(:field_values) }
it { is_expected.to have_many(:structure_changes) }
end
|
FactoryGirl.define do
factory :user, class: 'Authentify::User' do
name "Test User"
login 'testuser'
email "test@test.com"
password "password1"
password_confirmation {password}
status "active"
last_updated_by_id 1
auth_token "123"
password_reset_token nil
password_reset_sent_at nil
cell '123455'
allow_email false
allow_text_msg false
customer_id 1
end
end |
# frozen_string_literal: true
require 'socket'
module Dynflow
class Config
include Algebrick::TypeCheck
def self.config_attr(name, *types, &default)
self.send(:define_method, "validate_#{ name }!") do |value|
Type! value, *types unless types.empty?
end
self.send(:define_method, name) do
var_name = "@#{ name }"
if instance_variable_defined?(var_name)
return instance_variable_get(var_name)
else
return default
end
end
self.send(:attr_writer, name)
end
class ForWorld
attr_reader :world, :config
def initialize(config, world)
@config = config
@world = world
@cache = {}
end
def validate
@config.validate(self)
end
def queues
@queues ||= @config.queues.finalized_config(self)
end
def method_missing(name)
return @cache[name] if @cache.key?(name)
value = @config.send(name)
value = value.call(@world, self) if value.is_a? Proc
validation_method = "validate_#{ name }!"
@config.send(validation_method, value) if @config.respond_to?(validation_method)
@cache[name] = value
end
end
class QueuesConfig
attr_reader :queues
def initialize
@queues = {:default => {}}
end
# Add a new queue to the configuration
#
# @param [Hash] queue_options
# @option queue_options :pool_size The amount of workers available for the queue.
# By default, it uses global pool_size config option.
def add(name, queue_options = {})
Utils.validate_keys!(queue_options, :pool_size)
name = name.to_sym
raise ArgumentError, "Queue #{name} is already defined" if @queues.key?(name)
@queues[name] = queue_options
end
def finalized_config(config_for_world)
@queues.values.each do |queue_options|
queue_options[:pool_size] ||= config_for_world.pool_size
end
@queues
end
end
def queues
@queues ||= QueuesConfig.new
end
config_attr :logger_adapter, LoggerAdapters::Abstract do
LoggerAdapters::Simple.new
end
config_attr :transaction_adapter, TransactionAdapters::Abstract do
TransactionAdapters::None.new
end
config_attr :persistence_adapter, PersistenceAdapters::Abstract do
PersistenceAdapters::Sequel.new('sqlite:/')
end
config_attr :coordinator_adapter, CoordinatorAdapters::Abstract do |world|
CoordinatorAdapters::Sequel.new(world)
end
config_attr :pool_size, Integer do
5
end
config_attr :executor do |world, config|
Executors::Parallel::Core
end
def validate_executor!(value)
accepted_executors = [Executors::Parallel::Core]
accepted_executors << Executors::Sidekiq::Core if defined? Executors::Sidekiq::Core
if value && !accepted_executors.include?(value)
raise ArgumentError, "Executor #{value} is expected to be one of #{accepted_executors.inspect}"
end
end
config_attr :executor_semaphore, Semaphores::Abstract, FalseClass do |world, config|
Semaphores::Dummy.new
end
config_attr :executor_heartbeat_interval, Integer do
15
end
config_attr :ping_cache_age, Integer do
60
end
config_attr :connector, Connectors::Abstract do |world|
Connectors::Direct.new(world)
end
config_attr :auto_rescue, Algebrick::Types::Boolean do
true
end
config_attr :auto_validity_check, Algebrick::Types::Boolean do |world, config|
!!config.executor
end
config_attr :validity_check_timeout, Numeric do
30
end
config_attr :exit_on_terminate, Algebrick::Types::Boolean do
true
end
config_attr :auto_terminate, Algebrick::Types::Boolean do
true
end
config_attr :termination_timeout, Numeric do
60
end
config_attr :auto_execute, Algebrick::Types::Boolean do
true
end
config_attr :silent_dead_letter_matchers, Array do
# By default suppress dead letters sent by Clock
[
DeadLetterSilencer::Matcher.new(::Dynflow::Clock)
]
end
config_attr :delayed_executor, DelayedExecutors::Abstract, NilClass do |world|
options = { :poll_interval => 15,
:time_source => -> { Time.now.utc } }
DelayedExecutors::Polling.new(world, options)
end
config_attr :throttle_limiter, ::Dynflow::ThrottleLimiter do |world|
::Dynflow::ThrottleLimiter.new(world)
end
config_attr :execution_plan_cleaner, ::Dynflow::Actors::ExecutionPlanCleaner, NilClass do |world|
nil
end
config_attr :action_classes do
Action.all_children
end
config_attr :meta do |world, config|
{ 'hostname' => Socket.gethostname, 'pid' => Process.pid }
end
config_attr :backup_deleted_plans, Algebrick::Types::Boolean do
false
end
config_attr :backup_dir, String, NilClass do
'./backup'
end
config_attr :telemetry_adapter, ::Dynflow::TelemetryAdapters::Abstract do |world|
::Dynflow::TelemetryAdapters::Dummy.new
end
def validate(config_for_world)
if defined? ::ActiveRecord::Base
begin
ar_pool_size = ::ActiveRecord::Base.connection_pool.instance_variable_get(:@size)
if (config_for_world.pool_size / 2.0) > ar_pool_size
config_for_world.world.logger.warn 'Consider increasing ActiveRecord::Base.connection_pool size, ' +
"it's #{ar_pool_size} but there is #{config_for_world.pool_size} " +
'threads in Dynflow pool.'
end
rescue ActiveRecord::ConnectionNotEstablished # rubocop:disable Lint/HandleExceptions
# If in tests or in an environment where ActiveRecord doesn't have a
# real DB connection, we want to skip AR configuration altogether
end
end
end
end
end
|
require 'test_helper'
class HomeControllerTest < ActionController::TestCase
test "html updates" do
end
test "iphone version" do
end
test "rjs updates" do
end
test "should success access home" do
get :index
assert :success
end
test "should get last tags" do
get :index
assert_not_nil assigns(:data)
end
test "should redirect to url in english" do
# get :index, {:locale => "en"} #bug not pass locale how parameters, ex: blabal.com/?locale=en
# assert_redirected_to "/en"
end
test "should have slogan in english" do
get :index, :locale => "en"
assert_select 'p.slogan', "Online coverage of events in New Song"
end
test "should have slogan in spanish" do
get :index, :locale => "es"
assert_select 'p.slogan', "Línea de cobertura de los acontecimientos en Cancion Nueva"
end
test "should link to spanish" do
get :index, :locale => "es"
assert_select 'div#footer a[href=?]' , "/es/"
end
test "shoud link to english" do
get :index, :locale => "en"
assert_select 'div#footer a[href=?]' , "/en/"
end
test "should redirect from plug4life" do
@request.host = 'plug4life.com'
get :index
assert_redirected_to "http://mashup.cancaonova.com/"
end
test "should render mobile" do
@request.host = 'cancaonova.mobi'
get :index
assert_template "home/index.xhtml.haml"
end
test "should list 10 itens in last updates" do
get :index
assert_select "div#spotlight > div", 1..10
end
test "should render page even no analytic data" do
# get :index # should find a way to turn off google analyitcs
# assert_select "div#popular li", 0
end
# iphone
test "should render iphone template" do
get :index , :format => "iphone"
assert_template "home/index.iphone.haml"
end
# test rss link_to
test "should link to rss with default tag" do
get :index
assert_select 'div#footer a.rss[href=?]' , "/cancaonova.rss"
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, authentication_keys: [:email, :team_name]
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>"}
validates_attachment_content_type :avatar, content_type: %w(image/jpeg image/jpg image/png)
#accessor
attr_accessor :team_name
#association
belongs_to :team
has_many :problems, :dependent => :destroy,foreign_key: [:id]
has_many :likes
#validation
before_create :team_name_to_id, if: :has_team_key?
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
team_name = conditions.delete(:team_name)
team_id = Team.where(name: team_name).first
email = conditions.delete(:email)
# devise認証を、複数項目に対応させる
if team_id && email
where(conditions).where(["team_id = :team_id AND email = :email",
{ team_id: team_id, email: email }]).first
elsif conditions.has_key?(:confirmation_token)
where(conditions).first
else
false
end
end
private
def has_team_key?
team_name.present?
end
def team_name_to_id
# team = Team.where(name: team_name).first_or_create
if Team.where(name: team_name).exists?
# チームがあったらそのチームに入れる
team = Team.where(name: team_name).first_or_create
else
# なかったら作成
team = Team.where(name: team_name, point: 0).create
end
self.team_id = team.id
end
end
|
class Component < ApplicationRecord
belongs_to :text
has_many :component_citations
accepts_nested_attributes_for :component_citations, reject_if: :all_blank, :allow_destroy => true
def translators
unless @translators
load_citations_by_role
end
@translators
end
def load_citations_by_role
@translators = []
component_citations.each do |citation|
if citation.role == 'translator'
@translators << "<a href=\"\">#{citation.name}</a>".html_safe
end
end
end
def sort_title
unless title
return ''
end
title.gsub(/["'_\[\]]/, '').sub(/^(An? )|(The )/,'')
end
default_scope { order("ordinal ASC") }
end
|
json.articles @articles do |article|
json.published_at article.published_at
json.title article.title
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.