I'm using Redcarpet gem for markdown and i wanna to generate automatic anchors for h2 titles to allow linking to each section.
show.html.erb
<div class = "content"><%= markdown(#post.body) %></div>
application_helper.rb
class HTMLwithPygments < Redcarpet::Render::HTML
def block_code(code, language)
Pygments.highlight(code, :lexer => language)
end
end
def markdown(text)
renderer = HTMLwithPygments.new(:hard_wrap => true, :with_toc_data => true)
options = {
:fenced_code_blocks => true,
:no_intra_emphasis => true,
:autolink => true,
:strikethrough => true,
:lax_html_blocks => true,
:superscript => true,
}
Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end
I read about :with_toc_data => true but it doesn't works for me. I added it in options area.
I do the same thing as you describe which basically is
Redcarpet::Markdown.new(
Redcarpet::Render::HTML.new(with_toc_data: true), {}
).render(text)
My view contains the following code
- #article.description.scan(/(#+)(.*)/).each do |menu_item|
= content_tag(:a, menu_item[1], :href => "##{menu_item[1].downcase.strip.gsub(" ","-")}")
Maybe this helps.
Related
I am using RubyMine with rails 3.2.12 and I am getting following deprecated warning in my IDE. Any Idea How can I solve this deprecated warning?
find(:first) and find(:all) are deprecated in favour of first and all methods. Support will be removed from rails 3.2.
I changed my answer after #keithepley comment
#Post.find(:all, :conditions => { :approved => true })
Post.where(:approved => true).all
#Post.find(:first, :conditions => { :approved => true })
Post.where(:approved => true).first
or
post = Post.first or post = Post.first!
or
post = Post.last or post = Post.last!
You can read more from this locations
deprecated statement
Post.find(:all, :conditions => { :approved => true })
better version
Post.all(:conditions => { :approved => true })
best version (1)
named_scope :approved, :conditions => { :approved => true }
Post.approved.all
best version (2)
Post.scoped(:conditions => { :approved => true }).all
Here is the Rails 3-4 way of doing it:
Post.where(approved: true) # All accepted posts
Post.find_by_approved(true) # The first accepted post
# Or Post.find_by(approved: true)
# Or Post.where(approved: true).first
Post.first
Post.last
Post.all
Use the new ActiveRecord::Relation stuff that was added in Rails 3. Find more info here: http://guides.rubyonrails.org/active_record_querying.html
Instead of #find, use #first, #last, #all, etc. on your model, and the methods that return a ActiveRecord::Relation, like #where.
#User.find(:first)
User.first
#User.find(:all, :conditions => {:foo => true})
User.where(:foo => true).all
I am working on ruby on rails. I am trying to do a file attachment (image/audio/video) .
So i have a common method like
byteArray = StringIO.new(File.open("path").read)
Is it possible to find the content type of the byteArray to check whether the uploaded file is a image/audio/video/pdf in ruby.
I saw this was tagged paperclip, so I will give you how we do it with paperclip:
class Attachment < ActiveRecord::Base
has_attached_file :attachment,
styles: lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"} : {:thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10}, :medium => { :geometry => "300x300#", :format => 'jpg', :time => 10}}},
:processors => lambda { |a| a.is_video? ? [ :ffmpeg ] : [ :thumbnail ] }
def is_video?
attachment.instance.attachment_content_type =~ %r(video)
end
def is_image?
attachment.instance.attachment_content_type =~ %r(image)
end
end
If you manage to get your file into Paperclip, it basically cuts it up into content_type already. This means that if you use a lambda to determine whether the attachment content_type contains image or video
If you give me some more info on what you're trying to achieve, I can give you some refactored code to help with your issue specifically :)
Can't figure out how to do this? and couldn't find much help from anywhere else!
I have set up the paperclip and fog like this;
config/initializers/fog.rb
connection = Fog::Storage.new({
:provider => 'Rackspace',
:rackspace_username => '',
:rackspace_api_key => ''
})
environment.rb;
Paperclip::Attachment.default_options.update({
:path => ":attachment/:id/:timestamp_:style.:extension",
:storage => :fog,
:fog_credentials => {
:provider => 'Rackspace',
:rackspace_username => '',
:rackspace_api_key => '',
:persistent => false
},
:fog_directory => '',
:fog_public => true
})
I am using file_field to get an image and then posting it to my controller. This gets me something like this in;
"pic"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f90ac06a6c8 #original_filename="3245-1920x1200.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"cloth[pic][image]\"; filename=\"3245-1920x1200.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/tmp/RackMultipart20130104-5386-103laem>>}
What I can't understand is that how do I go about actually saving this file to cloud files using something like this;
file = directory.files.create(
:key => 'resume.html',
:body => File.open("/path/to/my/resume.html"),
:public => true
)
EDIT
Relevant Models;
class Cloth
include Mongoid::Document
has_many :pics
class Pic
include Mongoid::Document
include Mongoid::Paperclip
belongs_to :cloth
has_mongoid_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
And in the controller this is how I am currently creating pic based on above params;
#cloth = Cloth.new
#cloth.pics.create!(params[:cloth][:pic])
Let's step back and look at the problem from different perspective. Can you see if the following script will upload an image to your container:
require 'fog'
service = Fog::Storage.new({
:provider => 'Rackspace',
:rackspace_username => YOUR_USERNAME,
:rackspace_api_key => YOUR_API_KEY
})
container = service.directories.new(:key => YOUR_CONTAINER_NAME)
container.files.create :key => 'my-pix.jpg', :body => File.open PATH_TO_FILE
Update the uppercase parameters with the appropriate variables and let me know what happens. Hopefully this will help narrow down the problem.
Paperclip and ActiveRecord should automatically handle the file upload for you. Here is a good quick start explaining the process:
https://github.com/thoughtbot/paperclip#quick-start
If you are still having issues, can you provide me with the relevant controller and model code?
In my project I am trying to print a PDF in Greyscale with a couple of images and text from HTML using the wicked_PDF. The Gem provides a function for the same, but it doesn't seem to be working.
Here is my code:
render :pdf => "MyObject",
:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
:template => '/widgets/pdf/show_myObject.erb',
:page_size => 'A4',
:header => { :html => { :template => "/widgets/pdf/myObject_header.erb" }},
:footer => { :html => { :template => "/widgets/pdf/myObject_footer.erb" }, :line => true },
:margin => { :top => 0, :left => 3, :right => 3 },
:greyscale => true
I am passing the images as background. But it renders in color. Am I missing something? Why is wicked_PDF gem unable to process greyscale function as expected?
Their documentation did not have any help regarding this.
Turns out the wkhtmltopdf --grayscale option was incorrectly coded in wicked_pdf as --greyscale
(swap the 'e' for an 'a').
I've pushed a fix, and cut a new version of the gem (0.7.9) for this. Thanks for pointing it out!
:grayscale => true
Now works as intended.
I've implemented the framework outlined in this post: How to use jquery-Tokeninput and Acts-as-taggable-on with some difficulty. This is working insofar as prepopulating with the appropriate theme and ajax search, but when I enter a new tag, it is immediately deleted when the text area loses focus. I'm not sure what I'm doing wrong. Here's some of my relevant code:
User Model (does the tagging):
class User < ActiveRecord::Base
[...]
# tagging
acts_as_tagger
Item Model (accepts a tag):
class Item < ActiveRecord::Base
attr_accessible :title, :tag_list
#tagging functionality
acts_as_taggable_on :tags
Item Controller:
def tags
#tags = ActsAsTaggableOn::Tag.where("tags.name LIKE ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => #tags.collect{|t| {:id => t.name, :name => t.name }}}
end
end
On my form partial:
<%= f.input :tag_list, :label => "Tags", :input_html => { :class => "text_field short", "data-pre" => #item.tags.map(&:attributes).to_json }, :hint => "separate tags by a space" %>
my routes:
get "items/tags" => "items#tags", :as => :tags
resources :items
[almost there!!!]
the js on the form [note: the id of the element is assigned dynamically]:
<script type="text/javascript">
$(function() {
$("#item_tag_list").tokenInput("/art_items/tags", {
prePopulate: $("#item_tag_list").data("pre"),
preventDuplicates: true,
crossDomain: false,
theme: "facebook"
});
});
</script>
If you still want to use Jquery TokenInput and add tags there are different ways to do it.
1.
This is actually from my same question; the newest answer: How to use jquery-Tokeninput and Acts-as-taggable-on
This could go in your controller.
def tags
query = params[:q]
if query[-1,1] == " "
query = query.gsub(" ", "")
Tag.find_or_create_by_name(query)
end
#Do the search in memory for better performance
#tags = ActsAsTaggableOn::Tag.all
#tags = #tags.select { |v| v.name =~ /#{query}/i }
respond_to do |format|
format.json{ render :json => #tags.map(&:attributes) }
end
end
This will create the tag, whenever the space bar is hit.
You could then add this search setting in the jquery script:
noResultsText: 'No result, hit space to create a new tag',
It's a little dirty but it works for me.
2.
Check out this guy's method: https://github.com/vdepizzol/jquery-tokeninput
He made a custom entry ability:
$(function() {
$("#book_author_tokens").tokenInput("/authors.json", {
crossDomain: false,
prePopulate: $("#book_author_tokens").data("pre"),
theme: "facebook",
allowCustomEntry: true
});
});
3.
Not to sure about this one but it may help: Rails : Using jquery tokeninput (railscast #258) to create new entries
4.
This one seems legit as well: https://github.com/loopj/jquery-tokeninput/pull/219
I personally like the first one, seems easiest to get and install.