How to do that I have got resource in sinatra
http://localhost:port/resource.json ??
Install the json gem:
sudo gem install json
then just
require 'json'
get '/resource.json' do
content_type :json
{ :name => 'Michal', :location => 'unknown' }.to_json
end
Related
I'm having a problem in Sinatra where I can't respond with just a json and I can't find good sinatra docs anywhere, most of things seems outdated.
Anyways, here's the code:
module MemcachedManager
class App < Sinatra::Base
register Sinatra::Contrib
helpers Sinatra::JSON
get '/' do
json({ hello: 'world' })
end
end
end
MemcachedManager::App.run! if __FILE__ == $0
The response that I do get is:
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><p>{\"hello\":\"world\"}</p></body></html>\n"
Where it should have been only the json part. Why is it rendering html tags when I didn't ask for it?
Have you seen this blog post?
require 'json'
get '/example.json' do
content_type :json
{ :key1 => 'value1', :key2 => 'value2' }.to_json
end
I would also modify this to:
get '/example.json', :provides => :json do
to stop HTML/XML calls using the route. Since you're using the sinatra-contrib gem, and since Ruby doesn't need all those parens etc, you can also simplify the code you've given as an example to:
require 'sinatra/json'
module MemcachedManager
class App < Sinatra::Base
helpers Sinatra::JSON
get '/', :provides => :json do
json hello: 'world'
end
end
end
MemcachedManager::App.run! if __FILE__ == $0
Try putting
content_type :json
before the json(...) call
I am trying to use HTTParty in my class FindXYZ extending Thor but it is not working. All I wish to do is use HTTParty get to query couchdb in my method xyz
When I try to run I see error cannot find get
require 'json'
require 'httparty'
require 'thor'
class FindXyz < Thor
include Thor::Actions
include HTTParty
headers 'Accept' => 'application/json'
server = '192.168.5.50:5984'
user = 'uname'
password = 'passo'
couchdb_url = "http://#{user}:#{password}##{server}"
basic_auth user, password
base_uri couchdb_url
default_params :output => 'json'
format :json
desc "xyz", "Find scenarios that contains SSL"
method_option :name, :aliases => "-t", :required => true
method_option :location, :aliases => "-s",:required => true
def xyz
name = options[:name]
loc = options[:location]
file_path = File.join(loc, name)
t_json = JSON.parse(File.read(file_path))
t_json["ids"].each do |temp|
path_to_doc = "/test123/#{temp}"
response = get(path_to_doc)
puts "Found => #{temp}" if response.to_s.include?('Birdy')
end #close the loop
end #close the method xyz
end #close class
Try it this way from outside the class
puts FindXyz.get('....').inspect
and HTTParty.get(...) inside FinXyz class
I'm trying to use mocha outside of unit tests to mock an Net::HTTPResponse object. here is a simple example:
#!/usr/bin/env ruby -w
require 'net/http'
require 'rubygems'
require 'mocha'
response = mock('Net::HTTPResponse')
response.stubs(:code => '500', :message => "Failed", :content_type => "text/plaint", :body => '')
I get this error:
undefined method `mock' for main:Object (NoMethodError)
I'd recommend using the fakeweb gem for this. It's designed to stub out http requests.
require 'rubygems'
require 'fakeweb'
FakeWeb.register_uri(:get, "http://something.com/", :body => "", :status => ["500", "Server Error"])
More info: https://github.com/chrisk/fakeweb
I'm trying to use paperclip with heroku and s3, but I have many tables that can be associated with photos, we'll use :review for example.
I'm trying to seperate the photo from the review and upload that seperately, but since I'm new to ruby, I think I'm failing miserably.
I have the 'aws-s3' gem installed and bundled.
This is the error I'm getting:
LoadError in ReviewsController#create
no such file to load -- aws/s3 (You may need to install the aws-s3 gem)
Rails.root: C:/www/devise
Application Trace | Framework Trace | Full Trace
app/controllers/reviews_controller.rb:56:in `new'
app/controllers/reviews_controller.rb:56:in `block in create'
app/controllers/reviews_controller.rb:54:in `create'
app/controllers/redirect_back.rb:23:in `store_location'
This error occurred while loading the following files:
aws/s3
photo Model:
class Photo < ActiveRecord::Base
belongs_to :user
belongs_to :shop
belongs_to :baristum
belongs_to :review
#paperclip
has_attached_file :photo,
:styles => {
:thumb=> "100x100#",
:small => "400x400>",
:original => "800x800" },
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => "/:style/:id/:filename"
end
photo schema:
t.string "file_name"
t.string "content_type"
t.integer "file_size"
t.integer "user_id"
t.integer "barista_id"
t.integer "review_id"
t.integer "shop_id"
t.datetime "created_at"
t.datetime "updated_at"
review Controller:
def create
#add the current user to the review hash, from the session var.
params[:review][:user_id] = current_user.id
#move the photo to another var, so I can remove it from the review insert
#photoUpload = params[:review][:photo]
params[:review].delete("photo")
#review = Review.new(params[:review])
respond_to do |format|
if #review.save
#photo = Photo.new(:photo => #photoUpload, :review_id => #review.id)
#photo.save
format.html { redirect_to(#review, :notice => 'Review was successfully created.') }
format.xml { render :xml => #review, :status => :created, :location => #review }
else
#shopList = Shop.find(:all)
format.html { render :action => "new" }
format.xml { render :xml => #review.errors, :status => :unprocessable_entity }
end
end
end
gemfile
source 'http://rubygems.org'
gem 'pg'
gem 'rake', '~> 0.8.7'
gem 'rails', '3.0.5'
#gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'devise', :git => 'git://github.com/plataformatec/devise', :branch => 'master'
gem 'omniauth', '0.2.0'
gem 'paperclip'
#gem 'RMagick'
gem "simple_form", "~> 1.2.2"
gem 'twitter_oauth', '0.4.3'
gem "rest-client", "1.6.1", :require => "restclient"
gem "sluggable"
gem 'gmaps4rails'
gem 'exception_notification', :require => 'exception_notifier'
gem 'yaml_db'
#gem 'mysql'
gem 'aws-s3'
#gem 'carrierwave'
#gem 'fog' #amazon s3
#gem 'nokogiri'
group :development, :test do
gem 'rspec-rails'
gem 'fixjour'
end
When you include in your gem file the 'aws-s3' gem remember to add the require statement.
gem 'aws-s3', :require => 'aws/s3'
Current versions of Paperclip use the aws-sdk gem, rather than the aws-s3 gem.
Try running the latest version of that gem, combined with the latest version of Paperclip which supports your Rails stack (Paperclip 2.x for Rails 2.3, or Paperclip 3.x for Rails 3+).
Looks like you need to have the following fields in your photos schema.
t.string :file_file_name
t.string :file_content_type
t.integer :file_file_size
t.datetime :file_updated_at
running this will generate a migration for you to do just that
#this convention: rails generate paperclip [model] [attachmentname]
rails generate paperclip photo file
You have to have the table columns named following this convention for paperclip to pick them up: 'attachmentname'_file_name, 'attachmentname'_content_type, etc... Where you're calling your Photo model's has_attachment "file".
I'm trying to use ActionMailer without Rails in a project, and I want to use Haml for the HTML email templates. Anyone have any luck getting this configured and initialized so that the templates will be found and rendered? I'm currently getting errors like:
ActionView::MissingTemplate: Missing template new_reg/daily_stats/full with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en]} in view paths "/home/petersen/new_reg/lib/new_reg/mailers/views"
To clarify, this is ActionMailer 3.0.4
Looks like the issue is that without the full Rails stack, Haml doesn't completely load, specifically the Haml::Plugin class. Adding require 'haml/template/plugin' after the normal require 'haml' line seems to solve the problems.
require 'haml/template/plugin' in the "configure do" block together with ActionMailer::Base.view_paths = "./views/" did it for me (Sinatra)
Not necessary in Rails -- but since you're using ActionMailer without Rails -- did you specify ActionMailer::Base.register_template_extension('haml')?
I'm seeing a similar issue and am using ActionMailer 3.0.3. register_template_extension does not exist in ActionMailer 3.
I'm using Sinatra. I've got mailer.rb (below) in APP_ROOT/lib and the views are located in APP_ROOT/views/mailer. This sends an email with a subject, the body is blank though.
require 'action_mailer'
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.view_paths = File.dirname(__FILE__)+"/../views/"
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => 'exmaple.com',
:user_name => 'user#exmaple.com',
:password => 'password',
:authentication => 'plain',
:enable_starttls_auto => true }
class Mailer < ActionMailer::Base
def new_comment_notifier(post,comment)
#post = post
#comment = comment
mail(:to => "user#example.com",
:subject => "new comment on: #{post.title}")
end
end