text stringlengths 10 2.61M |
|---|
#encoding: utf-8
class AfterFirstSigninsController < ApplicationController
before_filter :authenticate_user!
include Wicked::Wizard
steps :upload_avatar, :update_info, :follow_users, :follow_wines, :follow_wineries
def show
@user = current_user
case step
when :follow_users
@recommend_users = ... |
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
require 'kaitai/struct/struct'
require 'zlib'
unless Gem::Version.new(Kaitai::Struct::VERSION) >= Gem::Version.new('0.7')
raise "Incompatible Kaitai Struct Ruby API: 0.7 or later is required, but you have #{Kaitai::St... |
class ChelsController < ApplicationController
def index
@chels = Chel.all
@chel = Chel.new
end
def create
@chel = Chel.create!(chel_params)
if (!@chel.fullname.blank? && (countwords(@chel.fullname) > 1))
if (@chel.firstname.blank?)
@chel.firstname = chelfirstname(@chel.fullna... |
class Relationship < ApplicationRecord
belongs_to :supervisor, class_name: "Lecturer"
belongs_to :supervised, class_name: "User"
validates :supervisor_id, presence: true
validates :supervised_id, presence: true
end
|
class UsersController < ApplicationController
def social_login
access_token = params[:access_token] ? params[:access_token] : nil
email = params[:email] ? params[:email] : nil
msg = ensure_params(:email, :access_token) and return
if msg
error_with_message(msg, 400)
else
begin
@... |
class Cotizmescam < ApplicationRecord
numeroMinimoCaracteresNombreCliente = 3
numeroMaximoCaracteresNombreCliente = 25
expresionRegularEmailValido = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :colchon, presence: true
validates :material, presence: true
validates :color, presence: true
validat... |
class Node
attr_accessor :value, :left_child, :right_child
def initialize(value, parent=nil, left_child=nil, right_child=nil)
@value = value
@left_child = left_child
@right_child = right_child
end
end
def build_tree(arr, first=0, last=arr.length-1)
return if first > last
mid = first + (last -... |
Rails.application.routes.draw do
devise_for :users, path: '', path_names: {sign_in: 'login', sign_up: 'register', sign_out: 'logout'}
resources :portfolios, except: [:show]
get 'portfolio/:id', to: 'portfolios#show', as: 'portfolio_show' # aqui aparte de pasarle una url que nosotros quisimos con as: le pas... |
class User
attr_reader :email, :employee_id, :submitted_at
attr_accessor :submissions
def initialize(email, employee_id, submitted_at)
@email = email
@employee_id = employee_id
@submitted_at = submitted_at
@submissions = []
end
def submitted?
@submitted_at != nil
end
def submissions... |
# frozen_string_literal: true
FactoryBot.define do
factory :storehouse do
sequence(:name) { |n| "store#{n}" }
end
end
|
str_1 = 'abcde'
str_2 = 'bababef'
# I knew intersection would be helpful, but used
# https://stackoverflow.com/questions/38020334/ruby-array-intersection-with-duplicates
# to speed things up.
def char_counts(chars)
chars.each_with_object(Hash.new(0)) { |c, memo| memo[c] += 1 }
end
chars_1 = str_1.split('')
count_1... |
module DaisyBookHelper
class BatchHelper
ROOT_XPATH = "/xmlns:dtbook"
def self.batch_add_descriptions_to_book job_id, current_library
job = Job.where(:id => job_id).first
# Retrieve file from S3
repository = RepositoryChooser.choose
enter_params = job.json_enter_params
password... |
# frozen_string_literal: true
class CreateAnswers < ActiveRecord::Migration[5.1]
def change
create_table :answers, id: :uuid do |t|
t.datetime :start_time
t.datetime :submit_time
t.text :response
t.belongs_to :question, type: :uuid, index: true
t.belongs_to :image, type: :uuid, ind... |
class HomeController < ApplicationController
def index
@recent_files = MediaFile.recent(:limit => 10)
@recent_albums = Album.recent(:limit => 10)
end
end
|
class Category < ActiveRecord::Base
attr_accessible :description, :title
has_and_belongs_to_many :links
validates_presence_of :title
end
|
class PodcastsController < ApplicationController
def index
@podcasts = Podcast.order(:title).page(params[:page]).per(10)
end
def show
@podcast = Podcast.find(params[:id])
@tags = Tag.all
if !!current_user
@episodes_listened_to = Episode.listened_to_by(params[:id], current_user.id)
... |
# frozen_string_literal: true
# This is what we use to delete sessions
class LogoutsController < ApplicationController
def show
logout
redirect_to login_path
end
end
|
# frozen_string_literal: true
class CreateImagesForDicomService
attr_reader :dicom
def initialize(dicom)
@dicom = dicom
end
def perform!
d_obj.images.each_with_index do |image, i|
image_path = store_file(image, i)
Image.create(
dicom_id: dicom.id,
file: File.open(image_path... |
#!/usr/bin/env ruby
# baseclass
#
# Author:: James Nuckolls
# Copyright:: Copyright (c) 2009 SoftLayer. All rights reserved.
#
#= Description
#
#= ToDo
#
require 'rubygems' rescue LoadError
require 'soap/wsdlDriver'
require 'softlayer'
require 'softlayer/util'
module SoftLayer
# The Base class for our generated c... |
class RenameColumnInCharacters < ActiveRecord::Migration[5.2]
def change
rename_column :characters, :class, :char_class
end
end
|
=begin
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Example:
makeNegative(1); # return -1
makeNegative(-5); # return -5
makeNegative(0); # return 0
Notes:
The number can be negative already, in which case no change is required.
Zero (0) is n... |
require "includes"
class TrackTest < Minitest::Test
def generate_test_data
test_tracks = {}
test_tracks[:blank] = Track.new("bass", "")
test_tracks[:solo] = Track.new("bass", "X")
test_tracks[:with_overflow] = Track.new("bass", "...X")
test_tracks[:with_barlines] = Track.new("bass", "|X.X.|X.X.|... |
class AddUserIdToRecipes < ActiveRecord::Migration[5.2]
def up
execute "DELETE FROM recipes;"
add_reference :recipes, :user, null: false, index: true
end
def down
remove_reference :recipes, :user, index: true
end
end
|
# Advent of Code 2019 Day 13 Part One https://adventofcode.com/2019/day/13
# Care Package: Intcode-driven paddleball game
class Integer
def split_digits
return [0] if zero?
res = []
quotient = self.abs #take care of negative integers
until quotient.zero? do
quotient, modulus = quotient.divmod(10... |
class AgentsController < ApplicationController
def index
@agents = Agent.all
end
# GET /agents/1
# GET /agents/1.json
def show
@agent = Agent.find(params[:id])
@agent_properties = @agent.agent_properties
respond_to do |format|
format.html # show.html.erb
format.json { render jso... |
class ViewsController < ApplicationController
def application_template
render template: '/application_template'
end
def partial_template
render template: "partials/#{partial_to_render}", layout: nil
end
private
def partial_to_render
params[:path]
end
end |
class MotoCicleta
def initialize(fabricante, cor)
# Variáveis de instância
@fabricante = fabricante
@cor = cor
end
def ligaMotor
if @estado_motor
puts 'O motor já está ligado!'
else
@estado_motor = true
puts 'Motor ocioso!'
end
end
end
#load inclui o arquivo fonte refe... |
class Comment < ActiveRecord::Base
belongs_to :post
def test(post_id)
Comment.where(post_id: post_id).update_all(post_id: nil)
self.update(post_id: post_id)
end
end
|
class DropDepartments < ActiveRecord::Migration[6.0]
def change
drop_table :departments
end
end
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PokerHands::Hand::TwoPairs do
it_behaves_like 'a hand'
it_behaves_like 'same type comparison' do
let(:left) { '3C 3D 9H 2D 9S' }
let(:right) { '7C 7D 8H 4D 8S' }
end
it_behaves_like 'same type comparison' do
let(:left) { '3C 3D 8... |
require 'bundler'
Bundler.require
require 'sinatra/activerecord/rake'
ActiveRecord::Base.establish_connection({
adapter: 'postgresql',
database: 'blog_db'
})
namespace :db do
desc "Create blog_db database"
task :create_db do
conn = PG::Connection.open()
conn.exec('CREATE DATABASE blog_db;')
conn.c... |
module AnnualReports
module UpdateWithStatistics
class Builder
private
attr_reader :annual_report, :statistics
public
def initialize(annual_report)
@annual_report = annual_report
end
def call
build_statistics_collection
build_statistics
end
... |
statement = "The Flintstones Rock"
def countletters(statement)
countit = Hash.new(0)
statement.each_char do |char|
next unless char =~/\w/
countit[char] += 1
end
countit
end
countletters(statement) |
RSpec.describe 'spies' do
let(:animal) { spy('animal') }
it 'confirms that a message has been received' do
animal.eat_food
expect(animal).to have_received(:eat_food)
expect(animal).not_to have_received(:bark)
end
it 'resets between example' do
expect(animal).not_to have_received(:eat_food)
e... |
class RestaurantDish < ActiveRecord::Base
belongs_to :dish
belongs_to :restaurant
end
|
# CSVUtil
module CSVUtil
def get_headers(file)
CSV.read(file, headers: true, encoding: 'iso-8859-1:utf-8').headers
end
def headers_to_hash(headers)
headers_hash = {}
headers.each_with_index do |header, index|
headers_hash[header] = index
end
headers_hash
end
end
|
class AddTypeNameAndCountToUsers < ActiveRecord::Migration
def change
add_column :users, :type, :string, default: 'Writer'
add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :posts_count, :integer, default: 0
end
end
|
# This file was written by hand.
$LOAD_PATH << 'lib'
require 'ecdsa/version'
Gem::Specification.new do |s|
s.name = 'ecdsa'
s.version = ECDSA::VERSION
s.date = Time.now.strftime('%Y-%m-%d')
# The summary should be the same as the description at https://github.com/DavidEGrayson/ruby_ecdsa
s.summary = 'This... |
class AddChartFieldCampaignComments < ActiveRecord::Migration
def up
add_column :campaign_comments, :chart, :text
end
def down
remove_column :campaign_comments, :chart
end
end
|
require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
@item.image = fixture_file_upload('app/assets/images/furima-footer.png')
end
it "imageがないと登録できない" do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't... |
module Dotpkgbuilder
class Pkg < Stage
delegate :templates_dir, :source_dir, :pkg_dir, :package_name,
:number_of_files, :install_kbytes,
:preinstall, :preinstall_file, :postinstall, :postinstall_file, to: :context
PKGINFO_FILE = "PackageInfo".freeze
def run
use Payload
use S... |
json.array!(@critters) do |critter|
json.extract! critter, :id, :name, :description
json.url critter_url(critter, format: :json)
end
|
class MembershipsController < ApplicationController
before_action :require_login
before_action :require_lot, except: [:index]
def index
@memberships = Membership.find(params[:user_id])
end
def new
@membership = @lot.memberships.build
end
def create
@membership = @lot.memberships.build(memb... |
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context "新規登録がうまくいく"
it "全部正常に入力されれば登録できる" do
expect(@user).to be_valid
end
end
context '新規登録がうまくいかない'do
it "nicknameが空だと登録できない" do
... |
class Brand < ApplicationRecord
has_many :items
def self.getBrandNamesArray
return brand_name = Brand.pluck(:name)
end
end
|
class ConsolesController < ApplicationController
before_action :signed_in_user, only: [:new, :edit, :update]
def index
@console = ConsoleGeneral.order("eng_name").uniq.pluck(:eng_name)
end
def show
@console = Consoles.find(params[:id])
end
def new
@console = Consoles.new
@region_array = R... |
# -- immutable: string
module Swow
module Constants
REGIONS = %w(us eu kr tw).to_set
CHARACTER_FIELDS = %w(achievements appearance feed guild hunterPets items
mounts pets petSlots professions pvp quests reputation
statistics stats talents titles audit).to_set
GUILD_FIELDS = %w(member... |
# frozen_string_literal: true
#
# Cookbook:: postgresql
# Resource:: install
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
check_email
return render 'error' unless errors.empty?
@user.save
end
private
def user_params
params.require(:user).permit(:email)
end
def check_email
errors.push("Please ente... |
class Users::PersonalPresenter
def initialize(user)
@user = user
end
def companies
@companies ||= @user.companies.all
end
def comments_total
@count ||= @user.comments.count
end
end |
class DocumentIndexedSerializer < ActiveModel::Serializer
self.root = false
class GradeSerializer < ActiveModel::Serializer
attributes :id, :name
end
class DocumentIdentitySerializer < ActiveModel::Serializer
attributes :id, :name, :type
def id
object.identity.id
end
def name
... |
class Doctor < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
def apps_sort_by_patient
appointments.sort_by {|app| app.patient.name}
end
end
|
# frozen_string_literal: true
shared_examples "movie json" do
let(:data) { received["data"] }
let(:attributes) { data["attributes"] }
let(:relationships) { data["relationships"] }
it "renders correct types" do
expect(data["id"]).to be_kind_of(String)
expect(attributes["id"]).to be_kind_of(String)
... |
# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
# https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
# https://docs.fastlane.tools/plugins/available-pl... |
class CreateTasks < ActiveRecord::Migration[5.1]
def change
create_table :tasks do |t|
t.string :name, null: false
t.string :slug, null: false
t.string :state, default: 'new', null: false
t.timestamps
end
add_index :tasks, :name
add_index :tasks, :slug, unique: true
add_i... |
class WelcomeController < ApplicationController
def landing
if user_signed_in?
redirect_to "/users/edit"
end
end
end
|
class Admin::VendorsController < ApplicationController
include ControllerVerification
def vendor_params
# ownership_ids allow us to add existing tags (since it's not supported by nested attributes)
# nested attributes let us add new tags and remove existing ones
params.require(:vendor).permit(:name, :p... |
class Role < ApplicationRecord
has_many :user, dependent: :restrict_with_error
after_initialize :set_defaults
before_destroy :check_for_users
enum permission_levels: [:restricted, :default, :reviewer, :admin]
validates :title,
presence: true,
uniqueness: {case_sensitive: false},
length... |
require 'test_helper'
class JuiceMixesControllerTest < ActionController::TestCase
setup do
@juice_mix = juice_mixes(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:juice_mixes)
end
test "should get new" do
get :new
assert_response :su... |
namespace :slack do
desc 'Import users, groups, channels and messages from Slack'
task import: :environment do
Rails.logger.info 'Importing users'
SlackServices::UsersImporter.import
Rails.logger.info 'Importing groups'
SlackServices::GroupsImporter.import
Rails.logger.info 'Importing channels... |
class CreateGalleries < ActiveRecord::Migration
def change
create_table :galleries do |t|
t.string :title, null: true, comment: 'Название коллекции'
t.boolean :is_published, null: false, default: false, comment: '1 - Опубликовано'
t.timestamps null: false
end
... |
require 'rails_helper'
RSpec.describe FacilitiesManagement::UploadsController, type: :controller do
describe 'POST create' do
let(:suppliers) { [] }
before do
allow(FacilitiesManagement::Upload)
.to receive(:upload_json!)
end
context 'when the app has upload privileges' do
befor... |
class Admin::AddressesController < ApplicationController
before_action :confirm_logged_in
def index
end
def new
@address = Address.new
@customer = @address.build_customer
end
def create
# params = {address: {address:, address2:, district:, city_id:, postal_code:, ph... |
class CategoriesController < ApplicationController
layout :resolve_layout
def index
@roots = Category.where("ancestry IS NULL").order(:name)
@categories = Category.arrange(:order=>:name)
@categoria= Category.find_by_id(params[:category]).subtree.map(&:id) if params[:category]
@ads = Ad.find(:a... |
require 'net/http'
require 'digest'
require 'json'
class VK
def initialize access_token, secret = nil
@access_token = access_token
@secret = secret
end
def callMethod name, params
params.update("access_token" => @access_token){ |_, b, c| b || c } #если access_token указан то оставим его, иначе доб... |
class CreateFootnotes < ActiveRecord::Migration[5.0]
def change
create_table :footnotes do |t|
t.timestamps null:false
t.integer :blog_post_id, null:false, index:true
t.text :description
t.text :url
end
end
end
|
class Album < ActiveRecord::Base
# validation for attributes
validates :title, :presence => true
# 1:n relation between 'album' and 'photo'
# add this line in model 'album':
# ... belongs_to :album
has_many :photos
def created_at_date
created_at.to_datetime.strftime("%A %d %b %Y").squeeze(' ')
... |
class AddAccountIdToCreativeUrls < ActiveRecord::Migration
def change
add_column :creative_urls, :account_id, :string
add_index :creative_urls, :account_id
end
end
|
#encoding:utf-8
module Deepspace
class Weapon
attr_reader :name, :type, :uses
def initialize(name, type, uses)
@name = name
@type = type
@uses = uses
end
def self.newCopy(copy)
Weapon.new(copy.name, copy.type, copy.uses)
end
def power
return type.power
end
def useIt
... |
# frozen_string_literal: true
module Stardew
# A single schedule
class SchedulePossibility
attr_accessor :name, :notes, :priority, :routes
def initialize(name, routes, notes, priority:, rain: false)
@name = name.dup
@notes = notes.dup
@priority = priority.dup
@rain = rain.dup
... |
class Ingredient < ActiveRecord::Base
validates_presence_of :name, :description
def self.find_ingredients_all
find(:all, :order => "name")
end
end
|
#require 'packetfu'
require 'socket'
begin
host_port = ARGV[0].to_i
rescue
print "Invalid host port\n"
exit(1)
end
begin
server_address = ARGV[1]
rescue
print "Invalid server address\n"
exit(1)
end
begin
server_port = ARGV[2].to_i
rescue
print "Invalid server port\n"
exit(1)
end
print "Starting client with... |
require "rails_helper"
RSpec.describe RestaurantFoodType, type: :model do
it {should belong_to(:restaurant)}
it {should belong_to(:food_type)}
it {should_not belong_to(:user)}
end
|
class ManageIQ::Providers::IbmTerraform::Inventory::Persister::ConfigurationManager < ManageIQ::Providers::IbmTerraform::Inventory::Persister
def initialize_inventory_collections
add_collection(configuration, :configuration_profiles)
add_collection(configuration, :configured_systems)
add_collection(config... |
FactoryBot.define do
factory :destination_card do
postal_code {'123-4567'}
prefecture_id {2}
city {'テスト'}
address {'テスト1−1'}
house_name {'テスト'}
phone_number {'09012345678'}
token {'sample'}
end
end |
require 'key_flatten'
RSpec.describe KeyFlatten do
describe '.key_flatten' do
context 'without options' do
it 'flattens keys of Hash' do
expect(KeyFlatten.key_flatten({foo: 'bar'})).to eq({'foo' => 'bar'})
expect(KeyFlatten.key_flatten({foo: {bar: 'baz'}})).to eq({'foo.bar' => 'baz'})
... |
class Ingredient
attr_accessor :calorie_count, :name, :dessert
@@all = []
def initialize(name, dessert, calorie_count)
@name = name
@dessert = dessert
@calorie_count = calorie_count
@@all << self
end
def bakery
self.dessert.bakery
end
def self... |
require 'sqlite3'
require 'singleton'
class PlayDBConnection < SQLite3::Database
include Singleton
def initialize
super('plays.db')
self.ty_translation = true
self.results_as_hash = true
end
end
class Play
def self.all
end
def initialize(options)
@id = options['id']
@title = options['title']
@ye... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.ssh.insert_key = false
#Servidor que almacena logs
config.vm.define :elasticsearch_server do |elasticsearch_server|
elasticsearch_server.vm.box = "centos1706_v0.2.0"
elasticsearch_server.vm.network :private_netw... |
class NotificationsController < ApplicationController
def user_index
@notifications = Notification.where(target: current_user.id)
end
def create
@notification = Notification.where(event_id: params[:event_id], target: params[:user_id])
if @notification.empty?
@notification = Notification.... |
class Game
require 'yaml'
require 'date'
require 'io/console'
public
def play
welcome_screen
until game_over?
interact_with_board
end
game_over_screen
end
private
def game_over?
return true if @board.stalemate? || @board.checkmate?
end
def current_player
... |
# frozen_string_literal: true
## --- BEGIN LICENSE BLOCK ---
# Copyright (c) 2016-present WeWantToKnow AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including wit... |
class AddRatesUpdateToChain < ActiveRecord::Migration
def change
add_column :chains, :rates_update, :datetime
remove_column :chains, :prices_published
end
end
|
#encoding: utf-8
class UsersController < ApplicationController
before_filter :redirect_to_root_if_logged_in, only: [:signup, :login]
before_filter :set_return_to, only: [:signup, :show, :edit]
def signup
@user = User.new
end
def login
end
def create_login_session
user = User.find_by_email(param... |
module GTD::Renderers
class TmuxRenderer < Base
attr_reader :fname
def initialize(fname: "/tmp/tmux_gtd_statusbar")
@fname = fname
end
def render(worked: nil, total: nil)
File.open(fname, "w") do |f|
f << bar(worked: worked, total: total)
end
end
def cleanup
... |
class PlantSerializer
include FastJsonapi::ObjectSerializer
attributes :image
attributes :name
attributes :species
attributes :description
attributes :light_requirements
attributes :water_requirements
attributes :when_to_plant
attributes :harvest_time
attributes :common_pests
attributes :id
h... |
require 'test_helper'
class PatientTest < ActiveSupport::TestCase
test "belongs_to room doctor association" do
assert_not patients(:one).doctor.nil?
assert_not patients(:one).room.nil?
end
test "has_many nurses association" do
assert_equal 1, patients(:one).nurses.size
end
... |
# -*- encoding : utf-8 -*-
class AdmissionsAdmin::AdmissionsController < ApplicationController
layout 'admissions'
filter_access_to [:show, :statistics]
def show
@admission = Admission.find(params[:id])
@my_groups = current_user.my_groups
@job_application = JobApplication.new
if @my_groups.lengt... |
class ResourceManagersController < ApplicationController
before_filter :authenticate_user!, :except=>[:activate]
before_filter :is_admin
def index
if params[:id].blank? || params[:id].nil?
if current_user.is_super_admin?
@resources=ResourceManager.order.page(params[:page]).per(15)
else
... |
require ('rspec')
require ('scrabble_score')
describe('String#scrabble_score') do
it("returns a scrabble score for a letter") do
expect("a".scrabble_score()).to(eq(1))
end
it("returns a scrabble score of 2 for letters D or G") do
expect("d".scrabble_score()).to(eq(2))
end
it("returns a scrabble score... |
class AddPoiIdToPoiData < ActiveRecord::Migration
def change
add_column :poi_data, :poi_id, :integer
add_index :poi_data, [:poi_id, :created_at]
end
end
|
# -*- coding: utf-8 -*-
# DO NOT EDIT THIS FILE!
# Represents a playing card.
class Card
SUIT_STRINGS = {
clubs: :black,
diamonds: :red,
hearts: :red,
spades: :black
}
VALUE_STRINGS = {
ace: 1,
deuce: 2,
three: 3,
four: 4,
five: 5,
six: 6,
... |
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe "ユーザー新規登録" do
it 'nicknameが空では登録できない' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'emailが空で... |
class Backend::SongPoemsController < Backend::BaseController
load_and_authorize_resource
def index
@q = SongPoem.ransack(params[:q])
@song_poems = @q.result.page(params[:page])
end
def new
end
def create
@song_poem.save
respond_with @song_poem, location: -> { [ :backend, SongPoem ] }
e... |
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'set_of_ranges/version'
Gem::Specification.new do |gem|
gem.name = "set_of_ranges"
gem.version = SetOfRanges::VERSION
gem.authors = ["Galen Palmer"]
gem.emai... |
class PlantCategory < ActiveRecord::Base
belongs_to :plant_category
has_many :genus
has_many :plants
scope :roots, lambda { where(:plant_category_id => nil ) }
scope :children, lambda { |id| where(:plant_category_id => id) }
attr_accessible :description, :lat_name, :name
attr_accessible :plant_category_... |
class CommentsController < ApplicationController
before_action :authenticate_user!, only: [:new, :edit, :create, :update, :destroy]
before_action :set_comment, except: [:index, :create]
# before_action :set_comment, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :set_post, only: [:sh... |
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
Rails.application.load_tasks
require 'rake/testtask'
require 'resque/tasks'
# unit tests
Rake::TestT... |
class CreateDogs < ActiveRecord::Migration[5.2]
def change
create_table :dogs do |c|
c.string :name
c.date :birthday
c.string :breed
end
end
end
|
class TestServiceWithAirbrake
include ExecuteWithRescue::Mixins::WithAirbrake
def call
execute_with_rescue do
do_something
end
end
private
def do_something
# do nothing
end
end
class TestServiceWithAirbrakeWithError < TestServiceWithAirbrake
def do_something
fail StandardError
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.