text
stringlengths
10
2.61M
class TocatRoleSerializer < ActiveModel::Serializer include Rails.application.routes.url_helpers attributes :id, :name, :position, :permissions, :links private def links data = {} if object.id data[:href] = tocat_role_path(object) data[:rel] = 'self' end data end end
class CareerStat < ApplicationRecord belongs_to :player validates_uniqueness_of :player_id end
def roll_call_dwarves(names) # Your code here names.each_with_index do |name, index| puts "#{index + 1} #{name}" end end def summon_captain_planet(calls) # Your code here calls.collect do |call| call.capitalize + "!" end end def long_planeteer_calls(calls) # Your code here calls.any? do |call|...
module ApplicationHelper # Method used to "present" an object with its associated presenter. def present(object, klass = nil) klass ||= "#{object.class}Presenter".constantize presenter = klass.new(object, self) yield presenter if block_given? presenter end def first_image_url(html_string) i...
class SentencesController < ApplicationController def create story = Story.find(params[:story_id]) story.sentences.create( user: current_user, body: sentence_params[:body].squish ) redirect_to story end def vote story = Story.find(params[:story_id]) sentence = story.sentence...
require 'pony' module EnglishGate class EmailNotifier < EnglishGate::Notifier attr_accessor :subject def send Pony.mail({ :from => @from, :to => @to, :subject => @subject, :body => @message, :charset => 'utf-8', :via => :smtp, :via_options => {...
module OpenAPIParser::Parser::Value def _openapi_attr_values @_openapi_attr_values ||= {} end def openapi_attr_values(*names) names.each { |name| openapi_attr_value(name) } end def openapi_attr_value(name, options = {}) target_klass.send(:attr_reader, name) _openapi_attr_values[name] = OpenA...
#!/usr/bin/env ruby # vim: noet module Fuzz::Token class Gender < Base Male = ["male", "man", "boy", "m"] Female = ["female", "woman", "girl", "f"] Pattern = (Male + Female).join("|") # whatever variation of gender was # matched, return a regular symbol def normalize(gender_str) Male.include?(gender...
class UsersController < ApplicationController # GET /users # GET /users.xml before_filter :check_login_status def search @search_string = params[:search][:title] # @user = User.find(session[:user_id]) puts "===> inside /user/search search string = " + @search_string @users = User.find(:all, :c...
# Settings set :source, '..' set :css_dir, 'middleman/assets/stylesheets' set :js_dir, 'middleman/assets/javascripts' set :images_dir, 'middleman/assets/images' set :fonts_dir, 'middleman/assets/fonts' set :layouts_dir, 'middleman/layouts' set :data_dir, 'data' set :helpers_dir, 'helpers' ## Playbook settings set :pla...
require 'test_helper' class UserTest < ActiveSupport::TestCase test "all components included" do assert User.create(name: "test", email: "test@test.com", fbid: "123456", wallet: 0).valid? assert_not User.create(name: "test", email: "test@te...
Pod::Spec.new do |s| s.name = 'glomex' s.version = '1.0.0' s.summary = 'This pod can be user for a Glomex Content SDK' s.description = <<-DESC This pod can be user for a Glomex Content SDK. Please find the instruction on README DESC s.homepage ...
class User attr_accessor :balance, :cards, :name def initialize(desk) @desk = desk @balance = 100 @cards = [] end def add_card(card) @cards << card end def score @desk.score(@cards) end end
module QunitForRails class QunitTestsController < ApplicationController skip_before_filter :authorize layout "qunit_for_rails/main" def index test_files = [] Dir.glob(::Rails.root.to_s + "/public/javascripts/test/*").each { |file| if file.end_with?('_test.js') te...
class CreateActors < ActiveRecord::Migration[4.2] def change create_table :actors do |n| n.string :first_name n.string :last_name end end end
class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken include ActionController::MimeResponds include Pundit def pundit_user current_users_model end def skip_bullet previous_value = Bullet.enable? Bullet.enable = false yield ensure Bulle...
class ApiController < ActionController::Base skip_before_action :verify_authenticity_token before_action :authentication_user_from_token! before_action :set_default_format def set_default_format request.format = :json end def authentication_user_from_token! if params[:auth_token].present? u...
require 'fileutils' require 'hashie/mash' require 'proton' require 'wallarm/common/proton_file_info' require 'wallarm/common/sys_info' class NodeDataSyncer FORMATS = { 'proton.db' => Proton::DB_VERSION, 'lom' => Proton::LOM_VERSION } DEFAULTS = { enabled: true, key_file: '/etc/wallarm/licens...
=begin This is assignment 21 and is due on Feb 05, 2015. Write a Person class and some code to use it, following the directions below. First Create a Person class with attributes: first name, last name, and birthdate. First name and last name should not be able to be written to, but should be readable. Birthdate can ...
require 'spec_helper' require 'rose/active_record' module RoseActiveRecordSpecs class Person < ActiveRecord::Base attr_protected :password end class Admin < Person end class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post belongs_to ...
# frozen_string_literal: true require 'rails_helper' describe 'Servers index table', type: :feature do it 'displays server information' do create(:server_index) visit servers_path expect(body).to have_text('server-dev') expect(body).to have_text('123.45.67.890') expect(body).to have_text('pupgra...
class Person attr_accessor :name def initialize(name) @name = name end def greeting "Hello #{name}" end end person = Person.new person.name = "Dennis" puts person.greeting
name 'adminscripts' maintainer 'Boye Holden' maintainer_email 'boye.holden@hist.no' license 'Apache 2.0' description 'Collection of useful adminscripts we want to deploy' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.2.0' recipe 'adminscrip...
class ProjectSerializer < ActiveModel::Serializer attributes :id, :name, :description has_many :issues, embed: :ids end
# class to build a person object class Person attr_accessor :name attr_reader :age @@people = [] def initialize(initial_name, initial_age) @name = initial_name @age = initial_age @@people.push(self) end def say_name puts 'Hi, my name is ' + @name + '.' end def say_age puts "I am #...
class CommentsController < ApplicationController load_and_authorize_resource before_action :load_product, only: :update def create @comment = current_user.comments.build comment_params @product = @comment.product if @comment.save respond_to do |format| format.js end else ...
class TicketsController < ApplicationController before_action :current_board def new end def create title = params[:ticket][:title] description = params[:ticket][:description] status = params[:ticket][:status] ticket = current_board.tickets.new(title: title,description: description, status: st...
class Achievement < ApplicationRecord belongs_to :user validates :name, presence: true validates :majors, presence: true validates :organization, presence: true validates :received_time, presence: true end
require "rspec" require "haversine" require "pry" module Locatable def distance_to lat, long first_station = Station.new(lat,long) distance = Haversine.distance(self.latitude, self.longitude, lat, long) distance.to_miles end def Locatable.included other other.extend Locatable::ClassMethods en...
module CommissionsHelper COMMISSION_RATE = '.04'.to_f BREAKAGE_RATE = '1.18'.to_f # leave at 1 if no amount is deducted from commission def positive_adjustment_commission(event) additional_charges = event.additional_charges.nil? ? 0 : event.additional_charges comm = ((additional_charges + ((event.amount...
cask "tm-asciidoc" do version "0.2" sha256 "d099f2a92667cb8de9233e951181199ec40e542608d33ecd552ea790bda1a8ac" url "https://github.com/mattneub/AsciiDoc-TextMate-2.tmbundle/archive/v#{version}.tar.gz" name "AsciiDoc bundle for TextMate 2" homepage "https://github.com/mattneub/AsciiDoc-TextMate-2.tmbundle" ...
# # Make assets # namespace :grunt do task :build do on roles(:app), in: :sequence, wait: 5 do within fetch(:assets_path, release_path) do execute :grunt, fetch(:grunt_build) end end end end
MRuby::Gem::Specification.new('mruby-require') do |spec| spec.licenses = ["MIT"] spec.authors = ["Nathan Ladd"] spec.summary = "require, require_relative, load backfill" spec.homepage = "https://github.com/test-bench/mruby-ruby-compat" spec.bins = ['mruby-require'] end
# frozen_string_literal: true require './frame' class Game def initialize(game_score) all_score = take_in_game(game_score) sepalated_score = separate_game_to_frame(all_score) @frames = sepalated_score.map { |s| Frame.new(*s) } end def score after_adjustment = @frames.map.with_index do |frame, i...
require 'rspec/core' describe 'permit_actions matcher' do context 'no actions are specified' do before do class PermitActionsTestPolicy1 end end subject { PermitActionsTestPolicy1.new } it { is_expected.not_to permit_actions([]) } end context 'one action is specified' do before ...
require 'rails_helper' describe LineItem do it "has a valid factory" do expect(build(:line_item)).to be_valid end it "can calculate total price per line item" do food = create(:food, price:15000) line_item = create(:line_item, food: food, quantity:2) expect(line_item.total_price).to eq(30000) ...
class Tagging < ActiveRecord::Base attr_accessible :taggable_id, :taggable_type belongs_to :tag belongs_to :taggable, :polymorphic => true def caption self.taggable_type.constantize.find(self.taggable_id).caption end def id self.taggable_type.constantize.find(self.taggable_id).id end def namespace "#{t...
json.array!(@text_book_exams) do |text_book_exam| json.extract! text_book_exam, :id, :text_book_id, :student_id, :point, :exam_date json.url text_book_exam_url(text_book_exam, format: :json) end
FactoryGirl.define do factory :todo_list do sequence(:name) { |n| "List #{n}" } end factory :todo_item do name { Faker::Company.bs } description { Faker::Lorem.paragraph(rand 5) } priority 0 end end
# Copyright (c) 2016, Regents of the University of Michigan. # All rights reserved. See LICENSE.txt for details. # The Umlaut service for ThreeSixtyLink class ThreeSixtyLink < Service required_config_params :base_url attr_reader :base_url # Call super at the end of configuring defaults def initialize(config) ...
require 'test_helper' class SiteLayoutTest < ActionDispatch::IntegrationTest test "test presence of site links" do login_user get '/' assert_template 'thoughts/index' assert_template layout: 'layouts/application' assert_select "a[href=?]", root_path, count: 2 assert_select "a[href=?]", my_ne...
class CentroContratoDetalle < ActiveRecord::Base attr_accessible :id, :centro_contrato_id, :dia_id scope :ordenado_id, -> {order("id")} scope :ordenado_id_desc, -> {order("id desc")} belongs_to :centro_contrato belongs_to :dia end
module ValidateZipcode class Validator def initialize(zipcode, locale) @zipcode = zipcode variables(locale) unless @zipcode.blank? end def valid? return true if @zipcode.blank? @match end private def variables(locale) @match = regex_zipcode(locale.upcase) ...
class User < ActiveRecord::Base validates :name, :lastname, {presence: true, length: {minimum: 2, maximum: 20}} validates :password, :password_confirmation, {presence: true, length: {minimum: 6, maximum: 20}} has_secure_password end
class RbbtGraph attr_accessor :knowledge_base, :entities, :aesthetics, :associations, :rules def initialize @entities = {} @aesthetics = {} @associations = {} @rules = {} end def add_associations(associations, type = :edge) @associations[type] ||= [] @associations[type].concat associat...
require 'spec_helper' describe GraphQLIncludable::Includes do subject { described_class.new(nil) } describe '#dig' do it 'digs' do a = subject.add_child(:a) b = subject.add_child(:b) a.add_child(:a_2).add_child(:a_3) b.add_child(:b_2) expect(subject.dig).to eq(subject.included_c...
require_relative 'retrier' module Ehonda module Middleware module Server module ActiveRecord class Transaction RETRIER_OPTIONS = %i(tries sleep on_retriable_error) TRANSACTION_OPTIONS = %i(requires_new joinable isolation) def initialize options = {} @trans...
module ToDoApp module Controllers module Home include ToDoApp::Controller action 'Index' do include Lotus::Action::Session expose :tasks expose :user def call(params) user_id = session[:user] puts "SESSION: #{user_id}" if params[:new...
class User < ApplicationRecord # 各フォームに値が入っているか確認 validates :name, presence: { message: "%{value} を入力してください" } validates :email, presence: { message: "%{value} を入力してください" } validates :password, presence: { message: "%{value} を入力してください" } #名前の文字数制限 validates :name, length: { maximum: 15,message: "は15字以内にし...
class CreateWardProfiles < ActiveRecord::Migration def self.up create_table :ward_profiles do |t| t.date :quarter t.integer :total_families t.integer :active t.integer :less_active t.integer :unknown t.integer :not_interested t.integer :dnc t.integer :new t.in...
class CreateDailyMeals < ActiveRecord::Migration def change create_table :daily_meals do |t| t.belongs_to :recipe, index: true t.belongs_to :meal_plan, index: true t.timestamps end end end
# Exercise 7: More Printing # https://learnrubythehardway.org/book/ex7.html # prints a string puts "Mary had a little lamb." # prints a string with another string embedded puts "Its fleece was white as #{'snow'}." # prints a string puts "And everywhere that Mary went." # prints a string multiplied by 10, as a resul...
Rails.application.routes.draw do resource :offers_requests, only: [:new, :create] root 'offers_requests#new' end
class TopicsController < ApplicationController before_action :authenticate_user before_action :ensure_correct_user, {only: [:edit, :update, :destroy]} def new @topic = Topic.new end def create @topic = Topic.new( description: params[:description], user_id: @current_user.id ) ...
class Report class GroupedCommentsFetcher def initialize(report:, user:) @report = report @user = user end def all comments.group_by(&:associated_activity) end private attr_reader :report, :user def comments if user.partner_organisation? report.comments....
class PruneOldAccountsJob < ApplicationJob queue_as :default def perform(*args) accounts = Account.without_matches.sole_accounts.not_recently_updated.includes(:user) if accounts.count < 1 Rails.logger.info 'PruneOldAccountsJob no old single accounts without matches' return end Rails.lo...
class ValidatesOptions attr_accessor :validations, :column def initialize(column, options = {}) @validations = Hash.new { |hash, key| hash[key] = false } options.each do |validation, status| validations[validation] = status end @column = column end end module Validatable def validates(...
module AuthService class LogoutUser prepend SimpleCommand attr_accessor :user def initialize(user = nil) @user = user end def call user.token = nil user.save! end end end
require 'spec_helper' describe User do context 'validations' do let(:user) { create(:user) } it 'should be valid with mandatory attributes' do expect(user).to be_valid end it 'should not be valid without an email' do user.email = nil expect(user).not_to be_valid end it 's...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name =>...
class Api::FilmsController < ApplicationController skip_before_action :verify_authenticity_token def actors film = Film.find(params[:film_id]) actors = film.actors if actors render json: actors else render json: 404 end end def index films = Film.sorted # films = Film.search(p...
require "aethyr/core/actions/commands/aconfig" require "aethyr/core/registry" require "aethyr/core/input_handlers/admin/admin_handler" module Aethyr module Core module Commands module Aconfig class AconfigHandler < Aethyr::Extend::AdminHandler def self.create_help_entries hel...
require 'test_helper' class ExercicesControllerTest < ActionDispatch::IntegrationTest setup do @exercice = exercices(:one) end test "should get index" do get exercices_url assert_response :success end test "should get new" do get new_exercice_url assert_response :success end test "...
# encoding: utf-8 class Contentr::Admin::ParagraphsController < Contentr::Admin::ApplicationController before_filter :find_page_or_site def index @paragraphs = @page.paragraphs.order_by(:area_name, :asc).order_by(:position, :asc) end def new @area_name = params[:area_name] if params[:type].present...
JSONAPI.configure do |config| # Built in paginators are :none, :offset, :paged config.default_paginator = :paged config.default_page_size = 10 config.maximum_page_size = 50 config.top_level_meta_include_record_count = true config.top_level_meta_record_count_key = :record_count end
#mastername.rb Puppet::Functions.create_function(:mastername) do dispatch :mastername do param 'String', :filename optional_param 'String', :foo return_type 'String' end def mastername(*arguments) #puts filename.to_s File.open('/etc/puppetlabs/puppet/puppet.conf').grep(/server\s*=/).join.s...
require 'rails_helper' RSpec.describe LoginController, :type => :controller do describe "POST #create (login)" do let(:user) { FactoryGirl.create(:person, name: "pepe", lastname: "lopez", email: "qw@qwe.com", password: "1")} it "authenticates user and redirects to root url index with id in session" do...
class Card < ApplicationRecord validates :original_text, :translated_text, presence: { message: 'Все поля должны быть заполнены!' } validate :fields_equal? validate :set_review_date_to_now private def fields_equal? if self.original_text.to_s.downcase == self.translated_text.to_s.downcase errors....
class StartpageController < ApplicationController def index @user = current_user @blog_posts = BlogPost.limit(3) end end
module ActiveSupport module Cache class FileStore < Store def read(name, options = nil) super file_name = real_file_path(name) expires = expires_in(options) if exist_without_instrument?(file_name, expires) File.open(file_name, 'rb') { |f| Marshal.load(f) } ...
class MyList < ApplicationRecord validates :movie_id, uniqueness: { scope: :user_id} belongs_to :movie belongs_to :user end
# frozen_string_literal: true require "webauthn/error" module WebAuthn module AttestationStatement class FormatNotSupportedError < Error; end ATTESTATION_FORMAT_NONE = "none" ATTESTATION_FORMAT_FIDO_U2F = "fido-u2f" ATTESTATION_FORMAT_PACKED = 'packed' ATTESTATION_FORMAT_ANDROID_SAFETYNET = "an...
# -*- encoding : utf-8 -*- module V1 module Strokes module Entities class Strokes < Grape::Entity expose :uuid expose :sequence expose :distance_from_hole expose :point_of_fall expose :penalties expose :club end class Scorecard < Grape::Entity ...
class CreateForecasts < ActiveRecord::Migration[5.1] def change create_table :forecasts do |t| t.integer :provider, default: 0 t.string :spot t.json :forecast t.timestamps end add_index :forecasts, [:spot, :provider], unique: true end end
FactoryGirl.define do sequence :email do |n| "email#{n}@factory.com" end factory :user do |f| f.firstname Faker::Name.first_name f.lastname Faker::Name.last_name f.email #this email field is unique for every user because of sequencing defined above f.password Faker::Lorem.characters(8) end end
require 'rails_helper' RSpec.describe 'questions/index.json.jbuilder', type: :view do let(:json_result) { JSON.parse(rendered) } let(:questions) { create_list(:question, 2) } before(:each) do assign(:questions, questions) render end it 'renders a JSON list of the right size' do expect(json_resul...
module InContact class Api attr_reader :token def initialize @token = InContact::Tokens.get end def agents @agents ||= create_resource(InContact::Resources::AGENTS) end def contacts @contacts ||= create_resource(InContact::Resources::CONTACTS) end def agent_sessio...
require_relative 'base_page' class BoxCigarsPage < BasePage path '/cigars/box-cigars' validate :url, %r{/cigars/box-cigars(?:\?.*|)$} validate :title, /^#{Regexp.escape('Box of Cigars: Box Selections Starting Under $20 | Famous Smoke')}$/ end
class CreateFilms < ActiveRecord::Migration def change create_table :films do |t| t.string :title t.integer :year t.string :slogan t.integer :director_id t.integer :budget t.float :rating t.float :our_rating t.integer :duration t.timestamps end end end
require 'test_helper' class UserTest < ActiveSupport::TestCase # Replace this with your real tests. test "is reg finished" do user = User.create({:email=>"email@mail.com",:password=>"pass"}) assert_equal false, user.is_reg_finished user.is_reg_finished=true user.update_attributes(:email=>'mod@mail....
class AddColumnHasBeenAcceptedToJoins < ActiveRecord::Migration[5.2] def change add_column :pet_applications, :was_approved, :boolean end end
# frozen_string_literal: true ActiveAdmin.register User do menu priority: 2 actions :index, :edit, :show filter :aasm_state, as: :select, label: 'State' index as: :table do column I18n.t('admin.content') do |user| link_to image_tag(user.image.avatar.url), admin_user_path(user.id) end column ...
class FieldOfView def initialize(options=Hash.new, block&) @light_passes = block& @options = { :topology => :eight } options.each { |k, v| @options[k] = v } end def compute(x, y, r, block&) end private def get_circle(cx, cy, r) result = Array.new dirs, count_factor, start_offset = ni...
Given /^provider "([^\"]*)" has valid payment gateway$/ do |provider_name| provider_account = Account.find_by_org_name!(provider_name) provider_account.update_attribute(:payment_gateway_type, :bogus) end Given /^the provider has a deprecated payment gateway$/ do @provider.gateway_setting.attributes = { gate...
require 'quaker/tag_matcher' require 'deep_merge' module Quaker class Templates def apply services templates = services.select {|name, _| template?(name)} services .reject {|name, _| template?(name)} .inject({}) {|acc, (name, spec)| acc.update(name => extend_with_matching_te...
require File.expand_path(File.dirname(__FILE__) + "/../util_helper") class QaQuestion include UtilHelper def initialize(title, body, photos) if title == nil @title = "Question_" + random_number else @title = title end if body == nil @body = "Question_Body_" + ...
Rails.application.routes.draw do mount_devise_token_auth_for 'User', at: 'auth' scope module: 'api' do namespace :v1 do resources :tracked_times, only: [:index, :create] end end end
class Article < ActiveRecord::Base has_and_belongs_to_many :tags, join_table: "articles_tags" accepts_nested_attributes_for :tags end
Puppet::Type.newtype(:modprobe) do desc <<-EOT Load or unload a kernel module. EOT ensurable do desc "What state the kernel module should be in." newvalue(:present) do provider.create end newvalue(:absent) do provider.destroy end defaultto :present end newparam(:n...
require 'rails_helper' describe User do it "is valid with a valid email and password" do user = build(:user) expect(user).to be_valid end it "is invalid without a valid email address" do user = build(:user, email: "not_an_email") expect(user).to_not be_valid end end
class LayersController < ApplicationController layout 'layerdetail', only: [:show, :edit, :export, :metadata] before_action :authenticate_user! , except: [:wms, :wms2, :show_kml, :show, :index, :metadata, :maps, :thumb, :tile, :trace, :id] before_action :check_administrator_role, only: [:publish, :toggle_visibil...
class HorsesController < ApplicationController # GET /horses def index all_horses end # GET /horses/1 def show horse end # GET /horses/new def new new_horse end # POST /horses def create if new_horse(horse_params).save redirect_to new_horse, notice: 'Horse was success...
require 'spec_helper' require 'httparty' describe TMDBParty::Movie do before(:each) do stub_get('/Movie.getInfo/en/json/key/1858', 'transformers.json') end let :transformers do HTTParty::Parser.call(fixture_file('transformers.json'), :json).first end let :transformers_movie do TMDBParty::Mo...
class CreateWorkAttributes < ActiveRecord::Migration def change create_table :work_attributes do |t| t.string :title t.text :summary t.text :to t.text :from t.boolean :current t.integer :workplace_id t.integer :user_id t.integer :added_by t.boolean :visible, :...
INDUSTRIES = ['Advertising', 'Agriculture and Forestry', 'Architects', 'Arts and Cultures Industries', 'Catering', 'Charities', 'Clubs and Associations', 'Construction Industry', 'Dentists', 'Distribution and...
class Uploader attr_accessor :bucket def initialize(bucket) @bucket = bucket end def upload_to_s3(path, key) s3_obj = bucket.objects[key] retries = 3 begin s3_obj.write(File.open(path, 'rb', :encoding => 'BINARY')) rescue => ex retries -= 1 if retries > 0 puts "ER...
FactoryGirl.define do factory :opendata_part_mypage_login, class: Opendata::Part::MypageLogin, traits: [:cms_part] do transient do node nil end route "opendata/mypage_login" filename { node.blank? ? "#{name}.part.html" : "#{node.filename}/#{name}.part.html" } end factory :opendata_part_dat...
class ContactDetail < ActiveRecord::Base validates_presence_of :address, :telephone, :fax, :email end
require 'ripper' require 'ripper_ruby_parser/syntax_error' module RipperRubyParser # Variant of Ripper's SexpBuilder parser class that inserts comments as # Sexps into the built parse tree. # # @api private class CommentingRipperParser < Ripper::SexpBuilder def initialize(*args) super @commen...
$:.push File.expand_path("lib", __dir__) # Maintain your gem's version: require "quilt_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = "quilt_rails" spec.version = Quilt::VERSION spec.authors = ["Mathew Allen"] spec.email = ["m...