text stringlengths 10 2.61M |
|---|
#!/usr/local/opt/ruby/bin/ruby
# encoding: UTF-8
# frozen_string_literal: true
=begin
Script qui permet de "builder" un fichier Markdown, c'est-à-dire
de produire le fichier HTML ou le fichier PDF avec la commande
CMD-B
TODO
* Tester tous les cas : avec fichier .css, avec fichier .sass,
avec temp... |
class ButtonLabel < Draco::Component
attribute :text
attribute :size, default: 0
attribute :padding, default: 12
end
|
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.page params[:page]
end
# GET /comments/1
# GET /comments/1.json
def show
end
private
# Use callbacks to s... |
class BuildingsController < ApplicationController
before_action :authenticate_user!
before_action :set_company
before_action :set_building, only: [:show, :edit, :update, :destroy]
def index
@buildings = @company.buildings.all
end
def show
@meeting_rooms = @building.meeting_rooms
end
def new
... |
class CreateRestaurants < ActiveRecord::Migration[5.1]
def change
create_table :restaurants do |t|
t.string :name
t.integer :cuisine_id
t.integer :rating
t.boolean :accept_10_bis
t.float :lat
t.float :lon
t.string :max_delivery_time
t.timestamps
end
end
end
|
## Generated from bartender.proto for spotify.bartender.proto
require "beefcake"
module SpotifyWeb
module Schema
module Bartender
module FallbackArtistType
TYPE_UNKNOWN_FALLBACK = 0
TYPE_FOLLOWED_ARTIST = 1
TYPE_LOCAL_TRACK_ARTIST = 2
end
module RecentArtistType
... |
DB.create_table? :movements do
primary_key :id
foreign_key :room_name, :rooms, type: String
String :north
String :south
String :east
String :west
String :up
String :down
end
#The Movement class, specifies the valid movements in the room
class Movement < Sequel::Model
def room
Room[self.room_name... |
class SendEmailUserRequestWorker
include Sidekiq::Worker
def perform id
@request = Request.find_by id: id
@request.send_email_to_user_request if @request.nil?
end
end
|
require 'uuidtools'
require 'rails/mongoid'
class Note
include Mongoid::Document
include Mongoid::Timestamps::Created
store_in collection: "notes", database: "NotesWSD2021"
field :_id, type: String, default: ->{ SecureRandom.uuid.to_s}
field :title, type: String
field :text, type: String
... |
RSpec.shared_examples "interest acknowledgement worker" do
context "with an invalid id" do
it "returns :record_not_found when performed" do
expect(subject.perform(nil)).to eq :record_not_found
end
end
context "with a valid id" do
let :element do
described_class.to_s.gsub(/Acknowledgement... |
require 'net/https'
module Kender
# This module abstracts access to GitHub. It's current, sole purpose is to
# allow commit statuses to be created.
#
# See: https://github.com/blog/1227-commit-status-api
#
module GitHub
extend self
# Update the commit status for the current HEAD commit. Assumes t... |
class Route
attr_reader :stations
def initialize(first_station, last_station)
@stations =[first_station, last_station]
end
def add_station(station)
@stations.insert(-2, station)
end
def remove_station(station)
@stations.delete(station)
end
def print_route
puts @stations
end
end
|
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5'
# Use postgresql as the database for Active Record
gem 'mysql2', '~> 0.3.18'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1... |
class Race < ActiveRecord::Base
include Coded
serialize :body_options
def support_class
"Race::#{code.titleize.gsub(/\s/,"")}".constantize
end
def quadruped?
code == "centaur"
end
def description
support_class.description
end
def demonic?
group == "demon"
end
# Gets the skin ... |
module Eventable
extend ActiveSupport::Concern
included do
has_many :events, as: :source
after_create :touch_created_event
before_destroy :touch_destroyed_event
after_save :touch_finished_event
after_save :touch_assign_user_event
after_save :touch_change_user_event
after_save :touch_ch... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
config.vm.box = "hashicorp/precise64"
config.vm.define :nginxCodeTest
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.provider "virtualbox" do |vb|
vb.gui = false
vb.memory = "1024"
end
config.vm.synced... |
require 'rails_helper'
describe Users::NotificationService do
let(:user) { create(:user) }
before { ActionMailer::Base.deliveries.clear }
it 'notifies a user' do
subject.call(user, message: 'msg', link: 'link')
expect(user.notifications.size).to eq(1)
notification = user.notifications.first
ex... |
require 'spec_helper'
module Anticipate
describe Anticipate do
include Anticipate
let :anticipator do
mock("anticipator")
end
before do
anticipator.stub!(:anticipate).and_yield
end
describe "trying_every(n).seconds" do
it "yields" do
called = false
... |
class AddDefaultValueToUserLevelsCompleted < ActiveRecord::Migration
def up
change_column :user_levels, :completed, :boolean, :default => false
end
def down
change_column :user_levels, :completed, :boolean, nil
end
end
|
require_relative 'feature_spec_helper'
describe "A user who is not logged in" do
it "cannot access the checkout page" do
order = create :order
item = create :item
order.items << item
visit order_path(order)
expect(page).to_not have_content('Proceed to Checkout')
end
end
describe 'A user who... |
require "rails_helper"
RSpec.describe SendParticipantToVoicemail do
describe "#call" do
it "creates a new call with the existing participant" do
user = create(:user)
participant = build_stubbed(:participant)
stub_const("ConnectCallToVoicemail", spy(call: Result.success))
result = describ... |
class Objective < ActiveRecord::Base
belongs_to :user
validates :description, presence:true
validates :due, presence:true
end
|
# frozen_string_literal: true
desc "Add pokemon from the Johto region"
task populate_johto_pokemon: :environment do
start_time = Time.now
PopulatePokemon::Service.new(152, 251, "Johto").populate
time_diff = Time.at(Time.now - start_time).utc.strftime("%T")
puts "\nProcess finished in #{time_diff}."
end
|
=begin
Base class for all of our profile controllers. This class takes care of setting up
@profile_mode (my_home/aboutme), setting up @user (the user who's information we are
interested in). This class also handles protecting access to private
data (my_home) by insuring appropriate authentication and sessio... |
class Utilisateur
attr_accessor :nom
def initialize(nom)
@nom = nom
end
end
victor = Utilisateur.new("Victor Poiraud")
puts victor.nom
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: skills
#
# id :integer not null, primary key
# deleted_at :datetime
# skill_description :text
# skill_name :string not null
# created_at :datetime not null
# updated_at :dat... |
# GSPlan - Team commitment planning
#
# Copyright (C) 2008 Jan Schrage <jan@jschrage.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the License,
# or (at your option) ... |
class CreateAccountCredentials < ActiveRecord::Migration
def change
create_table :account_credentials do |t|
t.string :uid
t.string :token
t.string :token_secret
t.string :account_type
t.references :user
t.timestamps
end
end
end
|
# frozen_string_literal: true
class CreateScores < ActiveRecord::Migration[5.2]
def change
create_table :scores do |t|
t.date :wakeup_on, null: false
t.integer :score, null: false
t.string :reason, limit: 50, null: false
t.string :cause, limit: 50
t.timestamps
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ProductController, type: :controller do
render_views
describe 'GET #show' do
let(:product) { create :product }
subject { get :show, params: { id: product.id } }
context 'show product' do
it 'it render show view' do
is_... |
class PoorPokemon::Pokemon
attr_accessor :name, :type1, :type2, :hp, :att, :def, :spAtt, :spDef, :spd, :moves
def initialize(arr, flag=false)
#flag is for enemy to have perfect stats
@name, @type1, @type2, @hp, @att, @def, @spAtt, @spDef, @spd = arr
#Determines proper stats
#https://www.dragonfly... |
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(collection)
output = []
collection.each_with_index do |el, idx|
if el.split("").sort.join == word.split("").sort.join
output << collection[idx]
end
end
output
end
end
|
class AddParentToSpreeProperties < ActiveRecord::Migration
def change
add_reference :spree_properties, :parent, index: true
add_column :spree_properties, :position, :integer, default: 0
add_column :spree_properties, :lft, :integer, default: 0
add_column :spree_properties, :rgt, :integer, default: 0
... |
class Station < ActiveRecord::Base
has_many(:gas)
end
|
require "formula"
class Rsnapshot < Formula
homepage "http://rsnapshot.org"
stable do
url "http://rsnapshot.org/downloads/rsnapshot-1.3.1.tar.gz"
sha1 "a3aa3560dc389e1b00155a5869558522c4a29e05"
# Fix pod2man error; docs in HEAD do not have this problem
patch :DATA
end
head "https://github.co... |
require 'rails_helper'
RSpec.describe Playlist, type: :model do
it{ should belong_to :user }
it{ should have_many :videos }
it{ should validate_presence_of(:name)}
end
|
class CreateArtistBalances < ActiveRecord::Migration[6.1]
def change
create_table :artist_balances do |t|
t.references :artist, null: false, foreign_key: true
t.float :balance, null: false
t.timestamps
end
end
end
|
require 'spec_helper'
require 'lib/brewery_db/webhooks/shared_examples/events'
require 'lib/brewery_db/webhooks/shared_examples/social_accounts'
require 'brewery_db/webhooks/brewery'
describe BreweryDB::Webhooks::Brewery do
let(:model_id) { 'g0jHqt' }
let(:response) do
yaml = YAML.load_file("spec/support/vcr_c... |
class StaffAdmin::ChoferesController < StaffAdminController
include Geokit::Geocoders
add_breadcrumb "index", :staff_admin_choferes_path, :title => "Back to the Index"
rescue_from CanCan::AccessDenied do |exception|
redirect_to staff_admin_choferes_path, :alert => exception.message
end
def index
... |
class CreateInvitationsAndGuests < ActiveRecord::Migration[5.1]
def change
create_table :invitations do |t|
t.string :rsvp_code, null: false
t.string :addressee, null: false
t.string :address_line_1, null: false
t.string :address_line_2
t.string :city, null: false
t.string :sta... |
require_relative "Move.rb"
class Knight
attr_accessor :position
def initialize(position=[0, 0])
@position = Move.new(position, -1)
end
def knight_moves(starting_pos=@position, ending_pos=@position)
move_list = []
move_list.push(starting_pos)
i = 0
while(move_list[i].position != end... |
module SubstAttr
module Substitute
module NullObject
extend self
def build(interface=nil)
if interface
return strict(interface)
end
weak
end
def strict(interface)
Mimic.(interface, record: false)
end
def weak
Weak.new
... |
require "rails_helper"
RSpec.describe Publisher, type: :model do
describe ".publish" do
let(:compute_engine) { class_double(ComputeEngine).as_stubbed_const }
let(:project) { create(:project, id: "13371337-1337-1337-1337-133713371337") }
before { allow(compute_engine).to receive(:insert_instance) }
... |
FactoryGirl.define do
factory :restaurant, :class => Restaurant do |f|
f.user_id 0
f.menu_uid 0
f.slug "#{Faker::Name.name}#{Time.now.to_i}"
f.name {Faker::Name.name}
f.address {Faker::Address.street_address}
f.description 'Description'
f.phone Faker::Number.number(10)
f.email { Fak... |
class ForoMigration < ActiveRecord::Migration
def self.up
create_table :follows, :force => true do |t|
t.references :followable, :null => false
t.references :follower, :null => false
t.boolean :blocked, :default => false, :null => false
t.timestamps
end
add_index :follows, :foll... |
class RemoveIntroFacFromFaculities < ActiveRecord::Migration[5.1]
def change
remove_column :faculities, :intro_fac, :text
end
end
|
# モンスターの情報を管理するモデル
class Monster < ApplicationRecord
belongs_to :skill
with_options class_name: 'Attribute' do
belongs_to :element, foreign_key: :element_id
belongs_to :sub_element, foreign_key: :sub_element_id
end
has_many :monster_species
has_many :species, through: :monster_species
end
|
class Post < ApplicationRecord
belongs_to :user, optional: true
validates :title, presence: true
validates :body, presence: true
validates :title, uniqueness: {
message: "You can't have two posts with the same title."
}
def content_html
Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(body)
en... |
class Order < ApplicationRecord
belongs_to :user
belongs_to :item
has_one :address_info
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :shipping_area
end
|
class StepsTaken < ActiveRecord::Base
validates :steps_taken, presence: {message: 'You must enter the number of steps taken'}
validates :date_walked, presence: {message: 'You must enter a date for when you walked'}
end
|
DB = Sequel.connect(ENV['DATABASE_URL'])
class MP < Sequel::Model
BASE_URL = 'http://www.parliament.nz'
def self.parse(name, link, electorate_details, image)
last_name, first_name = name.split(',').map(&:strip)
electorate, party, list_mp = parse_electorate(electorate_details)
new(details_url: link,
... |
require 'spec_helper'
describe Guard::Notifier::GNTP do
let(:fake_gntp) do
Class.new do
def self.notify(options) end
end
end
before do
subject.stub(:require)
stub_const 'GNTP', fake_gntp
end
describe '.available?' do
context 'without the silent option' do
it 'shows an error... |
class MealAvailabilityLocation < ApplicationRecord
belongs_to :meal_availability
belongs_to :city
end
|
class AddSelectColorSchemaAtIssueToEasySettings < ActiveRecord::Migration
def change
EasySetting.create(:name => 'issue_color_scheme_for', :value => 'issue_priority')
end
end
|
module Api
module V1
class CartsController < ApplicationController
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate
def add_product
result = Cart.add_product(current_user.id, params[:product_id], params[:quantity])
if result[:error].present?
... |
class Image
attr_accessor :arr
def initialize(arr)
@arr = arr
end
def output_image(arr=@arr)
arr.each do |x|
x.each do |y|
print y
end
puts
end
end
def inside_matrix?(x, y)
x >= 0 && x <= @arr.size && y >= 0 && y <= @arr.first.size - 1
end
def manhattan(x1,y... |
class Interview < ActiveRecord::Base
include DateAndTimeMethods
belongs_to :user
belongs_to :application_record
delegate :department,
:position,
to: :application_record
validates :completed,
:hired,
inclusion: { in: [true, false], message: 'must be true or false... |
class StandardsController < InheritedResources::Base
def index
@standards = Standard.all
render component: 'Standards', props: { standards: @standards }
end
def create
@standard = Standard.new(standard_params)
if @standard.save
render :json => @standard
end
end
def update
... |
require 'spec_helper'
describe Circuit::Rack::Behavioral do
include Rack::Test::Methods
include SpecHelpers::MultiSiteHelper
class RenderMyMiddlewareBehavior
include ::Circuit::Behavior
use(Class.new do
def initialize(app)
@app = app
end
def call(env)
[200, {"Content-... |
class CreateUoms < ActiveRecord::Migration
def self.up
create_table :uoms do |t|
t.string :uom, :null => false
t.string :note
t.integer :updated_id # users
t.integer :created_id # users
t.timestamps
end
end
def self.down
drop_table :uoms
end
end
|
class CreateAllowedMethods < ActiveRecord::Migration
def change
create_table :allowed_methods do |t|
t.integer :challenge_id, :null => false
t.string :method, :null => false
t.timestamps
end
end
end
|
class ProductQuestionsWidenLabel < ActiveRecord::Migration
def self.up
change_column :product_questions, :label, :string, :limit => 128
end
def self.down
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# username :string not null
# password_digest :string not null
# session_token :string not null
# created_at :datetime not null
# updated_at :datetime ... |
require 'openstudio'
require 'json'
class OSModel < OpenStudio::Model::Model
def add_geometry(coords, gridSize, floors, floorHeight, wwr, name)
winH = floorHeight * wwr
wallH = (floorHeight - winH) / 2
bldgH = floors * floorHeight
wwrSub = (((winH - 0.05)* (gridSize - 0.05)) / (winH * gridSize)) - ... |
class Box < ApplicationRecord
# has_many :collections
# has_many :recipes, through: :collections
has_many :recipes
end
|
#!/usr/bin/ruby
# On Red Hat /etc/localtime is a copy of the relevant timezone file from
# /usr/share/zoneinfo. If Red Hat releases updated timezone data (via a
# new tzdata RPM) the files in /usr/share/zoneinfo get updated, but
# /etc/localtime does not. So we have etch manage /etc/localtime, this
# script feeding ... |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe RailsAdmin::Config::Fields::Types::StringLike do
describe '#treat_empty_as_nil?', active_record: true do
context 'with a nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :name
... |
require 'vanagon/engine/base'
require 'vanagon/logger'
require 'yaml'
### Note this class is deprecated in favor of using the ABS Engine. The pooler has changed it's API with regards to
# getting VMs for ondemand provisioning and would need to be updated here.
# See DIO-1066
class Vanagon
class Engine
class Poo... |
class CreatePermissions < ActiveRecord::Migration
def change
create_table :permissions do |t|
t.string :subject_class, limit: 60, default: ""
t.string :action, null: false, limit: 50, default:""
t.string :name, null: false, limit: 50, default:""
t.timestamps
end
create_table :per... |
class PostPolicy < ApplicationPolicy
def index?
true
end
def destroy?
user.present? && (record.user == user || user.admin? || user.moderator? )
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if @us... |
# Copyright (C) 2011-2014 Tanaka Akira <akr@fsij.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and t... |
class MixTask < Task
def initialize
super('Mix that batter up!')
end
def time_required
3 # Mix for 3 minutes
end
end
|
require 'spec_helper'
require 'animal_quiz/property'
require 'animal_quiz/question'
require 'animal_quiz/question_list'
require 'support/animal_properties_context'
require 'support/animal_questions_context'
describe AnimalQuiz::QuestionList do
include_context 'Animal Properties'
include_context 'Animal Questions'... |
# Modelo MotivoConsulta
# Tabla motivos_consulta
# Campos id:integer
# motivo:string
# created_at:datetime
# updated_at:datetime
class MotivoConsulta < ActiveRecord::Base
has_many :motivos_episodio_consulta, inverse_of: :motivo, dependent: :destroy
validates :motivo, presence: true, uniqueness... |
require 'http_parser.rb'
require 'websocket_parser'
require 'base64'
require 'digest/sha1'
require 'securerandom'
module Microprocess
use "http/5"
def ws_server(ip, port)
server(ip, port, WS::Server)
end
def ws_connect(ip, port)
connect(ip, port, WS::Client::Socket)
end
module WS
PROTOCOL_VE... |
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @param {Integer} x
# @return {ListNode}
def partition(head, x)
return head if head == nil
less_tha... |
class Motion; class ImageEditorView < UIView
def initWithFrame(frame)
super.tap do |view|
view.opaque = false
view.layer.opacity = 0.7
view.backgroundColor = UIColor.clearColor
view.addSubview(image_view)
view.setup_constraints
end
end
def setup_constraints
... |
require 'tb'
require 'test/unit'
class TestTbNDJSON < Test::Unit::TestCase
def parse_ndjson(ndjson)
Tb::NDJSONReader.new(StringIO.new(ndjson)).to_a
end
def generate_ndjson(ary)
writer = Tb::NDJSONWriter.new(out = '')
ary.each {|h| writer.put_hash h }
writer.finish
out
end
def test_reade... |
#!/usr/bin/env ruby
#tf_idf, tf_sub, fo, len, kp_freq
def getFeatures(str)
hash = Hash.new
tmpArray = str.split(/,/)
for tmp in tmpArray do
subArray = tmp.split(/=/)
key = subArray[0].strip
value = subArray[1].strip
hash["#{key}"] = value
end
return hash
end
path = ARGV[0]
arffFile = ARGV[1]... |
module Spree
class PurchaseOrderPayments < PaymentMethod
def payment_source_class
PurchaseOrderCheckout
end
def authorize(amount, source, gateway_options)
order_number = gateway_options[:order_id][/(\w+)-/,1]
order = Order.find_by_number(order_number)
if order && order.user && ord... |
# frozen_string_literal: true
require "rake"
require "rumrunner/manifest"
module Rum
##
# Defines the DSL methods for Rum Runner.
module DSL
private
##
# Rum base task block.
#
# Example
# rum :amancevice/rumrunner do
# tag %x(git describe --tags --always)
# # ...
... |
describe Nanoc::Int::Item do
it_behaves_like 'a document'
describe '#freeze' do
let(:item) { described_class.new('Hallo', { foo: { bar: 'asdf' } }, '/foo.md') }
before do
item.freeze
end
it 'prevents changes to children' do
expect { item.children << :lol }.to raise_frozen_error
en... |
require 'pathname'
module Logging
class LogDirectoryError < RuntimeError
end
class NullLogger
def unknown(*); end
def debug(*); end
def info(*); end
def warn(*); end
def error(*); end
def fatal(*); end
end
class << self
def logger=(new_logger)
@logger = new_logger
end
def logger
@logge... |
require 'test_helper'
class Fluent::PapertrailTest < Test::Unit::TestCase
class TestSocket
attr_reader :packets
def initialize()
@packets = []
end
def puts(message)
@packets << message
end
end
def setup
Fluent::Test.setup
@driver = Fluent::Test::BufferedOutputTestDrive... |
require 'rss'
require 'open-uri'
class RSSFeed
def initialize
puts "Enter RSS URL:"
puts
url = gets.chomp
read(url)
end
def read(url)
open(url) do |rss|
feed = RSS::Parser.parse(rss)
puts "Title: #{feed.channel.title}"
feed.items.each do |item|
puts "Item: #{item.ti... |
#! /usr/bin/env ruby
require 'kramdown'
require 'erb'
require 'stringio'
require 'base64'
require 'optparse'
require 'listen'
require 'rubydown'
def get_context
binding
end
class EvalDoc < Kramdown::Document
attr_accessor :context, :stdout
attr_reader :javascripts
def initialize(text, *opts)
super(text... |
module Support
module Paypal
module AdaptivePayments
module Pay
module Stub
def stub_paypal_pay!
allow_any_instance_of(::PayPal::SDK::AdaptivePayments::API).to receive(:pay).
and_return Pay.successful_response
end
def stub_paypal_pay_failure!... |
class AddDataSheetToDataTables < ActiveRecord::Migration[5.0]
def self.up
add_attachment :data_tables, :data_sheet
end
def self.down
remove_attachment :data_tables, :data_sheet
end
end
|
# This migration comes from refinery_elephants (originally 1)
class CreateElephantsElephants < ActiveRecord::Migration
def up
create_table :refinery_elephants do |t|
t.string :headline
t.string :link
t.integer :photo_id
t.string :author
t.integer :position
t.timestamps
en... |
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
class RenameBusinessLogoToAvatarInUsers < ActiveRecord::Migration
def change
rename_column :users, :business_logo, :avatar
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :username, presence: true, uniqueness: true
... |
namespace :demo do
desc "Reset Database"
task database: :environment do
Rake::Task['db:drop'].execute
Rake::Task['db:create'].execute
Rake::Task['db:migrate'].execute
Rake::Task['db:seed'].execute
end
end
|
# == Schema Information
#
# Table name: conversations
#
# id :bigint not null, primary key
# sender_id :bigint
# recipient_id :bigint
# identifier :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Conversation < ApplicationRecord
bel... |
module Base62
# http://refactormycode.com/codes/125-base-62-encoding
BASE62_CHARS = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a
BASE62_MAP = {}
BASE62_CHARS.zip((0..61).to_a){|ch,num| BASE62_MAP[ch]=num }
def self.i_to_s i
return '0' if i == 0
s = ''
while i > 0
s << BASE62_CHARS[i... |
class FriendsController < ApplicationController
before_action :set_friend, only: [:destroy]
def index
end
def friend_request
user_friend = User.find(params[:user])
#Criando a solicitação de amizade do usuário on-line
friend = Friend.new
friend.user_id = current_user.id
friend.friend_id = u... |
class Ability < ActiveRecord::Base
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :admin
can :manage, :all
else
can :read, :all
if user.role?(:seller)
can :create, Product
can :update, Product do |product|
product.t... |
require 'rails_helper'
describe User do
describe '#create' do
# 入力されている場合のテスト ▼
it "全ての項目の入力が存在すれば登録できること" do # テストしたいことの内容
user = build(:user) # 変数userにbuildメソッドを使用して、factory_botのダミーデータを代入
expect(user).to be_valid # 変数userの情報で登録がされるかどうかのテストを実行
end
it "nameがない場合は登録できないこと" do # テストしたいことの... |
class Acme::RegistrationsController < Devise::RegistrationsController
before_filter :configure_account_update_params, only: [:update]
def configure_account_update_params
devise_parameter_sanitizer.for(:account_update){ |u| u.permit(:image_uid, :image_name, :mobile_number, :prenom, :email, :password, :current_p... |
# Preview all emails at http://localhost:3000/rails/mailers/enquiry_mailer
class EnquiryMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/enquiry_mailer/created
def created
EnquiryMailer.created
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.