text
stringlengths
10
2.61M
class WishlistsController < ApplicationController def index @wishlists = Wishlist.all render json: @wishlists end end
class Cpu < ApplicationRecord belongs_to :company belongs_to :brand belongs_to :socket_cpu end
class Cadastro < ActiveRecord::Base validates_presence_of :nome, :message => " - Deve ser preenchido" end
class Post < ActiveRecord::Base mount_uploader :img, ImgUploader validates :title, presence: true validates :title, uniqueness: true belongs_to :user belongs_to :category, dependent: :destroy # acts_as_taggable # acts_as_imageable end
class CreatePatients < ActiveRecord::Migration def change create_table :patients do |t| t.text :name t.text :surname t.date :birthdate t.text :marital_status t.text :profession t.text :cpf t.text :identity t.text :cep t.text :address t.text :city t...
class AddForeignKeys < ActiveRecord::Migration[5.0] def change add_foreign_key :conversations_profiles, :conversations, on_delete: :cascade add_foreign_key :conversations_profiles, :profiles, on_delete: :cascade add_foreign_key :messages, :conversations, on_delete: :cascade add_foreign_key :photos, :a...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
require 'test_helper' class ProjectsControllerTest < ActionDispatch::IntegrationTest def setup @project = projects(:one) @user = users(:karam) @user2 = users(:glorious) end test "should get new" do log_in_as(@user) get projects_new_url assert_response :success end test "should redi...
class Users::MessagesController < ApplicationController before_action :authenticate_user! def create message = Message.new(message_params) message.user_id = current_user.id if message.save redirect_to room_path(message.room) else redirect_back(fallback_location: root_path) end end...
require_relative("../db/sql_runner.rb") class Movie attr_reader :id, :title, :genre, :rating, :budget attr_writer :title, :genre, :rating, :budget def initialize(options) @id = options["id"].to_i if options["id"] @title = options["title"] @genre = options["genre"] @rating = options["rating"] ...
# Loan Calculator Program # Program Methods def prompt(message) Kernel.puts("=> #{message}") end def integer?(input) input.to_i.to_s == input end def float?(input) input.to_f.to_s == input end def number?(input) integer?(input) || float?(input) end prompt("Welcome to the Loan Repayment Calculator") # Pro...
require 'cloudformation_mapper/resource' class CloudformationMapper::Resource::AwsResourceOpsworksElbattachment < CloudformationMapper::Resource register_type 'AWS::OpsWorks::ElasticLoadBalancerAttachment' type 'Template' parameter do type 'Template' name :Properties parameter do type 'Str...
class Student def initialize(name, major, student_number) @name = name @major = major @student_number = student_number end def learn; "I am learning"; end def pay_tuition; "I am paying tuition"; end def public_student_number "#{@name}'s student number is: ****#{student_number[4..-1]}" ...
# == Schema Information # # Table name: tag_products # # id :bigint not null, primary key # created_at :datetime not null # updated_at :datetime not null # product_id :bigint # tag_id :bigint # # Indexes # # index_tag_products_on_product_id (product_id) # index_tag_products...
class Error < ActiveRecord::Base scope :latest, order(:when).limit(10) def track(log) self.error = log self.save end end
namespace :kfc do desc 'Generate submissions for random stores for testing' task :generate_submissions => :environment do |t, args| unless ENV['APPEND'] Submission.destroy_all end count = (ENV['COUNT'] || Store.count).to_i uids = Store.pluck(:uid).shuffle.first(count) uids.each do |uid| ...
class AddAttachmentsImageToKind < ActiveRecord::Migration def self.up add_column :kinds, :image_file_name, :string add_column :kinds, :image_content_type, :string add_column :kinds, :image_file_size, :integer add_column :kinds, :image_updated_at, :datetime end def self.down remove_column :kin...
# frozen_string_literal: true module Main module View module Parts class Article < Hanami::View::Part def by author_name = [value.author.first_name, value.author.last_name].join(' ') "by <a href='https://twitter.com/sebwilgosz'>#{author_name}</a> " end end end ...
class Preference < ApplicationRecord # Define if preference should be uniq # Prevent of changing keys order KINDS = { local_token: true, server_token: true }.freeze enum kind: KINDS.keys validates_presence_of :kind validates_uniqueness_of :kind, if: -> (i){ KINDS[i] } class << self Prefe...
#encoing: utf-8 module Service module VoteService def self.is_liked? (voter, votable, &block) #binding.pry #result = Rails.cache.fetch([voter, votable, :liked]) do result = voter.voted_as_when_voted_for votable #end block.call(voter, votable) if block result ? true : false ...
module Prodder class Git GitError = Class.new(StandardError) do attr_reader :command, :error def initialize(command, error); @command, @error = command, error; end end NotFoundError = Class.new(StandardError) NotFastForward = Class.new(StandardError) do attr_reader :remote def...
class Song attr_accessor :name, :artist @@all=[] def initialize(name) @name=name @@all<< self end def self.all @@all end def artist=(artist) @artist=artist artist.songs<< self end def artist_name # binding.pry self.artist ? self.artist.name : nil end end
class SessionsController < ApplicationController def create user = FacebookUser.from_omniauth(env["omniauth.auth"]) session[:user_id] = user.id if user.nickname == "세종대학생" flash[:danger] = "별명을 설정해주세요" redirect_to edit_facebook_user_path(:id => session[:user_id]) else redirect_to root...
class FontNabla < Formula head "https://github.com/google/fonts/raw/main/ofl/nabla/Nabla%5BEDPT%2CEHLT%5D.ttf", verified: "github.com/google/fonts/" desc "Nabla" desc "Color font inspired by isometric computer games, built using the colrv1 format" homepage "https://fonts.google.com/specimen/Nabla" def install...
class ChangeResponseDataToTextInPurchaseTransction < ActiveRecord::Migration def up change_column :purchase_transactions, :response_data, :text end def down change_column :purchase_transactions, :response_data, :string end end
class Image < ActiveRecord::Base belongs_to :album validates :instagram_id, :ig_url, :ig_user, :ig_created_time, :ig_user_avatar, presence: true end
class RecipientUsersController < ApplicationController before_action :set_recipient_user, only: [:show, :edit, :update, :destroy] # GET /recipient_users # GET /recipient_users.json #def index # @recipient_users = RecipientUser.all #end # GET /recipient_users/1 # GET /recipient_users/1.json #def sho...
class AddColumnsToPosts < ActiveRecord::Migration def change add_column :posts, :post_title, :string add_column :posts, :post_description, :text add_column :posts, :board_id, :integer add_column :posts, :topic_id, :integer end end
module YrNo class Client # Creates a connection if there is none, otherwise returns the existing connection. # # @return [Faraday::Connection] Faraday connection for the client def connection @connection ||= build_connection return @connection end # Called by {#connection} to bui...
class Removeindexfromusers < ActiveRecord::Migration[6.0] def change remove_index "users", name: "index_users_on_email" add_index "users", "email", unique: false end end
class AddIndexesToGalleries < ActiveRecord::Migration[5.0] def change add_index :galleries, [:gid, :token] add_index :galleries, :tags, using: 'gin' execute "CREATE INDEX galleries_idx ON galleries USING gin(to_tsvector('english', title));" end end
require 'test_helper' class HonksControllerTest < ActionController::TestCase setup do @honk = honks(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:honks) end test "should get new" do get :new assert_response :success end test "s...
require 'byebug' class Maze attr_accessor :maze, :start, :end, :position def initialize(maze) @maze = maze.map { |line| line.split("") } end def set_points maze.each_with_index do |line, idx1| line.each_with_index do |char, idx2| if char == "S" @start = [idx1, idx2] els...
class CreateSessionActivities < ActiveRecord::Migration[5.1] def change create_table :session_activities, id: :uuid do |t| t.text :duration t.string :module_session_id t.text :objective t.text :procedure t.text :progress_indicators t.jsonb :resources t.string :title ...
class Meeting < ApplicationRecord validates :title, :agenda, :location, :time, presence: true validates :time > Time.now has_many :speaker_meetings has_many :speakers, through: :speaker_meetings end
module UserMacros def login setup_account log_in end def logout visit destroy_user_session_path end def fill_in_signup_data @user_email = 'test@example.com' fill_in_user_data(@user_email, 'sign_up') end private def setup_account @user ||= create(:user, email: 'test@e...
class UtilitiesController < ApplicationController skip_before_action :verify_authenticity_token before_action :set_flat, only: [:index, :new, :create, :show, :edit, :update, :destroy] before_action :set_utility, only: [:show, :edit, :update, :destroy] def index @utilities = @flat.utilities.order(:id) @...
class Admin::SolutionsController < ApplicationController layout 'admin' # 需要管理员权限 before_action :require_is_admin def index @solutions = Solution.order_by_created end def edit @solution = Solution.find(params[:id]) @solution_tags = SolutionTag.all end def new @solution = Solution.new ...
require File.join(File.dirname(__FILE__), 'spec_helper') describe Braintree::Card do it "should inherit from PaymentType" do Braintree::Card.new.should be_a_kind_of(Braintree::PaymentType) end it "should default payment to creditcard" do Braintree::Card.new.payment.should == 'creditcard' end end descr...
FactoryGirl.define do factory :bidding do association :catch_user, factory: :user catch_date_catch {Faker::Date.between(30.days.ago, Date.today)} association :catch_client, factory: :client association :catch_organ, factory: :organ association :catch_capture_form, factory: :capture_form catch_other_capture...
class EventsController < ApplicationController before_action :authorize_request before_action :set_event, only: [:show, :update, :destroy, :audit_finish] before_action -> { authorize_user(['admin', 'manager']) }, only: [:create, :destroy, :audit_finish] # GET /events def index @events = Event.all.ord...
spec = Gem::Specification.new do |s| s.name = "hector-secret-channels" s.version = "1.0.1" s.platform = Gem::Platform::RUBY s.authors = ["Ross Paffett"] s.email = ["ross@rosspaffett.com"] s.homepage = "http://github.com/raws/hector-secret-channels" s.summary = "Secret channels for Hector" s.description ...
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def validate error = "" self.errors.full_messages.each do |err| error << ((err.present? && error.present?)? "<br>#{err}" : "#{err}") end error end end
json.array!(@transactions) do |transaction| json.extract! transaction, :id, :flag, :date, :payee, :inflow, :outflow, :cleared, :account_id json.url transaction_url(transaction, format: :json) end
# encoding: utf-8 #! /usr/bin/env ruby ## # Auteur CrakeTeam # Version 0.1 : Date : Mon Mar 17 09:42 2013 # require_relative 'Fenetre' class FenetreOptions < Fenetre @boutonReinitialiser @boutonAfficherScores @texteInfos @boutonPrecedent attr_reader :boutonReinitialiser, :boutonAfficherSc...
Pod::Spec.new do |s| s.name = "LSWeekView" s.version = '1.0.5' s.summary = "iOS week view control, similar to the one used in the iOS 7 Calendar app (day view)." s.description = <<-DESC A scrollable week view that allows the user to select a date. Designed for iOS 7 and 8. See...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :export_document do export_type { ExportType.first } info "This is a great document requested by the account department." end end
class Recipe < ActiveRecord::Base @@categories = ["Main Course", "Side Dish", "Dessert"] belongs_to :food_item attr_accessible :dish_type, :if_signature, :if_recipe, :cuisine, :category, :treatment, :garnishing_tips, :serving_tips, :storage_instructions, :shelf_life, :equipment_required, :prepa...
class Design < ActiveResourceRecord self.site = "#{Figaro.env.locate_design_app}/api/v1/" has_many :design_requests belongs_to :design_version_for_production, class_name: "DesignVersion" def deal Deal.find(self.deal_id) end def job_request design_request = DesignRequest.where(design_id: self.id).f...
class AssociateApprovalsWithProposals < ActiveRecord::Migration def change add_reference :approvals, :proposal reversible do |dir| # http://stackoverflow.com/a/6257679/358804 dir.up do execute <<-SQL UPDATE approvals SET proposal_id = proposals.id FROM carts...
class AddPrayerAndLocationToPhotos < ActiveRecord::Migration def change add_column :photos, :prayer, :text add_column :photos, :location, :string add_column :photos, :for_date, :date end end
class Admin::PromotionsController < ApplicationController add_breadcrumb "dashboard", :admin_path add_breadcrumb "acties", :admin_promotions_path def index @promotions = Promotion.all.order(:id) end def show @promotion = Promotion.friendly.find(params[:id]) add_breadcrumb @promotion.title end ...
class DialTestController < UIViewController include CurrentUser def viewDidLoad super end def delegate @delegate ||= UIApplication.sharedApplication.delegate end def window @window ||= delegate.window end def development? RUBYMOTION_ENV == "development" end def height retur...
# frozen_string_literal: true require 'spec_helper' RSpec.describe PokerHands::DealtHand do describe '#new' do let(:dealt_hand) { described_class.new('2H 3D 5S 9C KD') } subject(:cards) { dealt_hand.cards } it { is_expected.to have(5).items } describe 'card' do subject { cards.to_a[0] } ...
class RemoveColumnContentFromDocuments < ActiveRecord::Migration[5.0] def change remove_column :documents, :content remove_column :documents, :content_path end end
class FreeItemRequest < ApplicationRecord acts_as_paranoid belongs_to :actual_owner, class_name: 'User', foreign_key: 'actual_owner_id' belongs_to :potential_owner, class_name: 'User', foreign_key: 'potential_owner_id' has_one :item, dependent: :nullify validates :item, presence: true end
class AddEvaluationsOpenedColumnToChallenge < ActiveRecord::Migration[5.0] def change add_column :challenges, :evaluations_opened, :boolean, default: true end end
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'wegift/version' Gem::Specification.new do |spec| spec.name = 'wegift-ruby-client' spec.version = Wegift::VERSION spec.authors = ['Klaas Endrikat'] spec.ema...
class Affiliate < ApplicationRecord #必須チェック validates :company, presence: true validates :a_id, presence: true validates :a_tag, presence: true #文字数チェック validates :company, length: { maximum: 20 } validates :a_id, length: { maximum: 50 } validates :a_tag, length: { maximum: 1000 } end
# == Schema Information # # Table name: contacts # # id :integer not null, primary key # address :string # title :string # phone_one :string # phone_two :string # latitude :float # longitude :float # created_at :datetime not null # updated_at :datetime not null # ...
#!/usr/bin/env ruby # Date: 2014.9.12 # Author: Hojung Yun require 'optparse' # set the version of script VERSION = "0.1" # set default value of arguments # do not add mandatory options here options = { :upper_case => false, :lower_case => false, :number => false, :special_ch => false } # option pa...
require_relative 'journey' class JourneyLog def initialize(journey_class = Journey) @journey_class = journey_class @journeys = [] end def start(station) journey = @journey_class.new(station) @journeys << journey @journeys.last.entry_station end def finish(station) current_journey.e...
# == Schema Information # # Table name: users # # id :integer not null, primary key # comments_count :integer # likes_count :integer # private :boolean # username :string # created_at :datetime not null # updated_at :datetime not null # class User < A...
name 'docker-images' maintainer 'Clinton Freeman' maintainer_email 'YOUR_EMAIL' license 'The MIT License' description 'Installs/Configures docker-image' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.3.16' supports 'ubuntu' recipe 'dock...
class PowerOrderUpdateValidator < ActiveModel::Validator def validate(record) # 更新されるのがrecord return if record.power.nil? # 空で入力されたら以降は無視 # 保存されている使用電力の合計 (これには更新前のレコードが含まれる). all = PowerOrder.where(group_id: record.group_id).sum(:power) # 更新前の電力量を引く all_without_updated = all - PowerOrder.find(...
require 'rails_helper' describe "user creates new idea" do scenario "creates new idea" do user = create(:user) create(:category) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit user_path(user) click_on('Create a new idea') expect(current_path).t...
class AddPaidToDoctorToHistories < ActiveRecord::Migration def change add_column :histories, :paid_to_doctor, :boolean add_column :histories, :paid_date, :datetime end end
class Admin::FichaTematicasController < ApplicationController layout 'admin' require_role "administrador" # GET /ficha_tematicas # GET /ficha_tematicas.xml def index @ficha_tematicas = FichaTematica.busqueda(params[:page], params[:generico], params[:buscar]) respond_to do |format| format.ht...
namespace :deploy do desc "save the local version of the init.d scripts to the server" task :send_initd_scripts, :roles => :app do Dir.glob('config/init.d/*').each do |file| dest = "#{shared_path}/#{File.basename(file)}" process_erb_file_and_upload file, :destination => dest run "chmod a+x #{d...
class Sitter < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_and_belongs_to_many :parents after_create :build_c...
# -*- encoding : utf-8 -*- class CreateGeneralPlans < ActiveRecord::Migration def change create_table :general_plans do |t| t.integer :aspirant_id t.integer :status t.timestamps end end end
class Api::V1::AuthenticateController < ApiController skip_before_action :ensure_user, only: :show expose(:user) { User.find_by email: params[:email] } def show head :not_found unless valid_user? end private def valid_user? user&.valid_password?(params[:password]) end end
class Ssend < ActiveRecord::Base belongs_to :po has_many :stocks attr_accessible :po_id , :po_attributes has_many :invards validates_uniqueness_of :po_id end
class CreateFilms < ActiveRecord::Migration[5.1] def change create_table :films do |t| t.string :name t.integer :ratings t.string :description t.date :released t.string :poster t.string :trailer end end end
# Copyright (c) 2009-2011 VMware, Inc. require 'time' SERVICES = 5 MARKED_INSTANCES_PER_SERVICE = 50 UNMARKED_INSTANCES_PER_SERVICE = 50 SNAPSHOTS_PER_INSTANCE = 10 GUID_LENGTH = 20 GUID_CHARS = ('a'..'f').to_a + ('0'..'9').to_a DAYS_BACK = 15 ONE_DAY = 60*60*24 # when called from the command line, the content of las...
class Comment < ActiveRecord::Base belongs_to :user belongs_to :company BASED_OPINION = {:gossips => 1, :interview => 2, :worked_there => 3} def based_opinion_text case self.based_opinion when BASED_OPINION[:gossips] "Gossips" when BASED_OPINION[:interview] "In a interview"...
class ApplicationController < ActionController::Base protect_from_forgery before_filter :get_actual_balance, :set_locale, :low_balance_warning rescue_from Exception, with: :render_500 def after_sign_in_path_for(resource) if current_user.locale.nil? flash[:notice] = t("flash.no_locale") edit_pro...
require 'optparse' require './lib/parsers/gradle_parser' require './lib/exceptions/parser_exit' RSpec.describe GradleParser do before do @parser = GradleParser.new end context "when parsing gradle projects" do before do subprojects_property = "subprojects: [ project ':spec:gradle_ap...
# For now, this class makes it possible to use asset_package with Heroku. # Later, I'll figure out a way to DRY this and config/asset_packages.yml up. module AssetsHelper def js_assets if Rails.env.production? ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', 'merged_packaged'] else...
class AssignmentAnswersController < ApplicationController before_filter :login_required filter_access_to :all,:except=>[:show,:edit,:update,:download_attachment,:new,:create] filter_access_to :show,:edit,:update,:attribute_check=>true, :load_method => lambda { current_user.parent? ? (current_user.guardian_entry.c...
module Faa module Asciidoctor module Extension VERSION = '0.0.6'.freeze end end end
class Audit < ApplicationRecord belongs_to :horse belongs_to :vet has_many :examinations end
class CreateShows < ActiveRecord::Migration def change create_table :shows do |t| t.references :game t.references :user t.integer :going, default: 0 t.integer :goals, default: -1 t.string :token t.timestamps end end end
# -------------------------------------------------------------------------- # # Copyright 2002-2018, OpenNebula Project, OpenNebula Systems # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # no...
require 'alpha' describe Alpha::Config do INVALID_CONFIG_PATH = 'config/invalid-config.yaml' before :each do @config = Alpha::Config.new Alpha::Runner.config_path end it 'cannot find config file did not throw error' do path = 'invalid/config/file.yaml' expect { Alpha::Config.new path }.to raise_err...
class Exercise < ApplicationRecord belongs_to :user has_many :exercise_lists has_many :workout_plans, through: :exercise_lists end
class BackofficeWorker include Sidekiq::Worker sidekiq_options retry: false def perform(options = {}) # if want to test on development please uncomment below # please turn off before commit, so we do not waste our event quota in kissmetrics # return unless (Rails.env.staging? || Rails.env.production...
class Item < ApplicationRecord enum status: { disabled: 0, enabled: 1 } belongs_to :merchant has_many :invoice_items, dependent: :destroy has_many :invoices, through: :invoice_items has_many :customers, through: :invoices has_many :transactions, through: :invoices delegate :top_revenue_day, to: :invoic...
require 'spec_helper' require 'ldap-relations/and' module Ldap::Relations describe And do let(:left) { stub 'Relation', to_filter: '(user=test)' } let(:right) { stub 'Relation', to_filter: '(mail=test)' } let(:and_group) { And.new left, right } describe '#to_filter' do subject { and_group.to_f...
require 'open-uri' module VocabulariSe ; module WikipediaExt # # A simple mixin adding Search request to Wikipedia class from # wikipedia-client gem # module Search # http://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=decibel%20AND%20sound def search( expr, options = {} ) request( { ...
module Tight module Engine module Defer def placeholders @placeholders ||= {} end def defer_element(name, args, opts) if settings.respond_to?(:deferred_elements) && settings.deferred_elements.include?(name) placeholders[name] = [ name, args, opts ] "%{placeho...
require 'rails_helper' feature 'Admin interacts with treatments' do let!(:treatment) { create(:treatment) } before do visit admin_treatments_path end scenario 'admin views treatments' do expect(page).to have_css 'td', text: treatment.title end scenario 'admin sees message when no treats available'...
# user_spec.rb require 'rubygems' require 'spec' require 'user' require 'user_manager' describe User do it "should let create new user" do User.new("admin", "pass", "name", "lastname").should be_instance_of(User) end it "shoould have username and password" do admin_account = User.new("admin", "...
class ImagesIndexView def initialize(search_tag:) @search_tag = search_tag end def index_page_title if search_tag_blank? 'All Images' else format('All Images with tag [%<search_tag>s]', search_tag: @search_tag) end end def search_tag_blank? @search_tag.blank? end end
require 'rails_helper' RSpec.describe News, type: :model do subject(:news) { FactoryGirl.build(:news) } #################### # VALIDATIONS #################### describe 'is valid' do it 'with default factory attributes' do expect(news).to be_valid end end describe 'is invalid' do ...
class MonthlyWorkout < ApplicationRecord belongs_to :workout belongs_to :child end
FactoryGirl.define do factory :condition, class: Cortex::Models::Condition do light 20 temperature 74.3 noise 44 moved 1 created_at { Time.now } end end
class Location < ActiveRecord::Base belongs_to :car attr_accessible :car_id, :address, :gmaps, :latitude, :longitude # acts_as_gmappable :process_geocoding => false geocoded_by :address # reverse_geocoded_by :latitude, :longitude # after_validation :geocode, :reverse_geocode validates :car_id, :latitude...
module Concerns::HygieneStatistics extend ActiveSupport::Concern def active_users(options={}) actives = users.with_device.joins(:opportunities).where('opportunities.start_time > ?', 1.week.ago).uniq actives = actives.by_role(options[:role]) if options[:role].present? actives end def inactive_user...
class Api::V1::AirportsController < ApplicationController def index response = AirportService.filter(api_params) if response.empty? json_response({error_message: 'No record found'}, :not_found) else json_response(response) end end def api_params params.permit(:country_code, :code, :international_a...