text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
require "rails_helper"
feature "Researcher - Participants", type: :feature do
fixtures :all
describe "Logged in as a researcher when the application doesn't have social functionality" do
let(:participant) { participants(:participant1) }
before do
allow(Rails.application.config).to receive(:include_social_features)
.and_return(false)
sign_in users :researcher1
end
it "should not display the 'Display Name' field when creating a participant" do
visit "/think_feel_do_dashboard/participants/new"
expect(page).to_not have_text "Display Name"
end
it "should not display the 'Display Name' field when viewing a participant" do
visit "/think_feel_do_dashboard/participants/#{participant.id}"
expect(page).to_not have_text "Display Name"
end
it "should not display the 'Display Name' field when editing a participant" do
visit "/think_feel_do_dashboard/participants/#{participant.id}/edit"
expect(page).to_not have_text "Display Name"
end
it "can generate a random password for the Participant", js: true do
visit "/think_feel_do_dashboard/participants/#{participant.id}/edit"
click_on "Generate password"
passphrase = find("#password-display").text.strip
click_on "Update"
expect(page).to have_text "Participant was successfully updated."
expect(participant.reload.valid_password?(passphrase)).to be true
end
end
describe "Logged in as a researcher when the application has social functionality" do
before do
allow(Rails.application.config).to receive(:include_social_features)
.and_return(true)
sign_in users :researcher1
visit "/think_feel_do_dashboard"
click_on "Participants"
end
after do
# click_on "Sign Out"
end
it "displays the participants that currently exist" do
expect(page).to have_text "TFD-1111"
end
it "should display errors if required fields aren't filled in when created" do
click_on "New"
click_on "Create"
expect(page).to have_text "prohibited this participant from being saved"
expect(page).to have_text "Study ID can't be blank"
end
it "should enable the creation of a participant" do
expect(page).to_not have_text "Inactive favoriteToken1!"
click_on "New"
fill_in "Study Id", with: "favoriteToken1!"
fill_in "Email", with: "gwashington@ex.co"
fill_in "Phone Number", with: "16085169918"
select "Phone", from: "Contact Preference"
click_on "Create"
expect(page).to have_text "Participant was successfully created"
expect(page).to have_text "Email: gwashington@ex.co"
expect(page).to have_text "Phone Number: 1(608) 516-9918"
expect(page).to have_text "Contact Preference: Phone"
expect(page).to have_text "Study Id: favoriteToken1!"
expect(page).to have_text "Membership Status: Inactive"
expect(page).to have_text "Below lists the all groups this participant has been a member of and whether they are currently active or inactive."
visit "/think_feel_do_dashboard/participants"
expect(page).to have_text "Inactive favoriteToken1!"
end
it "should display errors if required fields aren't filled in upon edit" do
click_on "TFD-1111"
click_on "Edit"
fill_in "Email", with: ""
fill_in "Phone Number", with: ""
fill_in "Study Id", with: ""
click_on "Update"
expect(page).to have_text "prohibited this participant from being saved"
end
it "should display errors if required fields aren't filled in upon edit" do
click_on "TFD-1111"
click_on "Edit"
fill_in "Study Id", with: ""
click_on "Update"
expect(page).to have_text "Study ID can't be blank"
end
it "should have a valid phone number if contact preference is 'phone'" do
click_on "TFD-1111"
click_on "Edit"
fill_in "Phone Number", with: "19991234223"
select "Phone", from: "Contact Preference"
click_on "Update"
expect(page).to have_text "Phone number is not valid"
end
it "should have a valid phone number if contact preference is 'phone'" do
click_on "TFD-1111"
click_on "Edit"
fill_in "Phone Number", with: ""
select "Phone", from: "Contact Preference"
click_on "Update"
expect(page).to have_text "Phone number can't be blank if your contact preference is phone."
end
it "should enable the updating of a participant" do
click_on "TFD-1111"
expect(page).to have_text "Email: participant1@example.com"
expect(page).to have_text "Phone Number: 1(608) 215-3900"
expect(page).to have_text "Contact Preference: Phone"
expect(page).to have_text "Study Id: TFD-1111"
expect(page).to_not have_text "Email: gwashington@ex.co"
expect(page).to_not have_text "Phone Number: 1(608) 845-6890"
expect(page).to_not have_text "Contact Preference: Email"
expect(page).to_not have_text "Study Id: favoriteToken1!"
click_on "Edit"
fill_in "Email", with: "gwashington@ex.co"
fill_in "Phone Number", with: "16088456890"
select "Email", from: "Contact Preference"
fill_in "Study Id", with: "favoriteToken1!"
click_on "Update"
expect(page).to_not have_text "Email: participant1@example.com"
expect(page).to_not have_text "Phone Number: 1(608) 215-3900"
expect(page).to_not have_text "Contact Preference: Phone"
expect(page).to_not have_text "Study Id: TFD-1111"
expect(page).to have_text "Email: gwashington@ex.co"
expect(page).to have_text "Phone Number: 1(608) 845-6890"
expect(page).to have_text "Contact Preference: Email"
expect(page).to have_text "Study Id: favoriteToken1!"
end
it "should be able to delete a user" do
click_on "TFD-1111"
click_on "Destroy"
expect(page).to have_text "Participant was successfully destroyed"
expect(page).to_not have_text "TFD-1111"
end
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
has_many :rooms
has_many :messages
has_one_attached :avatar
has_many :room_messages, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :username, uniqueness: true, presence: true
before_create :add_default_avatar
#def user_avatar(user_id)
#user = User.find(user_id)
# if user.avatar.attached?
# user.avatar
# else
# self.avatar.attach(io: File.open(Rails.root.join("app", "assets", "images", "default-profile.png")), filename: 'default-profile.png' , content_type: "image/png")
# end
# end
def add_default_avatar
unless avatar.attached?
self.avatar.attach(io: File.open(Rails.root.join("app", "assets", "images", "default-profile.png")), filename: 'default-profile.png' , content_type: "image/png")
end
end
end
|
module OpenBEL
module Plugin
EMPTY_ARRAY = [].freeze
INCLUSION_MUTEX = Mutex.new
private_constant :INCLUSION_MUTEX
def self.included(base)
INCLUSION_MUTEX.lock
begin
unless OpenBEL.const_defined?(:PluginClasses)
OpenBEL.const_set(:PluginClasses, [])
end
OpenBEL::PluginClasses << base
ensure
INCLUSION_MUTEX.unlock
end
end
def id
fail NotImplementedError.new("#{__method__} not implemented")
end
def name
fail NotImplementedError.new("#{__method__} not implemented")
end
def description
fail NotImplementedError.new("#{__method__} not implemented")
end
def type
fail NotImplementedError.new("#{__method__} not implemented.")
end
def required_extensions
[]
end
def optional_extensions
[]
end
def validate(extensions = {}, options = {})
validation_successful
end
def on_load; end
def configure(extensions = {}, options = {}); end
def create_instance; end
def on_unload; end
def <=>(other)
id_compare = id.to_s <=> other.to_s
return id_compare unless id_compare == 0
return self.name.to_s <=> other.name.to_s
end
def hash
[id, name].hash
end
def ==(other)
return false if other == nil
return true if self.equal? other
self.id == other.id && self.name == other.name
end
alias_method :eql?, :'=='
protected
def validation_successful
EMPTY_ARRAY
end
def mri?
defined?(RUBY_DESCRIPTION) && (/^ruby/ =~ RUBY_DESCRIPTION)
end
def jruby?
defined?(RUBY_PLATFORM) && ("java" == RUBY_PLATFORM)
end
def rubinius?
defined?(RUBY_ENGINE) && ("rbx" == RUBY_ENGINE)
end
ValidationError = Struct.new(:plugin, :field, :error) do
def to_s
"Error with #{field} field of #{plugin.id} (#{plugin.name}): #{error}"
end
end
end
end
|
module Haenawa
module Commands
class Unsupported < Command
def validate; end
def render
message = "γ΅γγΌγγγ¦γγͺγγ³γγ³γγ§γγ| #{command} | #{target} | #{value} |"
append_partial("raise \"#{escape_ruby(message)}\"")
end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Like, type: :model do
it 'is valid with valid attributes' do
@user = User.create(email: 'david44419@mail.com', password: Devise::Encryptor.digest(User, 'helloworld'))
@post =
Post.create(
title: 'Title',
user_id: @user.id,
description: 'My description here'
)
@like =
Like.new(
user_id: @user.id,
post_id: @post.id
)
expect(@like).to be_valid
end
it 'is not valid without a user_id' do
@user = User.create(email: 'david44421@mail.com', password: Devise::Encryptor.digest(User, 'helloworld'))
@post =
Post.create(
title: 'Title',
user_id: @user.id,
description: 'My description here'
)
@like =
Like.new(
user_id: nil,
post_id: @post.id
)
expect(@like).to_not be_valid
end
it 'is not valid without a post_id' do
@user = User.create(email: 'david44422@mail.com', password: Devise::Encryptor.digest(User, 'helloworld'))
@post =
Post.create(
title: 'Title',
user_id: @user.id,
description: 'My description here'
)
@like =
Like.new(
user_id: @user.id,
post_id: nil
)
expect(@like).to_not be_valid
end
end
|
class Retacerium < ApplicationRecord
validates :name, presence: {message: "Es necesario el nombre del producto"}
validates :cost, presence: {message: "Es necesario el campo Costo"}
validates :rinde, presence: {message: "Es necesario el campo Rinde"}
belongs_to :category
has_many :has_colors
has_many :colors, through: :has_colors
after_create :save_colors
after_update :update_colors
def arraycolors=(value)
@colors = value || []
end
def update_colors
if @colors.any?
has_colors = HasColor.where("retacerium_id = ?", self.id)
has_colors.each do |item|
item.destroy
end
@colors.each do |color_id|
HasColor.create(color_id: color_id, retacerium_id: self.id)
end
end
end
private
def save_colors
# raise @categories.to_yaml
if !@colors.nil?
@colors.each do |color_id|
HasColor.create(color_id: color_id, retacerium_id: self.id)
end
end
end
end
|
# encoding: utf-8
class MagazineMailer < ActionMailer::Base
default from: "info@cook24.vn"
def magazine( buffer )
@buffer = buffer
mail( subject: buffer.subject, to: buffer.to, from: buffer.from )
end
def recipe_magazine( profile, tmpl, recipe )
@recipe = recipe
@tmpl = tmpl
@profile = profile
mail( subject: "γγγ΄γΎγγ#{recipe.title}", to: @profile.email )
end
end
|
FactoryBot.define do
factory :product do
name { "Relogio" }
store_id { 1 }
price { 10.00 }
list_price { 15.00 }
installments_number { 1 }
installments_value { 10.00 }
image { "https://localhost/src/img.svg" }
end
end
|
class Event < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :genre
has_many :user_events
has_many :users, through: :user_events
has_many :tasks, dependent: :destroy
validates :name, :location, :date, :description, presence: true
validates :genre_id, numericality: { other_than: 1 }
end
|
class CreateAdminforms < ActiveRecord::Migration
def change
create_table :adminforms do |t|
t.integer :php_project
t.integer :redmine_project
t.string :php_title
t.string :redmine_title
t.timestamps
end
end
end
|
class RegistrationsController < ApplicationController
def new
end
def create
user = User.new user_params
if user.save
flash[:notice] = "Account Created"
redirect_to root_path
else
flash[:notice] = "Error in the creation"
redirect_to registrations_url
end
end
def user_params
params.require(:registrations).permit(:name, :last_name, :email, :phone, :password)
end
end
|
class AssignmentsController < ApplicationController
before_filter :require_login
def index
@course = Course.find_by_id(params[:course_id])
@assignments = @course.assignments.order(:assign_date).reverse
end
def show
@assignment = Assignment.find_by_id(params[:id])
end
def new
@assignment = Assignment.new
@course = Course.find_by_id(params[:id])
end
def edit
assignment_id = params[:id]
@assignment = Assignment.find_by_id(assignment_id)
render :edit
end
def create
new_assignment = Assignment.new(assignment_params)
@course = Course.find_by_id(params[:id])
new_assignment.course = @course
if @assignment = new_assignment.save
redirect_to course_path(@course)
else
new_assignment.errors.full_messages.each do |message|
flash[:error] = message
end
redirect_to new_assignment_path(@course)
end
end
def update
assignment_id = params[:id]
@assignment = Assignment.find_by_id(assignment_id)
if @assignment.update_attributes(assignment_params)
flash[:notice] = "Updated successfully."
redirect_to course_path(@assignment.course)
else
@assignment.errors.full_messages.each do |message|
flash[:error] = message
end
redirect_to edit_assignment_path(@assignment)
end
end
def destroy
end
private
def assignment_params
params.require(:assignment).permit(:title, :instructions, :assign_date, :due_date, :duration, :visible)
end
end
|
require 'spec_helper'
describe MagicArg do
describe 'self.new().parse()' do
it 'works' do
foo_init = "foo"
bar_init = :bar
foo, bar = MagicArg.new([foo_init, bar_init]).parse("foo, bar")
foo.should eq(foo_init)
bar.should eq(bar_init)
end
end
describe 'self.parse' do
it 'works' do
foo_init = "foo"
bar_init = :bar
foo, bar = MagicArg.parse([foo_init, bar_init], "foo, bar")
foo.should eq(foo_init)
bar.should eq(bar_init)
end
end
end |
require "spec_helper"
describe PagesController do
include Devise::TestHelpers
before do
@user = create_user
end
context "actions for not signed in user" do
context "GET 'home'" do
it "redirect to login path" do
get 'home'
expect(response).to redirect_to login_path
end
end
context "GET 'login'" do
it "renders the login template" do
get 'login'
expect(response).to render_template("login")
end
end
end
context "actions for signed in user" do
before { sign_in @user }
context "GET 'home'" do
it "renders the home tamplate" do
get 'home'
expect(response).to render_template("home")
end
it "assigns @form" do
get 'home'
expect(assigns(:form).class).to eq(BookmarkUrlForm)
end
end
context "GET 'login'" do
it "redirect to home" do
get 'login'
expect(response).to redirect_to root_path
end
end
end
end
|
require 'rails_helper'
RSpec.describe "V1::Sessions", type: :request do
describe '#create' do
let(:user) { create(:user) }
let(:valid_user) { {
user: {
email: user.email,
password: user.password
}
}.to_json }
let(:invalid_user) { {
user: {
email: user.email,
password: 'helloworld'
}
}.to_json }
context 'when the post request is invalid' do
before do
post v1_sessions_url, params: invalid_user, headers: default_header
end
include_examples 'invalid_credentials'
include_examples 'bad_request'
end
context 'when the post request is valid' do
before do
post v1_sessions_url, params: valid_user, headers: default_header
end
include_examples 'user_token'
end
end
describe '#show' do
let(:user) { create(:user) }
context 'when the user is logged in' do
before do
get v1_session_url('current_user'), headers: auth_header(user)
end
include_examples 'user_token'
end
end
end
|
class ReviewsController < ApplicationController
def create
product = Product.find(params[:product_id])
@review = product.reviews.new(review_params)
@review.user_id = current_user.id
if @review.save
redirect_to :back
flash[:success] = 'Review created succesfully.'
else
# raise @review.errors.full_messages.inspect
redirect_to :back, flash: { error: @review.errors.full_messages.first }
end
end
def destroy
delete_review = Review.find(params[:id]).destroy
flash[:success] = 'Review deleted succcesfully.'
redirect_to :back
end
private
def review_params
params.require(:review).permit(:rating, :description)
end
end
|
class CompanySignupJob < ActiveJob::Base
queue_as :default
def perform(company, secure_password, url)
@company = company
@url = url
@secure_password = secure_password
CompanySignupMailer.signup_company(@company, @secure_password, @url).deliver_later
end
end
|
require 'pathname'
require 'yaml'
module Testor
def self.root
@root ||= Pathname(File.dirname(__FILE__))
end
module Config
def self.root
@root ||= Testor.root.join('../config')
end
def self.[](key)
config[key]
end
private
def self.config
return @config if @config
@config = YAML.load_file(root.join('config.yml'))
end
end
end
|
class Investigator
attr_reader :base_willpower, :base_intellect, :base_combat, :base_agility, :elder_sign_value_resolver, :elder_sign_side_effects_resolver
def initialize(base_stats:, elder_sign_value_resolver:, elder_sign_side_effects_resolver: nil)
@base_willpower = base_stats[:willpower]
@base_intellect = base_stats[:intellect]
@base_combat = base_stats[:combat]
@base_agility = base_stats[:agility]
@elder_sign_value_resolver = elder_sign_value_resolver
@elder_sign_side_effects_resolver = elder_sign_side_effects_resolver
end
# def trigger_elder_sign_ability(skill_test_outcome:)
# @elder_sign_ability.call(skill_test_outcome)
# end
def willpower
@base_willpower
end
def intellect
@base_intellect
end
def combat
@base_combat
end
def agility
@base_agility
end
end |
class PdfReportsController < ApplicationController
before_action :set_report, only: :show
def index
@reports = Reports
end
def show
respond_to do |format|
format.html
format.pdf do
render pdf: 'report',
page_size: 'A4',
template: 'pdf_reports/show.html.erb',
layout: 'pdf.html',
orientation: 'portrait',
lowquality: true,
zoom: 1,
dpi: 75,
header: {
html: { template: 'pdf_reports/header.pdf.erb' },
},
footer: {
html: { template: 'pdf_reports/footer.pdf.erb'}
}
end
end
end
private
Reports = { 1 => {title: 'All Books', template: 'all_books'},
2 => {title: 'Books Grouped by Author', template: 'books_author' } }.freeze
def as_html
render template: Reports[@report_id][1][1]
end
def set_report
@report = Reports[params[:id].to_i]
@report_id = params[:id]
@authors = Book.all.map { |book| book.authors.map(&:name).to_sentence }.uniq.sort
end
end
|
class AddForeignKeyToSalesAndPointOfSales < ActiveRecord::Migration
def change
add_foreign_key :sales, :point_of_sales
end
end
|
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.5.1'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.1'
# Use postgresql as the database for Active Record
gem 'pg', '0.20'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
#gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
gem 'jquery-rails', '4.3.3'
gem 'sprockets-rails', '3.2.1'
gem 'bootstrap', '4.1.3'
gem 'font-awesome-rails', '4.7.0.4'
gem 'chartkick', '2.2.4'
gem 'draper', '3.0.1'
gem 'kaminari', '1.1.1'
gem 'jquery-tablesorter', '1.26.0'
gem 'haml', '5.0.4'
gem 'slack-ruby-client', '0.13.1'
gem 'figaro', '1.1.1'
gem 'tracker_api', '1.9.0'
gem 'reform-rails', '0.1.7'
gem 'httparty', '0.16.2'
gem 'jquery-datatables', '1.10.16'
gem 'ruby-freshbooks', '0.4.1'
gem 'jquery-ui-rails', '6.0.1'
gem 'annotate', '2.7.4'
gem 'momentjs-rails', '2.20.1'
gem 'fullcalendar-rails', '3.9.0.0'
# Used to generate image
gem 'imgkit', '1.6.1'
gem 'wkhtmltoimage-binary', '0.12.4'
# Used for pdf report generation
gem 'wicked_pdf', '1.1.0'
gem 'wkhtmltopdf-binary', '0.12.3.1'
gem 'rmagick', '2.16.0', :require => 'rmagick'
gem 'grim', '1.3.2'
# Used to upload image to s3
gem 'paperclip', '5.1.0'
gem 'aws-sdk', '2.9.29'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
gem 'chromedriver-helper'
end
group :production do
gem 'wkhtmltopdf-heroku', '2.12.4.0'
gem 'rails_12factor'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
source 'https://rails-assets.org' do
gem 'rails-assets-tether', '>= 1.3.3'
end
|
# frozen_string_literal: true
require_dependency 'beyond_canvas/application_controller'
module BeyondCanvas
class AuthenticationsController < ApplicationController # :nodoc:
layout 'beyond_canvas/public'
include ::BeyondCanvas::Authentication
include ::BeyondCanvas::CustomStyles
before_action :validate_app_installation_request!,
only: :new,
unless: -> { Rails.env.development? && BeyondCanvas.configuration.client_credentials }
before_action :clear_locale_cookie, only: [:new, :install]
def new
@shop = Shop.find_or_initialize_by(beyond_api_url: params[:api_url])
if @shop&.authenticated?
open_app(@shop)
elsif BeyondCanvas.configuration.preinstalled
preinstall
end
end
def install
@shop = Shop.create_with(shop_params).create_or_find_by(beyond_api_url: params[:shop][:api_url])
@shop.assign_attributes(shop_params)
if @shop.save
@shop.authenticate(params[:shop][:code])
@shop.subscribe_to_beyond_webhooks
redirect_to after_installation_path
else
render :new
end
end
private
def shop_params
beyond_canvas_parameter_sanitizer.sanitize.merge(http_host: request.env['HTTP_HOST'])
end
def after_preinstallation_path
params[:return_url]
end
def after_installation_path
params[:shop][:return_url]
end
def after_sign_in_path
BeyondCanvas.configuration.open_app_url
end
def preinstall
@shop = Shop.create_or_find_by(beyond_api_url: params[:api_url])
@shop.http_host = request.env['HTTP_HOST']
@shop.authenticate(params[:code])
@shop.subscribe_to_beyond_webhooks
redirect_to after_preinstallation_path
end
def open_app(shop)
shop.authenticate(params[:code]) if params[:code]
reset_session
log_in shop
cookies.delete(:custom_styles_url)
set_custom_styles_url shop if BeyondCanvas.configuration.cockpit_app
redirect_to after_sign_in_path
end
def clear_locale_cookie
cookies.delete :locale if BeyondCanvas.configuration.cockpit_app
end
end
end
|
class Tashvigh < ActiveRecord::Base
belongs_to :ppl
validates :amount, presence: :true, numericality: true
validates :mode, presence: :true
validates :wrote_on, presence: :true
before_save do
self.wrote_on = JalaliDate.new(self.wrote_on.year, self.wrote_on.month, self.wrote_on.day).to_gregorian
end
end
|
class Race < ActiveRecord::Base
has_and_belongs_to_many :modifiers
def to_s
self.name
end
def self.method_missing(method_name, *args, &block)
find_by(name: method_name.to_s.titleize)
end
def add_modifier(modifier)
if not self.modifiers.include? modifier then self.modifiers << modifier end
end
end
|
class Admin::DailyMealsController < ApplicationController
def show
@meal = Meal.find(params[:meal_id])
@user = current_user
@user.daily_meal = @meal
end
end
|
class Recipe < ActiveRecord::Base
validates :title, :description, presence: true
belongs_to :user
has_many :ingredient_recipes
has_many :images
has_many :comments
scope :most_recent, -> { order( created_at: :desc ) }
has_many :rates
def calculate_rate_for_recipe ()
if rates.count == 0
return 0
else
return rates.average(:value)
end
end
#Override the as_json method to include the user name:
def as_json(options = {})
super(options.merge(include: {
user: { only: [ :name,:id ] }
}
))
end
end
|
# frozen_string_literal: true
require "spec_helper"
RSpec.describe PgParty::Config do
let(:instance) { described_class.new }
describe "#caching" do
subject { instance.caching }
context "when defaulted" do
it { is_expected.to eq(true) }
end
context "when overridden" do
before { instance.caching = false }
it { is_expected.to eq(false) }
end
end
describe "#caching_ttl" do
subject { instance.caching_ttl }
context "when defaulted" do
it { is_expected.to eq(-1) }
end
context "when overridden" do
before { instance.caching_ttl = 60 }
it { is_expected.to eq(60) }
end
end
describe "#schema_exclude_partitions" do
subject { instance.schema_exclude_partitions }
context "when defaulted" do
it { is_expected.to eq(true) }
end
context "when overridden" do
before { instance.schema_exclude_partitions = false }
it { is_expected.to eq(false) }
end
end
describe "#create_template_tables" do
subject { instance.create_template_tables }
context "when defaulted" do
it { is_expected.to eq(true) }
end
context "when overridden" do
before { instance.create_template_tables = false }
it { is_expected.to eq(false) }
end
end
describe "#create_with_primary_key" do
subject { instance.create_with_primary_key }
context "when defaulted" do
it { is_expected.to eq(false) }
end
context "when overridden" do
before { instance.create_with_primary_key = true }
it { is_expected.to eq(true) }
end
end
describe "#include_subpartitions_in_partition_list" do
subject { instance.include_subpartitions_in_partition_list }
context "when defaulted" do
it { is_expected.to eq(false) }
end
context "when overridden" do
before { instance.include_subpartitions_in_partition_list = true }
it { is_expected.to eq(true) }
end
end
end
|
class AnswerPolicy < Struct.new(:user, :answer)
def create?
answer.exam.course.admins.include? user
end
def update?
create?
end
def destroy?
create?
end
end
|
# frozen_string_literal: true
namespace :dealers do
desc 'Auto generation for valid customers'
task generate_and_save_to_db: :environment do
AddDealersWorker.perform_async
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :appointment do
parent_names { Faker::Name.first_name + ' and ' + Faker::Name.first_name + ' ' + Faker::Name.last_name }
phone_numbers { Faker::PhoneNumber.phone_number }
email_addresses { Faker::Internet.email}
children_names { Faker::Name.first_name + ' and ' + Faker::Name.first_name }
children_ages { rand(6) + ' , ' + rand(6) }
other_info { Faker::Lorem.paragraph(2) }
tour_date { (rand(57)+3).days.from_now }
end
end
|
require 'bike'
describe Bike do
it { is_expected.to respond_to :condition }
it 'should, by default, be working' do
expect(subject.condition).to eq true
end
end |
module SchemaConformist
module Driver
include Committee::Test::Methods
def committee_options
{ schema: committee_schema }.merge(schema_conformist_committee_options)
end
def request_object
request
end
def response_data
[response.status, response.headers, response.body]
end
private
def committee_schema
@committee_schema ||= Committee::Drivers.load_from_file(schema_path)
end
def schema_path
Rails.application.config.schema_conformist.schema_path
end
def schema_conformist_committee_options
Rails.application.config.schema_conformist.committee
end
end
end
|
# frozen_string_literal: true
# It allows to set a list of valid
# - districts
# - district_councils
# for an authorization.
class CensusActionAuthorizer < Decidim::Verifications::DefaultActionAuthorizer
attr_reader :allowed_districts, :allowed_district_councils
# Overrides the parent class method, but it still uses it to keep the base behavior
def authorize
# Remove the additional setting from the options hash to avoid to be considered missing.
@allowed_districts ||= options.delete("district")&.split(/[\W,;]+/)
@allowed_district_councils ||= options.delete("district_council")&.split(/[\W,;]+/)
status_code, data = *super
extra_explanations = []
if allowed_districts.present?
# Does not authorize users with different districts
if status_code == :ok && !allowed_districts.member?(authorization.metadata['district'])
status_code = :unauthorized
data[:fields] = { 'district' => authorization.metadata['district'] }
# Adds an extra message to inform the user the additional restriction for this authorization
extra_explanations << { key: "extra_explanation.districts",
params: { scope: "decidim.verifications.census_authorization",
count: allowed_districts.count,
districts: allowed_districts.join(", ") } }
end
end
if allowed_district_councils.present?
# Does not authorize users with different districts
if status_code == :ok && !allowed_district_councils.member?(authorization.metadata['district_council'])
status_code = :unauthorized
data[:fields] = { 'district_council' => authorization.metadata['district_council'] }
# Adds an extra message to inform the user the additional restriction for this authorization
extra_explanations << { key: "extra_explanation.district_councils",
params: { scope: "decidim.verifications.census_authorization",
count: allowed_district_councils.count,
districts: allowed_district_councils.join(", ") } }
end
end
data[:extra_explanation] = extra_explanations if extra_explanations.any?
[status_code, data]
end
end |
class Spree::Admin::PosController < Spree::Admin::BaseController
before_filter :get_order , :except => :new
def get_order
order_number = params[:number]
@order = Spree::Order.find_by_number(order_number)
raise "No order found for -#{order_number}-" unless @order
end
def new
unless params[:force]
@order = Spree::Order.last # TODO , this could be per user
end
init if @order == nil or not @order.complete?
redirect_to :action => :show , :number => @order.number
end
def export
unless session[:items]
show
return
end
missing = []
session[:items].each do |key , item |
missing << item.variant.full_name if item.variant.ean.blank?
end
unless missing.empty?
flash[:error] = "All items must have ean set, missing: #{missing.join(' , ')}"
redirect_to :action => :show
return
end
opt = {}
session[:items].each do |key , item |
var = item.variant
opt[var.ean] = item.quantity
var.on_hand = var.on_hand - item.quantity
var.save!
end
init # reset this pos
opt[:host] = "" #Spree::Config[:pos_export]
opt[:controller] = "pos"
opt[:action] = "import"
redirect_to opt
end
def import
init
added = 0
params.each do |id , quant |
next if id == "action"
next if id == "controller"
v = Spree::Variant.find_by_ean id
if v
add_variant(v , quant )
added += 1
else
v = Spree::Variant.find_by_sku id
if v
add_variant(v , quant )
added += 1
else
add_error "No product found for EAN #{id} "
end
end
end
add_notice "Added #{added} products" if added
redirect_to :action => :show
end
def inventory
if @order.state == "complete"
flash[:error] = "Order was already completed (printed), please start with a new customer to add inventory"
redirect_to :action => :show
return
end
as = params[:as]
num = 0
prods = @order.line_items.count
@order.line_items.each do |item |
variant = item.variant
num += item.quantity
if as
variant.on_hand = item.quantity
else
variant.on_hand += item.quantity
end
variant.save!
end
@order.line_items.clear
flash.notice = "Total of #{num} items #{as ? 'inventoried': 'added'} for #{prods} products "
redirect_to :action => :show
end
def add
if pid = params[:item]
add_variant Spree::Variant.find pid
flash.notice = t('product_added')
end
redirect_to :action => :show
end
def remove
if pid = params[:item]
variant = Spree::Variant.find(pid)
line_item = @order.line_items.find { |line_item| line_item.variant_id == variant.id }
line_item.quantity -= 1
if line_item.quantity == 0
@order.line_items.delete line_item
else
line_item.save
end
flash.notice = t('product_removed')
end
redirect_to :action => :show
end
def print
unless @order.payment_ids.empty?
@order.payments.first.delete unless @order.payments.first.amount == @order.total
end
if @order.payment_ids.empty?
payment = Spree::Payment.new
payment.payment_method = Spree::PaymentMethod.find_by_type_and_environment( "Spree::PaymentMethod::Check" , Rails.env)
payment.amount = @order.total
payment.order = @order
payment.save!
payment.capture!
end
@order.state = "complete"
@order.completed_at = Time.now
@order.create_tax_charge!
@order.finalize!
@order.save!
url = SpreePos::Config[:pos_printing]
url = url.sub("number" , @order.number.to_s)
redirect_to url
end
def index
redirect_to :action => :new
end
def show
if params[:price] && request.post?
pid = params[:price].to_i
item = @order.line_items.find { |line_item| line_item.id == pid }
item.price = params["price#{pid}"].to_f
item.save
@order.reload # must be something cached in there, because it doesnt work without. shame.
flash.notice = I18n.t("price_changed")
end
if params[:quantity_id] && request.post?
iid = params[:quantity_id].to_i
item = @order.line_items.find { |line_item| line_item.id == iid }
#TODO error handling
item.quantity = params[:quantity].to_i
item.save
#TODO Hack to get the inventory to update. There must be a better way, but i'm lost in spree jungle
item.variant.product.save
@order.reload # must be something cached in there, because it doesnt work without. shame.
flash.notice = I18n.t("quantity_changed")
end
if discount = params[:discount]
if i_id = params[:item]
item = @order.line_items.find { |line_item| line_item.id.to_s == i_id }
item_discount( item , discount )
else
@order.line_items.each do |item|
item_discount( item , discount )
end
end
@order.reload # must be something cached in there, because it doesnt work without. shame.
end
if sku = params[:sku]
prods = Spree::Variant.where(:sku => sku ).limit(2)
if prods.length == 0 and Spree::Variant.instance_methods.include? "ean"
prods = Spree::Variant.where(:ean => sku ).limit(2)
end
if prods.length == 1
add_variant prods.first
else
redirect_to :action => :find , "q[product_name_cont]" => sku
return
end
end
end
def item_discount item , discount
item.price = item.variant.price * ( 1.0 - discount.to_f/100.0 )
item.save!
end
def find
init_search
if params[:index]
search = params[:q]
search["name_cont"] = search["variants_including_master_sku_cont"]
search["variants_including_master_sku_cont"] = nil
init_search
end
end
private
def add_notice no
flash[:notice] = "" unless flash[:notice]
flash[:notice] << no
end
def add_error no
flash[:error] = "" unless flash[:error]
flash[:error] << no
end
def init
@order = Spree::Order.new
@order.user = current_user
@order.bill_address = @order.user.bill_address
@order.ship_address = @order.user.ship_address
@order.email = current_user.email
@order.save!
method = Spree::ShippingMethod.find_by_name SpreePos::Config[:pos_shipping]
@order.shipping_method = method || Spree::ShippingMethod.first
@order.create_shipment!
session[:pos_order] = @order.number
end
def add_variant var , quant = 1
init unless @order
@order.add_variant(var , quant)
#TODO Hack to get the inventory to update. There must be a better way, but i'm lost in spree jungle
var.product.save
end
private
def init_search
params[:q] ||= {}
params[:q][:meta_sort] ||= "product_name asc"
params[:q][:deleted_at_null] = "1"
params[:q][:product_deleted_at_null] = "1"
@search = Spree::Variant.ransack(params[:q])
@variants = @search.result(:distinct => true).page(params[:page]).per(20)
end
end
|
class PagesController < ApplicationController
def welcome
@contacts = Contact.all
end
end
|
require_relative '../spec_helper'
RSpec.describe OpenAPIParser::ParameterValidator do
let(:root) { OpenAPIParser.parse(normal_schema, config) }
let(:config) { {} }
describe 'validate' do
subject { request_operation.validate_request_parameter(params, {}) }
let(:content_type) { 'application/json' }
let(:http_method) { :get }
let(:request_path) { '/validate' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
context 'correct' do
context 'no optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query' } }
it { expect(subject).to eq({ 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query' }) }
end
context 'with optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query', 'optional_integer' => 1 } }
it { expect(subject).to eq({ 'optional_integer' => 1, 'query_integer_list' => [1, 2], 'queryString' => 'Query', 'query_string' => 'query' }) }
end
end
context 'invalid' do
context 'not exist required' do
context 'not exist data' do
let(:params) { { 'query_integer_list' => [1, 2], 'queryString' => 'Query' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with('missing required parameters: query_string')
end
end
end
context 'not exist array' do
let(:params) { { 'query_string' => 'query', 'queryString' => 'Query' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with('missing required parameters: query_integer_list')
end
end
end
end
context 'non null check' do
context 'optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query', 'optional_integer' => nil } }
it { expect { subject }.to raise_error(OpenAPIParser::NotNullError) }
end
context 'optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => nil, 'queryString' => 'Query' } }
it { expect { subject }.to raise_error(OpenAPIParser::NotNullError) }
end
end
end
end
end
|
require 'active_support/core_ext/array/conversions'
require_relative 'action.rb'
class Event
include ActionContainer
attr_accessor :participants
def initialize
self.participants = []
end
def describe
return "#{self.participants.to_sentence} are engaged in some mysterious errand."
end
def tick
end
def add(actor)
self.participants << actor unless self.participants.index(actor)
end
def remove(actor)
self.participants.delete(actor)
end
def end
participants.dup.each{|participant| participant.leave_event(self)}
end
def escapable?
return true
end
def escape_clause
return "Should I keep doing this?"
end
end
|
class ChangeMessageColumnNames < ActiveRecord::Migration
def up
rename_column :messages, :from, :message_from
rename_column :messages, :to, :message_to
end
def down
rename_column :messages, :message_from, :from
rename_column :messages, :message_to, :to
end
end
|
# Methods added to this helper will be available to all templates in the application.
#module Admin
module Admin
module ApplicationHelper
def admin_title_tag
if ENV['RAILS_ENV'] == 'production'
return raw("<title> Admin Chavanga - "+
controller.controller_name.capitalize.split("_").join(" ") +
"</title>")
end
return raw("<title> Admin Developming Localhost Chavanga - "+
controller.controller_name.capitalize.split("_").join(" ") +
"</title>")
end
def admin_main_menu_link_to( _name, link_path )
raw(link_to(
_name,
link_path,
:class => 'main_menu'
))
end
def admin_main_menu_button( _name, _controller_name, style_name = "main_menu_admin_button" )
id = _name.split(" ").join("_")
result = raw("<div class='" + style_name + "'>
<div id='main_menu_td_"+id+"' class='main_menu_button_element'
onmouseover='main_menu_td_"+id+".setAttribute(\"class\",\"main_menu_button_element_mouse_over\");'
onmouseout='main_menu_td_"+id.to_s+".setAttribute(\"class\",\"main_menu_button_element\");' >")
result += raw admin_main_menu_link_to( _name, { :controller => _controller_name } )
result += raw "</div></div>";
end
def admin_main_menu_fishing_button( style_name = "main_menu_admin_button" )
_name = "FISHING TOURS"
id = _name
_controller_name = { :controller => :fishing_programs }
result = raw ("<div class='" + style_name + "'>
<div id='main_menu_td_"+id+"' class='main_menu_button_element'
onmouseover='showSubMenu(\"fishing_programs\");main_menu_td_"+id+".setAttribute(\"class\",\"main_menu_button_element_mouse_over\");'
onmouseout='hideSubMenu(\"fishing_programs\");main_menu_td_"+id+".setAttribute(\"class\",\"main_menu_button_element\");'>")
result += raw admin_main_menu_link_to( _name, _controller_name )
result += raw ("<div id='fishing_programs' class='drop_down_menu'>
<div class='drop_down_menu_element'>
<ul style='margin-left:-15px;'>")
@menu_fishing_programs.each do |fp|
result += raw("<li>")
result += " [hidden] " if fp.hidden
result += raw(link_to( fp.title, [:admin,fp], :class => 'drop_down_main_menu' ) )
if (Time.now - fp.created_at < 4.month)
result += image_tag('home/new.png')
end
fp.SubFishingPrograms.all(:conditions => { :visible => true } ).each do |sp|
result += raw("<ul style='margin-left:-15px;'><li>" + link_to( sp.title, admin_sub_fishing_program_path( sp ), :class => 'drop_down_main_menu' ) + "</li></ul>")
end
result += raw("</li>")
end
result += raw("</ul></div></div></div></div>");
end
def admin_main_menu_gallery_button( style_name = "main_menu_admin_button" )
_name = "GALLERY"
id = _name
_controller_name = [:admin,@gallery_group]
result = raw("<div class='" + style_name + "'>
<div id='main_menu_td_"+_name+"' class='main_menu_button_element'
onmouseover='showSubMenu(\"gallery_groups\");main_menu_td_"+id+".setAttribute(\"class\",\"main_menu_button_element_mouse_over\");'
onmouseout='hideSubMenu(\"gallery_groups\");main_menu_td_"+id+".setAttribute(\"class\",\"main_menu_button_element\");'>")
result += raw(admin_main_menu_link_to( _name, _controller_name ))
result += raw("<div id='gallery_groups' class='drop_down_menu'>
<div class='drop_down_menu_element'>")
result += raw(render :partial => 'layouts/admin/gallery_drop_down_menu', :object => @gallery_group)
result += raw("</div></div></div></div>")
end
end
end |
class ApplicationController < ActionController::Base
before_filter :get_user_email
protect_from_forgery
private
def check_authorization
if current_user.role != "admin"
redirect_to root_path
else
end
end
def get_user_email
if user_signed_in?
@users_email = current_user.email
end
end
end
|
shared_examples 'Direct Message Collection' do
include_context 'Page'
let (:username) { nil }
before :each do
target_page.load
end
it 'shows a list of direct messages' do
expect(target_page.dms.length).to be > 0
end
end
|
class WorkingGroupsController < ApplicationController
include GroupsHelper
include GroupMethods
skip_filter :login_required, :only => [:index]
def index
@working_group = true
@visibility_threshold = is_admin? ? -1 : 0
@groups = Group.find(:all, :conditions => ['location IS NULL AND visibility > ? AND requires_approval_to_join = true', @visibility_threshold]).paginate(:page => @page, :per_page => @per_page)
@results = @groups
respond_to do |format|
format.html { render :template => 'groups/index'}
format.xml { render :xml => @groups }
end
end
end
|
class User < ApplicationRecord
has_many :comments, dependent: :destroy
has_many :doctors, through: :comments
has_secure_password
validates_presence_of :username
validates_uniqueness_of :username, :case_sensitive => false
end
|
namespace :clean do
desc "Removes the compilation command files"
task :breadcrumbs do
if $configuration
rm_rf(FileList[*$configuration.source_directories.pathmap('%p/**/*.{compile,assemble}')],:verbose=>false)
end
end
end |
class AddForeignKeysSkills < ActiveRecord::Migration[5.1]
def change
add_column :skills, :service_id, :integer
add_column :skills, :worker_id, :integer
add_foreign_key :skills, :services
add_foreign_key :skills, :workers
add_index :skills, :service_id
add_index :skills, :worker_id
end
end
|
require 'test_helper'
class AdminControllerTest < ActionController::TestCase
setup do
sign_in users(:josh)
end
test "can request a MAL scrape" do
fake_request({
[:get, "http://myanimelist.net/anime/11757/"] => "mal_anime_11757_metadata",
[:get, %r|http://cdn.myanimelist.net/images/.*|] => "blank_png"
})
Sidekiq::Testing.fake! do
get :find_or_create_by_mal, mal_id: 11757, media: 'anime'
end
assert_instance_of Anime, assigns(:thing)
assert_redirected_to assigns(:thing)
end
test "is invisible when not an admin" do
sign_in users(:vikhyat)
assert_raise ActionController::RoutingError do
get :index
end
end
test "can see stats" do
get :stats, format: :json
assert_response :success
assert_includes JSON.parse(@response.body), "registrations"
end
end
|
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :restaurant do
vendor
name "first_restaurant"
description "restaurant_description"
phone "555-666-1234"
email {"#{name}.@example.com"}
address "Sunnyvale"
rating 1
image {
fixture_file_upload(
Rails.root.join(
"spec",
"images",
"default.jpg"
),
"image/jpg"
)
}
end
end
|
# update.rb
require 'sinatra/base'
require 'ipaddr'
require 'r53dyn/aws'
module R53Dyn
module Routes
class Update < Sinatra::Base
def initialize(app = nil, dnslib = R53Dyn::Aws.new)
super(app)
@dnslib = dnslib
end
def checkAuthentication(password, username)
if username.nil? || password.nil?
error 401, 'Authentication failed'
else
if ENV['R53DYN_USER'] != username || ENV['R53DYN_PASS'] != password
error 401, 'Authentication failed'
end
end
end
def checkHostname(domain, ipaddr)
begin
IPAddr.new ipaddr
rescue
error 500, 'Invalid IP address'
end
if (split = domain.split('.')).length == 3
domainparts = split[1, 2].join('.') + '.'
else
error 500, 'Domain must include a hostname'
end
domainparts
end
get '/update' do
domain = params[:domain] || nil
ipaddr = params[:ip] || nil
username = params[:user] || nil
password = params[:pass] || nil
if domain.nil? || ipaddr.nil?
error 500, 'Invalid parameters provided'
end
self.checkAuthentication(password, username)
# check domain and ip value
# domain must be a valid domain, better hostname validation required
domainparts = self.checkHostname(domain, ipaddr)
# Scan hosted zones for our domain
zoneid = @dnslib.get_zoneid(domainparts)
# Found the correct zone, update the ip record
if zoneid != nil
# Prepare the change record
resp_data = @dnslib.update_record(zoneid, domain, ipaddr)
if resp_data
"good %s\n" % ipaddr
else
error 500, 'Updating hostname failed'
end
else
error 500, 'Updating hostname failed'
end
end
end
end
end |
#!/usr/bin/env ruby
# If we have particular metadata, prepend it to a
# paragraph at the start of the document;
# as Word/ODT templates cannot handle this natively
#
# VERSION: 1.0.2
require 'paru/filter'
# here is our list of metadata to convert
prepend_list = {
:comments => "Comments",
:wordcount => "Wordcount",
:conflicts => "Conflict of interest statement",
:acknowledgements => "Acknowledgements",
:contributions => "Author contributions",
:institute => "Affiliations",
:keywords => "Keywords"
}
Paru::Filter.run do
prepend_list.each do |key,val|
next unless metadata.key?(key.to_s)
text = ''
kw = metadata[key.to_s]
if kw.is_a?(String)
text += kw
elsif kw.is_a?(Array)
kw.each do |x|
if x.is_a?(Hash)
text += '^' + x.keys[0].to_s + '^ ' + x.values[0].to_s + '; '
else
text += x.to_s + '; '
end
end
text = text[0..-3]
else
text = ''
end
next if text.empty?
text = '**' + val + '**: ' + text
p = Paru::PandocFilter::Para.new([])
p.inner_markdown = text
document.prepend(p)
end
stop!
end |
class ReminderAllMailer < Mailer
helper :reminder_all
def reminder_all(user, assigned_issues, days)
recipients = user.mail
issues_count = (assigned_issues).uniq.size
plural_subject_term = case issues_count
when 1 then
:mail_subject_reminder_all1
else
:mail_subject_reminder_all2
end
subject = l(plural_subject_term, :count => issues_count, :days => days)
@assigned_issues = assigned_issues
@days = days
@issues_url = url_for(:controller => 'issues', :action => 'index',
:set_filter => 1, :assigned_to_id => user.id,
:sort_key => 'due_date', :sort_order => 'asc')
mail :to => recipients, :subject => subject
end
def reminder_closed(user, assigned_issues)
recipients = user.mail
issues_count = (assigned_issues).uniq.size
if issues_count == 1
subject = l(:mail_subject_reminder_closed1, :count => issues_count)
else
subject = l(:mail_subject_reminder_closed2, :count => issues_count)
end
@assigned_issues = assigned_issues
@days = 30
@issues_url = url_for(:controller => 'issues', :action => 'index',
:set_filter => 1, :assigned_to_id => user.id,
:sort_key => 'due_date', :sort_order => 'asc')
mail :to => recipients, :subject => subject
end
def reminder_inactive(user,assigned_issues)
recipients = user.mail
issues_count = (assigned_issues).uniq.size
if issues_count == 1
subject = l(:mail_subject_reminder_inactive1, :count => issues_count)
else
subject = l(:mail_subject_reminder_inactive2, :count => issues_count)
end
@assigned_issues = assigned_issues
@days = 30
@issues_url = url_for(:controller => 'issues', :action => 'index',
:set_filter => 1, :assigned_to_id => user.id,
:sort_key => 'due_date', :sort_order => 'asc')
mail :to => recipients, :subject => subject
end
def self.deliver_reminder_all_if_any(user, assigned_issues, days)
issues_count = (assigned_issues).uniq.size
reminder_all(user, assigned_issues, days).deliver if issues_count > 0
end
def self.deliver_reminder_closed(user, assigned_issues)
issues_count = (assigned_issues).uniq.size
reminder_closed(user, assigned_issues).deliver if issues_count > 0
end
def self.deliver_reminder_inactive(user,assigned_issues)
issues_count = (assigned_issues).uniq.size
reminder_inactive(user,assigned_issues).deliver if issues_count > 0
end
end
|
require 'timeout'
require 'json'
class SnapDeploy::Provider::AWS::OpsWorks < Clamp::Command
option '--app-id', "APP_ID", "The application ID", :required => true
option '--instance-ids', "INSTANCE_IDS", "The instance IDs to deploy to", :multivalued => true
option '--[no-]wait', :flag, 'Wait until (or not) deployed and return the deployment status.', :default => true
option '--[no-]migrate', :flag, 'If the db should be automatically migrated.', :default => true
include SnapDeploy::CLI::DefaultOptions
include SnapDeploy::Helpers
def execute
require 'aws-sdk'
Timeout::timeout(600) do
create_deployment
end
rescue ::Timeout::Error
error 'Timeout: Could not finish deployment in 10 minutes.'
end
private
def create_deployment
data = client.create_deployment(
{
stack_id: ops_works_app[:stack_id],
command: {name: 'deploy'},
comment: deploy_comment,
custom_json: custom_json.to_json
}.merge(deploy_target)
)
info "Deployment created: #{data[:deployment_id]}"
return unless wait?
print "Deploying "
deployment = wait_until_deployed(data[:deployment_id])
print "\n"
if deployment[:status] == 'successful'
info "Deployment successful."
else
error "Deployment failed."
raise "Deployment failed."
end
end
def deploy_target
target = {app_id: app_id}
target[:instance_ids] = instance_ids_list if instance_ids_list && !instance_ids_list.empty?
return target
end
def custom_json
{
deploy: {
ops_works_app[:shortname] => {
migrate: !!migrate?,
scm: {
revision: snap_commit
}
}
}
}
end
def wait_until_deployed(deployment_id)
deployment = nil
loop do
result = client.describe_deployments(deployment_ids: [deployment_id])
deployment = result[:deployments].first
break unless deployment[:status] == "running"
print "."
sleep 5
end
deployment
end
def ops_works_app
@ops_works_app ||= fetch_ops_works_app
end
def fetch_ops_works_app
data = client.describe_apps(app_ids: [app_id])
unless data[:apps] && data[:apps].count == 1
raise "App #{app_id} not found."
end
data[:apps].first
end
def client
@client ||= begin
AWS.config(access_key_id: access_key_id, secret_access_key: secret_access_key, logger: logger, log_formatter: AWS::Core::LogFormatter.colored)
info "Logging in using Access Key ending with : #{access_key_id[-4..-1]}"
AWS::OpsWorks.new.client
end
end
end
|
#!/usr/bin/env ruby
require_relative '../lib/environment'
Environment.new do |e|
e.assert [:in, :box, :hall]
e.rule(:move) do |r|
r.conditions [:in, :@object, :hall]
r.activations do
e.retract [:in, @object, :hall]
e.assert [:in, @object, :garage]
end
end
p e.facts #>> [[:in, :box, :hall]]
e.step #>> "Firing rule MOVE with bindings {:@object=>:box}"
p e.facts #>> [[:in, :box, :garage]]
end
|
class RemoveUserFromComments < ActiveRecord::Migration
def up
remove_column :comments, :userid
end
def down
add_column :comments, :userid, :integer
end
end
|
Capistrano::Configuration.instance.load do
set_default( :rake_cmd ){ "#{bundle_cmd} exec rake"}
set_default( :rake_task ){ ENV['task'] }
namespace :rake do
desc "Runs a rake task on all rake servers."
task :default, roles: :rake, except: { no_release: true } do
run "cd '#{current_path}' && #{rake_cmd} #{rake_task} RAILS_ENV=#{rails_env}"
end
desc "Runs a rake task on one server."
task :one, roles: :rake, except: { no_release: true } do
host = find_servers_for_task(current_task).first
run "cd '#{current_path}' && #{rake_cmd} RAILS_ENV=#{rails_env}", hosts: host
end
end
end |
class TilesController < ApplicationController
layout 'boxed'
before_filter :select_tile, :only => [:show,:edit,:update,:destroy]
def show
redirect_to @tile.page,:anchor =>TilesHelper.coordinate_id(@tile.x,@tile.y)
end
def new
@tile = Tile.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @tile }
end
end
def edit
Tile.find(:all,:conditions=>{:image_file_name=>nil })
end
def create
@tile = Tile.new(params[:tile])
@tile.user = current_user
respond_to do |format|
if @tile.can_be_created?(current_user) && @tile.save
format.html { redirect_to :back }
else
fail
end
end
end
def update
case @tile.classify
when :reserved
if params[:tile][:image] #upload
ok=@tile.can_be_uploaded?(current_user)
fail User::PermissionDenied unless ok
@tile.image = params[:tile][:image]
@tile.activated=@tile.can_be_activated?(current_user) #activate automatically if possible
if @tile.save
redirect_to :action=>:show
else
@tile.image=nil if @tile.errors.on(:image)
render :file=>'tiles/edit',:id=>@tile.id,:layout=>'boxed'
end
end
when :uploaded,:activated
if params[:tile][:activated] #aktivieren/deaktivieren
ok=@tile.can_be_activated?(current_user)
fail User::PermissionDenied unless ok
@tile.activated=params[:tile][:activated]
@tile.save!
end
end
end
def destroy
fail User::PermissionDenied unless @tile.can_be_deleted?(current_user)
@page=@tile.page
@tile.destroy
redirect_to edit_page_path(@page)
end
private
def select_tile
@tile = Tile.find(params[:id])
end
end
|
# encoding: utf-8
describe Faceter::Functions, ".clean" do
let(:arguments) { [:clean, Selector.new(options)] }
let(:input) { { foo: { foo: :FOO }, bar: {}, baz: {}, qux: :QUX } }
it_behaves_like :transforming_immutable_data do
let(:options) { {} }
let(:output) { { foo: { foo: :FOO }, qux: :QUX } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: [:foo, :bar] } }
let(:output) { { foo: { foo: :FOO }, baz: {}, qux: :QUX } }
end
end # describe Faceter::Functions.clean
|
class ApiController < ApplicationController
before_filter :require_api_login
def photo_path
"/Users/devian/Projects/drewaltizer/photos"
end
def info
ext({
:success => true
})
end
end |
require 'spec_helper'
describe "profiles/edit" do
fixtures :all
before(:each) do
@profile = assign(:profile, profiles(:admin))
assign(:user_groups, UserGroup.all)
assign(:libraries, Library.all)
assign(:roles, Role.all)
assign(:available_languages, Language.available_languages)
view.stub(:current_user).and_return(User.friendly.find('enjuadmin'))
end
describe "when logged in as librarian" do
before(:each) do
@profile = assign(:profile, profiles(:librarian2))
user = users(:librarian1)
view.stub(:current_user).and_return(user)
end
it "renders the edit user form" do
allow(view).to receive(:policy).and_return double(destroy?: true)
render
assert_select "form", action: profiles_path(@profile), method: "post" do
assert_select "input#profile_user_number", name: "profile[user_number]"
end
end
it "should not display 'delete' link" do
allow(view).to receive(:policy).and_return double(destroy?: false)
render
expect(rendered).not_to have_selector("a[href='#{profile_path(@profile.id)}'][data-method='delete']")
end
it "should disable role selection" do
allow(view).to receive(:policy).and_return double(destroy?: true)
render
expect(rendered).to have_selector("select#profile_user_attributes_user_has_role_attributes_role_id[disabled='disabled']")
end
end
end
|
require 'spec_helper'
RSpec.describe Invitation::InviteEmails do
describe 'custom mailer' do
let(:mail) { double('Mail') }
let(:test_mailer) { double('InviteMailer') }
subject { described_class.new(invites, mailer: test_mailer).send_invites }
let(:invites) { [create(:invite, :recipient_is_existing_user)] }
it 'sends email through the given mailer' do
allow(mail).to receive(:deliver).once
expect(test_mailer).to receive(:existing_user).once.and_return(mail)
subject
end
end
end
|
# A Detail represents a piece of data associated with this User that is
# not represented in any other property or association of the User resource.
#
# This data is presented as key-value pairs.
#
# [UUID] Detail resources are wholly encapsulated within a User resource and
# do not have an exposed UUID
#
#
# [URI] Detail resources are wholly encapsulated within a User resource and
# are not directly addressable (except from within the User resource).
#
# <tt>/resources/users/{user-uuid}/details</tt>
class Restful::User::Detail < Restful::Resource::Base
self.model = ::UserDetail
finder :find, :all, :first, :last
helper ApplicationHelper
##
# :method: Version(1)
#
#
# ==== Examples
#
# JSON:
#
# {
# "key":"rewards_number",
# "value":"1234567890"
# }
#
#
# XML:
#
# <user-detail>
# <key>rewards_number</key>
# <value>1234567890</value>
# </user-detail>
version 1
##
# The key for this Detail.
#
# Return Type:: String
# Protected?:: Yes
attribute :key, :private => true
##
# The value for this Detail.
#
# Return Type:: String
# Protected?:: Yes
attribute :value, :private => true
end
|
# You are given an array of non-negative integers that represents a
# two-dimensional elevation map where each element is unit-width wall and the
# integer is the height. Suppose it will rain and all spots between two walls
# get filled up.
# Compute how many units of water remain trapped on the map in O(N) time and
# O(1) space.
# For example, given the input [2, 1, 2], we can hold 1 unit of water in the
# middle.
# Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index,
# 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would
# run off to the left), so we can trap 8 units of water.
require 'rspec/autorun'
def volume(arr)
volume = 0
left = 0
right = arr.count - 1
max_height_l = arr[left]
max_height_r = arr[right]
while left <= right
if max_height_l <= max_height_r
if arr[left] < max_height_l
volume += max_height_l - arr[left]
else
max_height_l = arr[left]
end
left += 1
else
if arr[right] < max_height_r
volume += max_height_r - arr[right]
else
max_height_r = arr[right]
end
r -= 1
end
end
volume
end
RSpec.describe 'Function' do
it 'returns correct volume given array of heights' do
expect(volume([3, 0, 1, 3, 0, 5])).to eq(8)
end
end |
class AssociationRenderer < ResourceRenderer::AttributeRenderer::Base
def display(attribute_name, label, options = {}, &block)
options.reverse_merge!(label_method: :to_s)
label_method = options.delete(:label_method)
associated = value_for_attribute(attribute_name)
return if associated.nil?
url = options.delete(:url)
label = associated.send(label_method)
target = url.call(model) if url.is_a?(Proc)
target = url if url.is_a?(String)
target = associated if url.is_a?(TrueClass)
if target.nil?
label
else
h.link_to(label, target)
end
end
end |
Rails.application.routes.draw do
get '/auth/twitter/callback', to: 'sessions#create'
get '/auth/spotify/callback', to: 'sessions#spotify'
delete 'sign_out', to: 'sessions#destroy', as: 'sign_out'
root to: 'pages#index'
get 'index' => 'pages#index'
get 'list' => 'pages#list'
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
require "yaml"
# Load vagrant-puppet-django config
current_dir = File.dirname(File.expand_path(__FILE__))
config_file = YAML.load_file("#{current_dir}/config.yaml")
working_path="/home/#{config_file['user']}"
manifests_path="#{working_path}/manifests"
code_path="#{working_path}/code"
logs_path="#{working_path}/logs"
virtualenvs_path="#{working_path}/virtualenvs"
requirements_path= "#{code_path}/#{config_file['project']}/#{config_file['requirements_path']}"
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/wily32"
config.vm.provider "virtualbox" do |vb|
vb.memory = "1024"
end
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.synced_folder "puppet/manifests/files", "#{manifests_path}"
config.vm.synced_folder "code", "#{code_path}"
config.vm.provision "puppet" do |puppet|
puppet.manifests_path = "puppet/manifests"
puppet.module_path = "puppet/modules"
puppet.manifest_file = "site.pp"
puppet.hiera_config_path = "puppet/hiera.yaml"
puppet.facter = {
"tz" => config_file["tz"],
"user" => config_file["user"],
"password" => config_file["password"],
"manifests_path" => "#{manifests_path}",
"code_path" => "#{code_path}",
"logs_path" => "#{logs_path}",
"virtualenvs_path" => "#{working_path}/virtualenvs",
"public_html_path" => "#{working_path}/public_html",
"requirements_path" => "#{requirements_path}",
"project" => config_file["project"],
"domain_name" => config_file["domain_name"],
"db_name" => config_file["db_name"],
"db_user" => config_file["db_user"],
"db_password" => config_file["db_password"],
}
end
end
|
module WiredUp
class TextGraph
attr_reader :lines
TextGraphNode = Struct.new :x, :y, :value
def initialize(lines)
@lines = lines
end
def [](x,y)
return nil unless in_bounds?(x, y)
lines[y][x]
end
def find_root
lines.each_with_index do |line, i|
if x = line.index('@')
return TextGraphNode.new x, i, '@'
end
end
nil
end
def in_bounds?(x, y)
(0...lines.length).include?(y) && (0...lines[y].length).include?(x)
end
def find_left_node(x, y)
turn = scan_left(x, y)
scan_down(turn.x, turn.y) unless turn.nil?
end
def find_right_node(x, y)
turn = scan_right(x, y)
scan_down(turn.x, turn.y) unless turn.nil?
end
def find_direct_node(x, y)
(x-1).downto(0) do |x|
return TextGraphNode.new x, y, self[x, y] if self[x, y] != '-'
end
nil
end
def direct_path?(x, y)
self[x-1, y] == '-'
end
def left_path?(x, y)
self[x, y+1] == '|'
end
def right_path?(x, y)
self[x, y-1] == '|'
end
private
def scan_left(x, y)
scan_across x, y, 1
end
def scan_right(x, y)
scan_across x, y, -1
end
def scan_across(x, y, dir)
while self[x, y + dir] == '|'
y += dir
end
TextGraphNode.new x, y, self[x, y]
end
def scan_down(x, y)
while self[x - 1, y] == '-'
x -= 1
end
TextGraphNode.new x - 1, y, self[x - 1, y]
end
end
end |
class GuideVisitor < ActiveRecord::Base
attr_accessible :guide_id, :year, :visit, :passengers, :active
belongs_to :guide
validates_presence_of :guide_id
end
|
# Copyright (c) 2016 Ricoh Company, Ltd. All Rights Reserved.
# See LICENSE for more information
module Concerns
module Authentication
extend ActiveSupport::Concern
class AuthenticationRequired < StandardError; end
class AnonymousAccessRequired < StandardError; end
included do
before_filter :optional_authentication
helper_method :current_account, :authenticated?
rescue_from AuthenticationRequired, with: :authentication_required!
rescue_from AnonymousAccessRequired, with: :anonymous_access_required!
end
def current_account
@current_account
end
def authenticated?
!current_account.blank?
end
def authentication_required!(e)
redirect_to root_url, flash: {
warning: e.message
}
end
def anonymous_access_required!(e)
redirect_to images_url
end
def optional_authentication
if session[:current_account]
authenticate Account.find_by_id(session[:current_account])
end
rescue ActiveRecord::RecordNotFound
unauthenticate!
end
def require_authentication
unless authenticated?
session[:after_logged_in_endpoint] = request.url if request.get?
raise AuthenticationRequired.new
end
end
def require_anonymous_access
raise AnonymousAccessRequired.new if authenticated?
end
def authenticate(account)
if account
@current_account = account
session[:current_account] = account.id
end
end
def unauthenticate!
@current_account = session[:current_account] = nil
end
end
end |
ActiveAdmin.register User do
index do
column :username
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
column :role
actions
end
filter :username
form do |f|
f.inputs "User Details" do
f.input :username
f.input :role, as: :radio,collection: {Member: "member",Admin: "admin"}
end
f.actions
end
# See permitted parameters documentation:
# https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
permit_params :role, :username, :email, :password, :firstname, :lastname
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if resource.something?
# permitted
# end
end
|
# Event Range Table Structure
require 'dm-core'
class EventRange
include DataMapper::Resource
property :erid, Serial
property :month, Integer
property :year, Integer
property :per_user, Integer
property :active, Integer
end
|
class EditSerializer < ActiveModel::Serializer
attributes :id, :project_id, :text, :created_at
end
|
# Install command-line tools using Homebrew
# Credit: https://github.com/mathiasbynens/dotfiles
# Usage: `brew bundle Brewfile`
# fix any issues
doctor
tap --repair
# Make sure weβre using the latest Homebrew
update
# Upgrade any already-installed formulae
upgrade
# Install GNU core utilities (those that come with OS X are outdated)
# Donβt forget to add `$(brew --prefix coreutils)/libexec/gnubin` to `$PATH`.
install coreutils
# Install some other useful utilities like `sponge`
install moreutils
# Install GNU `find`, `locate`, `updatedb`, and `xargs`, `g`-prefixed
install findutils
install luajit
# Install GNU `sed`, overwriting the built-in `sed`
install gnu-sed --default-names
# Install Bash 4
# Note: donβt forget to add `/usr/local/bin/bash` to `/etc/shells` before running `chsh`.
install bash
install bash-completion
# Install wget with IRI support
install wget --enable-iri
# Install more recent versions of some OS X tools
install vim --with-lua
install macvim --with-cscope --with-lua --custom-icons --with-luajit --override-system-vim
install homebrew/dupes/grep
install homebrew/php/php55 --with-gmp
# Install other useful binaries
install lua
install ack
install ag
install coreutils
install fasd
install findutils
install git
install hub
install git-extras
install htop-osx
install hub
install id3tool
install imagemagick --with-webp
install lesspipe
install lua
install macvim --with-cscope --with-lua --override-system-vim
install man2html
install maven
install mongo
install nmap
install node
install pv
install python
install rename
install ruby
install sl
install tmux
install tree
install webkit2png
install jmeter
install md5sha1sum
install redis
tap caskroom/cask
install brew-cask
linkapps
# Remove outdated versions from the cellar
cleanup
|
require_relative 'todo'
require_relative 'subject_not_allowed_error'
require 'test/unit'
require "delegate"
class TestTodo < Test::Unit::TestCase
def test_new_todo_state_and_subject
t = Todo.new("test")
assert_equal("test", t.subject)
assert_equal(:open, t.state)
end
def test_state_after_close
t = Todo.new("test")
t.close
assert_equal(:closed, t.state)
end
def test_state_after_reopen
t = Todo.new("test")
t.close
t.open
assert_equal(:open, t.state)
end
def test_equals
t1 = Todo.new("test")
t2 = Todo.new("test")
assert_equal(true, t1 == t2)
end
def test_less
t1 = Todo.new("test1")
t2 = Todo.new("test2")
assert_equal(true, t1 < t2)
end
def test_constructor_accept_only_correct_subject
assert_nothing_raised {Todo.new("<test")}
assert_nothing_raised {Todo.new("test>")}
assert_nothing_raised {Todo.new("te<st")}
assert_raise(SubjectNotAllowedError) {Todo.new("<test>")}
assert_raise(SubjectNotAllowedError) {Todo.new("<test \nsecond line>")}
end
end |
module GluttonRatelimit
class AveragedThrottle < ParentLimiter
def initialize executions, time_period
super(executions, time_period)
@tokens = nil
end
def reset_bucket
@before_previous_execution ||= Time.now
@oldest_timestamp = Time.now
@tokens = @executions
@total_task_time = 0
end
def executed_this_period
@executions - @tokens
end
def average_task_time
@total_task_time.to_f / executed_this_period
end
def wait
reset_bucket if @tokens.nil?
now = Time.now
delta_since_previous = now - @before_previous_execution
@total_task_time += delta_since_previous
remaining_time = @time_period - (now - @oldest_timestamp)
if @tokens.zero?
sleep(remaining_time) if remaining_time > 0
reset_bucket
elsif executed_this_period != 0
throttle = (remaining_time.to_f + delta_since_previous) / (@tokens+1) - average_task_time
sleep throttle if throttle > 0
end
@tokens -= 1
@before_previous_execution = Time.now
end
end
end
|
# == Schema Information
#
# Table name: translations
#
# id :integer not null, primary key
# translation :string
# i18n_key_id :integer
# locale_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Translation < ActiveRecord::Base
belongs_to :i18n_key
has_one :locale
end
|
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'json'
require 'pp'
class ShortURL
def self.expand(short_url)
# http://longurl.org/api
connection = Net::HTTP.new('api.longurl.org')
connection.start do |http|
headers = {
'Referer' => '',
'User-Agent' => ''
}
path = "/v2/expand?url=#{URI.encode(short_url)}&format=json"
response = http.request_get(path, headers)
data = JSON.parse(response.body)
if data['messages']
raise data['messages'][0]['message']
end
data['long-url']
end
end
end
redirect = "https://raw.githubusercontent.com/bjornrun/dotfiles-3/master/etc/install".split("/")
shorten = ShortURL.expand('http://dot.bjornrun.com').split("/")
exit(1) unless redirect[3..-1].join("/") == shorten[3..-1].join("/")
|
class CreateCustomers < ActiveRecord::Migration[6.0]
def change
create_table :customers do |t|
t.string :customer_no
t.string :customer_id
t.string :customer_type_id
t.string :country_id
t.string :names
t.string :gender
t.string :email
t.string :phone
t.string :address
t.string :postal_code
t.string :customer_status
t.string :id_no
t.datetime :customer_status_date
t.datetime :last_visit
t.datetime :last_invoice
t.datetime :last_receipt
t.string :is_active, :default => "1"
t.string :created_by
t.string :updated_by
t.timestamps
end
end
end
|
# == Schema Information
#
# Table name: user_answers
#
# id :integer not null, primary key
# answer_id :integer
# user_exam_id :integer
# correct :boolean
# created_at :datetime
# updated_at :datetime
# text :string(255)
# question_id :integer
#
require 'rails_helper'
RSpec.describe UserAnswer, :type => :model do
describe 'validation' do
subject { UserAnswer.new(user_exam_id: 1) }
it { is_expected.to validate_presence_of :user_exam }
it { is_expected.to validate_presence_of :question }
describe '#open_user_exam' do
before do
FactoryGirl.create :course
FactoryGirl.create :lesson_category
FactoryGirl.create :exam
FactoryGirl.create :user
FactoryGirl.create :user_exam
end
before do
@u_a = FactoryGirl.build :user_answer
allow(@u_a).to receive(:question) { FactoryGirl.build :question }
end
context "exam is open" do
it "is valid" do
expect(@u_a).to be_valid
end
end
context "exam is closed" do
before do
UserExam.first.update_attribute(:closed, true)
end
it "is invalid" do
expect(@u_a).to be_invalid
end
end
end
end
describe '#check_if_correct' do
context 'open' do
before do
FactoryGirl.create :course
FactoryGirl.create :lesson_category
FactoryGirl.create :exam
FactoryGirl.create :question_category
FactoryGirl.create :question, form: 2
FactoryGirl.create :user
FactoryGirl.create :user_exam
end
context 'answer exists' do
before do
Answer.create name: "TaK", question_id: 1
end
it 'is correct' do
u_a = UserAnswer.create!(user_exam_id: 1, text: "tAK", question_id: 1)
expect(u_a.correct).to eq true
end
end
context 'answer does not exist' do
before do
Answer.create name: "nie", question_id: 1
end
it 'is incorrect' do
u_a = UserAnswer.create!(user_exam_id: 1, text: "tAK", question_id: 1)
expect(u_a.correct).to eq false
end
end
end
context 'multiple or single' do
before do
FactoryGirl.create :course
FactoryGirl.create :lesson_category
FactoryGirl.create :exam
FactoryGirl.create :question_category
FactoryGirl.create :question, form: 0
Answer.create name: "nie", question_id: 1, correct: true
Answer.create name: "tak", question_id: 1, correct: false
FactoryGirl.create :user
FactoryGirl.create :user_exam
end
context 'answer is correct' do
it 'is correct' do
u_a = UserAnswer.create!(user_exam_id: 1, answer_id: 1, question_id: 1)
expect(u_a.correct).to eq true
end
end
context 'answer is incorrect' do
it 'is incorrect' do
u_a = UserAnswer.create!(user_exam_id: 1, answer_id: 2, question_id: 1)
expect(u_a.correct).to eq false
end
end
end
end
end
|
require 'serverspec'
set :backend, :exec
describe file('/opt/mongodb/2.4.5/bin/mongod') do
it { should be_file }
it { should be_executable }
end
describe file('/usr/local/bin/mongod') do
it { should be_linked_to('/opt/mongodb/2.4.5/bin/mongod') }
end
describe service('mongod-instance1') do
it { should be_running }
end
describe port(27017) do
it { should be_listening }
end
%w{ mongod.lock local.ns }.each do |mongofile|
describe file("/opt/mongodb/instance1/data/#{mongofile}") do
it { should be_file }
end
end
describe service('mongod-instance2') do
it { should be_running }
end
describe port(37017) do
it { should be_listening }
end
describe file('/etc/sv/mongod-instance2/run') do
its(:content) { should match /^# This service template originates from the test cookbook$/ }
end
%w{ mongod.lock local.ns }.each do |mongofile|
describe file("/opt/mongodb/instance2/data/#{mongofile}") do
it { should be_file }
end
end
describe file('/opt/mongodb/2.4.5/config/mongod-instance2.conf') do
its(:content) { should match /^nojournal = true$/ }
its(:content) { should match /^noprealloc = true$/ }
its(:content) { should match /^smallfiles = true$/ }
end
|
# frozen_string_literal: true
module SC::Billing::Stripe::Webhooks::Charges
class FailedOperation < SC::Billing::Stripe::Webhooks::Charges::SucceededOperation
set_event_type 'charge.failed'
end
end
|
require 'rails_helper'
RSpec.describe "Journals", type: :request do
describe 'GET #index' do
let(:user) { create(:user) }
let(:teacher) { create(:teacher) }
let(:parent) { create(:parent) }
let!(:student) { create(:student, grade: grade) }
let!(:grade) { create(:grade) }
before :each do
sign_in current_user
get journals_path
end
context 'with logged-in teacher' do
let(:current_user) { teacher.user }
it 'show status success' do
expect(response).to have_http_status(:success)
end
it 'show list of classes' do
expect(response).to render_template("journals/list_of_grades", "layouts/application")
end
end
context 'with logged-in parent' do
let(:current_user) { parent.user }
it 'status success' do
expect(response).to have_http_status(:success)
end
it 'show list of parents students' do
expect(response).to render_template("journals/list_of_students", "layouts/application")
end
end
context 'with logged-in student' do
let(:current_user) { student.user }
it 'status 302' do
expect(response).to have_http_status(302)
end
it 'redirects to show page' do
expect(response).to redirect_to(journal_path(id: student.grade.id))
end
end
context "with not logged-in user" do
let(:current_user) { 'not_user' }
it 'status 302' do
expect(response).to have_http_status(302)
end
it 'redirects to show page' do
expect(response).to redirect_to(new_user_session_path)
end
end
end
describe 'GET #show' do
let(:user) { create(:user) }
let(:teacher) { create(:teacher) }
let(:parent) { create(:parent) }
let!(:student) { create(:student, grade: grade) }
let!(:grade) { create(:grade) }
let!(:lessons) { create_list(:lesson, 3, grade_id: grade.id) }
before :each do
sign_in current_user
get journal_path(id: grade.id)
end
context 'with logged-in teacher' do
let(:current_user) { teacher.user }
it 'show status success' do
expect(response).to have_http_status(:success)
end
it 'render template show' do
expect(response).to render_template("journals/show")
end
it 'render the list of lessons for teacher' do
expect(assigns(:lessons)).to eq(lessons)
end
end
context 'with logged-in parent' do
let(:current_user) { parent.user }
it 'status success' do
expect(response).to have_http_status(:success)
end
it 'show list of parents students' do
expect(response).to render_template("journals/show")
end
it 'render the list of lessons for parents' do
expect(assigns(:lessons)).to eq(lessons)
end
end
context 'with logged-in student' do
let(:current_user) { student.user }
it 'status success' do
expect(response).to have_http_status(:success)
end
it 'redirects to show page' do
expect(response).to render_template("journals/show")
end
it 'render the list of lessons for students' do
expect(assigns(:lessons)).to eq(lessons)
end
end
context "with not logged-in user" do
let(:current_user) { 'not_user' }
it 'status 302' do
expect(response).to have_http_status(302)
end
it 'redirects to show page' do
expect(response).to redirect_to(new_user_session_path)
end
end
end
end
|
class MapSerializer < ActiveModel::Serializer
attributes :id, :name, :url, :tier, :map_type, :votes, :created_at, :updated_at
end
|
class AdminMailer < ActionMailer::Base
# Use application_mail.html.erb
layout 'application_mailer'
# Automatically inject css styles
include Roadie::Rails::Automatic
# default from: "from@example.com"
end
|
# frozen_string_literal: true
module Riskified
module Entities
class KeywordStruct < Struct
def initialize(**kwargs)
super(kwargs.keys)
kwargs.each {|k, v| self[k] = v}
end
end
end
end
|
module ImageHelper
def avatar(user)
if user.image.present?
user.image_url(:thumb).to_s
else
default_url = "#{root_url}assets/guest.png"
gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
"https://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
end
end
end |
class Offer < Offer.superclass
module Cell
# returns a nice English sentence that describes how one can earn the
# offer's bonus.
#
# @!method self.call(offer, options = {})
class Description < Abroaders::Cell::Base
property :condition
property :currency
property :currency_name
property :days
property :points_awarded
property :spend
def show
# technically it doesn't make sense for an offer to be anything other
# than 'no_bonus' if the product as no currency... but we don't enforce
# this, so make sure it's handled gracefully.
return '' if currency.nil?
case condition
when 'on_minimum_spend'
"Spend #{spend} within #{days} days to receive a bonus of "\
"#{points_awarded} #{currency_name} points"
when 'on_approval'
"#{points_awarded} #{currency_name} points awarded upon a successful application for this card."
when 'on_first_purchase'
"#{points_awarded} #{currency_name} points awarded upon making your first purchase using this card."
when 'no_bonus'
''
else raise 'this should never happen'
end
end
private
def points_awarded
number_with_delimiter(super)
end
def spend
number_to_currency(super)
end
end
end
end
|
require "rspec/autorun"
class Calc
def add(a,b)
a + b
end
def factorial(a)
if a == 0
return 1
else
a * factorial(a - 1)
end
end
end
describe Calc do
describe "#add" do
it "Adds two numbers" do
calculator = Calc.new
expect(calculator.add(1,1)).to eq(2)
end
end
describe '#factorial' do
it "It calculates the factorial of provided integer" do
fact = Calc.new
expect(fact.factorial(3)).to eq(6)
end
end
end |
# encoding: UTF-8
module ProjectsHelper
def get_proportion_of_project_and_report_duration_in_percent(project)
sum_report_duration = sum_of_duration(project.reports_worked)
percent = ((sum_report_duration / project.timebudget) * 100).round
percent > 100 ? (return 100) : (return percent)
end
end
|
require "spec_helper"
describe GitP4Sync::Sync do
before(:all) { @sync = GitP4Sync::Sync.new }
describe "constructor test" do
it "tests default values" do
expect(@sync.simulate).to be false
expect(@sync.show).to be false
expect(@sync.submit).to be false
expect(@sync.ignore).to be nil
expect(@sync.git_path).to eq("./")
end
end
describe "test for path verification method" do
it "takes a filename" do
expect(@sync).to receive(:exit_with_error).with("#{File.expand_path('./sync_spec.rb')} must exist and be a directory.",false)
@sync.verify_path_exist!(File.expand_path("./sync_spec.rb"))
end
it "takes non existing path" do
expect(@sync).to receive(:exit_with_error).with("#{File.expand_path('./random')} must exist and be a directory.",false)
@sync.verify_path_exist!(File.expand_path("./random"))
end
it "takes working path" do
expect(@sync).not_to receive(:exit_with_error)
expect(@sync.verify_path_exist!(File.expand_path("./"))).to be nil
end
end
describe "test method running commands" do
it "runs simuation" do
expect(STDOUT).to receive(:puts).with(" simulation: pwd")
expect(@sync).to receive(:exit_with_error)
expect(@sync.run_cmd("pwd",true).first).to be false
end
it "runs without simuation" do
expect(STDOUT).to receive(:puts).with(" pwd")
expect(@sync).to receive(:system).and_return(true)
expect(@sync.run_cmd("pwd").first).to be true
end
end
describe "add slash method test" do
it "tests for addition of slash" do
expect(@sync.add_slash("testing")).to eq("testing/")
end
it "tests for existing slash" do
expect(@sync.add_slash("testing/")).to eq("testing/")
end
end
describe "strip leading slash" do
it "removes leading slash" do
expect(@sync.strip_leading_slash("/testing/")).to eq("testing/")
end
end
describe "tests for is_ignored?" do
after(:each) { @sync.ignore_list = [] }
it "tests with file not in ignore list" do
expect(@sync.is_ignored?("cannot_exist.what")).to be false
end
it "tests with file in ignored list" do
@sync.ignore_list << "test_file.test"
expect(@sync.is_ignored?("test_file.test")).to be true
end
end
describe "show changes" do
after(:each) { @sync.diff_files = [] }
it "has no changes" do
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Change List : \n")
@sync.show_changes
end
it "has changes to show" do
@sync.diff_files << ["test","tset"]
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Change List : \n")
expect(STDOUT).to receive(:puts).with("TEST in Git: tset")
@sync.show_changes
end
end
describe "clean up method" do
it "checks for cleanup commands with failure" do
expect(@sync).to receive(:system).with("git checkout #{@sync.current_branch} && git branch -D temp_sync_branch_#{@sync.timestamp}").and_return(false)
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Could not delete the temp branch. Please delete it manually later.")
expect(STDOUT).to receive(:puts).with("Sync process completed. Please follow the logs to trace any discrepancies.")
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
@sync.cleanup
end
it "checks for cleanup commands with success" do
expect(@sync).to receive(:system).with("git checkout #{@sync.current_branch} && git branch -D temp_sync_branch_#{@sync.timestamp}").and_return(true)
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Sync process completed. Please follow the logs to trace any discrepancies.")
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
@sync.cleanup
end
end
describe "prep_ignored_files method" do
before(:each) do
expect(File).to receive(:exist?).and_return(true)
expect(File).to receive(:read).and_return("test1\ntest2")
@sync.ignore_list = [".git"]
end
after(:each) do
@sync.ignore = nil
@sync.ignore_list = [".git"]
end
it "runs without ignore parameter" do
@sync.prepare_ignored_files
expect(@sync.ignore_list.size).to eq(3)
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?("test2")).to be true
expect(@sync.ignore_list.include?(".git")).to be true
end
it "runs with ignore parameter having one file" do
@sync.ignore = "test.test"
@sync.prepare_ignored_files
expect(@sync.ignore_list.size).to eq(4)
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?(".git")).to be true
expect(@sync.ignore_list.include?("test.test")).to be true
end
it "runs with ignore parameter having comma separated files" do
@sync.ignore = "test.test,test1.test"
@sync.prepare_ignored_files
expect(@sync.ignore_list.size).to eq(5)
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?(".git")).to be true
expect(@sync.ignore_list.include?("test.test")).to be true
expect(@sync.ignore_list.include?("test1.test")).to be true
end
it "runs with ignore parameter having colon separated files" do
@sync.ignore = "test.test:test1.test"
@sync.prepare_ignored_files
expect(@sync.ignore_list.size).to eq(5)
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?("test1")).to be true
expect(@sync.ignore_list.include?(".git")).to be true
expect(@sync.ignore_list.include?("test.test")).to be true
expect(@sync.ignore_list.include?("test1.test")).to be true
end
end
describe "run method" do
after(:each) do
@sync.show = false
@sync.simulate = false
@sync.submit = false
@sync.diff_files = []
@sync.p4_path = nil
end
it "is runs with no simulate submit show and diffs" do
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("A total of 0 change(s) !")
@sync.run
end
it "is runs with no simulate submit show and some diff" do
@sync.diff_files << "testing"
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("A total of 1 change(s) !")
@sync.run
end
it "is runs with no simulate submit and with show and some diff" do
@sync.diff_files << "testing"
@sync.show = true
expect(@sync).to receive(:show_changes)
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("A total of 1 change(s) !")
@sync.run
end
it "is runs with no submit and with show, simulate and some diff" do
@sync.diff_files << "testing"
@sync.show = true
@sync.p4_path = "./"
@sync.simulate = true
expect(@sync).to receive(:show_changes)
expect(@sync).to receive(:handle_files)
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("A total of 1 change(s) !")
expect(@sync).to receive(:`).with("git show -v -s --pretty=format:\"%s : #{Time.at(@sync.timestamp)} : SHA:%H\"").and_return("1234 test_commit")
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Submitting changes to Perforce")
expect(@sync).to receive(:run_cmd).with("p4 submit -d '1234 test_commit'",true)
@sync.run
end
it "is runs with no simulate and with show, submit and some diff" do
@sync.diff_files << "testing"
@sync.show = true
@sync.p4_path = "./"
@sync.submit = true
expect(@sync).to receive(:show_changes)
expect(@sync).to receive(:handle_files)
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("A total of 1 change(s) !")
expect(@sync).to receive(:`).with("git show -v -s --pretty=format:\"%s : #{Time.at(@sync.timestamp)} : SHA:%H\"").and_return("1234 test_commit")
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Submitting changes to Perforce")
expect(@sync).to receive(:run_cmd).with("p4 submit -d '1234 test_commit'",false)
@sync.run
end
end
describe "prepare for sync test" do
before(:each) do
expect(File).to receive(:expand_path).and_return("./", "./")
expect(@sync).to receive(:add_slash).and_return("./", "./")
expect(@sync).to receive(:`).with("git rev-parse --abbrev-ref HEAD").and_return("test_branch")
expect(@sync).to receive(:prepare_ignored_files).once
expect(@sync).to receive(:verify_path_exist!).exactly(2).times
expect(STDOUT).to receive(:puts).with(/\*\*\*\*/)
expect(STDOUT).to receive(:puts).with("Preparing for sync.\nThis will create a branch named temp_sync_branch_<timestamp> in local from the given origin branch.\nThis branch will be deleted after the sync.")
end
after(:each) do
@sync.p4_path = nil
@sync.current_branch = nil
@sync.diff_files = []
end
# TODO - FIX THIS TEST !!
# it "tests with no diff" do
# expect(@sync).to receive(:diff_dirs).with("./","./").and_return([])
# expect(STDOUT).to receive(:puts).with("Directories are identical. Nothing to do.")
# expect(@sync).to receive(:exit).with(0)
# @sync.prepare_for_sync
# end
it "tests with unknown change type" do
expect(@sync).to receive(:diff_dirs).with("./","./").and_return([[:test,"test"]])
expect(@sync).to receive(:exit_with_error).with("Unknown change type present. Task aborted !")
expect(@sync).to receive(:system).and_return(true)
@sync.prepare_for_sync
end
it "tests with git checkout issues" do
expect(@sync).to receive(:diff_dirs).with("./","./").and_return([[:new,"test"]])
expect(@sync).to receive(:system).and_return(false)
expect(@sync).to receive(:exit_with_error).with("Cannot checkout, verify if git_path and branch name are correct.")
@sync.prepare_for_sync
end
it "tests with happy path" do
expect(@sync).to receive(:diff_dirs).with("./","./").and_return([[:new,"test"]])
expect(@sync).to receive(:system).and_return(true)
expect(@sync).not_to receive(:exit_with_error)
@sync.prepare_for_sync
end
end
describe "handle files" do
after(:each) do
@sync.diff_files = []
end
it "runs with no diff" do
expect(@sync).not_to receive(:run_cmd)
expect(@sync.handle_files).to be_empty
end
it "runs with new file in diff" do
@sync.p4_path = "./"
@sync.diff_files = [[:new, "test.rb"]]
expect(@sync).to receive(:strip_leading_slash).with("test.rb").and_return("test.rb")
expect(STDOUT).to receive(:puts).with("NEW in Git: test.rb")
expect(@sync).to receive(:run_cmd).with("cp -r './test.rb' './test.rb'",false)
expect(@sync).to receive(:run_cmd).with("#{@sync.p4_add_recursively("'./test.rb'")}",false)
@sync.handle_files
end
it "runs with modified file in diff" do
@sync.p4_path = "./"
@sync.diff_files = [[:modified, "test.rb"]]
expect(@sync).to receive(:strip_leading_slash).with("test.rb").and_return("test.rb")
expect(STDOUT).to receive(:puts).with("MODIFIED in Git: test.rb")
expect(@sync).to receive(:run_cmd).with("cp './test.rb' './test.rb'",false)
expect(@sync).to receive(:run_cmd).with("p4 edit './test.rb'",false)
@sync.handle_files
end
it "runs with deleted file in diff" do
@sync.p4_path = "./"
@sync.diff_files = [[:deleted, "test.rb"]]
expect(@sync).to receive(:strip_leading_slash).with("test.rb").and_return("test.rb")
expect(STDOUT).to receive(:puts).with("DELETED in Git: test.rb")
expect(Find).to receive(:find).and_yield("test.rb")
expect(STDOUT).to receive(:puts).with("DELETED in Git (dir contents): test.rb")
expect(@sync).to receive(:run_cmd).with("p4 delete 'test.rb'",false)
expect(FileUtils).to receive(:remove_entry_secure).with("./test.rb",{:force=>true})
@sync.handle_files
end
end
end |
require 'shellwords'
module ActiveRecord
module Snapshot
class MySQL
def self.dump(*args)
new.dump(*args)
end
def dump(tables:, output:)
dump_command("--no-data --set-gtid-purged=OFF #{database} > #{output}") &&
dump_command("--quick --set-gtid-purged=OFF #{database} #{tables.join(" ")} >> #{output}")
end
def self.import(*args)
new.import(*args)
end
def import(input:)
system(<<~SH)
nice mysql \\
--user=#{username} \\
#{password_string} \\
--host=#{host} \\
#{database} < #{input}
SH
end
private
def db_config
ActiveRecord::Snapshot.config.db
end
def escape(value)
Shellwords.escape(value)
end
def username
escape(db_config.username)
end
def password_string
return if db_config.password.blank?
"--password=#{escape(db_config.password)}"
end
def host
escape(db_config.host)
end
def database
escape(db_config.database)
end
def dump_command(args = "")
system(<<~SH)
nice mysqldump \\
--user=#{username} \\
#{password_string} \\
--host=#{host} \\
#{args}
SH
end
end
end
end
|
class Tag < ActiveRecord::Base
validates_presence_of :key
validates_presence_of :task_id
belongs_to :task
has_many :assignments
has_many :packages, :through => :assignments
def packages_can_show
__packages = []
self.packages.each do |package|
if package.status.blank? || package.status.can_show?
__packages << package
end
end
__packages
end
end
|
require_relative "../../test_helper"
module Unit
module Query
class TestSQL < MiniTest::Test
describe DirectiveRecord::Query::SQL do
before do
@base = mock
@directive_query = DirectiveRecord::Query::SQL.new(@base)
end
describe "#initialize" do
it "stores the passed base class as an instance variable" do
assert_equal @base, @directive_query.instance_variable_get(:@base)
end
end
describe "#path_delimiter" do
it "returns nil" do
assert_nil @directive_query.send(:path_delimiter)
end
end
describe "#aggregate_delimiter" do
it "raises an NotImplementedError" do
assert_raises NotImplementedError do
@directive_query.send :aggregate_delimiter
end
end
end
end
end
end
end
|
class CreateIndexFt < ActiveRecord::Migration[5.0]
def up
execute <<-SQL
CREATE INDEX ticket_seg_origin_index ON flight_tickets ((segment->>'origin'))
SQL
end
def down
drop_index :ticket_seg_origin_index
end
end
|
class AddMoreParamsToRentals < ActiveRecord::Migration
def change
add_column :rentals, :equipment_needed, :text
end
end
|
class TastingTermSerializer < ActiveModel::Serializer
attributes :id, :tasting_term
has_many :wines, serializer: WineSerializer
end
|
# == Schema Information
# Schema version: 20110529234238
#
# Table name: plus_ones
#
# id :integer not null, primary key
# rsvp_event_id :integer
# rsvp_invite_id :integer
# name :string(255)
# created_at :datetime
# updated_at :datetime
# vote_item_id :integer
#
class PlusOne < ActiveRecord::Base
belongs_to :rsvp_event
belongs_to :rsvp_invite
has_one :vote_item
validates :name, :presence => true
validates :rsvp_invite_id, :presence => true
validates :rsvp_event_id, :presence => true
end
|
class Cart < ActiveRecord::Base
belongs_to :cart_status
has_many :cart_items
before_create :set_cart_status
before_save :update_subtotal
def update_subtotal
cart_items.collect { |ci| ci.valid? ? (ci.quantity * ci.unit_price_per_pack) : 0 }.sum
end
private
def set_cart_status
self.cart_status_id = 1
end
def update_subtotal
self[:subtotal] = subtotal
end
end
|
class Devise::RegistrationsController < ApplicationController
prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]
include Devise::Controllers::InternalHelpers
# GET /resource/sign_up
def new
build_resource({})
render_with_scope :new
end
# POST /resource/
# def create
# build_resource
#
# if resource.save
# if resource.active?
# set_flash_message :notice, :signed_up
# sign_in_and_redirect(resource_name, resource)
# else
# set_flash_message :notice, :inactive_signed_up, :reason => resource.inactive_message.to_s
# expire_session_data_after_sign_in!
# redirect_to after_inactive_sign_up_path_for(resource)
# end
# else
# clean_up_passwords(resource)
# render_with_scope :new
# end
# end
#
# WITH JSON RESPONSE
def create
build_resource
if resource.save
set_flash_message :notice, :signed_up
sign_in_and_redirect(resource_name, resource)
else
clean_up_passwords(resource)
respond_to do |format|
format.html { render_with_scope :new }
format.json { render :json => {:result => :ko,
:errors => resource.errors, :status => :unprocessable_entity}}
end
end
end
# GET /resource/edit
def edit
render_with_scope :edit
end
# PUT /resource
def update
if self.resource.update_with_password(params[resource_name])
set_flash_message :notice, :updated
redirect_to after_sign_in_path_for(self.resource)
else
render_with_scope :edit
end
end
# DELETE /resource
def destroy
self.resource.destroy
set_flash_message :notice, :destroyed
sign_out_and_redirect(self.resource)
end
protected
# Authenticates the current scope and dup the resource
def authenticate_scope!
send(:"authenticate_#{resource_name}!")
self.resource = send(:"current_#{resource_name}").dup
end
end |
require 'spec_helper'
describe Puppet::Type.type(:nis) do
before do
@class = described_class
@profile_name = "current"
end
it "should have :name as its keyattribute" do
expect( @class.key_attributes).to be == [:name]
end
describe "when validating attributes" do
[:domainname, :ypservers, :securenets, :use_broadcast, :use_ypsetme
].each do |prop|
it "should have a #{prop} property" do
expect(@class.attrtype(prop)).to be == :property
end
end
end
describe "when validating values" do
describe "for domainname" do
def validate(dname)
@class.new(:name => @profile_name, :domainname => dname)
end
it "should allow a value to be set" do
expect { validate "foo.com" }.not_to raise_error
end
end # domainname
describe "for ypservers" do
error_pattern = /ypserver.*invalid/m
def validate(hostname)
@class.new(:name => @profile_name, :ypservers => hostname)
end
it "should reject hostnames greater than 255 characters" do
expect { validate "aaaa." * 51 << "a"
}.to raise_error(Puppet::Error, error_pattern)
end
it "should reject hostnames with double periods" do
expect { validate "double..isbad.com"
}.to raise_error(Puppet::Error, error_pattern)
end
it "should reject hostname segments larger than 63 characters" do
expect { validate "my." << "a" * 64 << ".com"
}.to raise_error(Puppet::Error, error_pattern)
end
it "should reject hostname segments not starting with a letter/digit" do
expect { validate "my._invalid.hostname"
}.to raise_error(Puppet::Error, error_pattern)
end
it "should reject hostname segments ending with a dash" do
expect { validate "my.invalid-.hostname"
}.to raise_error(Puppet::Error, error_pattern)
end
["192.168.1.253","1.2.3.4"].each do |ip|
it "should accept valid IP addresses #{ip}" do
expect { validate ip
}.not_to raise_error
end
end
["192.168.1.256","192.168.1."].each do |ip|
it "should reject invalid IP addresses #{ip}" do
expect { validate ip
}.to raise_error(Puppet::Error, error_pattern)
end
end
it "should accept an array of valid values" do
expect { validate(
[ "host1.hostarray.com", "host2.hostarray.com" ])
}.not_to raise_error
end
it "should return an array for a single value" do
mytype = @class.new(:name => @profile_name,
:ypservers => "host1.hostarray.com")
expect(mytype.property("ypservers").value).to be_an(Array)
end
end # ypservers
describe "for securenets" do
def validate(snets)
@class.new(:name => @profile_name, :securenets => snets)
end
it "should allow a value to be set" do
expect { @class.new(:name => @profile_name,
:securenets => ['1.1.1.1'])
}.not_to raise_error
end
it "should allow multiple values to be set" do
expect { @class.new(:name => @profile_name,
:securenets => [
'1.1.1.1/255.255.255.0',
'1.1.1.2/host',
'host/1.1.1.3',
'1.1.1.4'
]
) }.not_to raise_error
end
it "should fail on invalid multiple values" do
expect { @class.new(:name => @profile_name,
:securenets => [
'1.1.1.1/toast',
]
) }.to raise_error(Puppet::Error, /invalid net_address/)
end
it "should fail if argument value is not an IP address" do
expect { @class.new(:name => @profile_name,
:securenets => ['1.1.1'])
}.to raise_error(Puppet::Error, /invalid net_address/)
end
end # securenets
describe "for use_broadcast" do
error_pattern = /broadcast.*Invalid/m
def validate(ub)
@class.new(:name => @profile_name, :use_broadcast => ub)
end
[ "true", "false" ].each do |ubval|
it "should accept a value of #{ubval}" do
expect { validate(ubval) }.to_not raise_error
end
end
it "should reject invalid values" do
expect { validate "foo"
}.to raise_error(Puppet::Error, error_pattern)
end
end # use_broadcast
describe "for use_ypsetme" do
error_pattern = /ypsetme.*Invalid/m
def validate(ub)
@class.new(:name => @profile_name, :use_ypsetme => ub)
end
[ "true", "false" ].each do |ubval|
it "should accept a value of #{ubval}" do
expect { validate(ubval) }.to_not raise_error
end
end
it "should reject invalid values" do
expect { validate "foo"
}.to raise_error(Puppet::Error, error_pattern)
end
end # use_ypsetme
end # validating values
end
|
# encoding: utf-8
class AddColumnCaloryToFoodstuffDraft < ActiveRecord::Migration
def up
add_column :recipe_foodstuff_drafts, :calory, :integer, null: true
end
def down
remove_column :recipe_foodstuff_drafts, :calory
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.