Code Monkey home page Code Monkey logo

ruby-bbcode's Introduction

Ruby-BBCode

gem version Code Coverage

This gem adds support for BBCode to Ruby. The BBCode is parsed by a parser before converted to HTML, allowing to convert nested BBCode tags in strings to their correct HTML equivalent. The parser also checks whether the BBCode is valid and gives errors for incorrect BBCode texts. Additionally, annotations can be added to the BBCode string the showing errors that are present, assuming there are any errors.

The parser recognizes all official tags and allows to easily extend this set with custom tags.

Examples

bbcode_to_html can be used to convert a BBCode string to HTML:

'This is [b]bold[/b] and this is [i]italic[/i].'.bbcode_to_html
 => 'This is <strong>bold</strong> and this is <em>italic</em>.'

bbcode_show_errors can be used to convert a BBCode to BBCode annotated with errors (assuming the original BBCode did contain errors):

'[img=no_dimensions_here]image.png[/img]'.bbcode_show_errors
 => '<span class=\'bbcode_error\' data-bbcode-errors=\'["The image parameters \'no_dimensions_here\' are incorrect, \'<width>x<height>\' excepted"]\'>[img]</span>image.png[/img]'

These HTML attributes containing the JSON representation of the errors can be used to inform the user about the problems. The following JavaScript/jQuery example makes use of the Bootstrap tooltips plugin to show the errors in tooltip popups:

$(".bbcode_error").tooltip({
  title: function() {
    var errors = JSON.parse($(this).attr('data-bbcode-errors'));
    return errors.join("\n");
  }
});

Installing

Add the following line to the Gemfile of your application:

gem 'ruby-bbcode'

Or to use the source code from the repository:

gem 'ruby-bbcode', :git => 'git://github.com/veger/ruby-bbcode.git'

Run

bundle install

And Ruby-BBCode is available in your application.

Note: Do not forget to restart your server!

Acknowledgements

A big thanks to @TheNotary for all contributions he made to this project!

Some of the ideas and the tests came from bb-ruby of Craig P Jolicoeur.

License

MIT License. See the included MIT-LICENCE file.

ruby-bbcode's People

Contributors

dependabot[bot] avatar thenotary avatar veger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ruby-bbcode's Issues

The library is susceptible to HTML injection / XSS errors

The library is susceptible to HTML injection / XSS errors - and pretty easily, for example

'[url=http://www.google.com" onclick="javascript:alert]google[/url]'.bbcode_to_html

... i would recommend filtering out / escaping quotes from parameters, not sure if in bbtree_to_html or parse

Have [media]url[/media] decode to a youtube vid?

Hey, I'm noticing the string

"[media]https://www.youtube.com/watch?v=EUcPSerw56M[/media]".bbcode_to_html

Doesn't decode to anything interesting such as maybe:

"<iframe width="560" height="315" src="http://www.youtube.com/embed/EUcPSerw56M" frameborder="0" allowfullscreen></iframe>"

BUG: Tag Shifter is too greedy

The tag shifter is too greedy, raising an error:

Tag [color] must have 'color' parameter, Tag [color] must have 'color' parameter, [color] not closed, [color] not closed

This comes from page text with [COLOR-SOMETHING which is not a tag in the page text (was code).

Apologizes, but did not take the time to fix the tag sifter code to limit the scope of the matches.

Problem with lists

There are inexpected newline tags in the return string of lists.

[list]
[*]item 1
[*]item 2
[/list]

Converts to:

<ul><br />
<li>item 1<br />
</li>item 2<br />
</li></ul><br />

Use content_tag for bbcode :html parameter

Before that, sorry for my english.
Here's an example of simple custom bbcode

:spoiler => {
    :html_open => '
      <div class="block block-spoiler"><h2>Spoiler: %title%</h2>',
    :html_close => '</div>',
    # Ommitted for great justice
}

Now let's assume that the output has kinda complicated markup

:spoiler => {
    :html_open => '
      <div class="block block-spoiler">
        <div class="header">
          <h2>Spoiler: %title%</h2>
          <div class="side pull-right">
            <ul class="buttons">
              <li>
                <a href="#" class="block-toggle-spoiler tip" title="" data-original-title="Show content">
                  <span class="icon-chevron-down"></span>
                </a>
              </li>
            </ul>
          </div>
        </div>
        <div class="content" style="display:none;">',
    :html_close => '</div></div>',
    # Ommitted for great justice
}

It feels like some pain to theme html for output, can i process html in method? For example:

:spoiler => {
    :tag_template => spoiler_template(content, param_a),
    # Ommitted for great justice
}

# in somewhere
def spoiler_template(content, param_a)
  content_tag(:div, :class => "spoiler", :data => {:title => param_a}) do
    concat content_tag(:h2, "Spoiler")
    concat content_tag(:div, content, :class => "content")
  end
end

So it will be easier to theme bbcode to your taste.
The question is: Can i achieve that in current gem version somehow?

How are @bbtree[:nodes] built up during parsing?

It looks like when you convert bbcode to html, one of the last steps is to do something like

bbtree_to_html(@bbtree[:nodes], use_tags)

This happens after the bbcode string is completely parsed. So my question is, how does @bbtree[:nodes] become populated exactly? It looks like there's almost a recursive element to things because @bbtree isn't the thing that gets set directly, instead it's bbtree_current_node which receives the buildup...

.
.
.
bbtree_current_node[:nodes] << element unless element == nil
.
.
.
bbtree_current_node = @bbtree
bbtree_depth.times { bbtree_current_node = bbtree_current_node[:nodes].last }

I've been trying to refactor the code to be more straightforward (e.g. making the build up happen to a discrete variable designed solely to hold the buildup), but I'm not getting anywhere.

Let me know if this aspect of the code confuses you as much as it does me and I can give sorting it out another go. Otherwise please fill me in on what's going on.

Issue with [ul][li] and carrage returns

The editor I am using browser side produced BBC that looks like this:

Et congregans omnes principes sacerdotum:
[ul]
[li]et scribas populi[/li]
[li]sciscitabatur ab eis[/li]
[li]ubi Christus nasceretur[/li]
[/ul]
At illi dixerunt In Bethlehem Judæ sic enim

But when parsed into HTML via RubyBBCode.to_html The HTML looks like this:

Et congregans omnes principes sacerdotum:<br>
<ul><br>
<li>et scribas populi</li><br>
<li>sciscitabatur ab eis</li><br>
<li>ubi Christus nasceretur</li><br>
</ul><br>
At illi dixerunt In Bethlehem Judæ sic enim 

Is there a way to not have carriage returns inside of ul elements generate
.

Parser fail on bullet list with bold tag inside

Hi,

We are using your gem to decode some bbcode. We found an issue when we include a bold tag inside a bullet list.
here is our bbcode code:

[list]
  [*][b]De délicieuses pâtes et nouilles fraîches:[/b] Préparez 300 g de pâtes ou de nouilles en seulement 10 minutes
  [*][b]Processus automatique: [/b]Une fois que vous avez sélectionné votre programme et appuyé sur le bouton de démarrage, la machine mélange, pétrit et extrude automatiquement.
[/list]

it raise the following error when we call bbcode_to_html
[*] can only be used in [list], [ul] and [ol], so using it in a [*] tag is not allowed, Closing tag [/list] doesn't match [*], [list] not closed, [*] not closed, [*] not closed

if we remove the [b] and [/b] tag it works fine.
it look like there is an error in the parser `bbcode_to_html'

Any help si welcoming !
Thanks

Uppercased tag not parsed by bbcode_to_html method.

So, here it is, as described in issue title.
/test/ruby_bbcode_bbcode_test.rb
This test passes.

def test_uppercased_tags
  assert_equal '[B]simple[/B]', '[B]simple[/B]'.bbcode_show_errors
  assert_equal "[B]line 1\nline 2[/B]", "[B]line 1\nline 2[/B]".bbcode_show_errors
end

But this is not.
/test/ruby_bbcode_html_test.rb

def test_uppercased_tags
  assert_equal '<strong>simple</strong>', '[B]simple[/B]'.bbcode_to_html
  assert_equal "<strong>line 1<br />\nline 2</strong>", "[B]line 1\nline 2[/B]".bbcode_to_html
end

UPD:

My guess that is method RubyBBCode#determine_applicable_tags has to do something with that.
Clone final hash of bbcodes with uppercased keys maybe?

Standard Way of Including Custom Tags in Rails Type Frameworks

I've been wondering what the best way is to use custom tags in a rails app. Would you expect the standard way to fork this repo, edit the tags in the fork, and then point bundler at the fork? I feel like that works, but it's a little external, so there's either an easier way to do it, or it might be worth spending a little time on.

I've been thinking of a gem ruby-bbcode-rails similar to the rspec-rails gem, which when installed in a rails app will automatically create a rails initializer called config/initializer/ruby-bbcode.rb containing the tags definition.

This could lead to something like rails g ruby-bbcode:full-tags which would override the default minimal tag set and use a larger tagset located in the ruby-bbcode-rails repository.

I don't want to tackle something that big at the moment (I've already spent a little more time today off task than I meant to, lol) and it definitely should be kept out of this repo given that it's framework specific, but what are your thoughts on custom tags?

SoundCloud Embedding Support

Hey, it's good to see you're still giving life to the repo, Veger. How would you feel about adding a sound cloud tag, and making it available for use through the [media] tag. I think this feature would really make the gem look nice.

Example:
http://jsfiddle.net/33sdey01/1/

Resource:
(Note that the 'share' widget isn't being tested against firefox, so you need chrome to get the embed link copied, heh)
https://soundcloud.com/pages/embed

Example wordpress BBCode in the wild:
[soundcloud url="https://api.soundcloud.com/tracks/34019569" params="auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true" width="100%" height="450" iframe="true" /]

Let me know how you feel. It looks pretty straight forward and just needs a tag to be inserted and also a tiny bit of code to escape the '/' characters.

Add support to escape parameters

This would make the tags more flexible, especially if the parameter is used in an URL as some input for some (server-)script.

When escaping is required, the tag description should have a new field added, like :uri_escape=>true

full youtube urls don't have their video IDs automatically parsed out of their full URLS

Hey, I was showing a member of the staff how to upload youtube videos to the rails app and I realized it would be a heck of a lot easier for them if they just needed to copy and paste the full URL of the youtube video instead of having to manually parse out the videos ID value from the URL. I wrote a method that can turn a URL into a video ID as well as some tests.

https://gist.github.com/TheNotary/5138918

I'm not exactly sure how to implement my code though, heh. But what do you think of the feature. The less the developers need to explain to their clients, the better.

[ul][li] is kind of a pain to deal with right now

So these inputs won't parse well

[ul]
[li]First Element[/li]
[li]Second Element[/li]
[li]Third Element[/li]
[/ul]

And I think it should. The [ul] complains that it can't have
elements in it. Is this easy to fix?

Demo Project

Sorry for the issue bombardment, I'm on an OSS binge apparently, lol

I think it might be nice to have a demo project that use ruby-bbcode. There are three immediate benefits I can see.

  1. To aid in development, we can visually take a look at what ruby-bbcode looks like when rendered on a page.

  2. To aid in consumption, we can show prospective web developers how easy and straightforward it is to use the gem.

  3. To aid in consumption, we can recommend basic css styling to make things look ok.

I have been playing around with a really ugly looking demo. I included twitter bootstrap in the hopes that it would just make everything look fine, but no such luck, lol.

What I have is absolutely NOT finished (actually, I found a new bug by chance and worked on tracking that thing down). What I have so far isn't really even suitable enough for aiding development, but you can have a peek at what I've done so far at https://ruby-bbcode-demo.herokuapp.com/ . Code is at https://github.com/TheNotary/ruby-bbcode-demo you can see it's pretty bare bones now. I'd submit my work CSS, but we only use the video and image tags. If you have some HTML/CSS already made, perhaps that would be good to put up on heroku and link to from the readme.

I think eventually it would be good to show the users a list of all the codes, what it looks like when they're rendered, and then finally give them a little input box they can use to submit there own forum post or article.

Let me know your thoughts on deploying a live demo project. And if you don't feel a demo project will be of aid, feel free to close this issue, I feel I've dragged up enough issues in the past 16 hours :)

Parse(text, tags = {}) is a very long function, candidate for refactoring

Hey, I hope I don't find you at a busy time. There's nothing worse than having to look over old code when your plate is full of new, more interesting things.

I've been digging through this code trying to work on a proper pull request for you, but I got hung up for a long time on def self.parse(text, tags = {}) on line 43 of ruby-bbcode. I think it's a good candidate for a refactoring.

As an exercise for myself, I started refactoring it to be more of an OO style process. I think it's starting to look really pretty. I'm not sure if you'd be interested in receiving a pull request on it, it's a much more invasive kind of pull request than a simple feature request, but I think you'll appreciate the code, and it might spark more coders to work on the project if the code is easier to understand.

You can see my latest work here (notice the two new files in /lib/ruby-bbcode/):
https://github.com/TheNotary/ruby-bbcode/tree/development

It's completely unfinished atm, but should be done by the end of the night unless I run into more snafus.

The algorithm change is like this:

Instead of having one big function that parses through the string of BBCode, we can have a big function instantiate a "TagCollection" object which is responsible for storing the text, the tag_definitions, and error messages. It also is in charge of scanning the text and converting the tags into "TagInfo" items.

TagInfo is another class that is specific to each tag (or !is_tag items, i.e. text items). TagInfo items are a combination of your original ti hash, PLUS methods that make the parsing algorithm a smoother read.

Again, it's not quite finished yet, but let me know what you think of the refactoring. It's probably best that I contact you while it still looks mostly like your own code. And I apologize if this is a bad time to be fiddling with old code.

Ignore unknown/wrong tags

Right now when the parser encounters some text in [] that is not a known tag, it gives an error. There should be at least an option to ignore those tags and either just leave them as is or remove them completely.

Link tag with other tags inside

It should be possible to have other tags inside a [url] tag.
At least those: img, b, i, u, s.

Proposed solution - change the url tag settings in the parser.

gem release

Hi Maarten.

Could you release ruby-bbcode as a gem please?
I'm currently working on a forum engine for rails and I'd need your work (bbruby does not please me) to finalize the current version.

Best regards.

Use <p></p> instead of <br/>

It is nicer (HTML) to use paragraphs (<p>...</p>) instead of <br /> for newlines/paragraphs.

Furthermore, the <p> HTML elements can be styled (e.g. using CSS) making the output more flexible

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.